1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSwitch.h" 79 #include "llvm/ADT/Triple.h" 80 #include "llvm/Support/AtomicOrdering.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ConvertUTF.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/Locale.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/SaveAndRestore.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include <algorithm> 91 #include <bitset> 92 #include <cassert> 93 #include <cstddef> 94 #include <cstdint> 95 #include <functional> 96 #include <limits> 97 #include <string> 98 #include <tuple> 99 #include <utility> 100 101 using namespace clang; 102 using namespace sema; 103 104 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 105 unsigned ByteNo) const { 106 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 107 Context.getTargetInfo()); 108 } 109 110 /// Checks that a call expression's argument count is the desired number. 111 /// This is useful when doing custom type-checking. Returns true on error. 112 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 113 unsigned argCount = call->getNumArgs(); 114 if (argCount == desiredArgCount) return false; 115 116 if (argCount < desiredArgCount) 117 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 118 << 0 /*function call*/ << desiredArgCount << argCount 119 << call->getSourceRange(); 120 121 // Highlight all the excess arguments. 122 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 123 call->getArg(argCount - 1)->getEndLoc()); 124 125 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 126 << 0 /*function call*/ << desiredArgCount << argCount 127 << call->getArg(1)->getSourceRange(); 128 } 129 130 /// Check that the first argument to __builtin_annotation is an integer 131 /// and the second argument is a non-wide string literal. 132 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 133 if (checkArgCount(S, TheCall, 2)) 134 return true; 135 136 // First argument should be an integer. 137 Expr *ValArg = TheCall->getArg(0); 138 QualType Ty = ValArg->getType(); 139 if (!Ty->isIntegerType()) { 140 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 141 << ValArg->getSourceRange(); 142 return true; 143 } 144 145 // Second argument should be a constant string. 146 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 147 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 148 if (!Literal || !Literal->isAscii()) { 149 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 150 << StrArg->getSourceRange(); 151 return true; 152 } 153 154 TheCall->setType(Ty); 155 return false; 156 } 157 158 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 159 // We need at least one argument. 160 if (TheCall->getNumArgs() < 1) { 161 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 162 << 0 << 1 << TheCall->getNumArgs() 163 << TheCall->getCallee()->getSourceRange(); 164 return true; 165 } 166 167 // All arguments should be wide string literals. 168 for (Expr *Arg : TheCall->arguments()) { 169 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 170 if (!Literal || !Literal->isWide()) { 171 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 172 << Arg->getSourceRange(); 173 return true; 174 } 175 } 176 177 return false; 178 } 179 180 /// Check that the argument to __builtin_addressof is a glvalue, and set the 181 /// result type to the corresponding pointer type. 182 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 183 if (checkArgCount(S, TheCall, 1)) 184 return true; 185 186 ExprResult Arg(TheCall->getArg(0)); 187 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 188 if (ResultType.isNull()) 189 return true; 190 191 TheCall->setArg(0, Arg.get()); 192 TheCall->setType(ResultType); 193 return false; 194 } 195 196 /// Check the number of arguments and set the result type to 197 /// the argument type. 198 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 199 if (checkArgCount(S, TheCall, 1)) 200 return true; 201 202 TheCall->setType(TheCall->getArg(0)->getType()); 203 return false; 204 } 205 206 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 207 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 208 /// type (but not a function pointer) and that the alignment is a power-of-two. 209 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 210 if (checkArgCount(S, TheCall, 2)) 211 return true; 212 213 clang::Expr *Source = TheCall->getArg(0); 214 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 215 216 auto IsValidIntegerType = [](QualType Ty) { 217 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 218 }; 219 QualType SrcTy = Source->getType(); 220 // We should also be able to use it with arrays (but not functions!). 221 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 222 SrcTy = S.Context.getDecayedType(SrcTy); 223 } 224 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 225 SrcTy->isFunctionPointerType()) { 226 // FIXME: this is not quite the right error message since we don't allow 227 // floating point types, or member pointers. 228 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 229 << SrcTy; 230 return true; 231 } 232 233 clang::Expr *AlignOp = TheCall->getArg(1); 234 if (!IsValidIntegerType(AlignOp->getType())) { 235 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 236 << AlignOp->getType(); 237 return true; 238 } 239 Expr::EvalResult AlignResult; 240 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 241 // We can't check validity of alignment if it is value dependent. 242 if (!AlignOp->isValueDependent() && 243 AlignOp->EvaluateAsInt(AlignResult, S.Context, 244 Expr::SE_AllowSideEffects)) { 245 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 246 llvm::APSInt MaxValue( 247 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 248 if (AlignValue < 1) { 249 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 250 return true; 251 } 252 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 253 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 254 << MaxValue.toString(10); 255 return true; 256 } 257 if (!AlignValue.isPowerOf2()) { 258 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 259 return true; 260 } 261 if (AlignValue == 1) { 262 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 263 << IsBooleanAlignBuiltin; 264 } 265 } 266 267 ExprResult SrcArg = S.PerformCopyInitialization( 268 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 269 SourceLocation(), Source); 270 if (SrcArg.isInvalid()) 271 return true; 272 TheCall->setArg(0, SrcArg.get()); 273 ExprResult AlignArg = 274 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 275 S.Context, AlignOp->getType(), false), 276 SourceLocation(), AlignOp); 277 if (AlignArg.isInvalid()) 278 return true; 279 TheCall->setArg(1, AlignArg.get()); 280 // For align_up/align_down, the return type is the same as the (potentially 281 // decayed) argument type including qualifiers. For is_aligned(), the result 282 // is always bool. 283 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 284 return false; 285 } 286 287 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 288 unsigned BuiltinID) { 289 if (checkArgCount(S, TheCall, 3)) 290 return true; 291 292 // First two arguments should be integers. 293 for (unsigned I = 0; I < 2; ++I) { 294 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 295 if (Arg.isInvalid()) return true; 296 TheCall->setArg(I, Arg.get()); 297 298 QualType Ty = Arg.get()->getType(); 299 if (!Ty->isIntegerType()) { 300 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 301 << Ty << Arg.get()->getSourceRange(); 302 return true; 303 } 304 } 305 306 // Third argument should be a pointer to a non-const integer. 307 // IRGen correctly handles volatile, restrict, and address spaces, and 308 // the other qualifiers aren't possible. 309 { 310 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 311 if (Arg.isInvalid()) return true; 312 TheCall->setArg(2, Arg.get()); 313 314 QualType Ty = Arg.get()->getType(); 315 const auto *PtrTy = Ty->getAs<PointerType>(); 316 if (!PtrTy || 317 !PtrTy->getPointeeType()->isIntegerType() || 318 PtrTy->getPointeeType().isConstQualified()) { 319 S.Diag(Arg.get()->getBeginLoc(), 320 diag::err_overflow_builtin_must_be_ptr_int) 321 << Ty << Arg.get()->getSourceRange(); 322 return true; 323 } 324 } 325 326 // Disallow signed ExtIntType args larger than 128 bits to mul function until 327 // we improve backend support. 328 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 329 for (unsigned I = 0; I < 3; ++I) { 330 const auto Arg = TheCall->getArg(I); 331 // Third argument will be a pointer. 332 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 333 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 334 S.getASTContext().getIntWidth(Ty) > 128) 335 return S.Diag(Arg->getBeginLoc(), 336 diag::err_overflow_builtin_ext_int_max_size) 337 << 128; 338 } 339 } 340 341 return false; 342 } 343 344 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 345 if (checkArgCount(S, BuiltinCall, 2)) 346 return true; 347 348 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 349 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 350 Expr *Call = BuiltinCall->getArg(0); 351 Expr *Chain = BuiltinCall->getArg(1); 352 353 if (Call->getStmtClass() != Stmt::CallExprClass) { 354 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 355 << Call->getSourceRange(); 356 return true; 357 } 358 359 auto CE = cast<CallExpr>(Call); 360 if (CE->getCallee()->getType()->isBlockPointerType()) { 361 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 362 << Call->getSourceRange(); 363 return true; 364 } 365 366 const Decl *TargetDecl = CE->getCalleeDecl(); 367 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 368 if (FD->getBuiltinID()) { 369 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 370 << Call->getSourceRange(); 371 return true; 372 } 373 374 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 375 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 376 << Call->getSourceRange(); 377 return true; 378 } 379 380 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 381 if (ChainResult.isInvalid()) 382 return true; 383 if (!ChainResult.get()->getType()->isPointerType()) { 384 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 385 << Chain->getSourceRange(); 386 return true; 387 } 388 389 QualType ReturnTy = CE->getCallReturnType(S.Context); 390 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 391 QualType BuiltinTy = S.Context.getFunctionType( 392 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 393 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 394 395 Builtin = 396 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 397 398 BuiltinCall->setType(CE->getType()); 399 BuiltinCall->setValueKind(CE->getValueKind()); 400 BuiltinCall->setObjectKind(CE->getObjectKind()); 401 BuiltinCall->setCallee(Builtin); 402 BuiltinCall->setArg(1, ChainResult.get()); 403 404 return false; 405 } 406 407 namespace { 408 409 class EstimateSizeFormatHandler 410 : public analyze_format_string::FormatStringHandler { 411 size_t Size; 412 413 public: 414 EstimateSizeFormatHandler(StringRef Format) 415 : Size(std::min(Format.find(0), Format.size()) + 416 1 /* null byte always written by sprintf */) {} 417 418 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 419 const char *, unsigned SpecifierLen) override { 420 421 const size_t FieldWidth = computeFieldWidth(FS); 422 const size_t Precision = computePrecision(FS); 423 424 // The actual format. 425 switch (FS.getConversionSpecifier().getKind()) { 426 // Just a char. 427 case analyze_format_string::ConversionSpecifier::cArg: 428 case analyze_format_string::ConversionSpecifier::CArg: 429 Size += std::max(FieldWidth, (size_t)1); 430 break; 431 // Just an integer. 432 case analyze_format_string::ConversionSpecifier::dArg: 433 case analyze_format_string::ConversionSpecifier::DArg: 434 case analyze_format_string::ConversionSpecifier::iArg: 435 case analyze_format_string::ConversionSpecifier::oArg: 436 case analyze_format_string::ConversionSpecifier::OArg: 437 case analyze_format_string::ConversionSpecifier::uArg: 438 case analyze_format_string::ConversionSpecifier::UArg: 439 case analyze_format_string::ConversionSpecifier::xArg: 440 case analyze_format_string::ConversionSpecifier::XArg: 441 Size += std::max(FieldWidth, Precision); 442 break; 443 444 // %g style conversion switches between %f or %e style dynamically. 445 // %f always takes less space, so default to it. 446 case analyze_format_string::ConversionSpecifier::gArg: 447 case analyze_format_string::ConversionSpecifier::GArg: 448 449 // Floating point number in the form '[+]ddd.ddd'. 450 case analyze_format_string::ConversionSpecifier::fArg: 451 case analyze_format_string::ConversionSpecifier::FArg: 452 Size += std::max(FieldWidth, 1 /* integer part */ + 453 (Precision ? 1 + Precision 454 : 0) /* period + decimal */); 455 break; 456 457 // Floating point number in the form '[-]d.ddde[+-]dd'. 458 case analyze_format_string::ConversionSpecifier::eArg: 459 case analyze_format_string::ConversionSpecifier::EArg: 460 Size += 461 std::max(FieldWidth, 462 1 /* integer part */ + 463 (Precision ? 1 + Precision : 0) /* period + decimal */ + 464 1 /* e or E letter */ + 2 /* exponent */); 465 break; 466 467 // Floating point number in the form '[-]0xh.hhhhp±dd'. 468 case analyze_format_string::ConversionSpecifier::aArg: 469 case analyze_format_string::ConversionSpecifier::AArg: 470 Size += 471 std::max(FieldWidth, 472 2 /* 0x */ + 1 /* integer part */ + 473 (Precision ? 1 + Precision : 0) /* period + decimal */ + 474 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 475 break; 476 477 // Just a string. 478 case analyze_format_string::ConversionSpecifier::sArg: 479 case analyze_format_string::ConversionSpecifier::SArg: 480 Size += FieldWidth; 481 break; 482 483 // Just a pointer in the form '0xddd'. 484 case analyze_format_string::ConversionSpecifier::pArg: 485 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 486 break; 487 488 // A plain percent. 489 case analyze_format_string::ConversionSpecifier::PercentArg: 490 Size += 1; 491 break; 492 493 default: 494 break; 495 } 496 497 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 498 499 if (FS.hasAlternativeForm()) { 500 switch (FS.getConversionSpecifier().getKind()) { 501 default: 502 break; 503 // Force a leading '0'. 504 case analyze_format_string::ConversionSpecifier::oArg: 505 Size += 1; 506 break; 507 // Force a leading '0x'. 508 case analyze_format_string::ConversionSpecifier::xArg: 509 case analyze_format_string::ConversionSpecifier::XArg: 510 Size += 2; 511 break; 512 // Force a period '.' before decimal, even if precision is 0. 513 case analyze_format_string::ConversionSpecifier::aArg: 514 case analyze_format_string::ConversionSpecifier::AArg: 515 case analyze_format_string::ConversionSpecifier::eArg: 516 case analyze_format_string::ConversionSpecifier::EArg: 517 case analyze_format_string::ConversionSpecifier::fArg: 518 case analyze_format_string::ConversionSpecifier::FArg: 519 case analyze_format_string::ConversionSpecifier::gArg: 520 case analyze_format_string::ConversionSpecifier::GArg: 521 Size += (Precision ? 0 : 1); 522 break; 523 } 524 } 525 assert(SpecifierLen <= Size && "no underflow"); 526 Size -= SpecifierLen; 527 return true; 528 } 529 530 size_t getSizeLowerBound() const { return Size; } 531 532 private: 533 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 534 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 535 size_t FieldWidth = 0; 536 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 537 FieldWidth = FW.getConstantAmount(); 538 return FieldWidth; 539 } 540 541 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 542 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 543 size_t Precision = 0; 544 545 // See man 3 printf for default precision value based on the specifier. 546 switch (FW.getHowSpecified()) { 547 case analyze_format_string::OptionalAmount::NotSpecified: 548 switch (FS.getConversionSpecifier().getKind()) { 549 default: 550 break; 551 case analyze_format_string::ConversionSpecifier::dArg: // %d 552 case analyze_format_string::ConversionSpecifier::DArg: // %D 553 case analyze_format_string::ConversionSpecifier::iArg: // %i 554 Precision = 1; 555 break; 556 case analyze_format_string::ConversionSpecifier::oArg: // %d 557 case analyze_format_string::ConversionSpecifier::OArg: // %D 558 case analyze_format_string::ConversionSpecifier::uArg: // %d 559 case analyze_format_string::ConversionSpecifier::UArg: // %D 560 case analyze_format_string::ConversionSpecifier::xArg: // %d 561 case analyze_format_string::ConversionSpecifier::XArg: // %D 562 Precision = 1; 563 break; 564 case analyze_format_string::ConversionSpecifier::fArg: // %f 565 case analyze_format_string::ConversionSpecifier::FArg: // %F 566 case analyze_format_string::ConversionSpecifier::eArg: // %e 567 case analyze_format_string::ConversionSpecifier::EArg: // %E 568 case analyze_format_string::ConversionSpecifier::gArg: // %g 569 case analyze_format_string::ConversionSpecifier::GArg: // %G 570 Precision = 6; 571 break; 572 case analyze_format_string::ConversionSpecifier::pArg: // %d 573 Precision = 1; 574 break; 575 } 576 break; 577 case analyze_format_string::OptionalAmount::Constant: 578 Precision = FW.getConstantAmount(); 579 break; 580 default: 581 break; 582 } 583 return Precision; 584 } 585 }; 586 587 } // namespace 588 589 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 590 /// __builtin_*_chk function, then use the object size argument specified in the 591 /// source. Otherwise, infer the object size using __builtin_object_size. 592 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 593 CallExpr *TheCall) { 594 // FIXME: There are some more useful checks we could be doing here: 595 // - Evaluate strlen of strcpy arguments, use as object size. 596 597 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 598 isConstantEvaluated()) 599 return; 600 601 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 602 if (!BuiltinID) 603 return; 604 605 const TargetInfo &TI = getASTContext().getTargetInfo(); 606 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 607 608 unsigned DiagID = 0; 609 bool IsChkVariant = false; 610 Optional<llvm::APSInt> UsedSize; 611 unsigned SizeIndex, ObjectIndex; 612 switch (BuiltinID) { 613 default: 614 return; 615 case Builtin::BIsprintf: 616 case Builtin::BI__builtin___sprintf_chk: { 617 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 618 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 619 620 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 621 622 if (!Format->isAscii() && !Format->isUTF8()) 623 return; 624 625 StringRef FormatStrRef = Format->getString(); 626 EstimateSizeFormatHandler H(FormatStrRef); 627 const char *FormatBytes = FormatStrRef.data(); 628 const ConstantArrayType *T = 629 Context.getAsConstantArrayType(Format->getType()); 630 assert(T && "String literal not of constant array type!"); 631 size_t TypeSize = T->getSize().getZExtValue(); 632 633 // In case there's a null byte somewhere. 634 size_t StrLen = 635 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 636 if (!analyze_format_string::ParsePrintfString( 637 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 638 Context.getTargetInfo(), false)) { 639 DiagID = diag::warn_fortify_source_format_overflow; 640 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 641 .extOrTrunc(SizeTypeWidth); 642 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 643 IsChkVariant = true; 644 ObjectIndex = 2; 645 } else { 646 IsChkVariant = false; 647 ObjectIndex = 0; 648 } 649 break; 650 } 651 } 652 return; 653 } 654 case Builtin::BI__builtin___memcpy_chk: 655 case Builtin::BI__builtin___memmove_chk: 656 case Builtin::BI__builtin___memset_chk: 657 case Builtin::BI__builtin___strlcat_chk: 658 case Builtin::BI__builtin___strlcpy_chk: 659 case Builtin::BI__builtin___strncat_chk: 660 case Builtin::BI__builtin___strncpy_chk: 661 case Builtin::BI__builtin___stpncpy_chk: 662 case Builtin::BI__builtin___memccpy_chk: 663 case Builtin::BI__builtin___mempcpy_chk: { 664 DiagID = diag::warn_builtin_chk_overflow; 665 IsChkVariant = true; 666 SizeIndex = TheCall->getNumArgs() - 2; 667 ObjectIndex = TheCall->getNumArgs() - 1; 668 break; 669 } 670 671 case Builtin::BI__builtin___snprintf_chk: 672 case Builtin::BI__builtin___vsnprintf_chk: { 673 DiagID = diag::warn_builtin_chk_overflow; 674 IsChkVariant = true; 675 SizeIndex = 1; 676 ObjectIndex = 3; 677 break; 678 } 679 680 case Builtin::BIstrncat: 681 case Builtin::BI__builtin_strncat: 682 case Builtin::BIstrncpy: 683 case Builtin::BI__builtin_strncpy: 684 case Builtin::BIstpncpy: 685 case Builtin::BI__builtin_stpncpy: { 686 // Whether these functions overflow depends on the runtime strlen of the 687 // string, not just the buffer size, so emitting the "always overflow" 688 // diagnostic isn't quite right. We should still diagnose passing a buffer 689 // size larger than the destination buffer though; this is a runtime abort 690 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 691 DiagID = diag::warn_fortify_source_size_mismatch; 692 SizeIndex = TheCall->getNumArgs() - 1; 693 ObjectIndex = 0; 694 break; 695 } 696 697 case Builtin::BImemcpy: 698 case Builtin::BI__builtin_memcpy: 699 case Builtin::BImemmove: 700 case Builtin::BI__builtin_memmove: 701 case Builtin::BImemset: 702 case Builtin::BI__builtin_memset: 703 case Builtin::BImempcpy: 704 case Builtin::BI__builtin_mempcpy: { 705 DiagID = diag::warn_fortify_source_overflow; 706 SizeIndex = TheCall->getNumArgs() - 1; 707 ObjectIndex = 0; 708 break; 709 } 710 case Builtin::BIsnprintf: 711 case Builtin::BI__builtin_snprintf: 712 case Builtin::BIvsnprintf: 713 case Builtin::BI__builtin_vsnprintf: { 714 DiagID = diag::warn_fortify_source_size_mismatch; 715 SizeIndex = 1; 716 ObjectIndex = 0; 717 break; 718 } 719 } 720 721 llvm::APSInt ObjectSize; 722 // For __builtin___*_chk, the object size is explicitly provided by the caller 723 // (usually using __builtin_object_size). Use that value to check this call. 724 if (IsChkVariant) { 725 Expr::EvalResult Result; 726 Expr *SizeArg = TheCall->getArg(ObjectIndex); 727 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 728 return; 729 ObjectSize = Result.Val.getInt(); 730 731 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 732 } else { 733 // If the parameter has a pass_object_size attribute, then we should use its 734 // (potentially) more strict checking mode. Otherwise, conservatively assume 735 // type 0. 736 int BOSType = 0; 737 if (const auto *POS = 738 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 739 BOSType = POS->getType(); 740 741 Expr *ObjArg = TheCall->getArg(ObjectIndex); 742 uint64_t Result; 743 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 744 return; 745 // Get the object size in the target's size_t width. 746 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 747 } 748 749 // Evaluate the number of bytes of the object that this call will use. 750 if (!UsedSize) { 751 Expr::EvalResult Result; 752 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 753 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 754 return; 755 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 756 } 757 758 if (UsedSize.getValue().ule(ObjectSize)) 759 return; 760 761 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 762 // Skim off the details of whichever builtin was called to produce a better 763 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 764 if (IsChkVariant) { 765 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 766 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 767 } else if (FunctionName.startswith("__builtin_")) { 768 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 769 } 770 771 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 772 PDiag(DiagID) 773 << FunctionName << ObjectSize.toString(/*Radix=*/10) 774 << UsedSize.getValue().toString(/*Radix=*/10)); 775 } 776 777 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 778 Scope::ScopeFlags NeededScopeFlags, 779 unsigned DiagID) { 780 // Scopes aren't available during instantiation. Fortunately, builtin 781 // functions cannot be template args so they cannot be formed through template 782 // instantiation. Therefore checking once during the parse is sufficient. 783 if (SemaRef.inTemplateInstantiation()) 784 return false; 785 786 Scope *S = SemaRef.getCurScope(); 787 while (S && !S->isSEHExceptScope()) 788 S = S->getParent(); 789 if (!S || !(S->getFlags() & NeededScopeFlags)) { 790 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 791 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 792 << DRE->getDecl()->getIdentifier(); 793 return true; 794 } 795 796 return false; 797 } 798 799 static inline bool isBlockPointer(Expr *Arg) { 800 return Arg->getType()->isBlockPointerType(); 801 } 802 803 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 804 /// void*, which is a requirement of device side enqueue. 805 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 806 const BlockPointerType *BPT = 807 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 808 ArrayRef<QualType> Params = 809 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 810 unsigned ArgCounter = 0; 811 bool IllegalParams = false; 812 // Iterate through the block parameters until either one is found that is not 813 // a local void*, or the block is valid. 814 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 815 I != E; ++I, ++ArgCounter) { 816 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 817 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 818 LangAS::opencl_local) { 819 // Get the location of the error. If a block literal has been passed 820 // (BlockExpr) then we can point straight to the offending argument, 821 // else we just point to the variable reference. 822 SourceLocation ErrorLoc; 823 if (isa<BlockExpr>(BlockArg)) { 824 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 825 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 826 } else if (isa<DeclRefExpr>(BlockArg)) { 827 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 828 } 829 S.Diag(ErrorLoc, 830 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 831 IllegalParams = true; 832 } 833 } 834 835 return IllegalParams; 836 } 837 838 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 839 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 840 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 841 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 842 return true; 843 } 844 return false; 845 } 846 847 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 848 if (checkArgCount(S, TheCall, 2)) 849 return true; 850 851 if (checkOpenCLSubgroupExt(S, TheCall)) 852 return true; 853 854 // First argument is an ndrange_t type. 855 Expr *NDRangeArg = TheCall->getArg(0); 856 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 857 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 858 << TheCall->getDirectCallee() << "'ndrange_t'"; 859 return true; 860 } 861 862 Expr *BlockArg = TheCall->getArg(1); 863 if (!isBlockPointer(BlockArg)) { 864 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 865 << TheCall->getDirectCallee() << "block"; 866 return true; 867 } 868 return checkOpenCLBlockArgs(S, BlockArg); 869 } 870 871 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 872 /// get_kernel_work_group_size 873 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 874 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 875 if (checkArgCount(S, TheCall, 1)) 876 return true; 877 878 Expr *BlockArg = TheCall->getArg(0); 879 if (!isBlockPointer(BlockArg)) { 880 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 881 << TheCall->getDirectCallee() << "block"; 882 return true; 883 } 884 return checkOpenCLBlockArgs(S, BlockArg); 885 } 886 887 /// Diagnose integer type and any valid implicit conversion to it. 888 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 889 const QualType &IntType); 890 891 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 892 unsigned Start, unsigned End) { 893 bool IllegalParams = false; 894 for (unsigned I = Start; I <= End; ++I) 895 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 896 S.Context.getSizeType()); 897 return IllegalParams; 898 } 899 900 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 901 /// 'local void*' parameter of passed block. 902 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 903 Expr *BlockArg, 904 unsigned NumNonVarArgs) { 905 const BlockPointerType *BPT = 906 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 907 unsigned NumBlockParams = 908 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 909 unsigned TotalNumArgs = TheCall->getNumArgs(); 910 911 // For each argument passed to the block, a corresponding uint needs to 912 // be passed to describe the size of the local memory. 913 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 914 S.Diag(TheCall->getBeginLoc(), 915 diag::err_opencl_enqueue_kernel_local_size_args); 916 return true; 917 } 918 919 // Check that the sizes of the local memory are specified by integers. 920 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 921 TotalNumArgs - 1); 922 } 923 924 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 925 /// overload formats specified in Table 6.13.17.1. 926 /// int enqueue_kernel(queue_t queue, 927 /// kernel_enqueue_flags_t flags, 928 /// const ndrange_t ndrange, 929 /// void (^block)(void)) 930 /// int enqueue_kernel(queue_t queue, 931 /// kernel_enqueue_flags_t flags, 932 /// const ndrange_t ndrange, 933 /// uint num_events_in_wait_list, 934 /// clk_event_t *event_wait_list, 935 /// clk_event_t *event_ret, 936 /// void (^block)(void)) 937 /// int enqueue_kernel(queue_t queue, 938 /// kernel_enqueue_flags_t flags, 939 /// const ndrange_t ndrange, 940 /// void (^block)(local void*, ...), 941 /// uint size0, ...) 942 /// int enqueue_kernel(queue_t queue, 943 /// kernel_enqueue_flags_t flags, 944 /// const ndrange_t ndrange, 945 /// uint num_events_in_wait_list, 946 /// clk_event_t *event_wait_list, 947 /// clk_event_t *event_ret, 948 /// void (^block)(local void*, ...), 949 /// uint size0, ...) 950 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 951 unsigned NumArgs = TheCall->getNumArgs(); 952 953 if (NumArgs < 4) { 954 S.Diag(TheCall->getBeginLoc(), 955 diag::err_typecheck_call_too_few_args_at_least) 956 << 0 << 4 << NumArgs; 957 return true; 958 } 959 960 Expr *Arg0 = TheCall->getArg(0); 961 Expr *Arg1 = TheCall->getArg(1); 962 Expr *Arg2 = TheCall->getArg(2); 963 Expr *Arg3 = TheCall->getArg(3); 964 965 // First argument always needs to be a queue_t type. 966 if (!Arg0->getType()->isQueueT()) { 967 S.Diag(TheCall->getArg(0)->getBeginLoc(), 968 diag::err_opencl_builtin_expected_type) 969 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 970 return true; 971 } 972 973 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 974 if (!Arg1->getType()->isIntegerType()) { 975 S.Diag(TheCall->getArg(1)->getBeginLoc(), 976 diag::err_opencl_builtin_expected_type) 977 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 978 return true; 979 } 980 981 // Third argument is always an ndrange_t type. 982 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 983 S.Diag(TheCall->getArg(2)->getBeginLoc(), 984 diag::err_opencl_builtin_expected_type) 985 << TheCall->getDirectCallee() << "'ndrange_t'"; 986 return true; 987 } 988 989 // With four arguments, there is only one form that the function could be 990 // called in: no events and no variable arguments. 991 if (NumArgs == 4) { 992 // check that the last argument is the right block type. 993 if (!isBlockPointer(Arg3)) { 994 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 995 << TheCall->getDirectCallee() << "block"; 996 return true; 997 } 998 // we have a block type, check the prototype 999 const BlockPointerType *BPT = 1000 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1001 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1002 S.Diag(Arg3->getBeginLoc(), 1003 diag::err_opencl_enqueue_kernel_blocks_no_args); 1004 return true; 1005 } 1006 return false; 1007 } 1008 // we can have block + varargs. 1009 if (isBlockPointer(Arg3)) 1010 return (checkOpenCLBlockArgs(S, Arg3) || 1011 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1012 // last two cases with either exactly 7 args or 7 args and varargs. 1013 if (NumArgs >= 7) { 1014 // check common block argument. 1015 Expr *Arg6 = TheCall->getArg(6); 1016 if (!isBlockPointer(Arg6)) { 1017 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1018 << TheCall->getDirectCallee() << "block"; 1019 return true; 1020 } 1021 if (checkOpenCLBlockArgs(S, Arg6)) 1022 return true; 1023 1024 // Forth argument has to be any integer type. 1025 if (!Arg3->getType()->isIntegerType()) { 1026 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1027 diag::err_opencl_builtin_expected_type) 1028 << TheCall->getDirectCallee() << "integer"; 1029 return true; 1030 } 1031 // check remaining common arguments. 1032 Expr *Arg4 = TheCall->getArg(4); 1033 Expr *Arg5 = TheCall->getArg(5); 1034 1035 // Fifth argument is always passed as a pointer to clk_event_t. 1036 if (!Arg4->isNullPointerConstant(S.Context, 1037 Expr::NPC_ValueDependentIsNotNull) && 1038 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1039 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1040 diag::err_opencl_builtin_expected_type) 1041 << TheCall->getDirectCallee() 1042 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1043 return true; 1044 } 1045 1046 // Sixth argument is always passed as a pointer to clk_event_t. 1047 if (!Arg5->isNullPointerConstant(S.Context, 1048 Expr::NPC_ValueDependentIsNotNull) && 1049 !(Arg5->getType()->isPointerType() && 1050 Arg5->getType()->getPointeeType()->isClkEventT())) { 1051 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1052 diag::err_opencl_builtin_expected_type) 1053 << TheCall->getDirectCallee() 1054 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1055 return true; 1056 } 1057 1058 if (NumArgs == 7) 1059 return false; 1060 1061 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1062 } 1063 1064 // None of the specific case has been detected, give generic error 1065 S.Diag(TheCall->getBeginLoc(), 1066 diag::err_opencl_enqueue_kernel_incorrect_args); 1067 return true; 1068 } 1069 1070 /// Returns OpenCL access qual. 1071 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1072 return D->getAttr<OpenCLAccessAttr>(); 1073 } 1074 1075 /// Returns true if pipe element type is different from the pointer. 1076 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1077 const Expr *Arg0 = Call->getArg(0); 1078 // First argument type should always be pipe. 1079 if (!Arg0->getType()->isPipeType()) { 1080 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1081 << Call->getDirectCallee() << Arg0->getSourceRange(); 1082 return true; 1083 } 1084 OpenCLAccessAttr *AccessQual = 1085 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1086 // Validates the access qualifier is compatible with the call. 1087 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1088 // read_only and write_only, and assumed to be read_only if no qualifier is 1089 // specified. 1090 switch (Call->getDirectCallee()->getBuiltinID()) { 1091 case Builtin::BIread_pipe: 1092 case Builtin::BIreserve_read_pipe: 1093 case Builtin::BIcommit_read_pipe: 1094 case Builtin::BIwork_group_reserve_read_pipe: 1095 case Builtin::BIsub_group_reserve_read_pipe: 1096 case Builtin::BIwork_group_commit_read_pipe: 1097 case Builtin::BIsub_group_commit_read_pipe: 1098 if (!(!AccessQual || AccessQual->isReadOnly())) { 1099 S.Diag(Arg0->getBeginLoc(), 1100 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1101 << "read_only" << Arg0->getSourceRange(); 1102 return true; 1103 } 1104 break; 1105 case Builtin::BIwrite_pipe: 1106 case Builtin::BIreserve_write_pipe: 1107 case Builtin::BIcommit_write_pipe: 1108 case Builtin::BIwork_group_reserve_write_pipe: 1109 case Builtin::BIsub_group_reserve_write_pipe: 1110 case Builtin::BIwork_group_commit_write_pipe: 1111 case Builtin::BIsub_group_commit_write_pipe: 1112 if (!(AccessQual && AccessQual->isWriteOnly())) { 1113 S.Diag(Arg0->getBeginLoc(), 1114 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1115 << "write_only" << Arg0->getSourceRange(); 1116 return true; 1117 } 1118 break; 1119 default: 1120 break; 1121 } 1122 return false; 1123 } 1124 1125 /// Returns true if pipe element type is different from the pointer. 1126 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1127 const Expr *Arg0 = Call->getArg(0); 1128 const Expr *ArgIdx = Call->getArg(Idx); 1129 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1130 const QualType EltTy = PipeTy->getElementType(); 1131 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1132 // The Idx argument should be a pointer and the type of the pointer and 1133 // the type of pipe element should also be the same. 1134 if (!ArgTy || 1135 !S.Context.hasSameType( 1136 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1137 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1138 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1139 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1140 return true; 1141 } 1142 return false; 1143 } 1144 1145 // Performs semantic analysis for the read/write_pipe call. 1146 // \param S Reference to the semantic analyzer. 1147 // \param Call A pointer to the builtin call. 1148 // \return True if a semantic error has been found, false otherwise. 1149 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1150 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1151 // functions have two forms. 1152 switch (Call->getNumArgs()) { 1153 case 2: 1154 if (checkOpenCLPipeArg(S, Call)) 1155 return true; 1156 // The call with 2 arguments should be 1157 // read/write_pipe(pipe T, T*). 1158 // Check packet type T. 1159 if (checkOpenCLPipePacketType(S, Call, 1)) 1160 return true; 1161 break; 1162 1163 case 4: { 1164 if (checkOpenCLPipeArg(S, Call)) 1165 return true; 1166 // The call with 4 arguments should be 1167 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1168 // Check reserve_id_t. 1169 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1170 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1171 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1172 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1173 return true; 1174 } 1175 1176 // Check the index. 1177 const Expr *Arg2 = Call->getArg(2); 1178 if (!Arg2->getType()->isIntegerType() && 1179 !Arg2->getType()->isUnsignedIntegerType()) { 1180 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1181 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1182 << Arg2->getType() << Arg2->getSourceRange(); 1183 return true; 1184 } 1185 1186 // Check packet type T. 1187 if (checkOpenCLPipePacketType(S, Call, 3)) 1188 return true; 1189 } break; 1190 default: 1191 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1192 << Call->getDirectCallee() << Call->getSourceRange(); 1193 return true; 1194 } 1195 1196 return false; 1197 } 1198 1199 // Performs a semantic analysis on the {work_group_/sub_group_ 1200 // /_}reserve_{read/write}_pipe 1201 // \param S Reference to the semantic analyzer. 1202 // \param Call The call to the builtin function to be analyzed. 1203 // \return True if a semantic error was found, false otherwise. 1204 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1205 if (checkArgCount(S, Call, 2)) 1206 return true; 1207 1208 if (checkOpenCLPipeArg(S, Call)) 1209 return true; 1210 1211 // Check the reserve size. 1212 if (!Call->getArg(1)->getType()->isIntegerType() && 1213 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1214 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1215 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1216 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1217 return true; 1218 } 1219 1220 // Since return type of reserve_read/write_pipe built-in function is 1221 // reserve_id_t, which is not defined in the builtin def file , we used int 1222 // as return type and need to override the return type of these functions. 1223 Call->setType(S.Context.OCLReserveIDTy); 1224 1225 return false; 1226 } 1227 1228 // Performs a semantic analysis on {work_group_/sub_group_ 1229 // /_}commit_{read/write}_pipe 1230 // \param S Reference to the semantic analyzer. 1231 // \param Call The call to the builtin function to be analyzed. 1232 // \return True if a semantic error was found, false otherwise. 1233 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1234 if (checkArgCount(S, Call, 2)) 1235 return true; 1236 1237 if (checkOpenCLPipeArg(S, Call)) 1238 return true; 1239 1240 // Check reserve_id_t. 1241 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1242 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1243 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1244 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1245 return true; 1246 } 1247 1248 return false; 1249 } 1250 1251 // Performs a semantic analysis on the call to built-in Pipe 1252 // Query Functions. 1253 // \param S Reference to the semantic analyzer. 1254 // \param Call The call to the builtin function to be analyzed. 1255 // \return True if a semantic error was found, false otherwise. 1256 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1257 if (checkArgCount(S, Call, 1)) 1258 return true; 1259 1260 if (!Call->getArg(0)->getType()->isPipeType()) { 1261 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1262 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1263 return true; 1264 } 1265 1266 return false; 1267 } 1268 1269 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1270 // Performs semantic analysis for the to_global/local/private call. 1271 // \param S Reference to the semantic analyzer. 1272 // \param BuiltinID ID of the builtin function. 1273 // \param Call A pointer to the builtin call. 1274 // \return True if a semantic error has been found, false otherwise. 1275 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1276 CallExpr *Call) { 1277 if (checkArgCount(S, Call, 1)) 1278 return true; 1279 1280 auto RT = Call->getArg(0)->getType(); 1281 if (!RT->isPointerType() || RT->getPointeeType() 1282 .getAddressSpace() == LangAS::opencl_constant) { 1283 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1284 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1285 return true; 1286 } 1287 1288 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1289 S.Diag(Call->getArg(0)->getBeginLoc(), 1290 diag::warn_opencl_generic_address_space_arg) 1291 << Call->getDirectCallee()->getNameInfo().getAsString() 1292 << Call->getArg(0)->getSourceRange(); 1293 } 1294 1295 RT = RT->getPointeeType(); 1296 auto Qual = RT.getQualifiers(); 1297 switch (BuiltinID) { 1298 case Builtin::BIto_global: 1299 Qual.setAddressSpace(LangAS::opencl_global); 1300 break; 1301 case Builtin::BIto_local: 1302 Qual.setAddressSpace(LangAS::opencl_local); 1303 break; 1304 case Builtin::BIto_private: 1305 Qual.setAddressSpace(LangAS::opencl_private); 1306 break; 1307 default: 1308 llvm_unreachable("Invalid builtin function"); 1309 } 1310 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1311 RT.getUnqualifiedType(), Qual))); 1312 1313 return false; 1314 } 1315 1316 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1317 if (checkArgCount(S, TheCall, 1)) 1318 return ExprError(); 1319 1320 // Compute __builtin_launder's parameter type from the argument. 1321 // The parameter type is: 1322 // * The type of the argument if it's not an array or function type, 1323 // Otherwise, 1324 // * The decayed argument type. 1325 QualType ParamTy = [&]() { 1326 QualType ArgTy = TheCall->getArg(0)->getType(); 1327 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1328 return S.Context.getPointerType(Ty->getElementType()); 1329 if (ArgTy->isFunctionType()) { 1330 return S.Context.getPointerType(ArgTy); 1331 } 1332 return ArgTy; 1333 }(); 1334 1335 TheCall->setType(ParamTy); 1336 1337 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1338 if (!ParamTy->isPointerType()) 1339 return 0; 1340 if (ParamTy->isFunctionPointerType()) 1341 return 1; 1342 if (ParamTy->isVoidPointerType()) 1343 return 2; 1344 return llvm::Optional<unsigned>{}; 1345 }(); 1346 if (DiagSelect.hasValue()) { 1347 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1348 << DiagSelect.getValue() << TheCall->getSourceRange(); 1349 return ExprError(); 1350 } 1351 1352 // We either have an incomplete class type, or we have a class template 1353 // whose instantiation has not been forced. Example: 1354 // 1355 // template <class T> struct Foo { T value; }; 1356 // Foo<int> *p = nullptr; 1357 // auto *d = __builtin_launder(p); 1358 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1359 diag::err_incomplete_type)) 1360 return ExprError(); 1361 1362 assert(ParamTy->getPointeeType()->isObjectType() && 1363 "Unhandled non-object pointer case"); 1364 1365 InitializedEntity Entity = 1366 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1367 ExprResult Arg = 1368 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1369 if (Arg.isInvalid()) 1370 return ExprError(); 1371 TheCall->setArg(0, Arg.get()); 1372 1373 return TheCall; 1374 } 1375 1376 // Emit an error and return true if the current architecture is not in the list 1377 // of supported architectures. 1378 static bool 1379 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1380 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1381 llvm::Triple::ArchType CurArch = 1382 S.getASTContext().getTargetInfo().getTriple().getArch(); 1383 if (llvm::is_contained(SupportedArchs, CurArch)) 1384 return false; 1385 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1386 << TheCall->getSourceRange(); 1387 return true; 1388 } 1389 1390 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1391 SourceLocation CallSiteLoc); 1392 1393 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1394 CallExpr *TheCall) { 1395 switch (TI.getTriple().getArch()) { 1396 default: 1397 // Some builtins don't require additional checking, so just consider these 1398 // acceptable. 1399 return false; 1400 case llvm::Triple::arm: 1401 case llvm::Triple::armeb: 1402 case llvm::Triple::thumb: 1403 case llvm::Triple::thumbeb: 1404 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1405 case llvm::Triple::aarch64: 1406 case llvm::Triple::aarch64_32: 1407 case llvm::Triple::aarch64_be: 1408 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1409 case llvm::Triple::bpfeb: 1410 case llvm::Triple::bpfel: 1411 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1412 case llvm::Triple::hexagon: 1413 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1414 case llvm::Triple::mips: 1415 case llvm::Triple::mipsel: 1416 case llvm::Triple::mips64: 1417 case llvm::Triple::mips64el: 1418 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1419 case llvm::Triple::systemz: 1420 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1421 case llvm::Triple::x86: 1422 case llvm::Triple::x86_64: 1423 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1424 case llvm::Triple::ppc: 1425 case llvm::Triple::ppc64: 1426 case llvm::Triple::ppc64le: 1427 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1428 case llvm::Triple::amdgcn: 1429 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1430 } 1431 } 1432 1433 ExprResult 1434 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1435 CallExpr *TheCall) { 1436 ExprResult TheCallResult(TheCall); 1437 1438 // Find out if any arguments are required to be integer constant expressions. 1439 unsigned ICEArguments = 0; 1440 ASTContext::GetBuiltinTypeError Error; 1441 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1442 if (Error != ASTContext::GE_None) 1443 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1444 1445 // If any arguments are required to be ICE's, check and diagnose. 1446 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1447 // Skip arguments not required to be ICE's. 1448 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1449 1450 llvm::APSInt Result; 1451 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1452 return true; 1453 ICEArguments &= ~(1 << ArgNo); 1454 } 1455 1456 switch (BuiltinID) { 1457 case Builtin::BI__builtin___CFStringMakeConstantString: 1458 assert(TheCall->getNumArgs() == 1 && 1459 "Wrong # arguments to builtin CFStringMakeConstantString"); 1460 if (CheckObjCString(TheCall->getArg(0))) 1461 return ExprError(); 1462 break; 1463 case Builtin::BI__builtin_ms_va_start: 1464 case Builtin::BI__builtin_stdarg_start: 1465 case Builtin::BI__builtin_va_start: 1466 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1467 return ExprError(); 1468 break; 1469 case Builtin::BI__va_start: { 1470 switch (Context.getTargetInfo().getTriple().getArch()) { 1471 case llvm::Triple::aarch64: 1472 case llvm::Triple::arm: 1473 case llvm::Triple::thumb: 1474 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1475 return ExprError(); 1476 break; 1477 default: 1478 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1479 return ExprError(); 1480 break; 1481 } 1482 break; 1483 } 1484 1485 // The acquire, release, and no fence variants are ARM and AArch64 only. 1486 case Builtin::BI_interlockedbittestandset_acq: 1487 case Builtin::BI_interlockedbittestandset_rel: 1488 case Builtin::BI_interlockedbittestandset_nf: 1489 case Builtin::BI_interlockedbittestandreset_acq: 1490 case Builtin::BI_interlockedbittestandreset_rel: 1491 case Builtin::BI_interlockedbittestandreset_nf: 1492 if (CheckBuiltinTargetSupport( 1493 *this, BuiltinID, TheCall, 1494 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1495 return ExprError(); 1496 break; 1497 1498 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1499 case Builtin::BI_bittest64: 1500 case Builtin::BI_bittestandcomplement64: 1501 case Builtin::BI_bittestandreset64: 1502 case Builtin::BI_bittestandset64: 1503 case Builtin::BI_interlockedbittestandreset64: 1504 case Builtin::BI_interlockedbittestandset64: 1505 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1506 {llvm::Triple::x86_64, llvm::Triple::arm, 1507 llvm::Triple::thumb, llvm::Triple::aarch64})) 1508 return ExprError(); 1509 break; 1510 1511 case Builtin::BI__builtin_isgreater: 1512 case Builtin::BI__builtin_isgreaterequal: 1513 case Builtin::BI__builtin_isless: 1514 case Builtin::BI__builtin_islessequal: 1515 case Builtin::BI__builtin_islessgreater: 1516 case Builtin::BI__builtin_isunordered: 1517 if (SemaBuiltinUnorderedCompare(TheCall)) 1518 return ExprError(); 1519 break; 1520 case Builtin::BI__builtin_fpclassify: 1521 if (SemaBuiltinFPClassification(TheCall, 6)) 1522 return ExprError(); 1523 break; 1524 case Builtin::BI__builtin_isfinite: 1525 case Builtin::BI__builtin_isinf: 1526 case Builtin::BI__builtin_isinf_sign: 1527 case Builtin::BI__builtin_isnan: 1528 case Builtin::BI__builtin_isnormal: 1529 case Builtin::BI__builtin_signbit: 1530 case Builtin::BI__builtin_signbitf: 1531 case Builtin::BI__builtin_signbitl: 1532 if (SemaBuiltinFPClassification(TheCall, 1)) 1533 return ExprError(); 1534 break; 1535 case Builtin::BI__builtin_shufflevector: 1536 return SemaBuiltinShuffleVector(TheCall); 1537 // TheCall will be freed by the smart pointer here, but that's fine, since 1538 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1539 case Builtin::BI__builtin_prefetch: 1540 if (SemaBuiltinPrefetch(TheCall)) 1541 return ExprError(); 1542 break; 1543 case Builtin::BI__builtin_alloca_with_align: 1544 if (SemaBuiltinAllocaWithAlign(TheCall)) 1545 return ExprError(); 1546 LLVM_FALLTHROUGH; 1547 case Builtin::BI__builtin_alloca: 1548 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1549 << TheCall->getDirectCallee(); 1550 break; 1551 case Builtin::BI__assume: 1552 case Builtin::BI__builtin_assume: 1553 if (SemaBuiltinAssume(TheCall)) 1554 return ExprError(); 1555 break; 1556 case Builtin::BI__builtin_assume_aligned: 1557 if (SemaBuiltinAssumeAligned(TheCall)) 1558 return ExprError(); 1559 break; 1560 case Builtin::BI__builtin_dynamic_object_size: 1561 case Builtin::BI__builtin_object_size: 1562 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1563 return ExprError(); 1564 break; 1565 case Builtin::BI__builtin_longjmp: 1566 if (SemaBuiltinLongjmp(TheCall)) 1567 return ExprError(); 1568 break; 1569 case Builtin::BI__builtin_setjmp: 1570 if (SemaBuiltinSetjmp(TheCall)) 1571 return ExprError(); 1572 break; 1573 case Builtin::BI_setjmp: 1574 case Builtin::BI_setjmpex: 1575 if (checkArgCount(*this, TheCall, 1)) 1576 return true; 1577 break; 1578 case Builtin::BI__builtin_classify_type: 1579 if (checkArgCount(*this, TheCall, 1)) return true; 1580 TheCall->setType(Context.IntTy); 1581 break; 1582 case Builtin::BI__builtin_complex: 1583 if (SemaBuiltinComplex(TheCall)) 1584 return ExprError(); 1585 break; 1586 case Builtin::BI__builtin_constant_p: { 1587 if (checkArgCount(*this, TheCall, 1)) return true; 1588 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1589 if (Arg.isInvalid()) return true; 1590 TheCall->setArg(0, Arg.get()); 1591 TheCall->setType(Context.IntTy); 1592 break; 1593 } 1594 case Builtin::BI__builtin_launder: 1595 return SemaBuiltinLaunder(*this, TheCall); 1596 case Builtin::BI__sync_fetch_and_add: 1597 case Builtin::BI__sync_fetch_and_add_1: 1598 case Builtin::BI__sync_fetch_and_add_2: 1599 case Builtin::BI__sync_fetch_and_add_4: 1600 case Builtin::BI__sync_fetch_and_add_8: 1601 case Builtin::BI__sync_fetch_and_add_16: 1602 case Builtin::BI__sync_fetch_and_sub: 1603 case Builtin::BI__sync_fetch_and_sub_1: 1604 case Builtin::BI__sync_fetch_and_sub_2: 1605 case Builtin::BI__sync_fetch_and_sub_4: 1606 case Builtin::BI__sync_fetch_and_sub_8: 1607 case Builtin::BI__sync_fetch_and_sub_16: 1608 case Builtin::BI__sync_fetch_and_or: 1609 case Builtin::BI__sync_fetch_and_or_1: 1610 case Builtin::BI__sync_fetch_and_or_2: 1611 case Builtin::BI__sync_fetch_and_or_4: 1612 case Builtin::BI__sync_fetch_and_or_8: 1613 case Builtin::BI__sync_fetch_and_or_16: 1614 case Builtin::BI__sync_fetch_and_and: 1615 case Builtin::BI__sync_fetch_and_and_1: 1616 case Builtin::BI__sync_fetch_and_and_2: 1617 case Builtin::BI__sync_fetch_and_and_4: 1618 case Builtin::BI__sync_fetch_and_and_8: 1619 case Builtin::BI__sync_fetch_and_and_16: 1620 case Builtin::BI__sync_fetch_and_xor: 1621 case Builtin::BI__sync_fetch_and_xor_1: 1622 case Builtin::BI__sync_fetch_and_xor_2: 1623 case Builtin::BI__sync_fetch_and_xor_4: 1624 case Builtin::BI__sync_fetch_and_xor_8: 1625 case Builtin::BI__sync_fetch_and_xor_16: 1626 case Builtin::BI__sync_fetch_and_nand: 1627 case Builtin::BI__sync_fetch_and_nand_1: 1628 case Builtin::BI__sync_fetch_and_nand_2: 1629 case Builtin::BI__sync_fetch_and_nand_4: 1630 case Builtin::BI__sync_fetch_and_nand_8: 1631 case Builtin::BI__sync_fetch_and_nand_16: 1632 case Builtin::BI__sync_add_and_fetch: 1633 case Builtin::BI__sync_add_and_fetch_1: 1634 case Builtin::BI__sync_add_and_fetch_2: 1635 case Builtin::BI__sync_add_and_fetch_4: 1636 case Builtin::BI__sync_add_and_fetch_8: 1637 case Builtin::BI__sync_add_and_fetch_16: 1638 case Builtin::BI__sync_sub_and_fetch: 1639 case Builtin::BI__sync_sub_and_fetch_1: 1640 case Builtin::BI__sync_sub_and_fetch_2: 1641 case Builtin::BI__sync_sub_and_fetch_4: 1642 case Builtin::BI__sync_sub_and_fetch_8: 1643 case Builtin::BI__sync_sub_and_fetch_16: 1644 case Builtin::BI__sync_and_and_fetch: 1645 case Builtin::BI__sync_and_and_fetch_1: 1646 case Builtin::BI__sync_and_and_fetch_2: 1647 case Builtin::BI__sync_and_and_fetch_4: 1648 case Builtin::BI__sync_and_and_fetch_8: 1649 case Builtin::BI__sync_and_and_fetch_16: 1650 case Builtin::BI__sync_or_and_fetch: 1651 case Builtin::BI__sync_or_and_fetch_1: 1652 case Builtin::BI__sync_or_and_fetch_2: 1653 case Builtin::BI__sync_or_and_fetch_4: 1654 case Builtin::BI__sync_or_and_fetch_8: 1655 case Builtin::BI__sync_or_and_fetch_16: 1656 case Builtin::BI__sync_xor_and_fetch: 1657 case Builtin::BI__sync_xor_and_fetch_1: 1658 case Builtin::BI__sync_xor_and_fetch_2: 1659 case Builtin::BI__sync_xor_and_fetch_4: 1660 case Builtin::BI__sync_xor_and_fetch_8: 1661 case Builtin::BI__sync_xor_and_fetch_16: 1662 case Builtin::BI__sync_nand_and_fetch: 1663 case Builtin::BI__sync_nand_and_fetch_1: 1664 case Builtin::BI__sync_nand_and_fetch_2: 1665 case Builtin::BI__sync_nand_and_fetch_4: 1666 case Builtin::BI__sync_nand_and_fetch_8: 1667 case Builtin::BI__sync_nand_and_fetch_16: 1668 case Builtin::BI__sync_val_compare_and_swap: 1669 case Builtin::BI__sync_val_compare_and_swap_1: 1670 case Builtin::BI__sync_val_compare_and_swap_2: 1671 case Builtin::BI__sync_val_compare_and_swap_4: 1672 case Builtin::BI__sync_val_compare_and_swap_8: 1673 case Builtin::BI__sync_val_compare_and_swap_16: 1674 case Builtin::BI__sync_bool_compare_and_swap: 1675 case Builtin::BI__sync_bool_compare_and_swap_1: 1676 case Builtin::BI__sync_bool_compare_and_swap_2: 1677 case Builtin::BI__sync_bool_compare_and_swap_4: 1678 case Builtin::BI__sync_bool_compare_and_swap_8: 1679 case Builtin::BI__sync_bool_compare_and_swap_16: 1680 case Builtin::BI__sync_lock_test_and_set: 1681 case Builtin::BI__sync_lock_test_and_set_1: 1682 case Builtin::BI__sync_lock_test_and_set_2: 1683 case Builtin::BI__sync_lock_test_and_set_4: 1684 case Builtin::BI__sync_lock_test_and_set_8: 1685 case Builtin::BI__sync_lock_test_and_set_16: 1686 case Builtin::BI__sync_lock_release: 1687 case Builtin::BI__sync_lock_release_1: 1688 case Builtin::BI__sync_lock_release_2: 1689 case Builtin::BI__sync_lock_release_4: 1690 case Builtin::BI__sync_lock_release_8: 1691 case Builtin::BI__sync_lock_release_16: 1692 case Builtin::BI__sync_swap: 1693 case Builtin::BI__sync_swap_1: 1694 case Builtin::BI__sync_swap_2: 1695 case Builtin::BI__sync_swap_4: 1696 case Builtin::BI__sync_swap_8: 1697 case Builtin::BI__sync_swap_16: 1698 return SemaBuiltinAtomicOverloaded(TheCallResult); 1699 case Builtin::BI__sync_synchronize: 1700 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1701 << TheCall->getCallee()->getSourceRange(); 1702 break; 1703 case Builtin::BI__builtin_nontemporal_load: 1704 case Builtin::BI__builtin_nontemporal_store: 1705 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1706 case Builtin::BI__builtin_memcpy_inline: { 1707 clang::Expr *SizeOp = TheCall->getArg(2); 1708 // We warn about copying to or from `nullptr` pointers when `size` is 1709 // greater than 0. When `size` is value dependent we cannot evaluate its 1710 // value so we bail out. 1711 if (SizeOp->isValueDependent()) 1712 break; 1713 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1714 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1715 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1716 } 1717 break; 1718 } 1719 #define BUILTIN(ID, TYPE, ATTRS) 1720 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1721 case Builtin::BI##ID: \ 1722 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1723 #include "clang/Basic/Builtins.def" 1724 case Builtin::BI__annotation: 1725 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1726 return ExprError(); 1727 break; 1728 case Builtin::BI__builtin_annotation: 1729 if (SemaBuiltinAnnotation(*this, TheCall)) 1730 return ExprError(); 1731 break; 1732 case Builtin::BI__builtin_addressof: 1733 if (SemaBuiltinAddressof(*this, TheCall)) 1734 return ExprError(); 1735 break; 1736 case Builtin::BI__builtin_is_aligned: 1737 case Builtin::BI__builtin_align_up: 1738 case Builtin::BI__builtin_align_down: 1739 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1740 return ExprError(); 1741 break; 1742 case Builtin::BI__builtin_add_overflow: 1743 case Builtin::BI__builtin_sub_overflow: 1744 case Builtin::BI__builtin_mul_overflow: 1745 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1746 return ExprError(); 1747 break; 1748 case Builtin::BI__builtin_operator_new: 1749 case Builtin::BI__builtin_operator_delete: { 1750 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1751 ExprResult Res = 1752 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1753 if (Res.isInvalid()) 1754 CorrectDelayedTyposInExpr(TheCallResult.get()); 1755 return Res; 1756 } 1757 case Builtin::BI__builtin_dump_struct: { 1758 // We first want to ensure we are called with 2 arguments 1759 if (checkArgCount(*this, TheCall, 2)) 1760 return ExprError(); 1761 // Ensure that the first argument is of type 'struct XX *' 1762 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1763 const QualType PtrArgType = PtrArg->getType(); 1764 if (!PtrArgType->isPointerType() || 1765 !PtrArgType->getPointeeType()->isRecordType()) { 1766 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1767 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1768 << "structure pointer"; 1769 return ExprError(); 1770 } 1771 1772 // Ensure that the second argument is of type 'FunctionType' 1773 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1774 const QualType FnPtrArgType = FnPtrArg->getType(); 1775 if (!FnPtrArgType->isPointerType()) { 1776 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1777 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1778 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1779 return ExprError(); 1780 } 1781 1782 const auto *FuncType = 1783 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1784 1785 if (!FuncType) { 1786 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1787 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1788 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1789 return ExprError(); 1790 } 1791 1792 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1793 if (!FT->getNumParams()) { 1794 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1795 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1796 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1797 return ExprError(); 1798 } 1799 QualType PT = FT->getParamType(0); 1800 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1801 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1802 !PT->getPointeeType().isConstQualified()) { 1803 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1804 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1805 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1806 return ExprError(); 1807 } 1808 } 1809 1810 TheCall->setType(Context.IntTy); 1811 break; 1812 } 1813 case Builtin::BI__builtin_expect_with_probability: { 1814 // We first want to ensure we are called with 3 arguments 1815 if (checkArgCount(*this, TheCall, 3)) 1816 return ExprError(); 1817 // then check probability is constant float in range [0.0, 1.0] 1818 const Expr *ProbArg = TheCall->getArg(2); 1819 SmallVector<PartialDiagnosticAt, 8> Notes; 1820 Expr::EvalResult Eval; 1821 Eval.Diag = &Notes; 1822 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 1823 Context)) || 1824 !Eval.Val.isFloat()) { 1825 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1826 << ProbArg->getSourceRange(); 1827 for (const PartialDiagnosticAt &PDiag : Notes) 1828 Diag(PDiag.first, PDiag.second); 1829 return ExprError(); 1830 } 1831 llvm::APFloat Probability = Eval.Val.getFloat(); 1832 bool LoseInfo = false; 1833 Probability.convert(llvm::APFloat::IEEEdouble(), 1834 llvm::RoundingMode::Dynamic, &LoseInfo); 1835 if (!(Probability >= llvm::APFloat(0.0) && 1836 Probability <= llvm::APFloat(1.0))) { 1837 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1838 << ProbArg->getSourceRange(); 1839 return ExprError(); 1840 } 1841 break; 1842 } 1843 case Builtin::BI__builtin_preserve_access_index: 1844 if (SemaBuiltinPreserveAI(*this, TheCall)) 1845 return ExprError(); 1846 break; 1847 case Builtin::BI__builtin_call_with_static_chain: 1848 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1849 return ExprError(); 1850 break; 1851 case Builtin::BI__exception_code: 1852 case Builtin::BI_exception_code: 1853 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1854 diag::err_seh___except_block)) 1855 return ExprError(); 1856 break; 1857 case Builtin::BI__exception_info: 1858 case Builtin::BI_exception_info: 1859 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1860 diag::err_seh___except_filter)) 1861 return ExprError(); 1862 break; 1863 case Builtin::BI__GetExceptionInfo: 1864 if (checkArgCount(*this, TheCall, 1)) 1865 return ExprError(); 1866 1867 if (CheckCXXThrowOperand( 1868 TheCall->getBeginLoc(), 1869 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1870 TheCall)) 1871 return ExprError(); 1872 1873 TheCall->setType(Context.VoidPtrTy); 1874 break; 1875 // OpenCL v2.0, s6.13.16 - Pipe functions 1876 case Builtin::BIread_pipe: 1877 case Builtin::BIwrite_pipe: 1878 // Since those two functions are declared with var args, we need a semantic 1879 // check for the argument. 1880 if (SemaBuiltinRWPipe(*this, TheCall)) 1881 return ExprError(); 1882 break; 1883 case Builtin::BIreserve_read_pipe: 1884 case Builtin::BIreserve_write_pipe: 1885 case Builtin::BIwork_group_reserve_read_pipe: 1886 case Builtin::BIwork_group_reserve_write_pipe: 1887 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1888 return ExprError(); 1889 break; 1890 case Builtin::BIsub_group_reserve_read_pipe: 1891 case Builtin::BIsub_group_reserve_write_pipe: 1892 if (checkOpenCLSubgroupExt(*this, TheCall) || 1893 SemaBuiltinReserveRWPipe(*this, TheCall)) 1894 return ExprError(); 1895 break; 1896 case Builtin::BIcommit_read_pipe: 1897 case Builtin::BIcommit_write_pipe: 1898 case Builtin::BIwork_group_commit_read_pipe: 1899 case Builtin::BIwork_group_commit_write_pipe: 1900 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1901 return ExprError(); 1902 break; 1903 case Builtin::BIsub_group_commit_read_pipe: 1904 case Builtin::BIsub_group_commit_write_pipe: 1905 if (checkOpenCLSubgroupExt(*this, TheCall) || 1906 SemaBuiltinCommitRWPipe(*this, TheCall)) 1907 return ExprError(); 1908 break; 1909 case Builtin::BIget_pipe_num_packets: 1910 case Builtin::BIget_pipe_max_packets: 1911 if (SemaBuiltinPipePackets(*this, TheCall)) 1912 return ExprError(); 1913 break; 1914 case Builtin::BIto_global: 1915 case Builtin::BIto_local: 1916 case Builtin::BIto_private: 1917 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1918 return ExprError(); 1919 break; 1920 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1921 case Builtin::BIenqueue_kernel: 1922 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1923 return ExprError(); 1924 break; 1925 case Builtin::BIget_kernel_work_group_size: 1926 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1927 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1928 return ExprError(); 1929 break; 1930 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1931 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1932 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1933 return ExprError(); 1934 break; 1935 case Builtin::BI__builtin_os_log_format: 1936 Cleanup.setExprNeedsCleanups(true); 1937 LLVM_FALLTHROUGH; 1938 case Builtin::BI__builtin_os_log_format_buffer_size: 1939 if (SemaBuiltinOSLogFormat(TheCall)) 1940 return ExprError(); 1941 break; 1942 case Builtin::BI__builtin_frame_address: 1943 case Builtin::BI__builtin_return_address: { 1944 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1945 return ExprError(); 1946 1947 // -Wframe-address warning if non-zero passed to builtin 1948 // return/frame address. 1949 Expr::EvalResult Result; 1950 if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1951 Result.Val.getInt() != 0) 1952 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1953 << ((BuiltinID == Builtin::BI__builtin_return_address) 1954 ? "__builtin_return_address" 1955 : "__builtin_frame_address") 1956 << TheCall->getSourceRange(); 1957 break; 1958 } 1959 1960 case Builtin::BI__builtin_matrix_transpose: 1961 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1962 1963 case Builtin::BI__builtin_matrix_column_major_load: 1964 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1965 1966 case Builtin::BI__builtin_matrix_column_major_store: 1967 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1968 } 1969 1970 // Since the target specific builtins for each arch overlap, only check those 1971 // of the arch we are compiling for. 1972 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1973 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1974 assert(Context.getAuxTargetInfo() && 1975 "Aux Target Builtin, but not an aux target?"); 1976 1977 if (CheckTSBuiltinFunctionCall( 1978 *Context.getAuxTargetInfo(), 1979 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 1980 return ExprError(); 1981 } else { 1982 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 1983 TheCall)) 1984 return ExprError(); 1985 } 1986 } 1987 1988 return TheCallResult; 1989 } 1990 1991 // Get the valid immediate range for the specified NEON type code. 1992 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1993 NeonTypeFlags Type(t); 1994 int IsQuad = ForceQuad ? true : Type.isQuad(); 1995 switch (Type.getEltType()) { 1996 case NeonTypeFlags::Int8: 1997 case NeonTypeFlags::Poly8: 1998 return shift ? 7 : (8 << IsQuad) - 1; 1999 case NeonTypeFlags::Int16: 2000 case NeonTypeFlags::Poly16: 2001 return shift ? 15 : (4 << IsQuad) - 1; 2002 case NeonTypeFlags::Int32: 2003 return shift ? 31 : (2 << IsQuad) - 1; 2004 case NeonTypeFlags::Int64: 2005 case NeonTypeFlags::Poly64: 2006 return shift ? 63 : (1 << IsQuad) - 1; 2007 case NeonTypeFlags::Poly128: 2008 return shift ? 127 : (1 << IsQuad) - 1; 2009 case NeonTypeFlags::Float16: 2010 assert(!shift && "cannot shift float types!"); 2011 return (4 << IsQuad) - 1; 2012 case NeonTypeFlags::Float32: 2013 assert(!shift && "cannot shift float types!"); 2014 return (2 << IsQuad) - 1; 2015 case NeonTypeFlags::Float64: 2016 assert(!shift && "cannot shift float types!"); 2017 return (1 << IsQuad) - 1; 2018 case NeonTypeFlags::BFloat16: 2019 assert(!shift && "cannot shift float types!"); 2020 return (4 << IsQuad) - 1; 2021 } 2022 llvm_unreachable("Invalid NeonTypeFlag!"); 2023 } 2024 2025 /// getNeonEltType - Return the QualType corresponding to the elements of 2026 /// the vector type specified by the NeonTypeFlags. This is used to check 2027 /// the pointer arguments for Neon load/store intrinsics. 2028 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2029 bool IsPolyUnsigned, bool IsInt64Long) { 2030 switch (Flags.getEltType()) { 2031 case NeonTypeFlags::Int8: 2032 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2033 case NeonTypeFlags::Int16: 2034 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2035 case NeonTypeFlags::Int32: 2036 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2037 case NeonTypeFlags::Int64: 2038 if (IsInt64Long) 2039 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2040 else 2041 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2042 : Context.LongLongTy; 2043 case NeonTypeFlags::Poly8: 2044 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2045 case NeonTypeFlags::Poly16: 2046 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2047 case NeonTypeFlags::Poly64: 2048 if (IsInt64Long) 2049 return Context.UnsignedLongTy; 2050 else 2051 return Context.UnsignedLongLongTy; 2052 case NeonTypeFlags::Poly128: 2053 break; 2054 case NeonTypeFlags::Float16: 2055 return Context.HalfTy; 2056 case NeonTypeFlags::Float32: 2057 return Context.FloatTy; 2058 case NeonTypeFlags::Float64: 2059 return Context.DoubleTy; 2060 case NeonTypeFlags::BFloat16: 2061 return Context.BFloat16Ty; 2062 } 2063 llvm_unreachable("Invalid NeonTypeFlag!"); 2064 } 2065 2066 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2067 // Range check SVE intrinsics that take immediate values. 2068 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2069 2070 switch (BuiltinID) { 2071 default: 2072 return false; 2073 #define GET_SVE_IMMEDIATE_CHECK 2074 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2075 #undef GET_SVE_IMMEDIATE_CHECK 2076 } 2077 2078 // Perform all the immediate checks for this builtin call. 2079 bool HasError = false; 2080 for (auto &I : ImmChecks) { 2081 int ArgNum, CheckTy, ElementSizeInBits; 2082 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2083 2084 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2085 2086 // Function that checks whether the operand (ArgNum) is an immediate 2087 // that is one of the predefined values. 2088 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2089 int ErrDiag) -> bool { 2090 // We can't check the value of a dependent argument. 2091 Expr *Arg = TheCall->getArg(ArgNum); 2092 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2093 return false; 2094 2095 // Check constant-ness first. 2096 llvm::APSInt Imm; 2097 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2098 return true; 2099 2100 if (!CheckImm(Imm.getSExtValue())) 2101 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2102 return false; 2103 }; 2104 2105 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2106 case SVETypeFlags::ImmCheck0_31: 2107 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2108 HasError = true; 2109 break; 2110 case SVETypeFlags::ImmCheck0_13: 2111 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2112 HasError = true; 2113 break; 2114 case SVETypeFlags::ImmCheck1_16: 2115 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2116 HasError = true; 2117 break; 2118 case SVETypeFlags::ImmCheck0_7: 2119 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2120 HasError = true; 2121 break; 2122 case SVETypeFlags::ImmCheckExtract: 2123 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2124 (2048 / ElementSizeInBits) - 1)) 2125 HasError = true; 2126 break; 2127 case SVETypeFlags::ImmCheckShiftRight: 2128 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2129 HasError = true; 2130 break; 2131 case SVETypeFlags::ImmCheckShiftRightNarrow: 2132 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2133 ElementSizeInBits / 2)) 2134 HasError = true; 2135 break; 2136 case SVETypeFlags::ImmCheckShiftLeft: 2137 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2138 ElementSizeInBits - 1)) 2139 HasError = true; 2140 break; 2141 case SVETypeFlags::ImmCheckLaneIndex: 2142 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2143 (128 / (1 * ElementSizeInBits)) - 1)) 2144 HasError = true; 2145 break; 2146 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2147 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2148 (128 / (2 * ElementSizeInBits)) - 1)) 2149 HasError = true; 2150 break; 2151 case SVETypeFlags::ImmCheckLaneIndexDot: 2152 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2153 (128 / (4 * ElementSizeInBits)) - 1)) 2154 HasError = true; 2155 break; 2156 case SVETypeFlags::ImmCheckComplexRot90_270: 2157 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2158 diag::err_rotation_argument_to_cadd)) 2159 HasError = true; 2160 break; 2161 case SVETypeFlags::ImmCheckComplexRotAll90: 2162 if (CheckImmediateInSet( 2163 [](int64_t V) { 2164 return V == 0 || V == 90 || V == 180 || V == 270; 2165 }, 2166 diag::err_rotation_argument_to_cmla)) 2167 HasError = true; 2168 break; 2169 case SVETypeFlags::ImmCheck0_1: 2170 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2171 HasError = true; 2172 break; 2173 case SVETypeFlags::ImmCheck0_2: 2174 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2175 HasError = true; 2176 break; 2177 case SVETypeFlags::ImmCheck0_3: 2178 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2179 HasError = true; 2180 break; 2181 } 2182 } 2183 2184 return HasError; 2185 } 2186 2187 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2188 unsigned BuiltinID, CallExpr *TheCall) { 2189 llvm::APSInt Result; 2190 uint64_t mask = 0; 2191 unsigned TV = 0; 2192 int PtrArgNum = -1; 2193 bool HasConstPtr = false; 2194 switch (BuiltinID) { 2195 #define GET_NEON_OVERLOAD_CHECK 2196 #include "clang/Basic/arm_neon.inc" 2197 #include "clang/Basic/arm_fp16.inc" 2198 #undef GET_NEON_OVERLOAD_CHECK 2199 } 2200 2201 // For NEON intrinsics which are overloaded on vector element type, validate 2202 // the immediate which specifies which variant to emit. 2203 unsigned ImmArg = TheCall->getNumArgs()-1; 2204 if (mask) { 2205 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2206 return true; 2207 2208 TV = Result.getLimitedValue(64); 2209 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2210 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2211 << TheCall->getArg(ImmArg)->getSourceRange(); 2212 } 2213 2214 if (PtrArgNum >= 0) { 2215 // Check that pointer arguments have the specified type. 2216 Expr *Arg = TheCall->getArg(PtrArgNum); 2217 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2218 Arg = ICE->getSubExpr(); 2219 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2220 QualType RHSTy = RHS.get()->getType(); 2221 2222 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2223 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2224 Arch == llvm::Triple::aarch64_32 || 2225 Arch == llvm::Triple::aarch64_be; 2226 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2227 QualType EltTy = 2228 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2229 if (HasConstPtr) 2230 EltTy = EltTy.withConst(); 2231 QualType LHSTy = Context.getPointerType(EltTy); 2232 AssignConvertType ConvTy; 2233 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2234 if (RHS.isInvalid()) 2235 return true; 2236 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2237 RHS.get(), AA_Assigning)) 2238 return true; 2239 } 2240 2241 // For NEON intrinsics which take an immediate value as part of the 2242 // instruction, range check them here. 2243 unsigned i = 0, l = 0, u = 0; 2244 switch (BuiltinID) { 2245 default: 2246 return false; 2247 #define GET_NEON_IMMEDIATE_CHECK 2248 #include "clang/Basic/arm_neon.inc" 2249 #include "clang/Basic/arm_fp16.inc" 2250 #undef GET_NEON_IMMEDIATE_CHECK 2251 } 2252 2253 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2254 } 2255 2256 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2257 switch (BuiltinID) { 2258 default: 2259 return false; 2260 #include "clang/Basic/arm_mve_builtin_sema.inc" 2261 } 2262 } 2263 2264 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2265 CallExpr *TheCall) { 2266 bool Err = false; 2267 switch (BuiltinID) { 2268 default: 2269 return false; 2270 #include "clang/Basic/arm_cde_builtin_sema.inc" 2271 } 2272 2273 if (Err) 2274 return true; 2275 2276 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2277 } 2278 2279 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2280 const Expr *CoprocArg, bool WantCDE) { 2281 if (isConstantEvaluated()) 2282 return false; 2283 2284 // We can't check the value of a dependent argument. 2285 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2286 return false; 2287 2288 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2289 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2290 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2291 2292 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2293 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2294 2295 if (IsCDECoproc != WantCDE) 2296 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2297 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2298 2299 return false; 2300 } 2301 2302 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2303 unsigned MaxWidth) { 2304 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2305 BuiltinID == ARM::BI__builtin_arm_ldaex || 2306 BuiltinID == ARM::BI__builtin_arm_strex || 2307 BuiltinID == ARM::BI__builtin_arm_stlex || 2308 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2309 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2310 BuiltinID == AArch64::BI__builtin_arm_strex || 2311 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2312 "unexpected ARM builtin"); 2313 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2314 BuiltinID == ARM::BI__builtin_arm_ldaex || 2315 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2316 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2317 2318 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2319 2320 // Ensure that we have the proper number of arguments. 2321 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2322 return true; 2323 2324 // Inspect the pointer argument of the atomic builtin. This should always be 2325 // a pointer type, whose element is an integral scalar or pointer type. 2326 // Because it is a pointer type, we don't have to worry about any implicit 2327 // casts here. 2328 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2329 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2330 if (PointerArgRes.isInvalid()) 2331 return true; 2332 PointerArg = PointerArgRes.get(); 2333 2334 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2335 if (!pointerType) { 2336 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2337 << PointerArg->getType() << PointerArg->getSourceRange(); 2338 return true; 2339 } 2340 2341 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2342 // task is to insert the appropriate casts into the AST. First work out just 2343 // what the appropriate type is. 2344 QualType ValType = pointerType->getPointeeType(); 2345 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2346 if (IsLdrex) 2347 AddrType.addConst(); 2348 2349 // Issue a warning if the cast is dodgy. 2350 CastKind CastNeeded = CK_NoOp; 2351 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2352 CastNeeded = CK_BitCast; 2353 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2354 << PointerArg->getType() << Context.getPointerType(AddrType) 2355 << AA_Passing << PointerArg->getSourceRange(); 2356 } 2357 2358 // Finally, do the cast and replace the argument with the corrected version. 2359 AddrType = Context.getPointerType(AddrType); 2360 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2361 if (PointerArgRes.isInvalid()) 2362 return true; 2363 PointerArg = PointerArgRes.get(); 2364 2365 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2366 2367 // In general, we allow ints, floats and pointers to be loaded and stored. 2368 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2369 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2370 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2371 << PointerArg->getType() << PointerArg->getSourceRange(); 2372 return true; 2373 } 2374 2375 // But ARM doesn't have instructions to deal with 128-bit versions. 2376 if (Context.getTypeSize(ValType) > MaxWidth) { 2377 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2378 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2379 << PointerArg->getType() << PointerArg->getSourceRange(); 2380 return true; 2381 } 2382 2383 switch (ValType.getObjCLifetime()) { 2384 case Qualifiers::OCL_None: 2385 case Qualifiers::OCL_ExplicitNone: 2386 // okay 2387 break; 2388 2389 case Qualifiers::OCL_Weak: 2390 case Qualifiers::OCL_Strong: 2391 case Qualifiers::OCL_Autoreleasing: 2392 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2393 << ValType << PointerArg->getSourceRange(); 2394 return true; 2395 } 2396 2397 if (IsLdrex) { 2398 TheCall->setType(ValType); 2399 return false; 2400 } 2401 2402 // Initialize the argument to be stored. 2403 ExprResult ValArg = TheCall->getArg(0); 2404 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2405 Context, ValType, /*consume*/ false); 2406 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2407 if (ValArg.isInvalid()) 2408 return true; 2409 TheCall->setArg(0, ValArg.get()); 2410 2411 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2412 // but the custom checker bypasses all default analysis. 2413 TheCall->setType(Context.IntTy); 2414 return false; 2415 } 2416 2417 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2418 CallExpr *TheCall) { 2419 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2420 BuiltinID == ARM::BI__builtin_arm_ldaex || 2421 BuiltinID == ARM::BI__builtin_arm_strex || 2422 BuiltinID == ARM::BI__builtin_arm_stlex) { 2423 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2424 } 2425 2426 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2427 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2428 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2429 } 2430 2431 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2432 BuiltinID == ARM::BI__builtin_arm_wsr64) 2433 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2434 2435 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2436 BuiltinID == ARM::BI__builtin_arm_rsrp || 2437 BuiltinID == ARM::BI__builtin_arm_wsr || 2438 BuiltinID == ARM::BI__builtin_arm_wsrp) 2439 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2440 2441 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2442 return true; 2443 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2444 return true; 2445 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2446 return true; 2447 2448 // For intrinsics which take an immediate value as part of the instruction, 2449 // range check them here. 2450 // FIXME: VFP Intrinsics should error if VFP not present. 2451 switch (BuiltinID) { 2452 default: return false; 2453 case ARM::BI__builtin_arm_ssat: 2454 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2455 case ARM::BI__builtin_arm_usat: 2456 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2457 case ARM::BI__builtin_arm_ssat16: 2458 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2459 case ARM::BI__builtin_arm_usat16: 2460 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2461 case ARM::BI__builtin_arm_vcvtr_f: 2462 case ARM::BI__builtin_arm_vcvtr_d: 2463 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2464 case ARM::BI__builtin_arm_dmb: 2465 case ARM::BI__builtin_arm_dsb: 2466 case ARM::BI__builtin_arm_isb: 2467 case ARM::BI__builtin_arm_dbg: 2468 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2469 case ARM::BI__builtin_arm_cdp: 2470 case ARM::BI__builtin_arm_cdp2: 2471 case ARM::BI__builtin_arm_mcr: 2472 case ARM::BI__builtin_arm_mcr2: 2473 case ARM::BI__builtin_arm_mrc: 2474 case ARM::BI__builtin_arm_mrc2: 2475 case ARM::BI__builtin_arm_mcrr: 2476 case ARM::BI__builtin_arm_mcrr2: 2477 case ARM::BI__builtin_arm_mrrc: 2478 case ARM::BI__builtin_arm_mrrc2: 2479 case ARM::BI__builtin_arm_ldc: 2480 case ARM::BI__builtin_arm_ldcl: 2481 case ARM::BI__builtin_arm_ldc2: 2482 case ARM::BI__builtin_arm_ldc2l: 2483 case ARM::BI__builtin_arm_stc: 2484 case ARM::BI__builtin_arm_stcl: 2485 case ARM::BI__builtin_arm_stc2: 2486 case ARM::BI__builtin_arm_stc2l: 2487 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2488 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2489 /*WantCDE*/ false); 2490 } 2491 } 2492 2493 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2494 unsigned BuiltinID, 2495 CallExpr *TheCall) { 2496 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2497 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2498 BuiltinID == AArch64::BI__builtin_arm_strex || 2499 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2500 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2501 } 2502 2503 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2504 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2505 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2506 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2507 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2508 } 2509 2510 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2511 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2512 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2513 2514 // Memory Tagging Extensions (MTE) Intrinsics 2515 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2516 BuiltinID == AArch64::BI__builtin_arm_addg || 2517 BuiltinID == AArch64::BI__builtin_arm_gmi || 2518 BuiltinID == AArch64::BI__builtin_arm_ldg || 2519 BuiltinID == AArch64::BI__builtin_arm_stg || 2520 BuiltinID == AArch64::BI__builtin_arm_subp) { 2521 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2522 } 2523 2524 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2525 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2526 BuiltinID == AArch64::BI__builtin_arm_wsr || 2527 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2528 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2529 2530 // Only check the valid encoding range. Any constant in this range would be 2531 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2532 // an exception for incorrect registers. This matches MSVC behavior. 2533 if (BuiltinID == AArch64::BI_ReadStatusReg || 2534 BuiltinID == AArch64::BI_WriteStatusReg) 2535 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2536 2537 if (BuiltinID == AArch64::BI__getReg) 2538 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2539 2540 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2541 return true; 2542 2543 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2544 return true; 2545 2546 // For intrinsics which take an immediate value as part of the instruction, 2547 // range check them here. 2548 unsigned i = 0, l = 0, u = 0; 2549 switch (BuiltinID) { 2550 default: return false; 2551 case AArch64::BI__builtin_arm_dmb: 2552 case AArch64::BI__builtin_arm_dsb: 2553 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2554 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2555 } 2556 2557 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2558 } 2559 2560 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2561 if (Arg->getType()->getAsPlaceholderType()) 2562 return false; 2563 2564 // The first argument needs to be a record field access. 2565 // If it is an array element access, we delay decision 2566 // to BPF backend to check whether the access is a 2567 // field access or not. 2568 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2569 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2570 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2571 } 2572 2573 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2574 QualType ArgType = Arg->getType(); 2575 if (ArgType->getAsPlaceholderType()) 2576 return false; 2577 2578 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2579 // format: 2580 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2581 // 2. <type> var; 2582 // __builtin_preserve_type_info(var, flag); 2583 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2584 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2585 return false; 2586 2587 // Typedef type. 2588 if (ArgType->getAs<TypedefType>()) 2589 return true; 2590 2591 // Record type or Enum type. 2592 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2593 if (const auto *RT = Ty->getAs<RecordType>()) { 2594 if (!RT->getDecl()->getDeclName().isEmpty()) 2595 return true; 2596 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2597 if (!ET->getDecl()->getDeclName().isEmpty()) 2598 return true; 2599 } 2600 2601 return false; 2602 } 2603 2604 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2605 QualType ArgType = Arg->getType(); 2606 if (ArgType->getAsPlaceholderType()) 2607 return false; 2608 2609 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2610 // format: 2611 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2612 // flag); 2613 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2614 if (!UO) 2615 return false; 2616 2617 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2618 if (!CE || CE->getCastKind() != CK_IntegralToPointer) 2619 return false; 2620 2621 // The integer must be from an EnumConstantDecl. 2622 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2623 if (!DR) 2624 return false; 2625 2626 const EnumConstantDecl *Enumerator = 2627 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2628 if (!Enumerator) 2629 return false; 2630 2631 // The type must be EnumType. 2632 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2633 const auto *ET = Ty->getAs<EnumType>(); 2634 if (!ET) 2635 return false; 2636 2637 // The enum value must be supported. 2638 for (auto *EDI : ET->getDecl()->enumerators()) { 2639 if (EDI == Enumerator) 2640 return true; 2641 } 2642 2643 return false; 2644 } 2645 2646 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2647 CallExpr *TheCall) { 2648 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2649 BuiltinID == BPF::BI__builtin_btf_type_id || 2650 BuiltinID == BPF::BI__builtin_preserve_type_info || 2651 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2652 "unexpected BPF builtin"); 2653 2654 if (checkArgCount(*this, TheCall, 2)) 2655 return true; 2656 2657 // The second argument needs to be a constant int 2658 Expr *Arg = TheCall->getArg(1); 2659 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2660 diag::kind kind; 2661 if (!Value) { 2662 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2663 kind = diag::err_preserve_field_info_not_const; 2664 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2665 kind = diag::err_btf_type_id_not_const; 2666 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2667 kind = diag::err_preserve_type_info_not_const; 2668 else 2669 kind = diag::err_preserve_enum_value_not_const; 2670 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2671 return true; 2672 } 2673 2674 // The first argument 2675 Arg = TheCall->getArg(0); 2676 bool InvalidArg = false; 2677 bool ReturnUnsignedInt = true; 2678 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2679 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2680 InvalidArg = true; 2681 kind = diag::err_preserve_field_info_not_field; 2682 } 2683 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2684 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2685 InvalidArg = true; 2686 kind = diag::err_preserve_type_info_invalid; 2687 } 2688 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2689 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2690 InvalidArg = true; 2691 kind = diag::err_preserve_enum_value_invalid; 2692 } 2693 ReturnUnsignedInt = false; 2694 } 2695 2696 if (InvalidArg) { 2697 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2698 return true; 2699 } 2700 2701 if (ReturnUnsignedInt) 2702 TheCall->setType(Context.UnsignedIntTy); 2703 else 2704 TheCall->setType(Context.UnsignedLongTy); 2705 return false; 2706 } 2707 2708 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2709 struct ArgInfo { 2710 uint8_t OpNum; 2711 bool IsSigned; 2712 uint8_t BitWidth; 2713 uint8_t Align; 2714 }; 2715 struct BuiltinInfo { 2716 unsigned BuiltinID; 2717 ArgInfo Infos[2]; 2718 }; 2719 2720 static BuiltinInfo Infos[] = { 2721 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2722 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2723 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2724 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2725 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2726 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2727 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2728 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2729 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2730 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2731 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2732 2733 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2734 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2735 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2736 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2737 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2738 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2739 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2740 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2742 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2743 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2744 2745 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2746 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2748 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2749 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2750 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2761 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2797 {{ 1, false, 6, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2805 {{ 1, false, 5, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2812 { 2, false, 5, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2814 { 2, false, 6, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2816 { 3, false, 5, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2818 { 3, false, 6, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2835 {{ 2, false, 4, 0 }, 2836 { 3, false, 5, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2838 {{ 2, false, 4, 0 }, 2839 { 3, false, 5, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2841 {{ 2, false, 4, 0 }, 2842 { 3, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2844 {{ 2, false, 4, 0 }, 2845 { 3, false, 5, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2857 { 2, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2859 { 2, false, 6, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2869 {{ 1, false, 4, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2872 {{ 1, false, 4, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2893 {{ 3, false, 1, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2898 {{ 3, false, 1, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2903 {{ 3, false, 1, 0 }} }, 2904 }; 2905 2906 // Use a dynamically initialized static to sort the table exactly once on 2907 // first run. 2908 static const bool SortOnce = 2909 (llvm::sort(Infos, 2910 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2911 return LHS.BuiltinID < RHS.BuiltinID; 2912 }), 2913 true); 2914 (void)SortOnce; 2915 2916 const BuiltinInfo *F = llvm::partition_point( 2917 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2918 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2919 return false; 2920 2921 bool Error = false; 2922 2923 for (const ArgInfo &A : F->Infos) { 2924 // Ignore empty ArgInfo elements. 2925 if (A.BitWidth == 0) 2926 continue; 2927 2928 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2929 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2930 if (!A.Align) { 2931 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2932 } else { 2933 unsigned M = 1 << A.Align; 2934 Min *= M; 2935 Max *= M; 2936 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2937 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2938 } 2939 } 2940 return Error; 2941 } 2942 2943 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2944 CallExpr *TheCall) { 2945 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2946 } 2947 2948 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2949 unsigned BuiltinID, CallExpr *TheCall) { 2950 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2951 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2952 } 2953 2954 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2955 CallExpr *TheCall) { 2956 2957 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2958 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2959 if (!TI.hasFeature("dsp")) 2960 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2961 } 2962 2963 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2964 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2965 if (!TI.hasFeature("dspr2")) 2966 return Diag(TheCall->getBeginLoc(), 2967 diag::err_mips_builtin_requires_dspr2); 2968 } 2969 2970 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2971 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2972 if (!TI.hasFeature("msa")) 2973 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2974 } 2975 2976 return false; 2977 } 2978 2979 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2980 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2981 // ordering for DSP is unspecified. MSA is ordered by the data format used 2982 // by the underlying instruction i.e., df/m, df/n and then by size. 2983 // 2984 // FIXME: The size tests here should instead be tablegen'd along with the 2985 // definitions from include/clang/Basic/BuiltinsMips.def. 2986 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2987 // be too. 2988 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2989 unsigned i = 0, l = 0, u = 0, m = 0; 2990 switch (BuiltinID) { 2991 default: return false; 2992 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2993 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2994 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2995 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2996 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2997 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2998 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2999 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3000 // df/m field. 3001 // These intrinsics take an unsigned 3 bit immediate. 3002 case Mips::BI__builtin_msa_bclri_b: 3003 case Mips::BI__builtin_msa_bnegi_b: 3004 case Mips::BI__builtin_msa_bseti_b: 3005 case Mips::BI__builtin_msa_sat_s_b: 3006 case Mips::BI__builtin_msa_sat_u_b: 3007 case Mips::BI__builtin_msa_slli_b: 3008 case Mips::BI__builtin_msa_srai_b: 3009 case Mips::BI__builtin_msa_srari_b: 3010 case Mips::BI__builtin_msa_srli_b: 3011 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3012 case Mips::BI__builtin_msa_binsli_b: 3013 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3014 // These intrinsics take an unsigned 4 bit immediate. 3015 case Mips::BI__builtin_msa_bclri_h: 3016 case Mips::BI__builtin_msa_bnegi_h: 3017 case Mips::BI__builtin_msa_bseti_h: 3018 case Mips::BI__builtin_msa_sat_s_h: 3019 case Mips::BI__builtin_msa_sat_u_h: 3020 case Mips::BI__builtin_msa_slli_h: 3021 case Mips::BI__builtin_msa_srai_h: 3022 case Mips::BI__builtin_msa_srari_h: 3023 case Mips::BI__builtin_msa_srli_h: 3024 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3025 case Mips::BI__builtin_msa_binsli_h: 3026 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3027 // These intrinsics take an unsigned 5 bit immediate. 3028 // The first block of intrinsics actually have an unsigned 5 bit field, 3029 // not a df/n field. 3030 case Mips::BI__builtin_msa_cfcmsa: 3031 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3032 case Mips::BI__builtin_msa_clei_u_b: 3033 case Mips::BI__builtin_msa_clei_u_h: 3034 case Mips::BI__builtin_msa_clei_u_w: 3035 case Mips::BI__builtin_msa_clei_u_d: 3036 case Mips::BI__builtin_msa_clti_u_b: 3037 case Mips::BI__builtin_msa_clti_u_h: 3038 case Mips::BI__builtin_msa_clti_u_w: 3039 case Mips::BI__builtin_msa_clti_u_d: 3040 case Mips::BI__builtin_msa_maxi_u_b: 3041 case Mips::BI__builtin_msa_maxi_u_h: 3042 case Mips::BI__builtin_msa_maxi_u_w: 3043 case Mips::BI__builtin_msa_maxi_u_d: 3044 case Mips::BI__builtin_msa_mini_u_b: 3045 case Mips::BI__builtin_msa_mini_u_h: 3046 case Mips::BI__builtin_msa_mini_u_w: 3047 case Mips::BI__builtin_msa_mini_u_d: 3048 case Mips::BI__builtin_msa_addvi_b: 3049 case Mips::BI__builtin_msa_addvi_h: 3050 case Mips::BI__builtin_msa_addvi_w: 3051 case Mips::BI__builtin_msa_addvi_d: 3052 case Mips::BI__builtin_msa_bclri_w: 3053 case Mips::BI__builtin_msa_bnegi_w: 3054 case Mips::BI__builtin_msa_bseti_w: 3055 case Mips::BI__builtin_msa_sat_s_w: 3056 case Mips::BI__builtin_msa_sat_u_w: 3057 case Mips::BI__builtin_msa_slli_w: 3058 case Mips::BI__builtin_msa_srai_w: 3059 case Mips::BI__builtin_msa_srari_w: 3060 case Mips::BI__builtin_msa_srli_w: 3061 case Mips::BI__builtin_msa_srlri_w: 3062 case Mips::BI__builtin_msa_subvi_b: 3063 case Mips::BI__builtin_msa_subvi_h: 3064 case Mips::BI__builtin_msa_subvi_w: 3065 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3066 case Mips::BI__builtin_msa_binsli_w: 3067 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3068 // These intrinsics take an unsigned 6 bit immediate. 3069 case Mips::BI__builtin_msa_bclri_d: 3070 case Mips::BI__builtin_msa_bnegi_d: 3071 case Mips::BI__builtin_msa_bseti_d: 3072 case Mips::BI__builtin_msa_sat_s_d: 3073 case Mips::BI__builtin_msa_sat_u_d: 3074 case Mips::BI__builtin_msa_slli_d: 3075 case Mips::BI__builtin_msa_srai_d: 3076 case Mips::BI__builtin_msa_srari_d: 3077 case Mips::BI__builtin_msa_srli_d: 3078 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3079 case Mips::BI__builtin_msa_binsli_d: 3080 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3081 // These intrinsics take a signed 5 bit immediate. 3082 case Mips::BI__builtin_msa_ceqi_b: 3083 case Mips::BI__builtin_msa_ceqi_h: 3084 case Mips::BI__builtin_msa_ceqi_w: 3085 case Mips::BI__builtin_msa_ceqi_d: 3086 case Mips::BI__builtin_msa_clti_s_b: 3087 case Mips::BI__builtin_msa_clti_s_h: 3088 case Mips::BI__builtin_msa_clti_s_w: 3089 case Mips::BI__builtin_msa_clti_s_d: 3090 case Mips::BI__builtin_msa_clei_s_b: 3091 case Mips::BI__builtin_msa_clei_s_h: 3092 case Mips::BI__builtin_msa_clei_s_w: 3093 case Mips::BI__builtin_msa_clei_s_d: 3094 case Mips::BI__builtin_msa_maxi_s_b: 3095 case Mips::BI__builtin_msa_maxi_s_h: 3096 case Mips::BI__builtin_msa_maxi_s_w: 3097 case Mips::BI__builtin_msa_maxi_s_d: 3098 case Mips::BI__builtin_msa_mini_s_b: 3099 case Mips::BI__builtin_msa_mini_s_h: 3100 case Mips::BI__builtin_msa_mini_s_w: 3101 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3102 // These intrinsics take an unsigned 8 bit immediate. 3103 case Mips::BI__builtin_msa_andi_b: 3104 case Mips::BI__builtin_msa_nori_b: 3105 case Mips::BI__builtin_msa_ori_b: 3106 case Mips::BI__builtin_msa_shf_b: 3107 case Mips::BI__builtin_msa_shf_h: 3108 case Mips::BI__builtin_msa_shf_w: 3109 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3110 case Mips::BI__builtin_msa_bseli_b: 3111 case Mips::BI__builtin_msa_bmnzi_b: 3112 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3113 // df/n format 3114 // These intrinsics take an unsigned 4 bit immediate. 3115 case Mips::BI__builtin_msa_copy_s_b: 3116 case Mips::BI__builtin_msa_copy_u_b: 3117 case Mips::BI__builtin_msa_insve_b: 3118 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3119 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3120 // These intrinsics take an unsigned 3 bit immediate. 3121 case Mips::BI__builtin_msa_copy_s_h: 3122 case Mips::BI__builtin_msa_copy_u_h: 3123 case Mips::BI__builtin_msa_insve_h: 3124 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3125 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3126 // These intrinsics take an unsigned 2 bit immediate. 3127 case Mips::BI__builtin_msa_copy_s_w: 3128 case Mips::BI__builtin_msa_copy_u_w: 3129 case Mips::BI__builtin_msa_insve_w: 3130 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3131 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3132 // These intrinsics take an unsigned 1 bit immediate. 3133 case Mips::BI__builtin_msa_copy_s_d: 3134 case Mips::BI__builtin_msa_copy_u_d: 3135 case Mips::BI__builtin_msa_insve_d: 3136 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3137 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3138 // Memory offsets and immediate loads. 3139 // These intrinsics take a signed 10 bit immediate. 3140 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3141 case Mips::BI__builtin_msa_ldi_h: 3142 case Mips::BI__builtin_msa_ldi_w: 3143 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3144 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3145 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3146 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3147 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3148 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3149 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3150 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3151 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3152 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3153 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3154 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3155 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3156 } 3157 3158 if (!m) 3159 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3160 3161 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3162 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3163 } 3164 3165 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3166 CallExpr *TheCall) { 3167 unsigned i = 0, l = 0, u = 0; 3168 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3169 BuiltinID == PPC::BI__builtin_divdeu || 3170 BuiltinID == PPC::BI__builtin_bpermd; 3171 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3172 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3173 BuiltinID == PPC::BI__builtin_divweu || 3174 BuiltinID == PPC::BI__builtin_divde || 3175 BuiltinID == PPC::BI__builtin_divdeu; 3176 3177 if (Is64BitBltin && !IsTarget64Bit) 3178 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3179 << TheCall->getSourceRange(); 3180 3181 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3182 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3183 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3184 << TheCall->getSourceRange(); 3185 3186 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3187 if (!TI.hasFeature("vsx")) 3188 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3189 << TheCall->getSourceRange(); 3190 return false; 3191 }; 3192 3193 switch (BuiltinID) { 3194 default: return false; 3195 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3196 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3197 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3198 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3199 case PPC::BI__builtin_altivec_dss: 3200 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3201 case PPC::BI__builtin_tbegin: 3202 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3203 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3204 case PPC::BI__builtin_tabortwc: 3205 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3206 case PPC::BI__builtin_tabortwci: 3207 case PPC::BI__builtin_tabortdci: 3208 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3209 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3210 case PPC::BI__builtin_altivec_dst: 3211 case PPC::BI__builtin_altivec_dstt: 3212 case PPC::BI__builtin_altivec_dstst: 3213 case PPC::BI__builtin_altivec_dststt: 3214 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3215 case PPC::BI__builtin_vsx_xxpermdi: 3216 case PPC::BI__builtin_vsx_xxsldwi: 3217 return SemaBuiltinVSX(TheCall); 3218 case PPC::BI__builtin_unpack_vector_int128: 3219 return SemaVSXCheck(TheCall) || 3220 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3221 case PPC::BI__builtin_pack_vector_int128: 3222 return SemaVSXCheck(TheCall); 3223 case PPC::BI__builtin_altivec_vgnb: 3224 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3225 case PPC::BI__builtin_vsx_xxeval: 3226 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3227 case PPC::BI__builtin_altivec_vsldbi: 3228 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3229 case PPC::BI__builtin_altivec_vsrdbi: 3230 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3231 case PPC::BI__builtin_vsx_xxpermx: 3232 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3233 } 3234 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3235 } 3236 3237 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3238 CallExpr *TheCall) { 3239 // position of memory order and scope arguments in the builtin 3240 unsigned OrderIndex, ScopeIndex; 3241 switch (BuiltinID) { 3242 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3243 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3244 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3245 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3246 OrderIndex = 2; 3247 ScopeIndex = 3; 3248 break; 3249 case AMDGPU::BI__builtin_amdgcn_fence: 3250 OrderIndex = 0; 3251 ScopeIndex = 1; 3252 break; 3253 default: 3254 return false; 3255 } 3256 3257 ExprResult Arg = TheCall->getArg(OrderIndex); 3258 auto ArgExpr = Arg.get(); 3259 Expr::EvalResult ArgResult; 3260 3261 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3262 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3263 << ArgExpr->getType(); 3264 int ord = ArgResult.Val.getInt().getZExtValue(); 3265 3266 // Check valididty of memory ordering as per C11 / C++11's memody model. 3267 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3268 case llvm::AtomicOrderingCABI::acquire: 3269 case llvm::AtomicOrderingCABI::release: 3270 case llvm::AtomicOrderingCABI::acq_rel: 3271 case llvm::AtomicOrderingCABI::seq_cst: 3272 break; 3273 default: { 3274 return Diag(ArgExpr->getBeginLoc(), 3275 diag::warn_atomic_op_has_invalid_memory_order) 3276 << ArgExpr->getSourceRange(); 3277 } 3278 } 3279 3280 Arg = TheCall->getArg(ScopeIndex); 3281 ArgExpr = Arg.get(); 3282 Expr::EvalResult ArgResult1; 3283 // Check that sync scope is a constant literal 3284 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen, 3285 Context)) 3286 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3287 << ArgExpr->getType(); 3288 3289 return false; 3290 } 3291 3292 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3293 CallExpr *TheCall) { 3294 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3295 Expr *Arg = TheCall->getArg(0); 3296 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3297 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3298 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3299 << Arg->getSourceRange(); 3300 } 3301 3302 // For intrinsics which take an immediate value as part of the instruction, 3303 // range check them here. 3304 unsigned i = 0, l = 0, u = 0; 3305 switch (BuiltinID) { 3306 default: return false; 3307 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3308 case SystemZ::BI__builtin_s390_verimb: 3309 case SystemZ::BI__builtin_s390_verimh: 3310 case SystemZ::BI__builtin_s390_verimf: 3311 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3312 case SystemZ::BI__builtin_s390_vfaeb: 3313 case SystemZ::BI__builtin_s390_vfaeh: 3314 case SystemZ::BI__builtin_s390_vfaef: 3315 case SystemZ::BI__builtin_s390_vfaebs: 3316 case SystemZ::BI__builtin_s390_vfaehs: 3317 case SystemZ::BI__builtin_s390_vfaefs: 3318 case SystemZ::BI__builtin_s390_vfaezb: 3319 case SystemZ::BI__builtin_s390_vfaezh: 3320 case SystemZ::BI__builtin_s390_vfaezf: 3321 case SystemZ::BI__builtin_s390_vfaezbs: 3322 case SystemZ::BI__builtin_s390_vfaezhs: 3323 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3324 case SystemZ::BI__builtin_s390_vfisb: 3325 case SystemZ::BI__builtin_s390_vfidb: 3326 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3327 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3328 case SystemZ::BI__builtin_s390_vftcisb: 3329 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3330 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3331 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3332 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3333 case SystemZ::BI__builtin_s390_vstrcb: 3334 case SystemZ::BI__builtin_s390_vstrch: 3335 case SystemZ::BI__builtin_s390_vstrcf: 3336 case SystemZ::BI__builtin_s390_vstrczb: 3337 case SystemZ::BI__builtin_s390_vstrczh: 3338 case SystemZ::BI__builtin_s390_vstrczf: 3339 case SystemZ::BI__builtin_s390_vstrcbs: 3340 case SystemZ::BI__builtin_s390_vstrchs: 3341 case SystemZ::BI__builtin_s390_vstrcfs: 3342 case SystemZ::BI__builtin_s390_vstrczbs: 3343 case SystemZ::BI__builtin_s390_vstrczhs: 3344 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3345 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3346 case SystemZ::BI__builtin_s390_vfminsb: 3347 case SystemZ::BI__builtin_s390_vfmaxsb: 3348 case SystemZ::BI__builtin_s390_vfmindb: 3349 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3350 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3351 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3352 } 3353 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3354 } 3355 3356 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3357 /// This checks that the target supports __builtin_cpu_supports and 3358 /// that the string argument is constant and valid. 3359 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3360 CallExpr *TheCall) { 3361 Expr *Arg = TheCall->getArg(0); 3362 3363 // Check if the argument is a string literal. 3364 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3365 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3366 << Arg->getSourceRange(); 3367 3368 // Check the contents of the string. 3369 StringRef Feature = 3370 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3371 if (!TI.validateCpuSupports(Feature)) 3372 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3373 << Arg->getSourceRange(); 3374 return false; 3375 } 3376 3377 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3378 /// This checks that the target supports __builtin_cpu_is and 3379 /// that the string argument is constant and valid. 3380 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3381 Expr *Arg = TheCall->getArg(0); 3382 3383 // Check if the argument is a string literal. 3384 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3385 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3386 << Arg->getSourceRange(); 3387 3388 // Check the contents of the string. 3389 StringRef Feature = 3390 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3391 if (!TI.validateCpuIs(Feature)) 3392 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3393 << Arg->getSourceRange(); 3394 return false; 3395 } 3396 3397 // Check if the rounding mode is legal. 3398 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3399 // Indicates if this instruction has rounding control or just SAE. 3400 bool HasRC = false; 3401 3402 unsigned ArgNum = 0; 3403 switch (BuiltinID) { 3404 default: 3405 return false; 3406 case X86::BI__builtin_ia32_vcvttsd2si32: 3407 case X86::BI__builtin_ia32_vcvttsd2si64: 3408 case X86::BI__builtin_ia32_vcvttsd2usi32: 3409 case X86::BI__builtin_ia32_vcvttsd2usi64: 3410 case X86::BI__builtin_ia32_vcvttss2si32: 3411 case X86::BI__builtin_ia32_vcvttss2si64: 3412 case X86::BI__builtin_ia32_vcvttss2usi32: 3413 case X86::BI__builtin_ia32_vcvttss2usi64: 3414 ArgNum = 1; 3415 break; 3416 case X86::BI__builtin_ia32_maxpd512: 3417 case X86::BI__builtin_ia32_maxps512: 3418 case X86::BI__builtin_ia32_minpd512: 3419 case X86::BI__builtin_ia32_minps512: 3420 ArgNum = 2; 3421 break; 3422 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3423 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3424 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3425 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3426 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3427 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3428 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3429 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3430 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3431 case X86::BI__builtin_ia32_exp2pd_mask: 3432 case X86::BI__builtin_ia32_exp2ps_mask: 3433 case X86::BI__builtin_ia32_getexppd512_mask: 3434 case X86::BI__builtin_ia32_getexpps512_mask: 3435 case X86::BI__builtin_ia32_rcp28pd_mask: 3436 case X86::BI__builtin_ia32_rcp28ps_mask: 3437 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3438 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3439 case X86::BI__builtin_ia32_vcomisd: 3440 case X86::BI__builtin_ia32_vcomiss: 3441 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3442 ArgNum = 3; 3443 break; 3444 case X86::BI__builtin_ia32_cmppd512_mask: 3445 case X86::BI__builtin_ia32_cmpps512_mask: 3446 case X86::BI__builtin_ia32_cmpsd_mask: 3447 case X86::BI__builtin_ia32_cmpss_mask: 3448 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3449 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3450 case X86::BI__builtin_ia32_getexpss128_round_mask: 3451 case X86::BI__builtin_ia32_getmantpd512_mask: 3452 case X86::BI__builtin_ia32_getmantps512_mask: 3453 case X86::BI__builtin_ia32_maxsd_round_mask: 3454 case X86::BI__builtin_ia32_maxss_round_mask: 3455 case X86::BI__builtin_ia32_minsd_round_mask: 3456 case X86::BI__builtin_ia32_minss_round_mask: 3457 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3458 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3459 case X86::BI__builtin_ia32_reducepd512_mask: 3460 case X86::BI__builtin_ia32_reduceps512_mask: 3461 case X86::BI__builtin_ia32_rndscalepd_mask: 3462 case X86::BI__builtin_ia32_rndscaleps_mask: 3463 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3464 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3465 ArgNum = 4; 3466 break; 3467 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3468 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3469 case X86::BI__builtin_ia32_fixupimmps512_mask: 3470 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3471 case X86::BI__builtin_ia32_fixupimmsd_mask: 3472 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3473 case X86::BI__builtin_ia32_fixupimmss_mask: 3474 case X86::BI__builtin_ia32_fixupimmss_maskz: 3475 case X86::BI__builtin_ia32_getmantsd_round_mask: 3476 case X86::BI__builtin_ia32_getmantss_round_mask: 3477 case X86::BI__builtin_ia32_rangepd512_mask: 3478 case X86::BI__builtin_ia32_rangeps512_mask: 3479 case X86::BI__builtin_ia32_rangesd128_round_mask: 3480 case X86::BI__builtin_ia32_rangess128_round_mask: 3481 case X86::BI__builtin_ia32_reducesd_mask: 3482 case X86::BI__builtin_ia32_reducess_mask: 3483 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3484 case X86::BI__builtin_ia32_rndscaless_round_mask: 3485 ArgNum = 5; 3486 break; 3487 case X86::BI__builtin_ia32_vcvtsd2si64: 3488 case X86::BI__builtin_ia32_vcvtsd2si32: 3489 case X86::BI__builtin_ia32_vcvtsd2usi32: 3490 case X86::BI__builtin_ia32_vcvtsd2usi64: 3491 case X86::BI__builtin_ia32_vcvtss2si32: 3492 case X86::BI__builtin_ia32_vcvtss2si64: 3493 case X86::BI__builtin_ia32_vcvtss2usi32: 3494 case X86::BI__builtin_ia32_vcvtss2usi64: 3495 case X86::BI__builtin_ia32_sqrtpd512: 3496 case X86::BI__builtin_ia32_sqrtps512: 3497 ArgNum = 1; 3498 HasRC = true; 3499 break; 3500 case X86::BI__builtin_ia32_addpd512: 3501 case X86::BI__builtin_ia32_addps512: 3502 case X86::BI__builtin_ia32_divpd512: 3503 case X86::BI__builtin_ia32_divps512: 3504 case X86::BI__builtin_ia32_mulpd512: 3505 case X86::BI__builtin_ia32_mulps512: 3506 case X86::BI__builtin_ia32_subpd512: 3507 case X86::BI__builtin_ia32_subps512: 3508 case X86::BI__builtin_ia32_cvtsi2sd64: 3509 case X86::BI__builtin_ia32_cvtsi2ss32: 3510 case X86::BI__builtin_ia32_cvtsi2ss64: 3511 case X86::BI__builtin_ia32_cvtusi2sd64: 3512 case X86::BI__builtin_ia32_cvtusi2ss32: 3513 case X86::BI__builtin_ia32_cvtusi2ss64: 3514 ArgNum = 2; 3515 HasRC = true; 3516 break; 3517 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3518 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3519 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3520 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3521 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3522 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3523 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3524 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3525 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3526 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3527 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3528 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3529 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3530 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3531 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3532 ArgNum = 3; 3533 HasRC = true; 3534 break; 3535 case X86::BI__builtin_ia32_addss_round_mask: 3536 case X86::BI__builtin_ia32_addsd_round_mask: 3537 case X86::BI__builtin_ia32_divss_round_mask: 3538 case X86::BI__builtin_ia32_divsd_round_mask: 3539 case X86::BI__builtin_ia32_mulss_round_mask: 3540 case X86::BI__builtin_ia32_mulsd_round_mask: 3541 case X86::BI__builtin_ia32_subss_round_mask: 3542 case X86::BI__builtin_ia32_subsd_round_mask: 3543 case X86::BI__builtin_ia32_scalefpd512_mask: 3544 case X86::BI__builtin_ia32_scalefps512_mask: 3545 case X86::BI__builtin_ia32_scalefsd_round_mask: 3546 case X86::BI__builtin_ia32_scalefss_round_mask: 3547 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3548 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3549 case X86::BI__builtin_ia32_sqrtss_round_mask: 3550 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3551 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3552 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3553 case X86::BI__builtin_ia32_vfmaddss3_mask: 3554 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3555 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3556 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3557 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3558 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3559 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3560 case X86::BI__builtin_ia32_vfmaddps512_mask: 3561 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3562 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3563 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3564 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3565 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3566 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3567 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3568 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3569 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3570 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3571 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3572 ArgNum = 4; 3573 HasRC = true; 3574 break; 3575 } 3576 3577 llvm::APSInt Result; 3578 3579 // We can't check the value of a dependent argument. 3580 Expr *Arg = TheCall->getArg(ArgNum); 3581 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3582 return false; 3583 3584 // Check constant-ness first. 3585 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3586 return true; 3587 3588 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3589 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3590 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3591 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3592 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3593 Result == 8/*ROUND_NO_EXC*/ || 3594 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3595 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3596 return false; 3597 3598 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3599 << Arg->getSourceRange(); 3600 } 3601 3602 // Check if the gather/scatter scale is legal. 3603 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3604 CallExpr *TheCall) { 3605 unsigned ArgNum = 0; 3606 switch (BuiltinID) { 3607 default: 3608 return false; 3609 case X86::BI__builtin_ia32_gatherpfdpd: 3610 case X86::BI__builtin_ia32_gatherpfdps: 3611 case X86::BI__builtin_ia32_gatherpfqpd: 3612 case X86::BI__builtin_ia32_gatherpfqps: 3613 case X86::BI__builtin_ia32_scatterpfdpd: 3614 case X86::BI__builtin_ia32_scatterpfdps: 3615 case X86::BI__builtin_ia32_scatterpfqpd: 3616 case X86::BI__builtin_ia32_scatterpfqps: 3617 ArgNum = 3; 3618 break; 3619 case X86::BI__builtin_ia32_gatherd_pd: 3620 case X86::BI__builtin_ia32_gatherd_pd256: 3621 case X86::BI__builtin_ia32_gatherq_pd: 3622 case X86::BI__builtin_ia32_gatherq_pd256: 3623 case X86::BI__builtin_ia32_gatherd_ps: 3624 case X86::BI__builtin_ia32_gatherd_ps256: 3625 case X86::BI__builtin_ia32_gatherq_ps: 3626 case X86::BI__builtin_ia32_gatherq_ps256: 3627 case X86::BI__builtin_ia32_gatherd_q: 3628 case X86::BI__builtin_ia32_gatherd_q256: 3629 case X86::BI__builtin_ia32_gatherq_q: 3630 case X86::BI__builtin_ia32_gatherq_q256: 3631 case X86::BI__builtin_ia32_gatherd_d: 3632 case X86::BI__builtin_ia32_gatherd_d256: 3633 case X86::BI__builtin_ia32_gatherq_d: 3634 case X86::BI__builtin_ia32_gatherq_d256: 3635 case X86::BI__builtin_ia32_gather3div2df: 3636 case X86::BI__builtin_ia32_gather3div2di: 3637 case X86::BI__builtin_ia32_gather3div4df: 3638 case X86::BI__builtin_ia32_gather3div4di: 3639 case X86::BI__builtin_ia32_gather3div4sf: 3640 case X86::BI__builtin_ia32_gather3div4si: 3641 case X86::BI__builtin_ia32_gather3div8sf: 3642 case X86::BI__builtin_ia32_gather3div8si: 3643 case X86::BI__builtin_ia32_gather3siv2df: 3644 case X86::BI__builtin_ia32_gather3siv2di: 3645 case X86::BI__builtin_ia32_gather3siv4df: 3646 case X86::BI__builtin_ia32_gather3siv4di: 3647 case X86::BI__builtin_ia32_gather3siv4sf: 3648 case X86::BI__builtin_ia32_gather3siv4si: 3649 case X86::BI__builtin_ia32_gather3siv8sf: 3650 case X86::BI__builtin_ia32_gather3siv8si: 3651 case X86::BI__builtin_ia32_gathersiv8df: 3652 case X86::BI__builtin_ia32_gathersiv16sf: 3653 case X86::BI__builtin_ia32_gatherdiv8df: 3654 case X86::BI__builtin_ia32_gatherdiv16sf: 3655 case X86::BI__builtin_ia32_gathersiv8di: 3656 case X86::BI__builtin_ia32_gathersiv16si: 3657 case X86::BI__builtin_ia32_gatherdiv8di: 3658 case X86::BI__builtin_ia32_gatherdiv16si: 3659 case X86::BI__builtin_ia32_scatterdiv2df: 3660 case X86::BI__builtin_ia32_scatterdiv2di: 3661 case X86::BI__builtin_ia32_scatterdiv4df: 3662 case X86::BI__builtin_ia32_scatterdiv4di: 3663 case X86::BI__builtin_ia32_scatterdiv4sf: 3664 case X86::BI__builtin_ia32_scatterdiv4si: 3665 case X86::BI__builtin_ia32_scatterdiv8sf: 3666 case X86::BI__builtin_ia32_scatterdiv8si: 3667 case X86::BI__builtin_ia32_scattersiv2df: 3668 case X86::BI__builtin_ia32_scattersiv2di: 3669 case X86::BI__builtin_ia32_scattersiv4df: 3670 case X86::BI__builtin_ia32_scattersiv4di: 3671 case X86::BI__builtin_ia32_scattersiv4sf: 3672 case X86::BI__builtin_ia32_scattersiv4si: 3673 case X86::BI__builtin_ia32_scattersiv8sf: 3674 case X86::BI__builtin_ia32_scattersiv8si: 3675 case X86::BI__builtin_ia32_scattersiv8df: 3676 case X86::BI__builtin_ia32_scattersiv16sf: 3677 case X86::BI__builtin_ia32_scatterdiv8df: 3678 case X86::BI__builtin_ia32_scatterdiv16sf: 3679 case X86::BI__builtin_ia32_scattersiv8di: 3680 case X86::BI__builtin_ia32_scattersiv16si: 3681 case X86::BI__builtin_ia32_scatterdiv8di: 3682 case X86::BI__builtin_ia32_scatterdiv16si: 3683 ArgNum = 4; 3684 break; 3685 } 3686 3687 llvm::APSInt Result; 3688 3689 // We can't check the value of a dependent argument. 3690 Expr *Arg = TheCall->getArg(ArgNum); 3691 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3692 return false; 3693 3694 // Check constant-ness first. 3695 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3696 return true; 3697 3698 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3699 return false; 3700 3701 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3702 << Arg->getSourceRange(); 3703 } 3704 3705 enum { TileRegLow = 0, TileRegHigh = 7 }; 3706 3707 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 3708 ArrayRef<int> ArgNums) { 3709 for (int ArgNum : ArgNums) { 3710 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 3711 return true; 3712 } 3713 return false; 3714 } 3715 3716 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, int ArgNum) { 3717 return SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh); 3718 } 3719 3720 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 3721 ArrayRef<int> ArgNums) { 3722 // Because the max number of tile register is TileRegHigh + 1, so here we use 3723 // each bit to represent the usage of them in bitset. 3724 std::bitset<TileRegHigh + 1> ArgValues; 3725 for (int ArgNum : ArgNums) { 3726 llvm::APSInt Arg; 3727 SemaBuiltinConstantArg(TheCall, ArgNum, Arg); 3728 int ArgExtValue = Arg.getExtValue(); 3729 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 3730 "Incorrect tile register num."); 3731 if (ArgValues.test(ArgExtValue)) 3732 return Diag(TheCall->getBeginLoc(), 3733 diag::err_x86_builtin_tile_arg_duplicate) 3734 << TheCall->getArg(ArgNum)->getSourceRange(); 3735 ArgValues.set(ArgExtValue); 3736 } 3737 return false; 3738 } 3739 3740 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 3741 ArrayRef<int> ArgNums) { 3742 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 3743 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 3744 } 3745 3746 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 3747 switch (BuiltinID) { 3748 default: 3749 return false; 3750 case X86::BI__builtin_ia32_tileloadd64: 3751 case X86::BI__builtin_ia32_tileloaddt164: 3752 case X86::BI__builtin_ia32_tilestored64: 3753 case X86::BI__builtin_ia32_tilezero: 3754 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 3755 case X86::BI__builtin_ia32_tdpbssd: 3756 case X86::BI__builtin_ia32_tdpbsud: 3757 case X86::BI__builtin_ia32_tdpbusd: 3758 case X86::BI__builtin_ia32_tdpbuud: 3759 case X86::BI__builtin_ia32_tdpbf16ps: 3760 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 3761 } 3762 } 3763 static bool isX86_32Builtin(unsigned BuiltinID) { 3764 // These builtins only work on x86-32 targets. 3765 switch (BuiltinID) { 3766 case X86::BI__builtin_ia32_readeflags_u32: 3767 case X86::BI__builtin_ia32_writeeflags_u32: 3768 return true; 3769 } 3770 3771 return false; 3772 } 3773 3774 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3775 CallExpr *TheCall) { 3776 if (BuiltinID == X86::BI__builtin_cpu_supports) 3777 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3778 3779 if (BuiltinID == X86::BI__builtin_cpu_is) 3780 return SemaBuiltinCpuIs(*this, TI, TheCall); 3781 3782 // Check for 32-bit only builtins on a 64-bit target. 3783 const llvm::Triple &TT = TI.getTriple(); 3784 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3785 return Diag(TheCall->getCallee()->getBeginLoc(), 3786 diag::err_32_bit_builtin_64_bit_tgt); 3787 3788 // If the intrinsic has rounding or SAE make sure its valid. 3789 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3790 return true; 3791 3792 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3793 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3794 return true; 3795 3796 // If the intrinsic has a tile arguments, make sure they are valid. 3797 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 3798 return true; 3799 3800 // For intrinsics which take an immediate value as part of the instruction, 3801 // range check them here. 3802 int i = 0, l = 0, u = 0; 3803 switch (BuiltinID) { 3804 default: 3805 return false; 3806 case X86::BI__builtin_ia32_vec_ext_v2si: 3807 case X86::BI__builtin_ia32_vec_ext_v2di: 3808 case X86::BI__builtin_ia32_vextractf128_pd256: 3809 case X86::BI__builtin_ia32_vextractf128_ps256: 3810 case X86::BI__builtin_ia32_vextractf128_si256: 3811 case X86::BI__builtin_ia32_extract128i256: 3812 case X86::BI__builtin_ia32_extractf64x4_mask: 3813 case X86::BI__builtin_ia32_extracti64x4_mask: 3814 case X86::BI__builtin_ia32_extractf32x8_mask: 3815 case X86::BI__builtin_ia32_extracti32x8_mask: 3816 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3817 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3818 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3819 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3820 i = 1; l = 0; u = 1; 3821 break; 3822 case X86::BI__builtin_ia32_vec_set_v2di: 3823 case X86::BI__builtin_ia32_vinsertf128_pd256: 3824 case X86::BI__builtin_ia32_vinsertf128_ps256: 3825 case X86::BI__builtin_ia32_vinsertf128_si256: 3826 case X86::BI__builtin_ia32_insert128i256: 3827 case X86::BI__builtin_ia32_insertf32x8: 3828 case X86::BI__builtin_ia32_inserti32x8: 3829 case X86::BI__builtin_ia32_insertf64x4: 3830 case X86::BI__builtin_ia32_inserti64x4: 3831 case X86::BI__builtin_ia32_insertf64x2_256: 3832 case X86::BI__builtin_ia32_inserti64x2_256: 3833 case X86::BI__builtin_ia32_insertf32x4_256: 3834 case X86::BI__builtin_ia32_inserti32x4_256: 3835 i = 2; l = 0; u = 1; 3836 break; 3837 case X86::BI__builtin_ia32_vpermilpd: 3838 case X86::BI__builtin_ia32_vec_ext_v4hi: 3839 case X86::BI__builtin_ia32_vec_ext_v4si: 3840 case X86::BI__builtin_ia32_vec_ext_v4sf: 3841 case X86::BI__builtin_ia32_vec_ext_v4di: 3842 case X86::BI__builtin_ia32_extractf32x4_mask: 3843 case X86::BI__builtin_ia32_extracti32x4_mask: 3844 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3845 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3846 i = 1; l = 0; u = 3; 3847 break; 3848 case X86::BI_mm_prefetch: 3849 case X86::BI__builtin_ia32_vec_ext_v8hi: 3850 case X86::BI__builtin_ia32_vec_ext_v8si: 3851 i = 1; l = 0; u = 7; 3852 break; 3853 case X86::BI__builtin_ia32_sha1rnds4: 3854 case X86::BI__builtin_ia32_blendpd: 3855 case X86::BI__builtin_ia32_shufpd: 3856 case X86::BI__builtin_ia32_vec_set_v4hi: 3857 case X86::BI__builtin_ia32_vec_set_v4si: 3858 case X86::BI__builtin_ia32_vec_set_v4di: 3859 case X86::BI__builtin_ia32_shuf_f32x4_256: 3860 case X86::BI__builtin_ia32_shuf_f64x2_256: 3861 case X86::BI__builtin_ia32_shuf_i32x4_256: 3862 case X86::BI__builtin_ia32_shuf_i64x2_256: 3863 case X86::BI__builtin_ia32_insertf64x2_512: 3864 case X86::BI__builtin_ia32_inserti64x2_512: 3865 case X86::BI__builtin_ia32_insertf32x4: 3866 case X86::BI__builtin_ia32_inserti32x4: 3867 i = 2; l = 0; u = 3; 3868 break; 3869 case X86::BI__builtin_ia32_vpermil2pd: 3870 case X86::BI__builtin_ia32_vpermil2pd256: 3871 case X86::BI__builtin_ia32_vpermil2ps: 3872 case X86::BI__builtin_ia32_vpermil2ps256: 3873 i = 3; l = 0; u = 3; 3874 break; 3875 case X86::BI__builtin_ia32_cmpb128_mask: 3876 case X86::BI__builtin_ia32_cmpw128_mask: 3877 case X86::BI__builtin_ia32_cmpd128_mask: 3878 case X86::BI__builtin_ia32_cmpq128_mask: 3879 case X86::BI__builtin_ia32_cmpb256_mask: 3880 case X86::BI__builtin_ia32_cmpw256_mask: 3881 case X86::BI__builtin_ia32_cmpd256_mask: 3882 case X86::BI__builtin_ia32_cmpq256_mask: 3883 case X86::BI__builtin_ia32_cmpb512_mask: 3884 case X86::BI__builtin_ia32_cmpw512_mask: 3885 case X86::BI__builtin_ia32_cmpd512_mask: 3886 case X86::BI__builtin_ia32_cmpq512_mask: 3887 case X86::BI__builtin_ia32_ucmpb128_mask: 3888 case X86::BI__builtin_ia32_ucmpw128_mask: 3889 case X86::BI__builtin_ia32_ucmpd128_mask: 3890 case X86::BI__builtin_ia32_ucmpq128_mask: 3891 case X86::BI__builtin_ia32_ucmpb256_mask: 3892 case X86::BI__builtin_ia32_ucmpw256_mask: 3893 case X86::BI__builtin_ia32_ucmpd256_mask: 3894 case X86::BI__builtin_ia32_ucmpq256_mask: 3895 case X86::BI__builtin_ia32_ucmpb512_mask: 3896 case X86::BI__builtin_ia32_ucmpw512_mask: 3897 case X86::BI__builtin_ia32_ucmpd512_mask: 3898 case X86::BI__builtin_ia32_ucmpq512_mask: 3899 case X86::BI__builtin_ia32_vpcomub: 3900 case X86::BI__builtin_ia32_vpcomuw: 3901 case X86::BI__builtin_ia32_vpcomud: 3902 case X86::BI__builtin_ia32_vpcomuq: 3903 case X86::BI__builtin_ia32_vpcomb: 3904 case X86::BI__builtin_ia32_vpcomw: 3905 case X86::BI__builtin_ia32_vpcomd: 3906 case X86::BI__builtin_ia32_vpcomq: 3907 case X86::BI__builtin_ia32_vec_set_v8hi: 3908 case X86::BI__builtin_ia32_vec_set_v8si: 3909 i = 2; l = 0; u = 7; 3910 break; 3911 case X86::BI__builtin_ia32_vpermilpd256: 3912 case X86::BI__builtin_ia32_roundps: 3913 case X86::BI__builtin_ia32_roundpd: 3914 case X86::BI__builtin_ia32_roundps256: 3915 case X86::BI__builtin_ia32_roundpd256: 3916 case X86::BI__builtin_ia32_getmantpd128_mask: 3917 case X86::BI__builtin_ia32_getmantpd256_mask: 3918 case X86::BI__builtin_ia32_getmantps128_mask: 3919 case X86::BI__builtin_ia32_getmantps256_mask: 3920 case X86::BI__builtin_ia32_getmantpd512_mask: 3921 case X86::BI__builtin_ia32_getmantps512_mask: 3922 case X86::BI__builtin_ia32_vec_ext_v16qi: 3923 case X86::BI__builtin_ia32_vec_ext_v16hi: 3924 i = 1; l = 0; u = 15; 3925 break; 3926 case X86::BI__builtin_ia32_pblendd128: 3927 case X86::BI__builtin_ia32_blendps: 3928 case X86::BI__builtin_ia32_blendpd256: 3929 case X86::BI__builtin_ia32_shufpd256: 3930 case X86::BI__builtin_ia32_roundss: 3931 case X86::BI__builtin_ia32_roundsd: 3932 case X86::BI__builtin_ia32_rangepd128_mask: 3933 case X86::BI__builtin_ia32_rangepd256_mask: 3934 case X86::BI__builtin_ia32_rangepd512_mask: 3935 case X86::BI__builtin_ia32_rangeps128_mask: 3936 case X86::BI__builtin_ia32_rangeps256_mask: 3937 case X86::BI__builtin_ia32_rangeps512_mask: 3938 case X86::BI__builtin_ia32_getmantsd_round_mask: 3939 case X86::BI__builtin_ia32_getmantss_round_mask: 3940 case X86::BI__builtin_ia32_vec_set_v16qi: 3941 case X86::BI__builtin_ia32_vec_set_v16hi: 3942 i = 2; l = 0; u = 15; 3943 break; 3944 case X86::BI__builtin_ia32_vec_ext_v32qi: 3945 i = 1; l = 0; u = 31; 3946 break; 3947 case X86::BI__builtin_ia32_cmpps: 3948 case X86::BI__builtin_ia32_cmpss: 3949 case X86::BI__builtin_ia32_cmppd: 3950 case X86::BI__builtin_ia32_cmpsd: 3951 case X86::BI__builtin_ia32_cmpps256: 3952 case X86::BI__builtin_ia32_cmppd256: 3953 case X86::BI__builtin_ia32_cmpps128_mask: 3954 case X86::BI__builtin_ia32_cmppd128_mask: 3955 case X86::BI__builtin_ia32_cmpps256_mask: 3956 case X86::BI__builtin_ia32_cmppd256_mask: 3957 case X86::BI__builtin_ia32_cmpps512_mask: 3958 case X86::BI__builtin_ia32_cmppd512_mask: 3959 case X86::BI__builtin_ia32_cmpsd_mask: 3960 case X86::BI__builtin_ia32_cmpss_mask: 3961 case X86::BI__builtin_ia32_vec_set_v32qi: 3962 i = 2; l = 0; u = 31; 3963 break; 3964 case X86::BI__builtin_ia32_permdf256: 3965 case X86::BI__builtin_ia32_permdi256: 3966 case X86::BI__builtin_ia32_permdf512: 3967 case X86::BI__builtin_ia32_permdi512: 3968 case X86::BI__builtin_ia32_vpermilps: 3969 case X86::BI__builtin_ia32_vpermilps256: 3970 case X86::BI__builtin_ia32_vpermilpd512: 3971 case X86::BI__builtin_ia32_vpermilps512: 3972 case X86::BI__builtin_ia32_pshufd: 3973 case X86::BI__builtin_ia32_pshufd256: 3974 case X86::BI__builtin_ia32_pshufd512: 3975 case X86::BI__builtin_ia32_pshufhw: 3976 case X86::BI__builtin_ia32_pshufhw256: 3977 case X86::BI__builtin_ia32_pshufhw512: 3978 case X86::BI__builtin_ia32_pshuflw: 3979 case X86::BI__builtin_ia32_pshuflw256: 3980 case X86::BI__builtin_ia32_pshuflw512: 3981 case X86::BI__builtin_ia32_vcvtps2ph: 3982 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3983 case X86::BI__builtin_ia32_vcvtps2ph256: 3984 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3985 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3986 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3987 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3988 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3989 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3990 case X86::BI__builtin_ia32_rndscaleps_mask: 3991 case X86::BI__builtin_ia32_rndscalepd_mask: 3992 case X86::BI__builtin_ia32_reducepd128_mask: 3993 case X86::BI__builtin_ia32_reducepd256_mask: 3994 case X86::BI__builtin_ia32_reducepd512_mask: 3995 case X86::BI__builtin_ia32_reduceps128_mask: 3996 case X86::BI__builtin_ia32_reduceps256_mask: 3997 case X86::BI__builtin_ia32_reduceps512_mask: 3998 case X86::BI__builtin_ia32_prold512: 3999 case X86::BI__builtin_ia32_prolq512: 4000 case X86::BI__builtin_ia32_prold128: 4001 case X86::BI__builtin_ia32_prold256: 4002 case X86::BI__builtin_ia32_prolq128: 4003 case X86::BI__builtin_ia32_prolq256: 4004 case X86::BI__builtin_ia32_prord512: 4005 case X86::BI__builtin_ia32_prorq512: 4006 case X86::BI__builtin_ia32_prord128: 4007 case X86::BI__builtin_ia32_prord256: 4008 case X86::BI__builtin_ia32_prorq128: 4009 case X86::BI__builtin_ia32_prorq256: 4010 case X86::BI__builtin_ia32_fpclasspd128_mask: 4011 case X86::BI__builtin_ia32_fpclasspd256_mask: 4012 case X86::BI__builtin_ia32_fpclassps128_mask: 4013 case X86::BI__builtin_ia32_fpclassps256_mask: 4014 case X86::BI__builtin_ia32_fpclassps512_mask: 4015 case X86::BI__builtin_ia32_fpclasspd512_mask: 4016 case X86::BI__builtin_ia32_fpclasssd_mask: 4017 case X86::BI__builtin_ia32_fpclassss_mask: 4018 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4019 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4020 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4021 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4022 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4023 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4024 case X86::BI__builtin_ia32_kshiftliqi: 4025 case X86::BI__builtin_ia32_kshiftlihi: 4026 case X86::BI__builtin_ia32_kshiftlisi: 4027 case X86::BI__builtin_ia32_kshiftlidi: 4028 case X86::BI__builtin_ia32_kshiftriqi: 4029 case X86::BI__builtin_ia32_kshiftrihi: 4030 case X86::BI__builtin_ia32_kshiftrisi: 4031 case X86::BI__builtin_ia32_kshiftridi: 4032 i = 1; l = 0; u = 255; 4033 break; 4034 case X86::BI__builtin_ia32_vperm2f128_pd256: 4035 case X86::BI__builtin_ia32_vperm2f128_ps256: 4036 case X86::BI__builtin_ia32_vperm2f128_si256: 4037 case X86::BI__builtin_ia32_permti256: 4038 case X86::BI__builtin_ia32_pblendw128: 4039 case X86::BI__builtin_ia32_pblendw256: 4040 case X86::BI__builtin_ia32_blendps256: 4041 case X86::BI__builtin_ia32_pblendd256: 4042 case X86::BI__builtin_ia32_palignr128: 4043 case X86::BI__builtin_ia32_palignr256: 4044 case X86::BI__builtin_ia32_palignr512: 4045 case X86::BI__builtin_ia32_alignq512: 4046 case X86::BI__builtin_ia32_alignd512: 4047 case X86::BI__builtin_ia32_alignd128: 4048 case X86::BI__builtin_ia32_alignd256: 4049 case X86::BI__builtin_ia32_alignq128: 4050 case X86::BI__builtin_ia32_alignq256: 4051 case X86::BI__builtin_ia32_vcomisd: 4052 case X86::BI__builtin_ia32_vcomiss: 4053 case X86::BI__builtin_ia32_shuf_f32x4: 4054 case X86::BI__builtin_ia32_shuf_f64x2: 4055 case X86::BI__builtin_ia32_shuf_i32x4: 4056 case X86::BI__builtin_ia32_shuf_i64x2: 4057 case X86::BI__builtin_ia32_shufpd512: 4058 case X86::BI__builtin_ia32_shufps: 4059 case X86::BI__builtin_ia32_shufps256: 4060 case X86::BI__builtin_ia32_shufps512: 4061 case X86::BI__builtin_ia32_dbpsadbw128: 4062 case X86::BI__builtin_ia32_dbpsadbw256: 4063 case X86::BI__builtin_ia32_dbpsadbw512: 4064 case X86::BI__builtin_ia32_vpshldd128: 4065 case X86::BI__builtin_ia32_vpshldd256: 4066 case X86::BI__builtin_ia32_vpshldd512: 4067 case X86::BI__builtin_ia32_vpshldq128: 4068 case X86::BI__builtin_ia32_vpshldq256: 4069 case X86::BI__builtin_ia32_vpshldq512: 4070 case X86::BI__builtin_ia32_vpshldw128: 4071 case X86::BI__builtin_ia32_vpshldw256: 4072 case X86::BI__builtin_ia32_vpshldw512: 4073 case X86::BI__builtin_ia32_vpshrdd128: 4074 case X86::BI__builtin_ia32_vpshrdd256: 4075 case X86::BI__builtin_ia32_vpshrdd512: 4076 case X86::BI__builtin_ia32_vpshrdq128: 4077 case X86::BI__builtin_ia32_vpshrdq256: 4078 case X86::BI__builtin_ia32_vpshrdq512: 4079 case X86::BI__builtin_ia32_vpshrdw128: 4080 case X86::BI__builtin_ia32_vpshrdw256: 4081 case X86::BI__builtin_ia32_vpshrdw512: 4082 i = 2; l = 0; u = 255; 4083 break; 4084 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4085 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4086 case X86::BI__builtin_ia32_fixupimmps512_mask: 4087 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4088 case X86::BI__builtin_ia32_fixupimmsd_mask: 4089 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4090 case X86::BI__builtin_ia32_fixupimmss_mask: 4091 case X86::BI__builtin_ia32_fixupimmss_maskz: 4092 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4093 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4094 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4095 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4096 case X86::BI__builtin_ia32_fixupimmps128_mask: 4097 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4098 case X86::BI__builtin_ia32_fixupimmps256_mask: 4099 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4100 case X86::BI__builtin_ia32_pternlogd512_mask: 4101 case X86::BI__builtin_ia32_pternlogd512_maskz: 4102 case X86::BI__builtin_ia32_pternlogq512_mask: 4103 case X86::BI__builtin_ia32_pternlogq512_maskz: 4104 case X86::BI__builtin_ia32_pternlogd128_mask: 4105 case X86::BI__builtin_ia32_pternlogd128_maskz: 4106 case X86::BI__builtin_ia32_pternlogd256_mask: 4107 case X86::BI__builtin_ia32_pternlogd256_maskz: 4108 case X86::BI__builtin_ia32_pternlogq128_mask: 4109 case X86::BI__builtin_ia32_pternlogq128_maskz: 4110 case X86::BI__builtin_ia32_pternlogq256_mask: 4111 case X86::BI__builtin_ia32_pternlogq256_maskz: 4112 i = 3; l = 0; u = 255; 4113 break; 4114 case X86::BI__builtin_ia32_gatherpfdpd: 4115 case X86::BI__builtin_ia32_gatherpfdps: 4116 case X86::BI__builtin_ia32_gatherpfqpd: 4117 case X86::BI__builtin_ia32_gatherpfqps: 4118 case X86::BI__builtin_ia32_scatterpfdpd: 4119 case X86::BI__builtin_ia32_scatterpfdps: 4120 case X86::BI__builtin_ia32_scatterpfqpd: 4121 case X86::BI__builtin_ia32_scatterpfqps: 4122 i = 4; l = 2; u = 3; 4123 break; 4124 case X86::BI__builtin_ia32_reducesd_mask: 4125 case X86::BI__builtin_ia32_reducess_mask: 4126 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4127 case X86::BI__builtin_ia32_rndscaless_round_mask: 4128 i = 4; l = 0; u = 255; 4129 break; 4130 } 4131 4132 // Note that we don't force a hard error on the range check here, allowing 4133 // template-generated or macro-generated dead code to potentially have out-of- 4134 // range values. These need to code generate, but don't need to necessarily 4135 // make any sense. We use a warning that defaults to an error. 4136 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4137 } 4138 4139 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4140 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4141 /// Returns true when the format fits the function and the FormatStringInfo has 4142 /// been populated. 4143 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4144 FormatStringInfo *FSI) { 4145 FSI->HasVAListArg = Format->getFirstArg() == 0; 4146 FSI->FormatIdx = Format->getFormatIdx() - 1; 4147 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4148 4149 // The way the format attribute works in GCC, the implicit this argument 4150 // of member functions is counted. However, it doesn't appear in our own 4151 // lists, so decrement format_idx in that case. 4152 if (IsCXXMember) { 4153 if(FSI->FormatIdx == 0) 4154 return false; 4155 --FSI->FormatIdx; 4156 if (FSI->FirstDataArg != 0) 4157 --FSI->FirstDataArg; 4158 } 4159 return true; 4160 } 4161 4162 /// Checks if a the given expression evaluates to null. 4163 /// 4164 /// Returns true if the value evaluates to null. 4165 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4166 // If the expression has non-null type, it doesn't evaluate to null. 4167 if (auto nullability 4168 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4169 if (*nullability == NullabilityKind::NonNull) 4170 return false; 4171 } 4172 4173 // As a special case, transparent unions initialized with zero are 4174 // considered null for the purposes of the nonnull attribute. 4175 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4176 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4177 if (const CompoundLiteralExpr *CLE = 4178 dyn_cast<CompoundLiteralExpr>(Expr)) 4179 if (const InitListExpr *ILE = 4180 dyn_cast<InitListExpr>(CLE->getInitializer())) 4181 Expr = ILE->getInit(0); 4182 } 4183 4184 bool Result; 4185 return (!Expr->isValueDependent() && 4186 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4187 !Result); 4188 } 4189 4190 static void CheckNonNullArgument(Sema &S, 4191 const Expr *ArgExpr, 4192 SourceLocation CallSiteLoc) { 4193 if (CheckNonNullExpr(S, ArgExpr)) 4194 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4195 S.PDiag(diag::warn_null_arg) 4196 << ArgExpr->getSourceRange()); 4197 } 4198 4199 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4200 FormatStringInfo FSI; 4201 if ((GetFormatStringType(Format) == FST_NSString) && 4202 getFormatStringInfo(Format, false, &FSI)) { 4203 Idx = FSI.FormatIdx; 4204 return true; 4205 } 4206 return false; 4207 } 4208 4209 /// Diagnose use of %s directive in an NSString which is being passed 4210 /// as formatting string to formatting method. 4211 static void 4212 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4213 const NamedDecl *FDecl, 4214 Expr **Args, 4215 unsigned NumArgs) { 4216 unsigned Idx = 0; 4217 bool Format = false; 4218 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4219 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4220 Idx = 2; 4221 Format = true; 4222 } 4223 else 4224 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4225 if (S.GetFormatNSStringIdx(I, Idx)) { 4226 Format = true; 4227 break; 4228 } 4229 } 4230 if (!Format || NumArgs <= Idx) 4231 return; 4232 const Expr *FormatExpr = Args[Idx]; 4233 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4234 FormatExpr = CSCE->getSubExpr(); 4235 const StringLiteral *FormatString; 4236 if (const ObjCStringLiteral *OSL = 4237 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4238 FormatString = OSL->getString(); 4239 else 4240 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4241 if (!FormatString) 4242 return; 4243 if (S.FormatStringHasSArg(FormatString)) { 4244 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4245 << "%s" << 1 << 1; 4246 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4247 << FDecl->getDeclName(); 4248 } 4249 } 4250 4251 /// Determine whether the given type has a non-null nullability annotation. 4252 static bool isNonNullType(ASTContext &ctx, QualType type) { 4253 if (auto nullability = type->getNullability(ctx)) 4254 return *nullability == NullabilityKind::NonNull; 4255 4256 return false; 4257 } 4258 4259 static void CheckNonNullArguments(Sema &S, 4260 const NamedDecl *FDecl, 4261 const FunctionProtoType *Proto, 4262 ArrayRef<const Expr *> Args, 4263 SourceLocation CallSiteLoc) { 4264 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4265 4266 // Already checked by by constant evaluator. 4267 if (S.isConstantEvaluated()) 4268 return; 4269 // Check the attributes attached to the method/function itself. 4270 llvm::SmallBitVector NonNullArgs; 4271 if (FDecl) { 4272 // Handle the nonnull attribute on the function/method declaration itself. 4273 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4274 if (!NonNull->args_size()) { 4275 // Easy case: all pointer arguments are nonnull. 4276 for (const auto *Arg : Args) 4277 if (S.isValidPointerAttrType(Arg->getType())) 4278 CheckNonNullArgument(S, Arg, CallSiteLoc); 4279 return; 4280 } 4281 4282 for (const ParamIdx &Idx : NonNull->args()) { 4283 unsigned IdxAST = Idx.getASTIndex(); 4284 if (IdxAST >= Args.size()) 4285 continue; 4286 if (NonNullArgs.empty()) 4287 NonNullArgs.resize(Args.size()); 4288 NonNullArgs.set(IdxAST); 4289 } 4290 } 4291 } 4292 4293 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4294 // Handle the nonnull attribute on the parameters of the 4295 // function/method. 4296 ArrayRef<ParmVarDecl*> parms; 4297 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4298 parms = FD->parameters(); 4299 else 4300 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4301 4302 unsigned ParamIndex = 0; 4303 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4304 I != E; ++I, ++ParamIndex) { 4305 const ParmVarDecl *PVD = *I; 4306 if (PVD->hasAttr<NonNullAttr>() || 4307 isNonNullType(S.Context, PVD->getType())) { 4308 if (NonNullArgs.empty()) 4309 NonNullArgs.resize(Args.size()); 4310 4311 NonNullArgs.set(ParamIndex); 4312 } 4313 } 4314 } else { 4315 // If we have a non-function, non-method declaration but no 4316 // function prototype, try to dig out the function prototype. 4317 if (!Proto) { 4318 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4319 QualType type = VD->getType().getNonReferenceType(); 4320 if (auto pointerType = type->getAs<PointerType>()) 4321 type = pointerType->getPointeeType(); 4322 else if (auto blockType = type->getAs<BlockPointerType>()) 4323 type = blockType->getPointeeType(); 4324 // FIXME: data member pointers? 4325 4326 // Dig out the function prototype, if there is one. 4327 Proto = type->getAs<FunctionProtoType>(); 4328 } 4329 } 4330 4331 // Fill in non-null argument information from the nullability 4332 // information on the parameter types (if we have them). 4333 if (Proto) { 4334 unsigned Index = 0; 4335 for (auto paramType : Proto->getParamTypes()) { 4336 if (isNonNullType(S.Context, paramType)) { 4337 if (NonNullArgs.empty()) 4338 NonNullArgs.resize(Args.size()); 4339 4340 NonNullArgs.set(Index); 4341 } 4342 4343 ++Index; 4344 } 4345 } 4346 } 4347 4348 // Check for non-null arguments. 4349 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4350 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4351 if (NonNullArgs[ArgIndex]) 4352 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4353 } 4354 } 4355 4356 /// Handles the checks for format strings, non-POD arguments to vararg 4357 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4358 /// attributes. 4359 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4360 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4361 bool IsMemberFunction, SourceLocation Loc, 4362 SourceRange Range, VariadicCallType CallType) { 4363 // FIXME: We should check as much as we can in the template definition. 4364 if (CurContext->isDependentContext()) 4365 return; 4366 4367 // Printf and scanf checking. 4368 llvm::SmallBitVector CheckedVarArgs; 4369 if (FDecl) { 4370 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4371 // Only create vector if there are format attributes. 4372 CheckedVarArgs.resize(Args.size()); 4373 4374 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4375 CheckedVarArgs); 4376 } 4377 } 4378 4379 // Refuse POD arguments that weren't caught by the format string 4380 // checks above. 4381 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4382 if (CallType != VariadicDoesNotApply && 4383 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4384 unsigned NumParams = Proto ? Proto->getNumParams() 4385 : FDecl && isa<FunctionDecl>(FDecl) 4386 ? cast<FunctionDecl>(FDecl)->getNumParams() 4387 : FDecl && isa<ObjCMethodDecl>(FDecl) 4388 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4389 : 0; 4390 4391 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4392 // Args[ArgIdx] can be null in malformed code. 4393 if (const Expr *Arg = Args[ArgIdx]) { 4394 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4395 checkVariadicArgument(Arg, CallType); 4396 } 4397 } 4398 } 4399 4400 if (FDecl || Proto) { 4401 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4402 4403 // Type safety checking. 4404 if (FDecl) { 4405 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4406 CheckArgumentWithTypeTag(I, Args, Loc); 4407 } 4408 } 4409 4410 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4411 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4412 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4413 if (!Arg->isValueDependent()) { 4414 Expr::EvalResult Align; 4415 if (Arg->EvaluateAsInt(Align, Context)) { 4416 const llvm::APSInt &I = Align.Val.getInt(); 4417 if (!I.isPowerOf2()) 4418 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4419 << Arg->getSourceRange(); 4420 4421 if (I > Sema::MaximumAlignment) 4422 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4423 << Arg->getSourceRange() << Sema::MaximumAlignment; 4424 } 4425 } 4426 } 4427 4428 if (FD) 4429 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4430 } 4431 4432 /// CheckConstructorCall - Check a constructor call for correctness and safety 4433 /// properties not enforced by the C type system. 4434 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4435 ArrayRef<const Expr *> Args, 4436 const FunctionProtoType *Proto, 4437 SourceLocation Loc) { 4438 VariadicCallType CallType = 4439 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4440 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4441 Loc, SourceRange(), CallType); 4442 } 4443 4444 /// CheckFunctionCall - Check a direct function call for various correctness 4445 /// and safety properties not strictly enforced by the C type system. 4446 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4447 const FunctionProtoType *Proto) { 4448 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4449 isa<CXXMethodDecl>(FDecl); 4450 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4451 IsMemberOperatorCall; 4452 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4453 TheCall->getCallee()); 4454 Expr** Args = TheCall->getArgs(); 4455 unsigned NumArgs = TheCall->getNumArgs(); 4456 4457 Expr *ImplicitThis = nullptr; 4458 if (IsMemberOperatorCall) { 4459 // If this is a call to a member operator, hide the first argument 4460 // from checkCall. 4461 // FIXME: Our choice of AST representation here is less than ideal. 4462 ImplicitThis = Args[0]; 4463 ++Args; 4464 --NumArgs; 4465 } else if (IsMemberFunction) 4466 ImplicitThis = 4467 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4468 4469 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4470 IsMemberFunction, TheCall->getRParenLoc(), 4471 TheCall->getCallee()->getSourceRange(), CallType); 4472 4473 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4474 // None of the checks below are needed for functions that don't have 4475 // simple names (e.g., C++ conversion functions). 4476 if (!FnInfo) 4477 return false; 4478 4479 CheckAbsoluteValueFunction(TheCall, FDecl); 4480 CheckMaxUnsignedZero(TheCall, FDecl); 4481 4482 if (getLangOpts().ObjC) 4483 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4484 4485 unsigned CMId = FDecl->getMemoryFunctionKind(); 4486 if (CMId == 0) 4487 return false; 4488 4489 // Handle memory setting and copying functions. 4490 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4491 CheckStrlcpycatArguments(TheCall, FnInfo); 4492 else if (CMId == Builtin::BIstrncat) 4493 CheckStrncatArguments(TheCall, FnInfo); 4494 else 4495 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4496 4497 return false; 4498 } 4499 4500 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4501 ArrayRef<const Expr *> Args) { 4502 VariadicCallType CallType = 4503 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4504 4505 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4506 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4507 CallType); 4508 4509 return false; 4510 } 4511 4512 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4513 const FunctionProtoType *Proto) { 4514 QualType Ty; 4515 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4516 Ty = V->getType().getNonReferenceType(); 4517 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4518 Ty = F->getType().getNonReferenceType(); 4519 else 4520 return false; 4521 4522 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4523 !Ty->isFunctionProtoType()) 4524 return false; 4525 4526 VariadicCallType CallType; 4527 if (!Proto || !Proto->isVariadic()) { 4528 CallType = VariadicDoesNotApply; 4529 } else if (Ty->isBlockPointerType()) { 4530 CallType = VariadicBlock; 4531 } else { // Ty->isFunctionPointerType() 4532 CallType = VariadicFunction; 4533 } 4534 4535 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4536 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4537 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4538 TheCall->getCallee()->getSourceRange(), CallType); 4539 4540 return false; 4541 } 4542 4543 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4544 /// such as function pointers returned from functions. 4545 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4546 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4547 TheCall->getCallee()); 4548 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4549 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4550 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4551 TheCall->getCallee()->getSourceRange(), CallType); 4552 4553 return false; 4554 } 4555 4556 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4557 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4558 return false; 4559 4560 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4561 switch (Op) { 4562 case AtomicExpr::AO__c11_atomic_init: 4563 case AtomicExpr::AO__opencl_atomic_init: 4564 llvm_unreachable("There is no ordering argument for an init"); 4565 4566 case AtomicExpr::AO__c11_atomic_load: 4567 case AtomicExpr::AO__opencl_atomic_load: 4568 case AtomicExpr::AO__atomic_load_n: 4569 case AtomicExpr::AO__atomic_load: 4570 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4571 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4572 4573 case AtomicExpr::AO__c11_atomic_store: 4574 case AtomicExpr::AO__opencl_atomic_store: 4575 case AtomicExpr::AO__atomic_store: 4576 case AtomicExpr::AO__atomic_store_n: 4577 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4578 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4579 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4580 4581 default: 4582 return true; 4583 } 4584 } 4585 4586 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4587 AtomicExpr::AtomicOp Op) { 4588 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4589 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4590 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4591 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4592 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4593 Op); 4594 } 4595 4596 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4597 SourceLocation RParenLoc, MultiExprArg Args, 4598 AtomicExpr::AtomicOp Op, 4599 AtomicArgumentOrder ArgOrder) { 4600 // All the non-OpenCL operations take one of the following forms. 4601 // The OpenCL operations take the __c11 forms with one extra argument for 4602 // synchronization scope. 4603 enum { 4604 // C __c11_atomic_init(A *, C) 4605 Init, 4606 4607 // C __c11_atomic_load(A *, int) 4608 Load, 4609 4610 // void __atomic_load(A *, CP, int) 4611 LoadCopy, 4612 4613 // void __atomic_store(A *, CP, int) 4614 Copy, 4615 4616 // C __c11_atomic_add(A *, M, int) 4617 Arithmetic, 4618 4619 // C __atomic_exchange_n(A *, CP, int) 4620 Xchg, 4621 4622 // void __atomic_exchange(A *, C *, CP, int) 4623 GNUXchg, 4624 4625 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4626 C11CmpXchg, 4627 4628 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4629 GNUCmpXchg 4630 } Form = Init; 4631 4632 const unsigned NumForm = GNUCmpXchg + 1; 4633 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4634 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4635 // where: 4636 // C is an appropriate type, 4637 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4638 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4639 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4640 // the int parameters are for orderings. 4641 4642 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4643 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4644 "need to update code for modified forms"); 4645 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4646 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4647 AtomicExpr::AO__atomic_load, 4648 "need to update code for modified C11 atomics"); 4649 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4650 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4651 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4652 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4653 IsOpenCL; 4654 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4655 Op == AtomicExpr::AO__atomic_store_n || 4656 Op == AtomicExpr::AO__atomic_exchange_n || 4657 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4658 bool IsAddSub = false; 4659 4660 switch (Op) { 4661 case AtomicExpr::AO__c11_atomic_init: 4662 case AtomicExpr::AO__opencl_atomic_init: 4663 Form = Init; 4664 break; 4665 4666 case AtomicExpr::AO__c11_atomic_load: 4667 case AtomicExpr::AO__opencl_atomic_load: 4668 case AtomicExpr::AO__atomic_load_n: 4669 Form = Load; 4670 break; 4671 4672 case AtomicExpr::AO__atomic_load: 4673 Form = LoadCopy; 4674 break; 4675 4676 case AtomicExpr::AO__c11_atomic_store: 4677 case AtomicExpr::AO__opencl_atomic_store: 4678 case AtomicExpr::AO__atomic_store: 4679 case AtomicExpr::AO__atomic_store_n: 4680 Form = Copy; 4681 break; 4682 4683 case AtomicExpr::AO__c11_atomic_fetch_add: 4684 case AtomicExpr::AO__c11_atomic_fetch_sub: 4685 case AtomicExpr::AO__opencl_atomic_fetch_add: 4686 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4687 case AtomicExpr::AO__atomic_fetch_add: 4688 case AtomicExpr::AO__atomic_fetch_sub: 4689 case AtomicExpr::AO__atomic_add_fetch: 4690 case AtomicExpr::AO__atomic_sub_fetch: 4691 IsAddSub = true; 4692 LLVM_FALLTHROUGH; 4693 case AtomicExpr::AO__c11_atomic_fetch_and: 4694 case AtomicExpr::AO__c11_atomic_fetch_or: 4695 case AtomicExpr::AO__c11_atomic_fetch_xor: 4696 case AtomicExpr::AO__opencl_atomic_fetch_and: 4697 case AtomicExpr::AO__opencl_atomic_fetch_or: 4698 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4699 case AtomicExpr::AO__atomic_fetch_and: 4700 case AtomicExpr::AO__atomic_fetch_or: 4701 case AtomicExpr::AO__atomic_fetch_xor: 4702 case AtomicExpr::AO__atomic_fetch_nand: 4703 case AtomicExpr::AO__atomic_and_fetch: 4704 case AtomicExpr::AO__atomic_or_fetch: 4705 case AtomicExpr::AO__atomic_xor_fetch: 4706 case AtomicExpr::AO__atomic_nand_fetch: 4707 case AtomicExpr::AO__c11_atomic_fetch_min: 4708 case AtomicExpr::AO__c11_atomic_fetch_max: 4709 case AtomicExpr::AO__opencl_atomic_fetch_min: 4710 case AtomicExpr::AO__opencl_atomic_fetch_max: 4711 case AtomicExpr::AO__atomic_min_fetch: 4712 case AtomicExpr::AO__atomic_max_fetch: 4713 case AtomicExpr::AO__atomic_fetch_min: 4714 case AtomicExpr::AO__atomic_fetch_max: 4715 Form = Arithmetic; 4716 break; 4717 4718 case AtomicExpr::AO__c11_atomic_exchange: 4719 case AtomicExpr::AO__opencl_atomic_exchange: 4720 case AtomicExpr::AO__atomic_exchange_n: 4721 Form = Xchg; 4722 break; 4723 4724 case AtomicExpr::AO__atomic_exchange: 4725 Form = GNUXchg; 4726 break; 4727 4728 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4729 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4730 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4731 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4732 Form = C11CmpXchg; 4733 break; 4734 4735 case AtomicExpr::AO__atomic_compare_exchange: 4736 case AtomicExpr::AO__atomic_compare_exchange_n: 4737 Form = GNUCmpXchg; 4738 break; 4739 } 4740 4741 unsigned AdjustedNumArgs = NumArgs[Form]; 4742 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4743 ++AdjustedNumArgs; 4744 // Check we have the right number of arguments. 4745 if (Args.size() < AdjustedNumArgs) { 4746 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4747 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4748 << ExprRange; 4749 return ExprError(); 4750 } else if (Args.size() > AdjustedNumArgs) { 4751 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4752 diag::err_typecheck_call_too_many_args) 4753 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4754 << ExprRange; 4755 return ExprError(); 4756 } 4757 4758 // Inspect the first argument of the atomic operation. 4759 Expr *Ptr = Args[0]; 4760 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4761 if (ConvertedPtr.isInvalid()) 4762 return ExprError(); 4763 4764 Ptr = ConvertedPtr.get(); 4765 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4766 if (!pointerType) { 4767 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4768 << Ptr->getType() << Ptr->getSourceRange(); 4769 return ExprError(); 4770 } 4771 4772 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4773 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4774 QualType ValType = AtomTy; // 'C' 4775 if (IsC11) { 4776 if (!AtomTy->isAtomicType()) { 4777 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4778 << Ptr->getType() << Ptr->getSourceRange(); 4779 return ExprError(); 4780 } 4781 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4782 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4783 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4784 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4785 << Ptr->getSourceRange(); 4786 return ExprError(); 4787 } 4788 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4789 } else if (Form != Load && Form != LoadCopy) { 4790 if (ValType.isConstQualified()) { 4791 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4792 << Ptr->getType() << Ptr->getSourceRange(); 4793 return ExprError(); 4794 } 4795 } 4796 4797 // For an arithmetic operation, the implied arithmetic must be well-formed. 4798 if (Form == Arithmetic) { 4799 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4800 if (IsAddSub && !ValType->isIntegerType() 4801 && !ValType->isPointerType()) { 4802 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4803 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4804 return ExprError(); 4805 } 4806 if (!IsAddSub && !ValType->isIntegerType()) { 4807 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4808 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4809 return ExprError(); 4810 } 4811 if (IsC11 && ValType->isPointerType() && 4812 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4813 diag::err_incomplete_type)) { 4814 return ExprError(); 4815 } 4816 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4817 // For __atomic_*_n operations, the value type must be a scalar integral or 4818 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4819 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4820 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4821 return ExprError(); 4822 } 4823 4824 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4825 !AtomTy->isScalarType()) { 4826 // For GNU atomics, require a trivially-copyable type. This is not part of 4827 // the GNU atomics specification, but we enforce it for sanity. 4828 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4829 << Ptr->getType() << Ptr->getSourceRange(); 4830 return ExprError(); 4831 } 4832 4833 switch (ValType.getObjCLifetime()) { 4834 case Qualifiers::OCL_None: 4835 case Qualifiers::OCL_ExplicitNone: 4836 // okay 4837 break; 4838 4839 case Qualifiers::OCL_Weak: 4840 case Qualifiers::OCL_Strong: 4841 case Qualifiers::OCL_Autoreleasing: 4842 // FIXME: Can this happen? By this point, ValType should be known 4843 // to be trivially copyable. 4844 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4845 << ValType << Ptr->getSourceRange(); 4846 return ExprError(); 4847 } 4848 4849 // All atomic operations have an overload which takes a pointer to a volatile 4850 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4851 // into the result or the other operands. Similarly atomic_load takes a 4852 // pointer to a const 'A'. 4853 ValType.removeLocalVolatile(); 4854 ValType.removeLocalConst(); 4855 QualType ResultType = ValType; 4856 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4857 Form == Init) 4858 ResultType = Context.VoidTy; 4859 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4860 ResultType = Context.BoolTy; 4861 4862 // The type of a parameter passed 'by value'. In the GNU atomics, such 4863 // arguments are actually passed as pointers. 4864 QualType ByValType = ValType; // 'CP' 4865 bool IsPassedByAddress = false; 4866 if (!IsC11 && !IsN) { 4867 ByValType = Ptr->getType(); 4868 IsPassedByAddress = true; 4869 } 4870 4871 SmallVector<Expr *, 5> APIOrderedArgs; 4872 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4873 APIOrderedArgs.push_back(Args[0]); 4874 switch (Form) { 4875 case Init: 4876 case Load: 4877 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4878 break; 4879 case LoadCopy: 4880 case Copy: 4881 case Arithmetic: 4882 case Xchg: 4883 APIOrderedArgs.push_back(Args[2]); // Val1 4884 APIOrderedArgs.push_back(Args[1]); // Order 4885 break; 4886 case GNUXchg: 4887 APIOrderedArgs.push_back(Args[2]); // Val1 4888 APIOrderedArgs.push_back(Args[3]); // Val2 4889 APIOrderedArgs.push_back(Args[1]); // Order 4890 break; 4891 case C11CmpXchg: 4892 APIOrderedArgs.push_back(Args[2]); // Val1 4893 APIOrderedArgs.push_back(Args[4]); // Val2 4894 APIOrderedArgs.push_back(Args[1]); // Order 4895 APIOrderedArgs.push_back(Args[3]); // OrderFail 4896 break; 4897 case GNUCmpXchg: 4898 APIOrderedArgs.push_back(Args[2]); // Val1 4899 APIOrderedArgs.push_back(Args[4]); // Val2 4900 APIOrderedArgs.push_back(Args[5]); // Weak 4901 APIOrderedArgs.push_back(Args[1]); // Order 4902 APIOrderedArgs.push_back(Args[3]); // OrderFail 4903 break; 4904 } 4905 } else 4906 APIOrderedArgs.append(Args.begin(), Args.end()); 4907 4908 // The first argument's non-CV pointer type is used to deduce the type of 4909 // subsequent arguments, except for: 4910 // - weak flag (always converted to bool) 4911 // - memory order (always converted to int) 4912 // - scope (always converted to int) 4913 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4914 QualType Ty; 4915 if (i < NumVals[Form] + 1) { 4916 switch (i) { 4917 case 0: 4918 // The first argument is always a pointer. It has a fixed type. 4919 // It is always dereferenced, a nullptr is undefined. 4920 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4921 // Nothing else to do: we already know all we want about this pointer. 4922 continue; 4923 case 1: 4924 // The second argument is the non-atomic operand. For arithmetic, this 4925 // is always passed by value, and for a compare_exchange it is always 4926 // passed by address. For the rest, GNU uses by-address and C11 uses 4927 // by-value. 4928 assert(Form != Load); 4929 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4930 Ty = ValType; 4931 else if (Form == Copy || Form == Xchg) { 4932 if (IsPassedByAddress) { 4933 // The value pointer is always dereferenced, a nullptr is undefined. 4934 CheckNonNullArgument(*this, APIOrderedArgs[i], 4935 ExprRange.getBegin()); 4936 } 4937 Ty = ByValType; 4938 } else if (Form == Arithmetic) 4939 Ty = Context.getPointerDiffType(); 4940 else { 4941 Expr *ValArg = APIOrderedArgs[i]; 4942 // The value pointer is always dereferenced, a nullptr is undefined. 4943 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4944 LangAS AS = LangAS::Default; 4945 // Keep address space of non-atomic pointer type. 4946 if (const PointerType *PtrTy = 4947 ValArg->getType()->getAs<PointerType>()) { 4948 AS = PtrTy->getPointeeType().getAddressSpace(); 4949 } 4950 Ty = Context.getPointerType( 4951 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4952 } 4953 break; 4954 case 2: 4955 // The third argument to compare_exchange / GNU exchange is the desired 4956 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4957 if (IsPassedByAddress) 4958 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4959 Ty = ByValType; 4960 break; 4961 case 3: 4962 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4963 Ty = Context.BoolTy; 4964 break; 4965 } 4966 } else { 4967 // The order(s) and scope are always converted to int. 4968 Ty = Context.IntTy; 4969 } 4970 4971 InitializedEntity Entity = 4972 InitializedEntity::InitializeParameter(Context, Ty, false); 4973 ExprResult Arg = APIOrderedArgs[i]; 4974 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4975 if (Arg.isInvalid()) 4976 return true; 4977 APIOrderedArgs[i] = Arg.get(); 4978 } 4979 4980 // Permute the arguments into a 'consistent' order. 4981 SmallVector<Expr*, 5> SubExprs; 4982 SubExprs.push_back(Ptr); 4983 switch (Form) { 4984 case Init: 4985 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4986 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4987 break; 4988 case Load: 4989 SubExprs.push_back(APIOrderedArgs[1]); // Order 4990 break; 4991 case LoadCopy: 4992 case Copy: 4993 case Arithmetic: 4994 case Xchg: 4995 SubExprs.push_back(APIOrderedArgs[2]); // Order 4996 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4997 break; 4998 case GNUXchg: 4999 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5000 SubExprs.push_back(APIOrderedArgs[3]); // Order 5001 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5002 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5003 break; 5004 case C11CmpXchg: 5005 SubExprs.push_back(APIOrderedArgs[3]); // Order 5006 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5007 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5008 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5009 break; 5010 case GNUCmpXchg: 5011 SubExprs.push_back(APIOrderedArgs[4]); // Order 5012 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5013 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5014 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5015 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5016 break; 5017 } 5018 5019 if (SubExprs.size() >= 2 && Form != Init) { 5020 if (Optional<llvm::APSInt> Result = 5021 SubExprs[1]->getIntegerConstantExpr(Context)) 5022 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5023 Diag(SubExprs[1]->getBeginLoc(), 5024 diag::warn_atomic_op_has_invalid_memory_order) 5025 << SubExprs[1]->getSourceRange(); 5026 } 5027 5028 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5029 auto *Scope = Args[Args.size() - 1]; 5030 if (Optional<llvm::APSInt> Result = 5031 Scope->getIntegerConstantExpr(Context)) { 5032 if (!ScopeModel->isValid(Result->getZExtValue())) 5033 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5034 << Scope->getSourceRange(); 5035 } 5036 SubExprs.push_back(Scope); 5037 } 5038 5039 AtomicExpr *AE = new (Context) 5040 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5041 5042 if ((Op == AtomicExpr::AO__c11_atomic_load || 5043 Op == AtomicExpr::AO__c11_atomic_store || 5044 Op == AtomicExpr::AO__opencl_atomic_load || 5045 Op == AtomicExpr::AO__opencl_atomic_store ) && 5046 Context.AtomicUsesUnsupportedLibcall(AE)) 5047 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5048 << ((Op == AtomicExpr::AO__c11_atomic_load || 5049 Op == AtomicExpr::AO__opencl_atomic_load) 5050 ? 0 5051 : 1); 5052 5053 return AE; 5054 } 5055 5056 /// checkBuiltinArgument - Given a call to a builtin function, perform 5057 /// normal type-checking on the given argument, updating the call in 5058 /// place. This is useful when a builtin function requires custom 5059 /// type-checking for some of its arguments but not necessarily all of 5060 /// them. 5061 /// 5062 /// Returns true on error. 5063 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5064 FunctionDecl *Fn = E->getDirectCallee(); 5065 assert(Fn && "builtin call without direct callee!"); 5066 5067 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5068 InitializedEntity Entity = 5069 InitializedEntity::InitializeParameter(S.Context, Param); 5070 5071 ExprResult Arg = E->getArg(0); 5072 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5073 if (Arg.isInvalid()) 5074 return true; 5075 5076 E->setArg(ArgIndex, Arg.get()); 5077 return false; 5078 } 5079 5080 /// We have a call to a function like __sync_fetch_and_add, which is an 5081 /// overloaded function based on the pointer type of its first argument. 5082 /// The main BuildCallExpr routines have already promoted the types of 5083 /// arguments because all of these calls are prototyped as void(...). 5084 /// 5085 /// This function goes through and does final semantic checking for these 5086 /// builtins, as well as generating any warnings. 5087 ExprResult 5088 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5089 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5090 Expr *Callee = TheCall->getCallee(); 5091 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5092 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5093 5094 // Ensure that we have at least one argument to do type inference from. 5095 if (TheCall->getNumArgs() < 1) { 5096 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5097 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5098 return ExprError(); 5099 } 5100 5101 // Inspect the first argument of the atomic builtin. This should always be 5102 // a pointer type, whose element is an integral scalar or pointer type. 5103 // Because it is a pointer type, we don't have to worry about any implicit 5104 // casts here. 5105 // FIXME: We don't allow floating point scalars as input. 5106 Expr *FirstArg = TheCall->getArg(0); 5107 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5108 if (FirstArgResult.isInvalid()) 5109 return ExprError(); 5110 FirstArg = FirstArgResult.get(); 5111 TheCall->setArg(0, FirstArg); 5112 5113 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5114 if (!pointerType) { 5115 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5116 << FirstArg->getType() << FirstArg->getSourceRange(); 5117 return ExprError(); 5118 } 5119 5120 QualType ValType = pointerType->getPointeeType(); 5121 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5122 !ValType->isBlockPointerType()) { 5123 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5124 << FirstArg->getType() << FirstArg->getSourceRange(); 5125 return ExprError(); 5126 } 5127 5128 if (ValType.isConstQualified()) { 5129 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5130 << FirstArg->getType() << FirstArg->getSourceRange(); 5131 return ExprError(); 5132 } 5133 5134 switch (ValType.getObjCLifetime()) { 5135 case Qualifiers::OCL_None: 5136 case Qualifiers::OCL_ExplicitNone: 5137 // okay 5138 break; 5139 5140 case Qualifiers::OCL_Weak: 5141 case Qualifiers::OCL_Strong: 5142 case Qualifiers::OCL_Autoreleasing: 5143 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5144 << ValType << FirstArg->getSourceRange(); 5145 return ExprError(); 5146 } 5147 5148 // Strip any qualifiers off ValType. 5149 ValType = ValType.getUnqualifiedType(); 5150 5151 // The majority of builtins return a value, but a few have special return 5152 // types, so allow them to override appropriately below. 5153 QualType ResultType = ValType; 5154 5155 // We need to figure out which concrete builtin this maps onto. For example, 5156 // __sync_fetch_and_add with a 2 byte object turns into 5157 // __sync_fetch_and_add_2. 5158 #define BUILTIN_ROW(x) \ 5159 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5160 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5161 5162 static const unsigned BuiltinIndices[][5] = { 5163 BUILTIN_ROW(__sync_fetch_and_add), 5164 BUILTIN_ROW(__sync_fetch_and_sub), 5165 BUILTIN_ROW(__sync_fetch_and_or), 5166 BUILTIN_ROW(__sync_fetch_and_and), 5167 BUILTIN_ROW(__sync_fetch_and_xor), 5168 BUILTIN_ROW(__sync_fetch_and_nand), 5169 5170 BUILTIN_ROW(__sync_add_and_fetch), 5171 BUILTIN_ROW(__sync_sub_and_fetch), 5172 BUILTIN_ROW(__sync_and_and_fetch), 5173 BUILTIN_ROW(__sync_or_and_fetch), 5174 BUILTIN_ROW(__sync_xor_and_fetch), 5175 BUILTIN_ROW(__sync_nand_and_fetch), 5176 5177 BUILTIN_ROW(__sync_val_compare_and_swap), 5178 BUILTIN_ROW(__sync_bool_compare_and_swap), 5179 BUILTIN_ROW(__sync_lock_test_and_set), 5180 BUILTIN_ROW(__sync_lock_release), 5181 BUILTIN_ROW(__sync_swap) 5182 }; 5183 #undef BUILTIN_ROW 5184 5185 // Determine the index of the size. 5186 unsigned SizeIndex; 5187 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5188 case 1: SizeIndex = 0; break; 5189 case 2: SizeIndex = 1; break; 5190 case 4: SizeIndex = 2; break; 5191 case 8: SizeIndex = 3; break; 5192 case 16: SizeIndex = 4; break; 5193 default: 5194 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5195 << FirstArg->getType() << FirstArg->getSourceRange(); 5196 return ExprError(); 5197 } 5198 5199 // Each of these builtins has one pointer argument, followed by some number of 5200 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5201 // that we ignore. Find out which row of BuiltinIndices to read from as well 5202 // as the number of fixed args. 5203 unsigned BuiltinID = FDecl->getBuiltinID(); 5204 unsigned BuiltinIndex, NumFixed = 1; 5205 bool WarnAboutSemanticsChange = false; 5206 switch (BuiltinID) { 5207 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5208 case Builtin::BI__sync_fetch_and_add: 5209 case Builtin::BI__sync_fetch_and_add_1: 5210 case Builtin::BI__sync_fetch_and_add_2: 5211 case Builtin::BI__sync_fetch_and_add_4: 5212 case Builtin::BI__sync_fetch_and_add_8: 5213 case Builtin::BI__sync_fetch_and_add_16: 5214 BuiltinIndex = 0; 5215 break; 5216 5217 case Builtin::BI__sync_fetch_and_sub: 5218 case Builtin::BI__sync_fetch_and_sub_1: 5219 case Builtin::BI__sync_fetch_and_sub_2: 5220 case Builtin::BI__sync_fetch_and_sub_4: 5221 case Builtin::BI__sync_fetch_and_sub_8: 5222 case Builtin::BI__sync_fetch_and_sub_16: 5223 BuiltinIndex = 1; 5224 break; 5225 5226 case Builtin::BI__sync_fetch_and_or: 5227 case Builtin::BI__sync_fetch_and_or_1: 5228 case Builtin::BI__sync_fetch_and_or_2: 5229 case Builtin::BI__sync_fetch_and_or_4: 5230 case Builtin::BI__sync_fetch_and_or_8: 5231 case Builtin::BI__sync_fetch_and_or_16: 5232 BuiltinIndex = 2; 5233 break; 5234 5235 case Builtin::BI__sync_fetch_and_and: 5236 case Builtin::BI__sync_fetch_and_and_1: 5237 case Builtin::BI__sync_fetch_and_and_2: 5238 case Builtin::BI__sync_fetch_and_and_4: 5239 case Builtin::BI__sync_fetch_and_and_8: 5240 case Builtin::BI__sync_fetch_and_and_16: 5241 BuiltinIndex = 3; 5242 break; 5243 5244 case Builtin::BI__sync_fetch_and_xor: 5245 case Builtin::BI__sync_fetch_and_xor_1: 5246 case Builtin::BI__sync_fetch_and_xor_2: 5247 case Builtin::BI__sync_fetch_and_xor_4: 5248 case Builtin::BI__sync_fetch_and_xor_8: 5249 case Builtin::BI__sync_fetch_and_xor_16: 5250 BuiltinIndex = 4; 5251 break; 5252 5253 case Builtin::BI__sync_fetch_and_nand: 5254 case Builtin::BI__sync_fetch_and_nand_1: 5255 case Builtin::BI__sync_fetch_and_nand_2: 5256 case Builtin::BI__sync_fetch_and_nand_4: 5257 case Builtin::BI__sync_fetch_and_nand_8: 5258 case Builtin::BI__sync_fetch_and_nand_16: 5259 BuiltinIndex = 5; 5260 WarnAboutSemanticsChange = true; 5261 break; 5262 5263 case Builtin::BI__sync_add_and_fetch: 5264 case Builtin::BI__sync_add_and_fetch_1: 5265 case Builtin::BI__sync_add_and_fetch_2: 5266 case Builtin::BI__sync_add_and_fetch_4: 5267 case Builtin::BI__sync_add_and_fetch_8: 5268 case Builtin::BI__sync_add_and_fetch_16: 5269 BuiltinIndex = 6; 5270 break; 5271 5272 case Builtin::BI__sync_sub_and_fetch: 5273 case Builtin::BI__sync_sub_and_fetch_1: 5274 case Builtin::BI__sync_sub_and_fetch_2: 5275 case Builtin::BI__sync_sub_and_fetch_4: 5276 case Builtin::BI__sync_sub_and_fetch_8: 5277 case Builtin::BI__sync_sub_and_fetch_16: 5278 BuiltinIndex = 7; 5279 break; 5280 5281 case Builtin::BI__sync_and_and_fetch: 5282 case Builtin::BI__sync_and_and_fetch_1: 5283 case Builtin::BI__sync_and_and_fetch_2: 5284 case Builtin::BI__sync_and_and_fetch_4: 5285 case Builtin::BI__sync_and_and_fetch_8: 5286 case Builtin::BI__sync_and_and_fetch_16: 5287 BuiltinIndex = 8; 5288 break; 5289 5290 case Builtin::BI__sync_or_and_fetch: 5291 case Builtin::BI__sync_or_and_fetch_1: 5292 case Builtin::BI__sync_or_and_fetch_2: 5293 case Builtin::BI__sync_or_and_fetch_4: 5294 case Builtin::BI__sync_or_and_fetch_8: 5295 case Builtin::BI__sync_or_and_fetch_16: 5296 BuiltinIndex = 9; 5297 break; 5298 5299 case Builtin::BI__sync_xor_and_fetch: 5300 case Builtin::BI__sync_xor_and_fetch_1: 5301 case Builtin::BI__sync_xor_and_fetch_2: 5302 case Builtin::BI__sync_xor_and_fetch_4: 5303 case Builtin::BI__sync_xor_and_fetch_8: 5304 case Builtin::BI__sync_xor_and_fetch_16: 5305 BuiltinIndex = 10; 5306 break; 5307 5308 case Builtin::BI__sync_nand_and_fetch: 5309 case Builtin::BI__sync_nand_and_fetch_1: 5310 case Builtin::BI__sync_nand_and_fetch_2: 5311 case Builtin::BI__sync_nand_and_fetch_4: 5312 case Builtin::BI__sync_nand_and_fetch_8: 5313 case Builtin::BI__sync_nand_and_fetch_16: 5314 BuiltinIndex = 11; 5315 WarnAboutSemanticsChange = true; 5316 break; 5317 5318 case Builtin::BI__sync_val_compare_and_swap: 5319 case Builtin::BI__sync_val_compare_and_swap_1: 5320 case Builtin::BI__sync_val_compare_and_swap_2: 5321 case Builtin::BI__sync_val_compare_and_swap_4: 5322 case Builtin::BI__sync_val_compare_and_swap_8: 5323 case Builtin::BI__sync_val_compare_and_swap_16: 5324 BuiltinIndex = 12; 5325 NumFixed = 2; 5326 break; 5327 5328 case Builtin::BI__sync_bool_compare_and_swap: 5329 case Builtin::BI__sync_bool_compare_and_swap_1: 5330 case Builtin::BI__sync_bool_compare_and_swap_2: 5331 case Builtin::BI__sync_bool_compare_and_swap_4: 5332 case Builtin::BI__sync_bool_compare_and_swap_8: 5333 case Builtin::BI__sync_bool_compare_and_swap_16: 5334 BuiltinIndex = 13; 5335 NumFixed = 2; 5336 ResultType = Context.BoolTy; 5337 break; 5338 5339 case Builtin::BI__sync_lock_test_and_set: 5340 case Builtin::BI__sync_lock_test_and_set_1: 5341 case Builtin::BI__sync_lock_test_and_set_2: 5342 case Builtin::BI__sync_lock_test_and_set_4: 5343 case Builtin::BI__sync_lock_test_and_set_8: 5344 case Builtin::BI__sync_lock_test_and_set_16: 5345 BuiltinIndex = 14; 5346 break; 5347 5348 case Builtin::BI__sync_lock_release: 5349 case Builtin::BI__sync_lock_release_1: 5350 case Builtin::BI__sync_lock_release_2: 5351 case Builtin::BI__sync_lock_release_4: 5352 case Builtin::BI__sync_lock_release_8: 5353 case Builtin::BI__sync_lock_release_16: 5354 BuiltinIndex = 15; 5355 NumFixed = 0; 5356 ResultType = Context.VoidTy; 5357 break; 5358 5359 case Builtin::BI__sync_swap: 5360 case Builtin::BI__sync_swap_1: 5361 case Builtin::BI__sync_swap_2: 5362 case Builtin::BI__sync_swap_4: 5363 case Builtin::BI__sync_swap_8: 5364 case Builtin::BI__sync_swap_16: 5365 BuiltinIndex = 16; 5366 break; 5367 } 5368 5369 // Now that we know how many fixed arguments we expect, first check that we 5370 // have at least that many. 5371 if (TheCall->getNumArgs() < 1+NumFixed) { 5372 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5373 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5374 << Callee->getSourceRange(); 5375 return ExprError(); 5376 } 5377 5378 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5379 << Callee->getSourceRange(); 5380 5381 if (WarnAboutSemanticsChange) { 5382 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5383 << Callee->getSourceRange(); 5384 } 5385 5386 // Get the decl for the concrete builtin from this, we can tell what the 5387 // concrete integer type we should convert to is. 5388 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5389 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5390 FunctionDecl *NewBuiltinDecl; 5391 if (NewBuiltinID == BuiltinID) 5392 NewBuiltinDecl = FDecl; 5393 else { 5394 // Perform builtin lookup to avoid redeclaring it. 5395 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5396 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5397 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5398 assert(Res.getFoundDecl()); 5399 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5400 if (!NewBuiltinDecl) 5401 return ExprError(); 5402 } 5403 5404 // The first argument --- the pointer --- has a fixed type; we 5405 // deduce the types of the rest of the arguments accordingly. Walk 5406 // the remaining arguments, converting them to the deduced value type. 5407 for (unsigned i = 0; i != NumFixed; ++i) { 5408 ExprResult Arg = TheCall->getArg(i+1); 5409 5410 // GCC does an implicit conversion to the pointer or integer ValType. This 5411 // can fail in some cases (1i -> int**), check for this error case now. 5412 // Initialize the argument. 5413 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5414 ValType, /*consume*/ false); 5415 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5416 if (Arg.isInvalid()) 5417 return ExprError(); 5418 5419 // Okay, we have something that *can* be converted to the right type. Check 5420 // to see if there is a potentially weird extension going on here. This can 5421 // happen when you do an atomic operation on something like an char* and 5422 // pass in 42. The 42 gets converted to char. This is even more strange 5423 // for things like 45.123 -> char, etc. 5424 // FIXME: Do this check. 5425 TheCall->setArg(i+1, Arg.get()); 5426 } 5427 5428 // Create a new DeclRefExpr to refer to the new decl. 5429 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5430 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5431 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5432 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5433 5434 // Set the callee in the CallExpr. 5435 // FIXME: This loses syntactic information. 5436 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5437 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5438 CK_BuiltinFnToFnPtr); 5439 TheCall->setCallee(PromotedCall.get()); 5440 5441 // Change the result type of the call to match the original value type. This 5442 // is arbitrary, but the codegen for these builtins ins design to handle it 5443 // gracefully. 5444 TheCall->setType(ResultType); 5445 5446 // Prohibit use of _ExtInt with atomic builtins. 5447 // The arguments would have already been converted to the first argument's 5448 // type, so only need to check the first argument. 5449 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5450 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5451 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5452 return ExprError(); 5453 } 5454 5455 return TheCallResult; 5456 } 5457 5458 /// SemaBuiltinNontemporalOverloaded - We have a call to 5459 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5460 /// overloaded function based on the pointer type of its last argument. 5461 /// 5462 /// This function goes through and does final semantic checking for these 5463 /// builtins. 5464 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5465 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5466 DeclRefExpr *DRE = 5467 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5468 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5469 unsigned BuiltinID = FDecl->getBuiltinID(); 5470 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5471 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5472 "Unexpected nontemporal load/store builtin!"); 5473 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5474 unsigned numArgs = isStore ? 2 : 1; 5475 5476 // Ensure that we have the proper number of arguments. 5477 if (checkArgCount(*this, TheCall, numArgs)) 5478 return ExprError(); 5479 5480 // Inspect the last argument of the nontemporal builtin. This should always 5481 // be a pointer type, from which we imply the type of the memory access. 5482 // Because it is a pointer type, we don't have to worry about any implicit 5483 // casts here. 5484 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5485 ExprResult PointerArgResult = 5486 DefaultFunctionArrayLvalueConversion(PointerArg); 5487 5488 if (PointerArgResult.isInvalid()) 5489 return ExprError(); 5490 PointerArg = PointerArgResult.get(); 5491 TheCall->setArg(numArgs - 1, PointerArg); 5492 5493 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5494 if (!pointerType) { 5495 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5496 << PointerArg->getType() << PointerArg->getSourceRange(); 5497 return ExprError(); 5498 } 5499 5500 QualType ValType = pointerType->getPointeeType(); 5501 5502 // Strip any qualifiers off ValType. 5503 ValType = ValType.getUnqualifiedType(); 5504 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5505 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5506 !ValType->isVectorType()) { 5507 Diag(DRE->getBeginLoc(), 5508 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5509 << PointerArg->getType() << PointerArg->getSourceRange(); 5510 return ExprError(); 5511 } 5512 5513 if (!isStore) { 5514 TheCall->setType(ValType); 5515 return TheCallResult; 5516 } 5517 5518 ExprResult ValArg = TheCall->getArg(0); 5519 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5520 Context, ValType, /*consume*/ false); 5521 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5522 if (ValArg.isInvalid()) 5523 return ExprError(); 5524 5525 TheCall->setArg(0, ValArg.get()); 5526 TheCall->setType(Context.VoidTy); 5527 return TheCallResult; 5528 } 5529 5530 /// CheckObjCString - Checks that the argument to the builtin 5531 /// CFString constructor is correct 5532 /// Note: It might also make sense to do the UTF-16 conversion here (would 5533 /// simplify the backend). 5534 bool Sema::CheckObjCString(Expr *Arg) { 5535 Arg = Arg->IgnoreParenCasts(); 5536 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5537 5538 if (!Literal || !Literal->isAscii()) { 5539 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5540 << Arg->getSourceRange(); 5541 return true; 5542 } 5543 5544 if (Literal->containsNonAsciiOrNull()) { 5545 StringRef String = Literal->getString(); 5546 unsigned NumBytes = String.size(); 5547 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5548 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5549 llvm::UTF16 *ToPtr = &ToBuf[0]; 5550 5551 llvm::ConversionResult Result = 5552 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5553 ToPtr + NumBytes, llvm::strictConversion); 5554 // Check for conversion failure. 5555 if (Result != llvm::conversionOK) 5556 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5557 << Arg->getSourceRange(); 5558 } 5559 return false; 5560 } 5561 5562 /// CheckObjCString - Checks that the format string argument to the os_log() 5563 /// and os_trace() functions is correct, and converts it to const char *. 5564 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5565 Arg = Arg->IgnoreParenCasts(); 5566 auto *Literal = dyn_cast<StringLiteral>(Arg); 5567 if (!Literal) { 5568 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5569 Literal = ObjcLiteral->getString(); 5570 } 5571 } 5572 5573 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5574 return ExprError( 5575 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5576 << Arg->getSourceRange()); 5577 } 5578 5579 ExprResult Result(Literal); 5580 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5581 InitializedEntity Entity = 5582 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5583 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5584 return Result; 5585 } 5586 5587 /// Check that the user is calling the appropriate va_start builtin for the 5588 /// target and calling convention. 5589 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5590 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5591 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5592 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5593 TT.getArch() == llvm::Triple::aarch64_32); 5594 bool IsWindows = TT.isOSWindows(); 5595 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5596 if (IsX64 || IsAArch64) { 5597 CallingConv CC = CC_C; 5598 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5599 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5600 if (IsMSVAStart) { 5601 // Don't allow this in System V ABI functions. 5602 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5603 return S.Diag(Fn->getBeginLoc(), 5604 diag::err_ms_va_start_used_in_sysv_function); 5605 } else { 5606 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5607 // On x64 Windows, don't allow this in System V ABI functions. 5608 // (Yes, that means there's no corresponding way to support variadic 5609 // System V ABI functions on Windows.) 5610 if ((IsWindows && CC == CC_X86_64SysV) || 5611 (!IsWindows && CC == CC_Win64)) 5612 return S.Diag(Fn->getBeginLoc(), 5613 diag::err_va_start_used_in_wrong_abi_function) 5614 << !IsWindows; 5615 } 5616 return false; 5617 } 5618 5619 if (IsMSVAStart) 5620 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5621 return false; 5622 } 5623 5624 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5625 ParmVarDecl **LastParam = nullptr) { 5626 // Determine whether the current function, block, or obj-c method is variadic 5627 // and get its parameter list. 5628 bool IsVariadic = false; 5629 ArrayRef<ParmVarDecl *> Params; 5630 DeclContext *Caller = S.CurContext; 5631 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5632 IsVariadic = Block->isVariadic(); 5633 Params = Block->parameters(); 5634 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5635 IsVariadic = FD->isVariadic(); 5636 Params = FD->parameters(); 5637 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5638 IsVariadic = MD->isVariadic(); 5639 // FIXME: This isn't correct for methods (results in bogus warning). 5640 Params = MD->parameters(); 5641 } else if (isa<CapturedDecl>(Caller)) { 5642 // We don't support va_start in a CapturedDecl. 5643 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5644 return true; 5645 } else { 5646 // This must be some other declcontext that parses exprs. 5647 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5648 return true; 5649 } 5650 5651 if (!IsVariadic) { 5652 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5653 return true; 5654 } 5655 5656 if (LastParam) 5657 *LastParam = Params.empty() ? nullptr : Params.back(); 5658 5659 return false; 5660 } 5661 5662 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5663 /// for validity. Emit an error and return true on failure; return false 5664 /// on success. 5665 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5666 Expr *Fn = TheCall->getCallee(); 5667 5668 if (checkVAStartABI(*this, BuiltinID, Fn)) 5669 return true; 5670 5671 if (checkArgCount(*this, TheCall, 2)) 5672 return true; 5673 5674 // Type-check the first argument normally. 5675 if (checkBuiltinArgument(*this, TheCall, 0)) 5676 return true; 5677 5678 // Check that the current function is variadic, and get its last parameter. 5679 ParmVarDecl *LastParam; 5680 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5681 return true; 5682 5683 // Verify that the second argument to the builtin is the last argument of the 5684 // current function or method. 5685 bool SecondArgIsLastNamedArgument = false; 5686 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5687 5688 // These are valid if SecondArgIsLastNamedArgument is false after the next 5689 // block. 5690 QualType Type; 5691 SourceLocation ParamLoc; 5692 bool IsCRegister = false; 5693 5694 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5695 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5696 SecondArgIsLastNamedArgument = PV == LastParam; 5697 5698 Type = PV->getType(); 5699 ParamLoc = PV->getLocation(); 5700 IsCRegister = 5701 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5702 } 5703 } 5704 5705 if (!SecondArgIsLastNamedArgument) 5706 Diag(TheCall->getArg(1)->getBeginLoc(), 5707 diag::warn_second_arg_of_va_start_not_last_named_param); 5708 else if (IsCRegister || Type->isReferenceType() || 5709 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5710 // Promotable integers are UB, but enumerations need a bit of 5711 // extra checking to see what their promotable type actually is. 5712 if (!Type->isPromotableIntegerType()) 5713 return false; 5714 if (!Type->isEnumeralType()) 5715 return true; 5716 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5717 return !(ED && 5718 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5719 }()) { 5720 unsigned Reason = 0; 5721 if (Type->isReferenceType()) Reason = 1; 5722 else if (IsCRegister) Reason = 2; 5723 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5724 Diag(ParamLoc, diag::note_parameter_type) << Type; 5725 } 5726 5727 TheCall->setType(Context.VoidTy); 5728 return false; 5729 } 5730 5731 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5732 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5733 // const char *named_addr); 5734 5735 Expr *Func = Call->getCallee(); 5736 5737 if (Call->getNumArgs() < 3) 5738 return Diag(Call->getEndLoc(), 5739 diag::err_typecheck_call_too_few_args_at_least) 5740 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5741 5742 // Type-check the first argument normally. 5743 if (checkBuiltinArgument(*this, Call, 0)) 5744 return true; 5745 5746 // Check that the current function is variadic. 5747 if (checkVAStartIsInVariadicFunction(*this, Func)) 5748 return true; 5749 5750 // __va_start on Windows does not validate the parameter qualifiers 5751 5752 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5753 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5754 5755 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5756 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5757 5758 const QualType &ConstCharPtrTy = 5759 Context.getPointerType(Context.CharTy.withConst()); 5760 if (!Arg1Ty->isPointerType() || 5761 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5762 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5763 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5764 << 0 /* qualifier difference */ 5765 << 3 /* parameter mismatch */ 5766 << 2 << Arg1->getType() << ConstCharPtrTy; 5767 5768 const QualType SizeTy = Context.getSizeType(); 5769 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5770 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5771 << Arg2->getType() << SizeTy << 1 /* different class */ 5772 << 0 /* qualifier difference */ 5773 << 3 /* parameter mismatch */ 5774 << 3 << Arg2->getType() << SizeTy; 5775 5776 return false; 5777 } 5778 5779 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5780 /// friends. This is declared to take (...), so we have to check everything. 5781 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5782 if (checkArgCount(*this, TheCall, 2)) 5783 return true; 5784 5785 ExprResult OrigArg0 = TheCall->getArg(0); 5786 ExprResult OrigArg1 = TheCall->getArg(1); 5787 5788 // Do standard promotions between the two arguments, returning their common 5789 // type. 5790 QualType Res = UsualArithmeticConversions( 5791 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5792 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5793 return true; 5794 5795 // Make sure any conversions are pushed back into the call; this is 5796 // type safe since unordered compare builtins are declared as "_Bool 5797 // foo(...)". 5798 TheCall->setArg(0, OrigArg0.get()); 5799 TheCall->setArg(1, OrigArg1.get()); 5800 5801 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5802 return false; 5803 5804 // If the common type isn't a real floating type, then the arguments were 5805 // invalid for this operation. 5806 if (Res.isNull() || !Res->isRealFloatingType()) 5807 return Diag(OrigArg0.get()->getBeginLoc(), 5808 diag::err_typecheck_call_invalid_ordered_compare) 5809 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5810 << SourceRange(OrigArg0.get()->getBeginLoc(), 5811 OrigArg1.get()->getEndLoc()); 5812 5813 return false; 5814 } 5815 5816 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5817 /// __builtin_isnan and friends. This is declared to take (...), so we have 5818 /// to check everything. We expect the last argument to be a floating point 5819 /// value. 5820 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5821 if (checkArgCount(*this, TheCall, NumArgs)) 5822 return true; 5823 5824 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5825 // on all preceding parameters just being int. Try all of those. 5826 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5827 Expr *Arg = TheCall->getArg(i); 5828 5829 if (Arg->isTypeDependent()) 5830 return false; 5831 5832 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5833 5834 if (Res.isInvalid()) 5835 return true; 5836 TheCall->setArg(i, Res.get()); 5837 } 5838 5839 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5840 5841 if (OrigArg->isTypeDependent()) 5842 return false; 5843 5844 // Usual Unary Conversions will convert half to float, which we want for 5845 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5846 // type how it is, but do normal L->Rvalue conversions. 5847 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5848 OrigArg = UsualUnaryConversions(OrigArg).get(); 5849 else 5850 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5851 TheCall->setArg(NumArgs - 1, OrigArg); 5852 5853 // This operation requires a non-_Complex floating-point number. 5854 if (!OrigArg->getType()->isRealFloatingType()) 5855 return Diag(OrigArg->getBeginLoc(), 5856 diag::err_typecheck_call_invalid_unary_fp) 5857 << OrigArg->getType() << OrigArg->getSourceRange(); 5858 5859 return false; 5860 } 5861 5862 /// Perform semantic analysis for a call to __builtin_complex. 5863 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 5864 if (checkArgCount(*this, TheCall, 2)) 5865 return true; 5866 5867 bool Dependent = false; 5868 for (unsigned I = 0; I != 2; ++I) { 5869 Expr *Arg = TheCall->getArg(I); 5870 QualType T = Arg->getType(); 5871 if (T->isDependentType()) { 5872 Dependent = true; 5873 continue; 5874 } 5875 5876 // Despite supporting _Complex int, GCC requires a real floating point type 5877 // for the operands of __builtin_complex. 5878 if (!T->isRealFloatingType()) { 5879 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 5880 << Arg->getType() << Arg->getSourceRange(); 5881 } 5882 5883 ExprResult Converted = DefaultLvalueConversion(Arg); 5884 if (Converted.isInvalid()) 5885 return true; 5886 TheCall->setArg(I, Converted.get()); 5887 } 5888 5889 if (Dependent) { 5890 TheCall->setType(Context.DependentTy); 5891 return false; 5892 } 5893 5894 Expr *Real = TheCall->getArg(0); 5895 Expr *Imag = TheCall->getArg(1); 5896 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 5897 return Diag(Real->getBeginLoc(), 5898 diag::err_typecheck_call_different_arg_types) 5899 << Real->getType() << Imag->getType() 5900 << Real->getSourceRange() << Imag->getSourceRange(); 5901 } 5902 5903 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 5904 // don't allow this builtin to form those types either. 5905 // FIXME: Should we allow these types? 5906 if (Real->getType()->isFloat16Type()) 5907 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 5908 << "_Float16"; 5909 if (Real->getType()->isHalfType()) 5910 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 5911 << "half"; 5912 5913 TheCall->setType(Context.getComplexType(Real->getType())); 5914 return false; 5915 } 5916 5917 // Customized Sema Checking for VSX builtins that have the following signature: 5918 // vector [...] builtinName(vector [...], vector [...], const int); 5919 // Which takes the same type of vectors (any legal vector type) for the first 5920 // two arguments and takes compile time constant for the third argument. 5921 // Example builtins are : 5922 // vector double vec_xxpermdi(vector double, vector double, int); 5923 // vector short vec_xxsldwi(vector short, vector short, int); 5924 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5925 unsigned ExpectedNumArgs = 3; 5926 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 5927 return true; 5928 5929 // Check the third argument is a compile time constant 5930 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 5931 return Diag(TheCall->getBeginLoc(), 5932 diag::err_vsx_builtin_nonconstant_argument) 5933 << 3 /* argument index */ << TheCall->getDirectCallee() 5934 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5935 TheCall->getArg(2)->getEndLoc()); 5936 5937 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5938 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5939 5940 // Check the type of argument 1 and argument 2 are vectors. 5941 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5942 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5943 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5944 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5945 << TheCall->getDirectCallee() 5946 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5947 TheCall->getArg(1)->getEndLoc()); 5948 } 5949 5950 // Check the first two arguments are the same type. 5951 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5952 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5953 << TheCall->getDirectCallee() 5954 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5955 TheCall->getArg(1)->getEndLoc()); 5956 } 5957 5958 // When default clang type checking is turned off and the customized type 5959 // checking is used, the returning type of the function must be explicitly 5960 // set. Otherwise it is _Bool by default. 5961 TheCall->setType(Arg1Ty); 5962 5963 return false; 5964 } 5965 5966 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5967 // This is declared to take (...), so we have to check everything. 5968 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5969 if (TheCall->getNumArgs() < 2) 5970 return ExprError(Diag(TheCall->getEndLoc(), 5971 diag::err_typecheck_call_too_few_args_at_least) 5972 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5973 << TheCall->getSourceRange()); 5974 5975 // Determine which of the following types of shufflevector we're checking: 5976 // 1) unary, vector mask: (lhs, mask) 5977 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5978 QualType resType = TheCall->getArg(0)->getType(); 5979 unsigned numElements = 0; 5980 5981 if (!TheCall->getArg(0)->isTypeDependent() && 5982 !TheCall->getArg(1)->isTypeDependent()) { 5983 QualType LHSType = TheCall->getArg(0)->getType(); 5984 QualType RHSType = TheCall->getArg(1)->getType(); 5985 5986 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5987 return ExprError( 5988 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5989 << TheCall->getDirectCallee() 5990 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5991 TheCall->getArg(1)->getEndLoc())); 5992 5993 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5994 unsigned numResElements = TheCall->getNumArgs() - 2; 5995 5996 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5997 // with mask. If so, verify that RHS is an integer vector type with the 5998 // same number of elts as lhs. 5999 if (TheCall->getNumArgs() == 2) { 6000 if (!RHSType->hasIntegerRepresentation() || 6001 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6002 return ExprError(Diag(TheCall->getBeginLoc(), 6003 diag::err_vec_builtin_incompatible_vector) 6004 << TheCall->getDirectCallee() 6005 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6006 TheCall->getArg(1)->getEndLoc())); 6007 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6008 return ExprError(Diag(TheCall->getBeginLoc(), 6009 diag::err_vec_builtin_incompatible_vector) 6010 << TheCall->getDirectCallee() 6011 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6012 TheCall->getArg(1)->getEndLoc())); 6013 } else if (numElements != numResElements) { 6014 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6015 resType = Context.getVectorType(eltType, numResElements, 6016 VectorType::GenericVector); 6017 } 6018 } 6019 6020 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6021 if (TheCall->getArg(i)->isTypeDependent() || 6022 TheCall->getArg(i)->isValueDependent()) 6023 continue; 6024 6025 Optional<llvm::APSInt> Result; 6026 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6027 return ExprError(Diag(TheCall->getBeginLoc(), 6028 diag::err_shufflevector_nonconstant_argument) 6029 << TheCall->getArg(i)->getSourceRange()); 6030 6031 // Allow -1 which will be translated to undef in the IR. 6032 if (Result->isSigned() && Result->isAllOnesValue()) 6033 continue; 6034 6035 if (Result->getActiveBits() > 64 || 6036 Result->getZExtValue() >= numElements * 2) 6037 return ExprError(Diag(TheCall->getBeginLoc(), 6038 diag::err_shufflevector_argument_too_large) 6039 << TheCall->getArg(i)->getSourceRange()); 6040 } 6041 6042 SmallVector<Expr*, 32> exprs; 6043 6044 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6045 exprs.push_back(TheCall->getArg(i)); 6046 TheCall->setArg(i, nullptr); 6047 } 6048 6049 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6050 TheCall->getCallee()->getBeginLoc(), 6051 TheCall->getRParenLoc()); 6052 } 6053 6054 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6055 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6056 SourceLocation BuiltinLoc, 6057 SourceLocation RParenLoc) { 6058 ExprValueKind VK = VK_RValue; 6059 ExprObjectKind OK = OK_Ordinary; 6060 QualType DstTy = TInfo->getType(); 6061 QualType SrcTy = E->getType(); 6062 6063 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6064 return ExprError(Diag(BuiltinLoc, 6065 diag::err_convertvector_non_vector) 6066 << E->getSourceRange()); 6067 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6068 return ExprError(Diag(BuiltinLoc, 6069 diag::err_convertvector_non_vector_type)); 6070 6071 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6072 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6073 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6074 if (SrcElts != DstElts) 6075 return ExprError(Diag(BuiltinLoc, 6076 diag::err_convertvector_incompatible_vector) 6077 << E->getSourceRange()); 6078 } 6079 6080 return new (Context) 6081 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6082 } 6083 6084 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6085 // This is declared to take (const void*, ...) and can take two 6086 // optional constant int args. 6087 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6088 unsigned NumArgs = TheCall->getNumArgs(); 6089 6090 if (NumArgs > 3) 6091 return Diag(TheCall->getEndLoc(), 6092 diag::err_typecheck_call_too_many_args_at_most) 6093 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6094 6095 // Argument 0 is checked for us and the remaining arguments must be 6096 // constant integers. 6097 for (unsigned i = 1; i != NumArgs; ++i) 6098 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6099 return true; 6100 6101 return false; 6102 } 6103 6104 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6105 // __assume does not evaluate its arguments, and should warn if its argument 6106 // has side effects. 6107 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6108 Expr *Arg = TheCall->getArg(0); 6109 if (Arg->isInstantiationDependent()) return false; 6110 6111 if (Arg->HasSideEffects(Context)) 6112 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6113 << Arg->getSourceRange() 6114 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6115 6116 return false; 6117 } 6118 6119 /// Handle __builtin_alloca_with_align. This is declared 6120 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6121 /// than 8. 6122 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6123 // The alignment must be a constant integer. 6124 Expr *Arg = TheCall->getArg(1); 6125 6126 // We can't check the value of a dependent argument. 6127 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6128 if (const auto *UE = 6129 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6130 if (UE->getKind() == UETT_AlignOf || 6131 UE->getKind() == UETT_PreferredAlignOf) 6132 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6133 << Arg->getSourceRange(); 6134 6135 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6136 6137 if (!Result.isPowerOf2()) 6138 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6139 << Arg->getSourceRange(); 6140 6141 if (Result < Context.getCharWidth()) 6142 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6143 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6144 6145 if (Result > std::numeric_limits<int32_t>::max()) 6146 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6147 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6148 } 6149 6150 return false; 6151 } 6152 6153 /// Handle __builtin_assume_aligned. This is declared 6154 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6155 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6156 unsigned NumArgs = TheCall->getNumArgs(); 6157 6158 if (NumArgs > 3) 6159 return Diag(TheCall->getEndLoc(), 6160 diag::err_typecheck_call_too_many_args_at_most) 6161 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6162 6163 // The alignment must be a constant integer. 6164 Expr *Arg = TheCall->getArg(1); 6165 6166 // We can't check the value of a dependent argument. 6167 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6168 llvm::APSInt Result; 6169 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6170 return true; 6171 6172 if (!Result.isPowerOf2()) 6173 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6174 << Arg->getSourceRange(); 6175 6176 if (Result > Sema::MaximumAlignment) 6177 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6178 << Arg->getSourceRange() << Sema::MaximumAlignment; 6179 } 6180 6181 if (NumArgs > 2) { 6182 ExprResult Arg(TheCall->getArg(2)); 6183 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6184 Context.getSizeType(), false); 6185 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6186 if (Arg.isInvalid()) return true; 6187 TheCall->setArg(2, Arg.get()); 6188 } 6189 6190 return false; 6191 } 6192 6193 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6194 unsigned BuiltinID = 6195 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6196 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6197 6198 unsigned NumArgs = TheCall->getNumArgs(); 6199 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6200 if (NumArgs < NumRequiredArgs) { 6201 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6202 << 0 /* function call */ << NumRequiredArgs << NumArgs 6203 << TheCall->getSourceRange(); 6204 } 6205 if (NumArgs >= NumRequiredArgs + 0x100) { 6206 return Diag(TheCall->getEndLoc(), 6207 diag::err_typecheck_call_too_many_args_at_most) 6208 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6209 << TheCall->getSourceRange(); 6210 } 6211 unsigned i = 0; 6212 6213 // For formatting call, check buffer arg. 6214 if (!IsSizeCall) { 6215 ExprResult Arg(TheCall->getArg(i)); 6216 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6217 Context, Context.VoidPtrTy, false); 6218 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6219 if (Arg.isInvalid()) 6220 return true; 6221 TheCall->setArg(i, Arg.get()); 6222 i++; 6223 } 6224 6225 // Check string literal arg. 6226 unsigned FormatIdx = i; 6227 { 6228 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6229 if (Arg.isInvalid()) 6230 return true; 6231 TheCall->setArg(i, Arg.get()); 6232 i++; 6233 } 6234 6235 // Make sure variadic args are scalar. 6236 unsigned FirstDataArg = i; 6237 while (i < NumArgs) { 6238 ExprResult Arg = DefaultVariadicArgumentPromotion( 6239 TheCall->getArg(i), VariadicFunction, nullptr); 6240 if (Arg.isInvalid()) 6241 return true; 6242 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6243 if (ArgSize.getQuantity() >= 0x100) { 6244 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6245 << i << (int)ArgSize.getQuantity() << 0xff 6246 << TheCall->getSourceRange(); 6247 } 6248 TheCall->setArg(i, Arg.get()); 6249 i++; 6250 } 6251 6252 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6253 // call to avoid duplicate diagnostics. 6254 if (!IsSizeCall) { 6255 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6256 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6257 bool Success = CheckFormatArguments( 6258 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6259 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6260 CheckedVarArgs); 6261 if (!Success) 6262 return true; 6263 } 6264 6265 if (IsSizeCall) { 6266 TheCall->setType(Context.getSizeType()); 6267 } else { 6268 TheCall->setType(Context.VoidPtrTy); 6269 } 6270 return false; 6271 } 6272 6273 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6274 /// TheCall is a constant expression. 6275 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6276 llvm::APSInt &Result) { 6277 Expr *Arg = TheCall->getArg(ArgNum); 6278 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6279 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6280 6281 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6282 6283 Optional<llvm::APSInt> R; 6284 if (!(R = Arg->getIntegerConstantExpr(Context))) 6285 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6286 << FDecl->getDeclName() << Arg->getSourceRange(); 6287 Result = *R; 6288 return false; 6289 } 6290 6291 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6292 /// TheCall is a constant expression in the range [Low, High]. 6293 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6294 int Low, int High, bool RangeIsError) { 6295 if (isConstantEvaluated()) 6296 return false; 6297 llvm::APSInt Result; 6298 6299 // We can't check the value of a dependent argument. 6300 Expr *Arg = TheCall->getArg(ArgNum); 6301 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6302 return false; 6303 6304 // Check constant-ness first. 6305 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6306 return true; 6307 6308 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6309 if (RangeIsError) 6310 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6311 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6312 else 6313 // Defer the warning until we know if the code will be emitted so that 6314 // dead code can ignore this. 6315 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6316 PDiag(diag::warn_argument_invalid_range) 6317 << Result.toString(10) << Low << High 6318 << Arg->getSourceRange()); 6319 } 6320 6321 return false; 6322 } 6323 6324 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6325 /// TheCall is a constant expression is a multiple of Num.. 6326 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6327 unsigned Num) { 6328 llvm::APSInt Result; 6329 6330 // We can't check the value of a dependent argument. 6331 Expr *Arg = TheCall->getArg(ArgNum); 6332 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6333 return false; 6334 6335 // Check constant-ness first. 6336 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6337 return true; 6338 6339 if (Result.getSExtValue() % Num != 0) 6340 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6341 << Num << Arg->getSourceRange(); 6342 6343 return false; 6344 } 6345 6346 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6347 /// constant expression representing a power of 2. 6348 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6349 llvm::APSInt Result; 6350 6351 // We can't check the value of a dependent argument. 6352 Expr *Arg = TheCall->getArg(ArgNum); 6353 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6354 return false; 6355 6356 // Check constant-ness first. 6357 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6358 return true; 6359 6360 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6361 // and only if x is a power of 2. 6362 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6363 return false; 6364 6365 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6366 << Arg->getSourceRange(); 6367 } 6368 6369 static bool IsShiftedByte(llvm::APSInt Value) { 6370 if (Value.isNegative()) 6371 return false; 6372 6373 // Check if it's a shifted byte, by shifting it down 6374 while (true) { 6375 // If the value fits in the bottom byte, the check passes. 6376 if (Value < 0x100) 6377 return true; 6378 6379 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6380 // fails. 6381 if ((Value & 0xFF) != 0) 6382 return false; 6383 6384 // If the bottom 8 bits are all 0, but something above that is nonzero, 6385 // then shifting the value right by 8 bits won't affect whether it's a 6386 // shifted byte or not. So do that, and go round again. 6387 Value >>= 8; 6388 } 6389 } 6390 6391 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6392 /// a constant expression representing an arbitrary byte value shifted left by 6393 /// a multiple of 8 bits. 6394 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6395 unsigned ArgBits) { 6396 llvm::APSInt Result; 6397 6398 // We can't check the value of a dependent argument. 6399 Expr *Arg = TheCall->getArg(ArgNum); 6400 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6401 return false; 6402 6403 // Check constant-ness first. 6404 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6405 return true; 6406 6407 // Truncate to the given size. 6408 Result = Result.getLoBits(ArgBits); 6409 Result.setIsUnsigned(true); 6410 6411 if (IsShiftedByte(Result)) 6412 return false; 6413 6414 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6415 << Arg->getSourceRange(); 6416 } 6417 6418 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6419 /// TheCall is a constant expression representing either a shifted byte value, 6420 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6421 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6422 /// Arm MVE intrinsics. 6423 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6424 int ArgNum, 6425 unsigned ArgBits) { 6426 llvm::APSInt Result; 6427 6428 // We can't check the value of a dependent argument. 6429 Expr *Arg = TheCall->getArg(ArgNum); 6430 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6431 return false; 6432 6433 // Check constant-ness first. 6434 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6435 return true; 6436 6437 // Truncate to the given size. 6438 Result = Result.getLoBits(ArgBits); 6439 Result.setIsUnsigned(true); 6440 6441 // Check to see if it's in either of the required forms. 6442 if (IsShiftedByte(Result) || 6443 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6444 return false; 6445 6446 return Diag(TheCall->getBeginLoc(), 6447 diag::err_argument_not_shifted_byte_or_xxff) 6448 << Arg->getSourceRange(); 6449 } 6450 6451 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6452 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6453 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6454 if (checkArgCount(*this, TheCall, 2)) 6455 return true; 6456 Expr *Arg0 = TheCall->getArg(0); 6457 Expr *Arg1 = TheCall->getArg(1); 6458 6459 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6460 if (FirstArg.isInvalid()) 6461 return true; 6462 QualType FirstArgType = FirstArg.get()->getType(); 6463 if (!FirstArgType->isAnyPointerType()) 6464 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6465 << "first" << FirstArgType << Arg0->getSourceRange(); 6466 TheCall->setArg(0, FirstArg.get()); 6467 6468 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6469 if (SecArg.isInvalid()) 6470 return true; 6471 QualType SecArgType = SecArg.get()->getType(); 6472 if (!SecArgType->isIntegerType()) 6473 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6474 << "second" << SecArgType << Arg1->getSourceRange(); 6475 6476 // Derive the return type from the pointer argument. 6477 TheCall->setType(FirstArgType); 6478 return false; 6479 } 6480 6481 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6482 if (checkArgCount(*this, TheCall, 2)) 6483 return true; 6484 6485 Expr *Arg0 = TheCall->getArg(0); 6486 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6487 if (FirstArg.isInvalid()) 6488 return true; 6489 QualType FirstArgType = FirstArg.get()->getType(); 6490 if (!FirstArgType->isAnyPointerType()) 6491 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6492 << "first" << FirstArgType << Arg0->getSourceRange(); 6493 TheCall->setArg(0, FirstArg.get()); 6494 6495 // Derive the return type from the pointer argument. 6496 TheCall->setType(FirstArgType); 6497 6498 // Second arg must be an constant in range [0,15] 6499 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6500 } 6501 6502 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6503 if (checkArgCount(*this, TheCall, 2)) 6504 return true; 6505 Expr *Arg0 = TheCall->getArg(0); 6506 Expr *Arg1 = TheCall->getArg(1); 6507 6508 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6509 if (FirstArg.isInvalid()) 6510 return true; 6511 QualType FirstArgType = FirstArg.get()->getType(); 6512 if (!FirstArgType->isAnyPointerType()) 6513 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6514 << "first" << FirstArgType << Arg0->getSourceRange(); 6515 6516 QualType SecArgType = Arg1->getType(); 6517 if (!SecArgType->isIntegerType()) 6518 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6519 << "second" << SecArgType << Arg1->getSourceRange(); 6520 TheCall->setType(Context.IntTy); 6521 return false; 6522 } 6523 6524 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6525 BuiltinID == AArch64::BI__builtin_arm_stg) { 6526 if (checkArgCount(*this, TheCall, 1)) 6527 return true; 6528 Expr *Arg0 = TheCall->getArg(0); 6529 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6530 if (FirstArg.isInvalid()) 6531 return true; 6532 6533 QualType FirstArgType = FirstArg.get()->getType(); 6534 if (!FirstArgType->isAnyPointerType()) 6535 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6536 << "first" << FirstArgType << Arg0->getSourceRange(); 6537 TheCall->setArg(0, FirstArg.get()); 6538 6539 // Derive the return type from the pointer argument. 6540 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6541 TheCall->setType(FirstArgType); 6542 return false; 6543 } 6544 6545 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6546 Expr *ArgA = TheCall->getArg(0); 6547 Expr *ArgB = TheCall->getArg(1); 6548 6549 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6550 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6551 6552 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6553 return true; 6554 6555 QualType ArgTypeA = ArgExprA.get()->getType(); 6556 QualType ArgTypeB = ArgExprB.get()->getType(); 6557 6558 auto isNull = [&] (Expr *E) -> bool { 6559 return E->isNullPointerConstant( 6560 Context, Expr::NPC_ValueDependentIsNotNull); }; 6561 6562 // argument should be either a pointer or null 6563 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6564 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6565 << "first" << ArgTypeA << ArgA->getSourceRange(); 6566 6567 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6568 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6569 << "second" << ArgTypeB << ArgB->getSourceRange(); 6570 6571 // Ensure Pointee types are compatible 6572 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6573 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6574 QualType pointeeA = ArgTypeA->getPointeeType(); 6575 QualType pointeeB = ArgTypeB->getPointeeType(); 6576 if (!Context.typesAreCompatible( 6577 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6578 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6579 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6580 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6581 << ArgB->getSourceRange(); 6582 } 6583 } 6584 6585 // at least one argument should be pointer type 6586 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6587 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6588 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6589 6590 if (isNull(ArgA)) // adopt type of the other pointer 6591 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6592 6593 if (isNull(ArgB)) 6594 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6595 6596 TheCall->setArg(0, ArgExprA.get()); 6597 TheCall->setArg(1, ArgExprB.get()); 6598 TheCall->setType(Context.LongLongTy); 6599 return false; 6600 } 6601 assert(false && "Unhandled ARM MTE intrinsic"); 6602 return true; 6603 } 6604 6605 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6606 /// TheCall is an ARM/AArch64 special register string literal. 6607 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6608 int ArgNum, unsigned ExpectedFieldNum, 6609 bool AllowName) { 6610 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6611 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6612 BuiltinID == ARM::BI__builtin_arm_rsr || 6613 BuiltinID == ARM::BI__builtin_arm_rsrp || 6614 BuiltinID == ARM::BI__builtin_arm_wsr || 6615 BuiltinID == ARM::BI__builtin_arm_wsrp; 6616 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6617 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6618 BuiltinID == AArch64::BI__builtin_arm_rsr || 6619 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6620 BuiltinID == AArch64::BI__builtin_arm_wsr || 6621 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6622 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6623 6624 // We can't check the value of a dependent argument. 6625 Expr *Arg = TheCall->getArg(ArgNum); 6626 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6627 return false; 6628 6629 // Check if the argument is a string literal. 6630 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6631 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6632 << Arg->getSourceRange(); 6633 6634 // Check the type of special register given. 6635 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6636 SmallVector<StringRef, 6> Fields; 6637 Reg.split(Fields, ":"); 6638 6639 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6640 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6641 << Arg->getSourceRange(); 6642 6643 // If the string is the name of a register then we cannot check that it is 6644 // valid here but if the string is of one the forms described in ACLE then we 6645 // can check that the supplied fields are integers and within the valid 6646 // ranges. 6647 if (Fields.size() > 1) { 6648 bool FiveFields = Fields.size() == 5; 6649 6650 bool ValidString = true; 6651 if (IsARMBuiltin) { 6652 ValidString &= Fields[0].startswith_lower("cp") || 6653 Fields[0].startswith_lower("p"); 6654 if (ValidString) 6655 Fields[0] = 6656 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6657 6658 ValidString &= Fields[2].startswith_lower("c"); 6659 if (ValidString) 6660 Fields[2] = Fields[2].drop_front(1); 6661 6662 if (FiveFields) { 6663 ValidString &= Fields[3].startswith_lower("c"); 6664 if (ValidString) 6665 Fields[3] = Fields[3].drop_front(1); 6666 } 6667 } 6668 6669 SmallVector<int, 5> Ranges; 6670 if (FiveFields) 6671 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6672 else 6673 Ranges.append({15, 7, 15}); 6674 6675 for (unsigned i=0; i<Fields.size(); ++i) { 6676 int IntField; 6677 ValidString &= !Fields[i].getAsInteger(10, IntField); 6678 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6679 } 6680 6681 if (!ValidString) 6682 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6683 << Arg->getSourceRange(); 6684 } else if (IsAArch64Builtin && Fields.size() == 1) { 6685 // If the register name is one of those that appear in the condition below 6686 // and the special register builtin being used is one of the write builtins, 6687 // then we require that the argument provided for writing to the register 6688 // is an integer constant expression. This is because it will be lowered to 6689 // an MSR (immediate) instruction, so we need to know the immediate at 6690 // compile time. 6691 if (TheCall->getNumArgs() != 2) 6692 return false; 6693 6694 std::string RegLower = Reg.lower(); 6695 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6696 RegLower != "pan" && RegLower != "uao") 6697 return false; 6698 6699 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6700 } 6701 6702 return false; 6703 } 6704 6705 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6706 /// This checks that the target supports __builtin_longjmp and 6707 /// that val is a constant 1. 6708 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6709 if (!Context.getTargetInfo().hasSjLjLowering()) 6710 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6711 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6712 6713 Expr *Arg = TheCall->getArg(1); 6714 llvm::APSInt Result; 6715 6716 // TODO: This is less than ideal. Overload this to take a value. 6717 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6718 return true; 6719 6720 if (Result != 1) 6721 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6722 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6723 6724 return false; 6725 } 6726 6727 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6728 /// This checks that the target supports __builtin_setjmp. 6729 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6730 if (!Context.getTargetInfo().hasSjLjLowering()) 6731 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6732 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6733 return false; 6734 } 6735 6736 namespace { 6737 6738 class UncoveredArgHandler { 6739 enum { Unknown = -1, AllCovered = -2 }; 6740 6741 signed FirstUncoveredArg = Unknown; 6742 SmallVector<const Expr *, 4> DiagnosticExprs; 6743 6744 public: 6745 UncoveredArgHandler() = default; 6746 6747 bool hasUncoveredArg() const { 6748 return (FirstUncoveredArg >= 0); 6749 } 6750 6751 unsigned getUncoveredArg() const { 6752 assert(hasUncoveredArg() && "no uncovered argument"); 6753 return FirstUncoveredArg; 6754 } 6755 6756 void setAllCovered() { 6757 // A string has been found with all arguments covered, so clear out 6758 // the diagnostics. 6759 DiagnosticExprs.clear(); 6760 FirstUncoveredArg = AllCovered; 6761 } 6762 6763 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6764 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6765 6766 // Don't update if a previous string covers all arguments. 6767 if (FirstUncoveredArg == AllCovered) 6768 return; 6769 6770 // UncoveredArgHandler tracks the highest uncovered argument index 6771 // and with it all the strings that match this index. 6772 if (NewFirstUncoveredArg == FirstUncoveredArg) 6773 DiagnosticExprs.push_back(StrExpr); 6774 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6775 DiagnosticExprs.clear(); 6776 DiagnosticExprs.push_back(StrExpr); 6777 FirstUncoveredArg = NewFirstUncoveredArg; 6778 } 6779 } 6780 6781 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6782 }; 6783 6784 enum StringLiteralCheckType { 6785 SLCT_NotALiteral, 6786 SLCT_UncheckedLiteral, 6787 SLCT_CheckedLiteral 6788 }; 6789 6790 } // namespace 6791 6792 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6793 BinaryOperatorKind BinOpKind, 6794 bool AddendIsRight) { 6795 unsigned BitWidth = Offset.getBitWidth(); 6796 unsigned AddendBitWidth = Addend.getBitWidth(); 6797 // There might be negative interim results. 6798 if (Addend.isUnsigned()) { 6799 Addend = Addend.zext(++AddendBitWidth); 6800 Addend.setIsSigned(true); 6801 } 6802 // Adjust the bit width of the APSInts. 6803 if (AddendBitWidth > BitWidth) { 6804 Offset = Offset.sext(AddendBitWidth); 6805 BitWidth = AddendBitWidth; 6806 } else if (BitWidth > AddendBitWidth) { 6807 Addend = Addend.sext(BitWidth); 6808 } 6809 6810 bool Ov = false; 6811 llvm::APSInt ResOffset = Offset; 6812 if (BinOpKind == BO_Add) 6813 ResOffset = Offset.sadd_ov(Addend, Ov); 6814 else { 6815 assert(AddendIsRight && BinOpKind == BO_Sub && 6816 "operator must be add or sub with addend on the right"); 6817 ResOffset = Offset.ssub_ov(Addend, Ov); 6818 } 6819 6820 // We add an offset to a pointer here so we should support an offset as big as 6821 // possible. 6822 if (Ov) { 6823 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6824 "index (intermediate) result too big"); 6825 Offset = Offset.sext(2 * BitWidth); 6826 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6827 return; 6828 } 6829 6830 Offset = ResOffset; 6831 } 6832 6833 namespace { 6834 6835 // This is a wrapper class around StringLiteral to support offsetted string 6836 // literals as format strings. It takes the offset into account when returning 6837 // the string and its length or the source locations to display notes correctly. 6838 class FormatStringLiteral { 6839 const StringLiteral *FExpr; 6840 int64_t Offset; 6841 6842 public: 6843 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6844 : FExpr(fexpr), Offset(Offset) {} 6845 6846 StringRef getString() const { 6847 return FExpr->getString().drop_front(Offset); 6848 } 6849 6850 unsigned getByteLength() const { 6851 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6852 } 6853 6854 unsigned getLength() const { return FExpr->getLength() - Offset; } 6855 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6856 6857 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6858 6859 QualType getType() const { return FExpr->getType(); } 6860 6861 bool isAscii() const { return FExpr->isAscii(); } 6862 bool isWide() const { return FExpr->isWide(); } 6863 bool isUTF8() const { return FExpr->isUTF8(); } 6864 bool isUTF16() const { return FExpr->isUTF16(); } 6865 bool isUTF32() const { return FExpr->isUTF32(); } 6866 bool isPascal() const { return FExpr->isPascal(); } 6867 6868 SourceLocation getLocationOfByte( 6869 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6870 const TargetInfo &Target, unsigned *StartToken = nullptr, 6871 unsigned *StartTokenByteOffset = nullptr) const { 6872 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6873 StartToken, StartTokenByteOffset); 6874 } 6875 6876 SourceLocation getBeginLoc() const LLVM_READONLY { 6877 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6878 } 6879 6880 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6881 }; 6882 6883 } // namespace 6884 6885 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6886 const Expr *OrigFormatExpr, 6887 ArrayRef<const Expr *> Args, 6888 bool HasVAListArg, unsigned format_idx, 6889 unsigned firstDataArg, 6890 Sema::FormatStringType Type, 6891 bool inFunctionCall, 6892 Sema::VariadicCallType CallType, 6893 llvm::SmallBitVector &CheckedVarArgs, 6894 UncoveredArgHandler &UncoveredArg, 6895 bool IgnoreStringsWithoutSpecifiers); 6896 6897 // Determine if an expression is a string literal or constant string. 6898 // If this function returns false on the arguments to a function expecting a 6899 // format string, we will usually need to emit a warning. 6900 // True string literals are then checked by CheckFormatString. 6901 static StringLiteralCheckType 6902 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6903 bool HasVAListArg, unsigned format_idx, 6904 unsigned firstDataArg, Sema::FormatStringType Type, 6905 Sema::VariadicCallType CallType, bool InFunctionCall, 6906 llvm::SmallBitVector &CheckedVarArgs, 6907 UncoveredArgHandler &UncoveredArg, 6908 llvm::APSInt Offset, 6909 bool IgnoreStringsWithoutSpecifiers = false) { 6910 if (S.isConstantEvaluated()) 6911 return SLCT_NotALiteral; 6912 tryAgain: 6913 assert(Offset.isSigned() && "invalid offset"); 6914 6915 if (E->isTypeDependent() || E->isValueDependent()) 6916 return SLCT_NotALiteral; 6917 6918 E = E->IgnoreParenCasts(); 6919 6920 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6921 // Technically -Wformat-nonliteral does not warn about this case. 6922 // The behavior of printf and friends in this case is implementation 6923 // dependent. Ideally if the format string cannot be null then 6924 // it should have a 'nonnull' attribute in the function prototype. 6925 return SLCT_UncheckedLiteral; 6926 6927 switch (E->getStmtClass()) { 6928 case Stmt::BinaryConditionalOperatorClass: 6929 case Stmt::ConditionalOperatorClass: { 6930 // The expression is a literal if both sub-expressions were, and it was 6931 // completely checked only if both sub-expressions were checked. 6932 const AbstractConditionalOperator *C = 6933 cast<AbstractConditionalOperator>(E); 6934 6935 // Determine whether it is necessary to check both sub-expressions, for 6936 // example, because the condition expression is a constant that can be 6937 // evaluated at compile time. 6938 bool CheckLeft = true, CheckRight = true; 6939 6940 bool Cond; 6941 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6942 S.isConstantEvaluated())) { 6943 if (Cond) 6944 CheckRight = false; 6945 else 6946 CheckLeft = false; 6947 } 6948 6949 // We need to maintain the offsets for the right and the left hand side 6950 // separately to check if every possible indexed expression is a valid 6951 // string literal. They might have different offsets for different string 6952 // literals in the end. 6953 StringLiteralCheckType Left; 6954 if (!CheckLeft) 6955 Left = SLCT_UncheckedLiteral; 6956 else { 6957 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6958 HasVAListArg, format_idx, firstDataArg, 6959 Type, CallType, InFunctionCall, 6960 CheckedVarArgs, UncoveredArg, Offset, 6961 IgnoreStringsWithoutSpecifiers); 6962 if (Left == SLCT_NotALiteral || !CheckRight) { 6963 return Left; 6964 } 6965 } 6966 6967 StringLiteralCheckType Right = checkFormatStringExpr( 6968 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6969 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6970 IgnoreStringsWithoutSpecifiers); 6971 6972 return (CheckLeft && Left < Right) ? Left : Right; 6973 } 6974 6975 case Stmt::ImplicitCastExprClass: 6976 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6977 goto tryAgain; 6978 6979 case Stmt::OpaqueValueExprClass: 6980 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6981 E = src; 6982 goto tryAgain; 6983 } 6984 return SLCT_NotALiteral; 6985 6986 case Stmt::PredefinedExprClass: 6987 // While __func__, etc., are technically not string literals, they 6988 // cannot contain format specifiers and thus are not a security 6989 // liability. 6990 return SLCT_UncheckedLiteral; 6991 6992 case Stmt::DeclRefExprClass: { 6993 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6994 6995 // As an exception, do not flag errors for variables binding to 6996 // const string literals. 6997 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6998 bool isConstant = false; 6999 QualType T = DR->getType(); 7000 7001 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7002 isConstant = AT->getElementType().isConstant(S.Context); 7003 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7004 isConstant = T.isConstant(S.Context) && 7005 PT->getPointeeType().isConstant(S.Context); 7006 } else if (T->isObjCObjectPointerType()) { 7007 // In ObjC, there is usually no "const ObjectPointer" type, 7008 // so don't check if the pointee type is constant. 7009 isConstant = T.isConstant(S.Context); 7010 } 7011 7012 if (isConstant) { 7013 if (const Expr *Init = VD->getAnyInitializer()) { 7014 // Look through initializers like const char c[] = { "foo" } 7015 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7016 if (InitList->isStringLiteralInit()) 7017 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7018 } 7019 return checkFormatStringExpr(S, Init, Args, 7020 HasVAListArg, format_idx, 7021 firstDataArg, Type, CallType, 7022 /*InFunctionCall*/ false, CheckedVarArgs, 7023 UncoveredArg, Offset); 7024 } 7025 } 7026 7027 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7028 // special check to see if the format string is a function parameter 7029 // of the function calling the printf function. If the function 7030 // has an attribute indicating it is a printf-like function, then we 7031 // should suppress warnings concerning non-literals being used in a call 7032 // to a vprintf function. For example: 7033 // 7034 // void 7035 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7036 // va_list ap; 7037 // va_start(ap, fmt); 7038 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7039 // ... 7040 // } 7041 if (HasVAListArg) { 7042 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7043 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7044 int PVIndex = PV->getFunctionScopeIndex() + 1; 7045 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7046 // adjust for implicit parameter 7047 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7048 if (MD->isInstance()) 7049 ++PVIndex; 7050 // We also check if the formats are compatible. 7051 // We can't pass a 'scanf' string to a 'printf' function. 7052 if (PVIndex == PVFormat->getFormatIdx() && 7053 Type == S.GetFormatStringType(PVFormat)) 7054 return SLCT_UncheckedLiteral; 7055 } 7056 } 7057 } 7058 } 7059 } 7060 7061 return SLCT_NotALiteral; 7062 } 7063 7064 case Stmt::CallExprClass: 7065 case Stmt::CXXMemberCallExprClass: { 7066 const CallExpr *CE = cast<CallExpr>(E); 7067 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7068 bool IsFirst = true; 7069 StringLiteralCheckType CommonResult; 7070 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7071 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7072 StringLiteralCheckType Result = checkFormatStringExpr( 7073 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7074 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7075 IgnoreStringsWithoutSpecifiers); 7076 if (IsFirst) { 7077 CommonResult = Result; 7078 IsFirst = false; 7079 } 7080 } 7081 if (!IsFirst) 7082 return CommonResult; 7083 7084 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7085 unsigned BuiltinID = FD->getBuiltinID(); 7086 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7087 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7088 const Expr *Arg = CE->getArg(0); 7089 return checkFormatStringExpr(S, Arg, Args, 7090 HasVAListArg, format_idx, 7091 firstDataArg, Type, CallType, 7092 InFunctionCall, CheckedVarArgs, 7093 UncoveredArg, Offset, 7094 IgnoreStringsWithoutSpecifiers); 7095 } 7096 } 7097 } 7098 7099 return SLCT_NotALiteral; 7100 } 7101 case Stmt::ObjCMessageExprClass: { 7102 const auto *ME = cast<ObjCMessageExpr>(E); 7103 if (const auto *MD = ME->getMethodDecl()) { 7104 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7105 // As a special case heuristic, if we're using the method -[NSBundle 7106 // localizedStringForKey:value:table:], ignore any key strings that lack 7107 // format specifiers. The idea is that if the key doesn't have any 7108 // format specifiers then its probably just a key to map to the 7109 // localized strings. If it does have format specifiers though, then its 7110 // likely that the text of the key is the format string in the 7111 // programmer's language, and should be checked. 7112 const ObjCInterfaceDecl *IFace; 7113 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7114 IFace->getIdentifier()->isStr("NSBundle") && 7115 MD->getSelector().isKeywordSelector( 7116 {"localizedStringForKey", "value", "table"})) { 7117 IgnoreStringsWithoutSpecifiers = true; 7118 } 7119 7120 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7121 return checkFormatStringExpr( 7122 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7123 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7124 IgnoreStringsWithoutSpecifiers); 7125 } 7126 } 7127 7128 return SLCT_NotALiteral; 7129 } 7130 case Stmt::ObjCStringLiteralClass: 7131 case Stmt::StringLiteralClass: { 7132 const StringLiteral *StrE = nullptr; 7133 7134 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7135 StrE = ObjCFExpr->getString(); 7136 else 7137 StrE = cast<StringLiteral>(E); 7138 7139 if (StrE) { 7140 if (Offset.isNegative() || Offset > StrE->getLength()) { 7141 // TODO: It would be better to have an explicit warning for out of 7142 // bounds literals. 7143 return SLCT_NotALiteral; 7144 } 7145 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7146 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7147 firstDataArg, Type, InFunctionCall, CallType, 7148 CheckedVarArgs, UncoveredArg, 7149 IgnoreStringsWithoutSpecifiers); 7150 return SLCT_CheckedLiteral; 7151 } 7152 7153 return SLCT_NotALiteral; 7154 } 7155 case Stmt::BinaryOperatorClass: { 7156 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7157 7158 // A string literal + an int offset is still a string literal. 7159 if (BinOp->isAdditiveOp()) { 7160 Expr::EvalResult LResult, RResult; 7161 7162 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7163 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7164 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7165 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7166 7167 if (LIsInt != RIsInt) { 7168 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7169 7170 if (LIsInt) { 7171 if (BinOpKind == BO_Add) { 7172 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7173 E = BinOp->getRHS(); 7174 goto tryAgain; 7175 } 7176 } else { 7177 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7178 E = BinOp->getLHS(); 7179 goto tryAgain; 7180 } 7181 } 7182 } 7183 7184 return SLCT_NotALiteral; 7185 } 7186 case Stmt::UnaryOperatorClass: { 7187 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7188 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7189 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7190 Expr::EvalResult IndexResult; 7191 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7192 Expr::SE_NoSideEffects, 7193 S.isConstantEvaluated())) { 7194 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7195 /*RHS is int*/ true); 7196 E = ASE->getBase(); 7197 goto tryAgain; 7198 } 7199 } 7200 7201 return SLCT_NotALiteral; 7202 } 7203 7204 default: 7205 return SLCT_NotALiteral; 7206 } 7207 } 7208 7209 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7210 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7211 .Case("scanf", FST_Scanf) 7212 .Cases("printf", "printf0", FST_Printf) 7213 .Cases("NSString", "CFString", FST_NSString) 7214 .Case("strftime", FST_Strftime) 7215 .Case("strfmon", FST_Strfmon) 7216 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7217 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7218 .Case("os_trace", FST_OSLog) 7219 .Case("os_log", FST_OSLog) 7220 .Default(FST_Unknown); 7221 } 7222 7223 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7224 /// functions) for correct use of format strings. 7225 /// Returns true if a format string has been fully checked. 7226 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7227 ArrayRef<const Expr *> Args, 7228 bool IsCXXMember, 7229 VariadicCallType CallType, 7230 SourceLocation Loc, SourceRange Range, 7231 llvm::SmallBitVector &CheckedVarArgs) { 7232 FormatStringInfo FSI; 7233 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7234 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7235 FSI.FirstDataArg, GetFormatStringType(Format), 7236 CallType, Loc, Range, CheckedVarArgs); 7237 return false; 7238 } 7239 7240 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7241 bool HasVAListArg, unsigned format_idx, 7242 unsigned firstDataArg, FormatStringType Type, 7243 VariadicCallType CallType, 7244 SourceLocation Loc, SourceRange Range, 7245 llvm::SmallBitVector &CheckedVarArgs) { 7246 // CHECK: printf/scanf-like function is called with no format string. 7247 if (format_idx >= Args.size()) { 7248 Diag(Loc, diag::warn_missing_format_string) << Range; 7249 return false; 7250 } 7251 7252 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7253 7254 // CHECK: format string is not a string literal. 7255 // 7256 // Dynamically generated format strings are difficult to 7257 // automatically vet at compile time. Requiring that format strings 7258 // are string literals: (1) permits the checking of format strings by 7259 // the compiler and thereby (2) can practically remove the source of 7260 // many format string exploits. 7261 7262 // Format string can be either ObjC string (e.g. @"%d") or 7263 // C string (e.g. "%d") 7264 // ObjC string uses the same format specifiers as C string, so we can use 7265 // the same format string checking logic for both ObjC and C strings. 7266 UncoveredArgHandler UncoveredArg; 7267 StringLiteralCheckType CT = 7268 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7269 format_idx, firstDataArg, Type, CallType, 7270 /*IsFunctionCall*/ true, CheckedVarArgs, 7271 UncoveredArg, 7272 /*no string offset*/ llvm::APSInt(64, false) = 0); 7273 7274 // Generate a diagnostic where an uncovered argument is detected. 7275 if (UncoveredArg.hasUncoveredArg()) { 7276 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7277 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7278 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7279 } 7280 7281 if (CT != SLCT_NotALiteral) 7282 // Literal format string found, check done! 7283 return CT == SLCT_CheckedLiteral; 7284 7285 // Strftime is particular as it always uses a single 'time' argument, 7286 // so it is safe to pass a non-literal string. 7287 if (Type == FST_Strftime) 7288 return false; 7289 7290 // Do not emit diag when the string param is a macro expansion and the 7291 // format is either NSString or CFString. This is a hack to prevent 7292 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7293 // which are usually used in place of NS and CF string literals. 7294 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7295 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7296 return false; 7297 7298 // If there are no arguments specified, warn with -Wformat-security, otherwise 7299 // warn only with -Wformat-nonliteral. 7300 if (Args.size() == firstDataArg) { 7301 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7302 << OrigFormatExpr->getSourceRange(); 7303 switch (Type) { 7304 default: 7305 break; 7306 case FST_Kprintf: 7307 case FST_FreeBSDKPrintf: 7308 case FST_Printf: 7309 Diag(FormatLoc, diag::note_format_security_fixit) 7310 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7311 break; 7312 case FST_NSString: 7313 Diag(FormatLoc, diag::note_format_security_fixit) 7314 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7315 break; 7316 } 7317 } else { 7318 Diag(FormatLoc, diag::warn_format_nonliteral) 7319 << OrigFormatExpr->getSourceRange(); 7320 } 7321 return false; 7322 } 7323 7324 namespace { 7325 7326 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7327 protected: 7328 Sema &S; 7329 const FormatStringLiteral *FExpr; 7330 const Expr *OrigFormatExpr; 7331 const Sema::FormatStringType FSType; 7332 const unsigned FirstDataArg; 7333 const unsigned NumDataArgs; 7334 const char *Beg; // Start of format string. 7335 const bool HasVAListArg; 7336 ArrayRef<const Expr *> Args; 7337 unsigned FormatIdx; 7338 llvm::SmallBitVector CoveredArgs; 7339 bool usesPositionalArgs = false; 7340 bool atFirstArg = true; 7341 bool inFunctionCall; 7342 Sema::VariadicCallType CallType; 7343 llvm::SmallBitVector &CheckedVarArgs; 7344 UncoveredArgHandler &UncoveredArg; 7345 7346 public: 7347 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7348 const Expr *origFormatExpr, 7349 const Sema::FormatStringType type, unsigned firstDataArg, 7350 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7351 ArrayRef<const Expr *> Args, unsigned formatIdx, 7352 bool inFunctionCall, Sema::VariadicCallType callType, 7353 llvm::SmallBitVector &CheckedVarArgs, 7354 UncoveredArgHandler &UncoveredArg) 7355 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7356 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7357 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7358 inFunctionCall(inFunctionCall), CallType(callType), 7359 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7360 CoveredArgs.resize(numDataArgs); 7361 CoveredArgs.reset(); 7362 } 7363 7364 void DoneProcessing(); 7365 7366 void HandleIncompleteSpecifier(const char *startSpecifier, 7367 unsigned specifierLen) override; 7368 7369 void HandleInvalidLengthModifier( 7370 const analyze_format_string::FormatSpecifier &FS, 7371 const analyze_format_string::ConversionSpecifier &CS, 7372 const char *startSpecifier, unsigned specifierLen, 7373 unsigned DiagID); 7374 7375 void HandleNonStandardLengthModifier( 7376 const analyze_format_string::FormatSpecifier &FS, 7377 const char *startSpecifier, unsigned specifierLen); 7378 7379 void HandleNonStandardConversionSpecifier( 7380 const analyze_format_string::ConversionSpecifier &CS, 7381 const char *startSpecifier, unsigned specifierLen); 7382 7383 void HandlePosition(const char *startPos, unsigned posLen) override; 7384 7385 void HandleInvalidPosition(const char *startSpecifier, 7386 unsigned specifierLen, 7387 analyze_format_string::PositionContext p) override; 7388 7389 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7390 7391 void HandleNullChar(const char *nullCharacter) override; 7392 7393 template <typename Range> 7394 static void 7395 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7396 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7397 bool IsStringLocation, Range StringRange, 7398 ArrayRef<FixItHint> Fixit = None); 7399 7400 protected: 7401 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7402 const char *startSpec, 7403 unsigned specifierLen, 7404 const char *csStart, unsigned csLen); 7405 7406 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7407 const char *startSpec, 7408 unsigned specifierLen); 7409 7410 SourceRange getFormatStringRange(); 7411 CharSourceRange getSpecifierRange(const char *startSpecifier, 7412 unsigned specifierLen); 7413 SourceLocation getLocationOfByte(const char *x); 7414 7415 const Expr *getDataArg(unsigned i) const; 7416 7417 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7418 const analyze_format_string::ConversionSpecifier &CS, 7419 const char *startSpecifier, unsigned specifierLen, 7420 unsigned argIndex); 7421 7422 template <typename Range> 7423 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7424 bool IsStringLocation, Range StringRange, 7425 ArrayRef<FixItHint> Fixit = None); 7426 }; 7427 7428 } // namespace 7429 7430 SourceRange CheckFormatHandler::getFormatStringRange() { 7431 return OrigFormatExpr->getSourceRange(); 7432 } 7433 7434 CharSourceRange CheckFormatHandler:: 7435 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7436 SourceLocation Start = getLocationOfByte(startSpecifier); 7437 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7438 7439 // Advance the end SourceLocation by one due to half-open ranges. 7440 End = End.getLocWithOffset(1); 7441 7442 return CharSourceRange::getCharRange(Start, End); 7443 } 7444 7445 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7446 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7447 S.getLangOpts(), S.Context.getTargetInfo()); 7448 } 7449 7450 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7451 unsigned specifierLen){ 7452 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7453 getLocationOfByte(startSpecifier), 7454 /*IsStringLocation*/true, 7455 getSpecifierRange(startSpecifier, specifierLen)); 7456 } 7457 7458 void CheckFormatHandler::HandleInvalidLengthModifier( 7459 const analyze_format_string::FormatSpecifier &FS, 7460 const analyze_format_string::ConversionSpecifier &CS, 7461 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7462 using namespace analyze_format_string; 7463 7464 const LengthModifier &LM = FS.getLengthModifier(); 7465 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7466 7467 // See if we know how to fix this length modifier. 7468 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7469 if (FixedLM) { 7470 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7471 getLocationOfByte(LM.getStart()), 7472 /*IsStringLocation*/true, 7473 getSpecifierRange(startSpecifier, specifierLen)); 7474 7475 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7476 << FixedLM->toString() 7477 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7478 7479 } else { 7480 FixItHint Hint; 7481 if (DiagID == diag::warn_format_nonsensical_length) 7482 Hint = FixItHint::CreateRemoval(LMRange); 7483 7484 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7485 getLocationOfByte(LM.getStart()), 7486 /*IsStringLocation*/true, 7487 getSpecifierRange(startSpecifier, specifierLen), 7488 Hint); 7489 } 7490 } 7491 7492 void CheckFormatHandler::HandleNonStandardLengthModifier( 7493 const analyze_format_string::FormatSpecifier &FS, 7494 const char *startSpecifier, unsigned specifierLen) { 7495 using namespace analyze_format_string; 7496 7497 const LengthModifier &LM = FS.getLengthModifier(); 7498 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7499 7500 // See if we know how to fix this length modifier. 7501 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7502 if (FixedLM) { 7503 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7504 << LM.toString() << 0, 7505 getLocationOfByte(LM.getStart()), 7506 /*IsStringLocation*/true, 7507 getSpecifierRange(startSpecifier, specifierLen)); 7508 7509 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7510 << FixedLM->toString() 7511 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7512 7513 } else { 7514 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7515 << LM.toString() << 0, 7516 getLocationOfByte(LM.getStart()), 7517 /*IsStringLocation*/true, 7518 getSpecifierRange(startSpecifier, specifierLen)); 7519 } 7520 } 7521 7522 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7523 const analyze_format_string::ConversionSpecifier &CS, 7524 const char *startSpecifier, unsigned specifierLen) { 7525 using namespace analyze_format_string; 7526 7527 // See if we know how to fix this conversion specifier. 7528 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7529 if (FixedCS) { 7530 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7531 << CS.toString() << /*conversion specifier*/1, 7532 getLocationOfByte(CS.getStart()), 7533 /*IsStringLocation*/true, 7534 getSpecifierRange(startSpecifier, specifierLen)); 7535 7536 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7537 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7538 << FixedCS->toString() 7539 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7540 } else { 7541 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7542 << CS.toString() << /*conversion specifier*/1, 7543 getLocationOfByte(CS.getStart()), 7544 /*IsStringLocation*/true, 7545 getSpecifierRange(startSpecifier, specifierLen)); 7546 } 7547 } 7548 7549 void CheckFormatHandler::HandlePosition(const char *startPos, 7550 unsigned posLen) { 7551 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7552 getLocationOfByte(startPos), 7553 /*IsStringLocation*/true, 7554 getSpecifierRange(startPos, posLen)); 7555 } 7556 7557 void 7558 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7559 analyze_format_string::PositionContext p) { 7560 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7561 << (unsigned) p, 7562 getLocationOfByte(startPos), /*IsStringLocation*/true, 7563 getSpecifierRange(startPos, posLen)); 7564 } 7565 7566 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7567 unsigned posLen) { 7568 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7569 getLocationOfByte(startPos), 7570 /*IsStringLocation*/true, 7571 getSpecifierRange(startPos, posLen)); 7572 } 7573 7574 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7575 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7576 // The presence of a null character is likely an error. 7577 EmitFormatDiagnostic( 7578 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7579 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7580 getFormatStringRange()); 7581 } 7582 } 7583 7584 // Note that this may return NULL if there was an error parsing or building 7585 // one of the argument expressions. 7586 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7587 return Args[FirstDataArg + i]; 7588 } 7589 7590 void CheckFormatHandler::DoneProcessing() { 7591 // Does the number of data arguments exceed the number of 7592 // format conversions in the format string? 7593 if (!HasVAListArg) { 7594 // Find any arguments that weren't covered. 7595 CoveredArgs.flip(); 7596 signed notCoveredArg = CoveredArgs.find_first(); 7597 if (notCoveredArg >= 0) { 7598 assert((unsigned)notCoveredArg < NumDataArgs); 7599 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7600 } else { 7601 UncoveredArg.setAllCovered(); 7602 } 7603 } 7604 } 7605 7606 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7607 const Expr *ArgExpr) { 7608 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7609 "Invalid state"); 7610 7611 if (!ArgExpr) 7612 return; 7613 7614 SourceLocation Loc = ArgExpr->getBeginLoc(); 7615 7616 if (S.getSourceManager().isInSystemMacro(Loc)) 7617 return; 7618 7619 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7620 for (auto E : DiagnosticExprs) 7621 PDiag << E->getSourceRange(); 7622 7623 CheckFormatHandler::EmitFormatDiagnostic( 7624 S, IsFunctionCall, DiagnosticExprs[0], 7625 PDiag, Loc, /*IsStringLocation*/false, 7626 DiagnosticExprs[0]->getSourceRange()); 7627 } 7628 7629 bool 7630 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7631 SourceLocation Loc, 7632 const char *startSpec, 7633 unsigned specifierLen, 7634 const char *csStart, 7635 unsigned csLen) { 7636 bool keepGoing = true; 7637 if (argIndex < NumDataArgs) { 7638 // Consider the argument coverered, even though the specifier doesn't 7639 // make sense. 7640 CoveredArgs.set(argIndex); 7641 } 7642 else { 7643 // If argIndex exceeds the number of data arguments we 7644 // don't issue a warning because that is just a cascade of warnings (and 7645 // they may have intended '%%' anyway). We don't want to continue processing 7646 // the format string after this point, however, as we will like just get 7647 // gibberish when trying to match arguments. 7648 keepGoing = false; 7649 } 7650 7651 StringRef Specifier(csStart, csLen); 7652 7653 // If the specifier in non-printable, it could be the first byte of a UTF-8 7654 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7655 // hex value. 7656 std::string CodePointStr; 7657 if (!llvm::sys::locale::isPrint(*csStart)) { 7658 llvm::UTF32 CodePoint; 7659 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7660 const llvm::UTF8 *E = 7661 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7662 llvm::ConversionResult Result = 7663 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7664 7665 if (Result != llvm::conversionOK) { 7666 unsigned char FirstChar = *csStart; 7667 CodePoint = (llvm::UTF32)FirstChar; 7668 } 7669 7670 llvm::raw_string_ostream OS(CodePointStr); 7671 if (CodePoint < 256) 7672 OS << "\\x" << llvm::format("%02x", CodePoint); 7673 else if (CodePoint <= 0xFFFF) 7674 OS << "\\u" << llvm::format("%04x", CodePoint); 7675 else 7676 OS << "\\U" << llvm::format("%08x", CodePoint); 7677 OS.flush(); 7678 Specifier = CodePointStr; 7679 } 7680 7681 EmitFormatDiagnostic( 7682 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7683 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7684 7685 return keepGoing; 7686 } 7687 7688 void 7689 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7690 const char *startSpec, 7691 unsigned specifierLen) { 7692 EmitFormatDiagnostic( 7693 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7694 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7695 } 7696 7697 bool 7698 CheckFormatHandler::CheckNumArgs( 7699 const analyze_format_string::FormatSpecifier &FS, 7700 const analyze_format_string::ConversionSpecifier &CS, 7701 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7702 7703 if (argIndex >= NumDataArgs) { 7704 PartialDiagnostic PDiag = FS.usesPositionalArg() 7705 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7706 << (argIndex+1) << NumDataArgs) 7707 : S.PDiag(diag::warn_printf_insufficient_data_args); 7708 EmitFormatDiagnostic( 7709 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7710 getSpecifierRange(startSpecifier, specifierLen)); 7711 7712 // Since more arguments than conversion tokens are given, by extension 7713 // all arguments are covered, so mark this as so. 7714 UncoveredArg.setAllCovered(); 7715 return false; 7716 } 7717 return true; 7718 } 7719 7720 template<typename Range> 7721 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7722 SourceLocation Loc, 7723 bool IsStringLocation, 7724 Range StringRange, 7725 ArrayRef<FixItHint> FixIt) { 7726 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7727 Loc, IsStringLocation, StringRange, FixIt); 7728 } 7729 7730 /// If the format string is not within the function call, emit a note 7731 /// so that the function call and string are in diagnostic messages. 7732 /// 7733 /// \param InFunctionCall if true, the format string is within the function 7734 /// call and only one diagnostic message will be produced. Otherwise, an 7735 /// extra note will be emitted pointing to location of the format string. 7736 /// 7737 /// \param ArgumentExpr the expression that is passed as the format string 7738 /// argument in the function call. Used for getting locations when two 7739 /// diagnostics are emitted. 7740 /// 7741 /// \param PDiag the callee should already have provided any strings for the 7742 /// diagnostic message. This function only adds locations and fixits 7743 /// to diagnostics. 7744 /// 7745 /// \param Loc primary location for diagnostic. If two diagnostics are 7746 /// required, one will be at Loc and a new SourceLocation will be created for 7747 /// the other one. 7748 /// 7749 /// \param IsStringLocation if true, Loc points to the format string should be 7750 /// used for the note. Otherwise, Loc points to the argument list and will 7751 /// be used with PDiag. 7752 /// 7753 /// \param StringRange some or all of the string to highlight. This is 7754 /// templated so it can accept either a CharSourceRange or a SourceRange. 7755 /// 7756 /// \param FixIt optional fix it hint for the format string. 7757 template <typename Range> 7758 void CheckFormatHandler::EmitFormatDiagnostic( 7759 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7760 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7761 Range StringRange, ArrayRef<FixItHint> FixIt) { 7762 if (InFunctionCall) { 7763 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7764 D << StringRange; 7765 D << FixIt; 7766 } else { 7767 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7768 << ArgumentExpr->getSourceRange(); 7769 7770 const Sema::SemaDiagnosticBuilder &Note = 7771 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7772 diag::note_format_string_defined); 7773 7774 Note << StringRange; 7775 Note << FixIt; 7776 } 7777 } 7778 7779 //===--- CHECK: Printf format string checking ------------------------------===// 7780 7781 namespace { 7782 7783 class CheckPrintfHandler : public CheckFormatHandler { 7784 public: 7785 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7786 const Expr *origFormatExpr, 7787 const Sema::FormatStringType type, unsigned firstDataArg, 7788 unsigned numDataArgs, bool isObjC, const char *beg, 7789 bool hasVAListArg, ArrayRef<const Expr *> Args, 7790 unsigned formatIdx, bool inFunctionCall, 7791 Sema::VariadicCallType CallType, 7792 llvm::SmallBitVector &CheckedVarArgs, 7793 UncoveredArgHandler &UncoveredArg) 7794 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7795 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7796 inFunctionCall, CallType, CheckedVarArgs, 7797 UncoveredArg) {} 7798 7799 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7800 7801 /// Returns true if '%@' specifiers are allowed in the format string. 7802 bool allowsObjCArg() const { 7803 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7804 FSType == Sema::FST_OSTrace; 7805 } 7806 7807 bool HandleInvalidPrintfConversionSpecifier( 7808 const analyze_printf::PrintfSpecifier &FS, 7809 const char *startSpecifier, 7810 unsigned specifierLen) override; 7811 7812 void handleInvalidMaskType(StringRef MaskType) override; 7813 7814 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7815 const char *startSpecifier, 7816 unsigned specifierLen) override; 7817 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7818 const char *StartSpecifier, 7819 unsigned SpecifierLen, 7820 const Expr *E); 7821 7822 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7823 const char *startSpecifier, unsigned specifierLen); 7824 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7825 const analyze_printf::OptionalAmount &Amt, 7826 unsigned type, 7827 const char *startSpecifier, unsigned specifierLen); 7828 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7829 const analyze_printf::OptionalFlag &flag, 7830 const char *startSpecifier, unsigned specifierLen); 7831 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7832 const analyze_printf::OptionalFlag &ignoredFlag, 7833 const analyze_printf::OptionalFlag &flag, 7834 const char *startSpecifier, unsigned specifierLen); 7835 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7836 const Expr *E); 7837 7838 void HandleEmptyObjCModifierFlag(const char *startFlag, 7839 unsigned flagLen) override; 7840 7841 void HandleInvalidObjCModifierFlag(const char *startFlag, 7842 unsigned flagLen) override; 7843 7844 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7845 const char *flagsEnd, 7846 const char *conversionPosition) 7847 override; 7848 }; 7849 7850 } // namespace 7851 7852 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7853 const analyze_printf::PrintfSpecifier &FS, 7854 const char *startSpecifier, 7855 unsigned specifierLen) { 7856 const analyze_printf::PrintfConversionSpecifier &CS = 7857 FS.getConversionSpecifier(); 7858 7859 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7860 getLocationOfByte(CS.getStart()), 7861 startSpecifier, specifierLen, 7862 CS.getStart(), CS.getLength()); 7863 } 7864 7865 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7866 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7867 } 7868 7869 bool CheckPrintfHandler::HandleAmount( 7870 const analyze_format_string::OptionalAmount &Amt, 7871 unsigned k, const char *startSpecifier, 7872 unsigned specifierLen) { 7873 if (Amt.hasDataArgument()) { 7874 if (!HasVAListArg) { 7875 unsigned argIndex = Amt.getArgIndex(); 7876 if (argIndex >= NumDataArgs) { 7877 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7878 << k, 7879 getLocationOfByte(Amt.getStart()), 7880 /*IsStringLocation*/true, 7881 getSpecifierRange(startSpecifier, specifierLen)); 7882 // Don't do any more checking. We will just emit 7883 // spurious errors. 7884 return false; 7885 } 7886 7887 // Type check the data argument. It should be an 'int'. 7888 // Although not in conformance with C99, we also allow the argument to be 7889 // an 'unsigned int' as that is a reasonably safe case. GCC also 7890 // doesn't emit a warning for that case. 7891 CoveredArgs.set(argIndex); 7892 const Expr *Arg = getDataArg(argIndex); 7893 if (!Arg) 7894 return false; 7895 7896 QualType T = Arg->getType(); 7897 7898 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7899 assert(AT.isValid()); 7900 7901 if (!AT.matchesType(S.Context, T)) { 7902 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7903 << k << AT.getRepresentativeTypeName(S.Context) 7904 << T << Arg->getSourceRange(), 7905 getLocationOfByte(Amt.getStart()), 7906 /*IsStringLocation*/true, 7907 getSpecifierRange(startSpecifier, specifierLen)); 7908 // Don't do any more checking. We will just emit 7909 // spurious errors. 7910 return false; 7911 } 7912 } 7913 } 7914 return true; 7915 } 7916 7917 void CheckPrintfHandler::HandleInvalidAmount( 7918 const analyze_printf::PrintfSpecifier &FS, 7919 const analyze_printf::OptionalAmount &Amt, 7920 unsigned type, 7921 const char *startSpecifier, 7922 unsigned specifierLen) { 7923 const analyze_printf::PrintfConversionSpecifier &CS = 7924 FS.getConversionSpecifier(); 7925 7926 FixItHint fixit = 7927 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7928 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7929 Amt.getConstantLength())) 7930 : FixItHint(); 7931 7932 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7933 << type << CS.toString(), 7934 getLocationOfByte(Amt.getStart()), 7935 /*IsStringLocation*/true, 7936 getSpecifierRange(startSpecifier, specifierLen), 7937 fixit); 7938 } 7939 7940 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7941 const analyze_printf::OptionalFlag &flag, 7942 const char *startSpecifier, 7943 unsigned specifierLen) { 7944 // Warn about pointless flag with a fixit removal. 7945 const analyze_printf::PrintfConversionSpecifier &CS = 7946 FS.getConversionSpecifier(); 7947 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7948 << flag.toString() << CS.toString(), 7949 getLocationOfByte(flag.getPosition()), 7950 /*IsStringLocation*/true, 7951 getSpecifierRange(startSpecifier, specifierLen), 7952 FixItHint::CreateRemoval( 7953 getSpecifierRange(flag.getPosition(), 1))); 7954 } 7955 7956 void CheckPrintfHandler::HandleIgnoredFlag( 7957 const analyze_printf::PrintfSpecifier &FS, 7958 const analyze_printf::OptionalFlag &ignoredFlag, 7959 const analyze_printf::OptionalFlag &flag, 7960 const char *startSpecifier, 7961 unsigned specifierLen) { 7962 // Warn about ignored flag with a fixit removal. 7963 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7964 << ignoredFlag.toString() << flag.toString(), 7965 getLocationOfByte(ignoredFlag.getPosition()), 7966 /*IsStringLocation*/true, 7967 getSpecifierRange(startSpecifier, specifierLen), 7968 FixItHint::CreateRemoval( 7969 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7970 } 7971 7972 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7973 unsigned flagLen) { 7974 // Warn about an empty flag. 7975 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7976 getLocationOfByte(startFlag), 7977 /*IsStringLocation*/true, 7978 getSpecifierRange(startFlag, flagLen)); 7979 } 7980 7981 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7982 unsigned flagLen) { 7983 // Warn about an invalid flag. 7984 auto Range = getSpecifierRange(startFlag, flagLen); 7985 StringRef flag(startFlag, flagLen); 7986 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7987 getLocationOfByte(startFlag), 7988 /*IsStringLocation*/true, 7989 Range, FixItHint::CreateRemoval(Range)); 7990 } 7991 7992 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7993 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7994 // Warn about using '[...]' without a '@' conversion. 7995 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7996 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7997 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7998 getLocationOfByte(conversionPosition), 7999 /*IsStringLocation*/true, 8000 Range, FixItHint::CreateRemoval(Range)); 8001 } 8002 8003 // Determines if the specified is a C++ class or struct containing 8004 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8005 // "c_str()"). 8006 template<typename MemberKind> 8007 static llvm::SmallPtrSet<MemberKind*, 1> 8008 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8009 const RecordType *RT = Ty->getAs<RecordType>(); 8010 llvm::SmallPtrSet<MemberKind*, 1> Results; 8011 8012 if (!RT) 8013 return Results; 8014 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8015 if (!RD || !RD->getDefinition()) 8016 return Results; 8017 8018 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8019 Sema::LookupMemberName); 8020 R.suppressDiagnostics(); 8021 8022 // We just need to include all members of the right kind turned up by the 8023 // filter, at this point. 8024 if (S.LookupQualifiedName(R, RT->getDecl())) 8025 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8026 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8027 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8028 Results.insert(FK); 8029 } 8030 return Results; 8031 } 8032 8033 /// Check if we could call '.c_str()' on an object. 8034 /// 8035 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8036 /// allow the call, or if it would be ambiguous). 8037 bool Sema::hasCStrMethod(const Expr *E) { 8038 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8039 8040 MethodSet Results = 8041 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8042 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8043 MI != ME; ++MI) 8044 if ((*MI)->getMinRequiredArguments() == 0) 8045 return true; 8046 return false; 8047 } 8048 8049 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8050 // better diagnostic if so. AT is assumed to be valid. 8051 // Returns true when a c_str() conversion method is found. 8052 bool CheckPrintfHandler::checkForCStrMembers( 8053 const analyze_printf::ArgType &AT, const Expr *E) { 8054 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8055 8056 MethodSet Results = 8057 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8058 8059 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8060 MI != ME; ++MI) { 8061 const CXXMethodDecl *Method = *MI; 8062 if (Method->getMinRequiredArguments() == 0 && 8063 AT.matchesType(S.Context, Method->getReturnType())) { 8064 // FIXME: Suggest parens if the expression needs them. 8065 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8066 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8067 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8068 return true; 8069 } 8070 } 8071 8072 return false; 8073 } 8074 8075 bool 8076 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8077 &FS, 8078 const char *startSpecifier, 8079 unsigned specifierLen) { 8080 using namespace analyze_format_string; 8081 using namespace analyze_printf; 8082 8083 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8084 8085 if (FS.consumesDataArgument()) { 8086 if (atFirstArg) { 8087 atFirstArg = false; 8088 usesPositionalArgs = FS.usesPositionalArg(); 8089 } 8090 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8091 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8092 startSpecifier, specifierLen); 8093 return false; 8094 } 8095 } 8096 8097 // First check if the field width, precision, and conversion specifier 8098 // have matching data arguments. 8099 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8100 startSpecifier, specifierLen)) { 8101 return false; 8102 } 8103 8104 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8105 startSpecifier, specifierLen)) { 8106 return false; 8107 } 8108 8109 if (!CS.consumesDataArgument()) { 8110 // FIXME: Technically specifying a precision or field width here 8111 // makes no sense. Worth issuing a warning at some point. 8112 return true; 8113 } 8114 8115 // Consume the argument. 8116 unsigned argIndex = FS.getArgIndex(); 8117 if (argIndex < NumDataArgs) { 8118 // The check to see if the argIndex is valid will come later. 8119 // We set the bit here because we may exit early from this 8120 // function if we encounter some other error. 8121 CoveredArgs.set(argIndex); 8122 } 8123 8124 // FreeBSD kernel extensions. 8125 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8126 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8127 // We need at least two arguments. 8128 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8129 return false; 8130 8131 // Claim the second argument. 8132 CoveredArgs.set(argIndex + 1); 8133 8134 // Type check the first argument (int for %b, pointer for %D) 8135 const Expr *Ex = getDataArg(argIndex); 8136 const analyze_printf::ArgType &AT = 8137 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8138 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8139 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8140 EmitFormatDiagnostic( 8141 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8142 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8143 << false << Ex->getSourceRange(), 8144 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8145 getSpecifierRange(startSpecifier, specifierLen)); 8146 8147 // Type check the second argument (char * for both %b and %D) 8148 Ex = getDataArg(argIndex + 1); 8149 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8150 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8151 EmitFormatDiagnostic( 8152 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8153 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8154 << false << Ex->getSourceRange(), 8155 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8156 getSpecifierRange(startSpecifier, specifierLen)); 8157 8158 return true; 8159 } 8160 8161 // Check for using an Objective-C specific conversion specifier 8162 // in a non-ObjC literal. 8163 if (!allowsObjCArg() && CS.isObjCArg()) { 8164 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8165 specifierLen); 8166 } 8167 8168 // %P can only be used with os_log. 8169 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8170 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8171 specifierLen); 8172 } 8173 8174 // %n is not allowed with os_log. 8175 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8176 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8177 getLocationOfByte(CS.getStart()), 8178 /*IsStringLocation*/ false, 8179 getSpecifierRange(startSpecifier, specifierLen)); 8180 8181 return true; 8182 } 8183 8184 // Only scalars are allowed for os_trace. 8185 if (FSType == Sema::FST_OSTrace && 8186 (CS.getKind() == ConversionSpecifier::PArg || 8187 CS.getKind() == ConversionSpecifier::sArg || 8188 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8189 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8190 specifierLen); 8191 } 8192 8193 // Check for use of public/private annotation outside of os_log(). 8194 if (FSType != Sema::FST_OSLog) { 8195 if (FS.isPublic().isSet()) { 8196 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8197 << "public", 8198 getLocationOfByte(FS.isPublic().getPosition()), 8199 /*IsStringLocation*/ false, 8200 getSpecifierRange(startSpecifier, specifierLen)); 8201 } 8202 if (FS.isPrivate().isSet()) { 8203 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8204 << "private", 8205 getLocationOfByte(FS.isPrivate().getPosition()), 8206 /*IsStringLocation*/ false, 8207 getSpecifierRange(startSpecifier, specifierLen)); 8208 } 8209 } 8210 8211 // Check for invalid use of field width 8212 if (!FS.hasValidFieldWidth()) { 8213 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8214 startSpecifier, specifierLen); 8215 } 8216 8217 // Check for invalid use of precision 8218 if (!FS.hasValidPrecision()) { 8219 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8220 startSpecifier, specifierLen); 8221 } 8222 8223 // Precision is mandatory for %P specifier. 8224 if (CS.getKind() == ConversionSpecifier::PArg && 8225 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8226 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8227 getLocationOfByte(startSpecifier), 8228 /*IsStringLocation*/ false, 8229 getSpecifierRange(startSpecifier, specifierLen)); 8230 } 8231 8232 // Check each flag does not conflict with any other component. 8233 if (!FS.hasValidThousandsGroupingPrefix()) 8234 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8235 if (!FS.hasValidLeadingZeros()) 8236 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8237 if (!FS.hasValidPlusPrefix()) 8238 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8239 if (!FS.hasValidSpacePrefix()) 8240 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8241 if (!FS.hasValidAlternativeForm()) 8242 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8243 if (!FS.hasValidLeftJustified()) 8244 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8245 8246 // Check that flags are not ignored by another flag 8247 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8248 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8249 startSpecifier, specifierLen); 8250 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8251 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8252 startSpecifier, specifierLen); 8253 8254 // Check the length modifier is valid with the given conversion specifier. 8255 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8256 S.getLangOpts())) 8257 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8258 diag::warn_format_nonsensical_length); 8259 else if (!FS.hasStandardLengthModifier()) 8260 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8261 else if (!FS.hasStandardLengthConversionCombination()) 8262 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8263 diag::warn_format_non_standard_conversion_spec); 8264 8265 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8266 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8267 8268 // The remaining checks depend on the data arguments. 8269 if (HasVAListArg) 8270 return true; 8271 8272 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8273 return false; 8274 8275 const Expr *Arg = getDataArg(argIndex); 8276 if (!Arg) 8277 return true; 8278 8279 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8280 } 8281 8282 static bool requiresParensToAddCast(const Expr *E) { 8283 // FIXME: We should have a general way to reason about operator 8284 // precedence and whether parens are actually needed here. 8285 // Take care of a few common cases where they aren't. 8286 const Expr *Inside = E->IgnoreImpCasts(); 8287 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8288 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8289 8290 switch (Inside->getStmtClass()) { 8291 case Stmt::ArraySubscriptExprClass: 8292 case Stmt::CallExprClass: 8293 case Stmt::CharacterLiteralClass: 8294 case Stmt::CXXBoolLiteralExprClass: 8295 case Stmt::DeclRefExprClass: 8296 case Stmt::FloatingLiteralClass: 8297 case Stmt::IntegerLiteralClass: 8298 case Stmt::MemberExprClass: 8299 case Stmt::ObjCArrayLiteralClass: 8300 case Stmt::ObjCBoolLiteralExprClass: 8301 case Stmt::ObjCBoxedExprClass: 8302 case Stmt::ObjCDictionaryLiteralClass: 8303 case Stmt::ObjCEncodeExprClass: 8304 case Stmt::ObjCIvarRefExprClass: 8305 case Stmt::ObjCMessageExprClass: 8306 case Stmt::ObjCPropertyRefExprClass: 8307 case Stmt::ObjCStringLiteralClass: 8308 case Stmt::ObjCSubscriptRefExprClass: 8309 case Stmt::ParenExprClass: 8310 case Stmt::StringLiteralClass: 8311 case Stmt::UnaryOperatorClass: 8312 return false; 8313 default: 8314 return true; 8315 } 8316 } 8317 8318 static std::pair<QualType, StringRef> 8319 shouldNotPrintDirectly(const ASTContext &Context, 8320 QualType IntendedTy, 8321 const Expr *E) { 8322 // Use a 'while' to peel off layers of typedefs. 8323 QualType TyTy = IntendedTy; 8324 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8325 StringRef Name = UserTy->getDecl()->getName(); 8326 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8327 .Case("CFIndex", Context.getNSIntegerType()) 8328 .Case("NSInteger", Context.getNSIntegerType()) 8329 .Case("NSUInteger", Context.getNSUIntegerType()) 8330 .Case("SInt32", Context.IntTy) 8331 .Case("UInt32", Context.UnsignedIntTy) 8332 .Default(QualType()); 8333 8334 if (!CastTy.isNull()) 8335 return std::make_pair(CastTy, Name); 8336 8337 TyTy = UserTy->desugar(); 8338 } 8339 8340 // Strip parens if necessary. 8341 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8342 return shouldNotPrintDirectly(Context, 8343 PE->getSubExpr()->getType(), 8344 PE->getSubExpr()); 8345 8346 // If this is a conditional expression, then its result type is constructed 8347 // via usual arithmetic conversions and thus there might be no necessary 8348 // typedef sugar there. Recurse to operands to check for NSInteger & 8349 // Co. usage condition. 8350 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8351 QualType TrueTy, FalseTy; 8352 StringRef TrueName, FalseName; 8353 8354 std::tie(TrueTy, TrueName) = 8355 shouldNotPrintDirectly(Context, 8356 CO->getTrueExpr()->getType(), 8357 CO->getTrueExpr()); 8358 std::tie(FalseTy, FalseName) = 8359 shouldNotPrintDirectly(Context, 8360 CO->getFalseExpr()->getType(), 8361 CO->getFalseExpr()); 8362 8363 if (TrueTy == FalseTy) 8364 return std::make_pair(TrueTy, TrueName); 8365 else if (TrueTy.isNull()) 8366 return std::make_pair(FalseTy, FalseName); 8367 else if (FalseTy.isNull()) 8368 return std::make_pair(TrueTy, TrueName); 8369 } 8370 8371 return std::make_pair(QualType(), StringRef()); 8372 } 8373 8374 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8375 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8376 /// type do not count. 8377 static bool 8378 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8379 QualType From = ICE->getSubExpr()->getType(); 8380 QualType To = ICE->getType(); 8381 // It's an integer promotion if the destination type is the promoted 8382 // source type. 8383 if (ICE->getCastKind() == CK_IntegralCast && 8384 From->isPromotableIntegerType() && 8385 S.Context.getPromotedIntegerType(From) == To) 8386 return true; 8387 // Look through vector types, since we do default argument promotion for 8388 // those in OpenCL. 8389 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8390 From = VecTy->getElementType(); 8391 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8392 To = VecTy->getElementType(); 8393 // It's a floating promotion if the source type is a lower rank. 8394 return ICE->getCastKind() == CK_FloatingCast && 8395 S.Context.getFloatingTypeOrder(From, To) < 0; 8396 } 8397 8398 bool 8399 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8400 const char *StartSpecifier, 8401 unsigned SpecifierLen, 8402 const Expr *E) { 8403 using namespace analyze_format_string; 8404 using namespace analyze_printf; 8405 8406 // Now type check the data expression that matches the 8407 // format specifier. 8408 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8409 if (!AT.isValid()) 8410 return true; 8411 8412 QualType ExprTy = E->getType(); 8413 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8414 ExprTy = TET->getUnderlyingExpr()->getType(); 8415 } 8416 8417 // Diagnose attempts to print a boolean value as a character. Unlike other 8418 // -Wformat diagnostics, this is fine from a type perspective, but it still 8419 // doesn't make sense. 8420 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8421 E->isKnownToHaveBooleanValue()) { 8422 const CharSourceRange &CSR = 8423 getSpecifierRange(StartSpecifier, SpecifierLen); 8424 SmallString<4> FSString; 8425 llvm::raw_svector_ostream os(FSString); 8426 FS.toString(os); 8427 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8428 << FSString, 8429 E->getExprLoc(), false, CSR); 8430 return true; 8431 } 8432 8433 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8434 if (Match == analyze_printf::ArgType::Match) 8435 return true; 8436 8437 // Look through argument promotions for our error message's reported type. 8438 // This includes the integral and floating promotions, but excludes array 8439 // and function pointer decay (seeing that an argument intended to be a 8440 // string has type 'char [6]' is probably more confusing than 'char *') and 8441 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8442 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8443 if (isArithmeticArgumentPromotion(S, ICE)) { 8444 E = ICE->getSubExpr(); 8445 ExprTy = E->getType(); 8446 8447 // Check if we didn't match because of an implicit cast from a 'char' 8448 // or 'short' to an 'int'. This is done because printf is a varargs 8449 // function. 8450 if (ICE->getType() == S.Context.IntTy || 8451 ICE->getType() == S.Context.UnsignedIntTy) { 8452 // All further checking is done on the subexpression 8453 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8454 AT.matchesType(S.Context, ExprTy); 8455 if (ImplicitMatch == analyze_printf::ArgType::Match) 8456 return true; 8457 if (ImplicitMatch == ArgType::NoMatchPedantic || 8458 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8459 Match = ImplicitMatch; 8460 } 8461 } 8462 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8463 // Special case for 'a', which has type 'int' in C. 8464 // Note, however, that we do /not/ want to treat multibyte constants like 8465 // 'MooV' as characters! This form is deprecated but still exists. 8466 if (ExprTy == S.Context.IntTy) 8467 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8468 ExprTy = S.Context.CharTy; 8469 } 8470 8471 // Look through enums to their underlying type. 8472 bool IsEnum = false; 8473 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8474 ExprTy = EnumTy->getDecl()->getIntegerType(); 8475 IsEnum = true; 8476 } 8477 8478 // %C in an Objective-C context prints a unichar, not a wchar_t. 8479 // If the argument is an integer of some kind, believe the %C and suggest 8480 // a cast instead of changing the conversion specifier. 8481 QualType IntendedTy = ExprTy; 8482 if (isObjCContext() && 8483 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8484 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8485 !ExprTy->isCharType()) { 8486 // 'unichar' is defined as a typedef of unsigned short, but we should 8487 // prefer using the typedef if it is visible. 8488 IntendedTy = S.Context.UnsignedShortTy; 8489 8490 // While we are here, check if the value is an IntegerLiteral that happens 8491 // to be within the valid range. 8492 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8493 const llvm::APInt &V = IL->getValue(); 8494 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8495 return true; 8496 } 8497 8498 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8499 Sema::LookupOrdinaryName); 8500 if (S.LookupName(Result, S.getCurScope())) { 8501 NamedDecl *ND = Result.getFoundDecl(); 8502 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8503 if (TD->getUnderlyingType() == IntendedTy) 8504 IntendedTy = S.Context.getTypedefType(TD); 8505 } 8506 } 8507 } 8508 8509 // Special-case some of Darwin's platform-independence types by suggesting 8510 // casts to primitive types that are known to be large enough. 8511 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8512 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8513 QualType CastTy; 8514 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8515 if (!CastTy.isNull()) { 8516 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8517 // (long in ASTContext). Only complain to pedants. 8518 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8519 (AT.isSizeT() || AT.isPtrdiffT()) && 8520 AT.matchesType(S.Context, CastTy)) 8521 Match = ArgType::NoMatchPedantic; 8522 IntendedTy = CastTy; 8523 ShouldNotPrintDirectly = true; 8524 } 8525 } 8526 8527 // We may be able to offer a FixItHint if it is a supported type. 8528 PrintfSpecifier fixedFS = FS; 8529 bool Success = 8530 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8531 8532 if (Success) { 8533 // Get the fix string from the fixed format specifier 8534 SmallString<16> buf; 8535 llvm::raw_svector_ostream os(buf); 8536 fixedFS.toString(os); 8537 8538 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8539 8540 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8541 unsigned Diag; 8542 switch (Match) { 8543 case ArgType::Match: llvm_unreachable("expected non-matching"); 8544 case ArgType::NoMatchPedantic: 8545 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8546 break; 8547 case ArgType::NoMatchTypeConfusion: 8548 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8549 break; 8550 case ArgType::NoMatch: 8551 Diag = diag::warn_format_conversion_argument_type_mismatch; 8552 break; 8553 } 8554 8555 // In this case, the specifier is wrong and should be changed to match 8556 // the argument. 8557 EmitFormatDiagnostic(S.PDiag(Diag) 8558 << AT.getRepresentativeTypeName(S.Context) 8559 << IntendedTy << IsEnum << E->getSourceRange(), 8560 E->getBeginLoc(), 8561 /*IsStringLocation*/ false, SpecRange, 8562 FixItHint::CreateReplacement(SpecRange, os.str())); 8563 } else { 8564 // The canonical type for formatting this value is different from the 8565 // actual type of the expression. (This occurs, for example, with Darwin's 8566 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8567 // should be printed as 'long' for 64-bit compatibility.) 8568 // Rather than emitting a normal format/argument mismatch, we want to 8569 // add a cast to the recommended type (and correct the format string 8570 // if necessary). 8571 SmallString<16> CastBuf; 8572 llvm::raw_svector_ostream CastFix(CastBuf); 8573 CastFix << "("; 8574 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8575 CastFix << ")"; 8576 8577 SmallVector<FixItHint,4> Hints; 8578 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8579 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8580 8581 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8582 // If there's already a cast present, just replace it. 8583 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8584 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8585 8586 } else if (!requiresParensToAddCast(E)) { 8587 // If the expression has high enough precedence, 8588 // just write the C-style cast. 8589 Hints.push_back( 8590 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8591 } else { 8592 // Otherwise, add parens around the expression as well as the cast. 8593 CastFix << "("; 8594 Hints.push_back( 8595 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8596 8597 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8598 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8599 } 8600 8601 if (ShouldNotPrintDirectly) { 8602 // The expression has a type that should not be printed directly. 8603 // We extract the name from the typedef because we don't want to show 8604 // the underlying type in the diagnostic. 8605 StringRef Name; 8606 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8607 Name = TypedefTy->getDecl()->getName(); 8608 else 8609 Name = CastTyName; 8610 unsigned Diag = Match == ArgType::NoMatchPedantic 8611 ? diag::warn_format_argument_needs_cast_pedantic 8612 : diag::warn_format_argument_needs_cast; 8613 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8614 << E->getSourceRange(), 8615 E->getBeginLoc(), /*IsStringLocation=*/false, 8616 SpecRange, Hints); 8617 } else { 8618 // In this case, the expression could be printed using a different 8619 // specifier, but we've decided that the specifier is probably correct 8620 // and we should cast instead. Just use the normal warning message. 8621 EmitFormatDiagnostic( 8622 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8623 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8624 << E->getSourceRange(), 8625 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8626 } 8627 } 8628 } else { 8629 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8630 SpecifierLen); 8631 // Since the warning for passing non-POD types to variadic functions 8632 // was deferred until now, we emit a warning for non-POD 8633 // arguments here. 8634 switch (S.isValidVarArgType(ExprTy)) { 8635 case Sema::VAK_Valid: 8636 case Sema::VAK_ValidInCXX11: { 8637 unsigned Diag; 8638 switch (Match) { 8639 case ArgType::Match: llvm_unreachable("expected non-matching"); 8640 case ArgType::NoMatchPedantic: 8641 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8642 break; 8643 case ArgType::NoMatchTypeConfusion: 8644 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8645 break; 8646 case ArgType::NoMatch: 8647 Diag = diag::warn_format_conversion_argument_type_mismatch; 8648 break; 8649 } 8650 8651 EmitFormatDiagnostic( 8652 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8653 << IsEnum << CSR << E->getSourceRange(), 8654 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8655 break; 8656 } 8657 case Sema::VAK_Undefined: 8658 case Sema::VAK_MSVCUndefined: 8659 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8660 << S.getLangOpts().CPlusPlus11 << ExprTy 8661 << CallType 8662 << AT.getRepresentativeTypeName(S.Context) << CSR 8663 << E->getSourceRange(), 8664 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8665 checkForCStrMembers(AT, E); 8666 break; 8667 8668 case Sema::VAK_Invalid: 8669 if (ExprTy->isObjCObjectType()) 8670 EmitFormatDiagnostic( 8671 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8672 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8673 << AT.getRepresentativeTypeName(S.Context) << CSR 8674 << E->getSourceRange(), 8675 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8676 else 8677 // FIXME: If this is an initializer list, suggest removing the braces 8678 // or inserting a cast to the target type. 8679 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8680 << isa<InitListExpr>(E) << ExprTy << CallType 8681 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8682 break; 8683 } 8684 8685 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8686 "format string specifier index out of range"); 8687 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8688 } 8689 8690 return true; 8691 } 8692 8693 //===--- CHECK: Scanf format string checking ------------------------------===// 8694 8695 namespace { 8696 8697 class CheckScanfHandler : public CheckFormatHandler { 8698 public: 8699 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8700 const Expr *origFormatExpr, Sema::FormatStringType type, 8701 unsigned firstDataArg, unsigned numDataArgs, 8702 const char *beg, bool hasVAListArg, 8703 ArrayRef<const Expr *> Args, unsigned formatIdx, 8704 bool inFunctionCall, Sema::VariadicCallType CallType, 8705 llvm::SmallBitVector &CheckedVarArgs, 8706 UncoveredArgHandler &UncoveredArg) 8707 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8708 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8709 inFunctionCall, CallType, CheckedVarArgs, 8710 UncoveredArg) {} 8711 8712 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8713 const char *startSpecifier, 8714 unsigned specifierLen) override; 8715 8716 bool HandleInvalidScanfConversionSpecifier( 8717 const analyze_scanf::ScanfSpecifier &FS, 8718 const char *startSpecifier, 8719 unsigned specifierLen) override; 8720 8721 void HandleIncompleteScanList(const char *start, const char *end) override; 8722 }; 8723 8724 } // namespace 8725 8726 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8727 const char *end) { 8728 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8729 getLocationOfByte(end), /*IsStringLocation*/true, 8730 getSpecifierRange(start, end - start)); 8731 } 8732 8733 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8734 const analyze_scanf::ScanfSpecifier &FS, 8735 const char *startSpecifier, 8736 unsigned specifierLen) { 8737 const analyze_scanf::ScanfConversionSpecifier &CS = 8738 FS.getConversionSpecifier(); 8739 8740 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8741 getLocationOfByte(CS.getStart()), 8742 startSpecifier, specifierLen, 8743 CS.getStart(), CS.getLength()); 8744 } 8745 8746 bool CheckScanfHandler::HandleScanfSpecifier( 8747 const analyze_scanf::ScanfSpecifier &FS, 8748 const char *startSpecifier, 8749 unsigned specifierLen) { 8750 using namespace analyze_scanf; 8751 using namespace analyze_format_string; 8752 8753 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8754 8755 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8756 // be used to decide if we are using positional arguments consistently. 8757 if (FS.consumesDataArgument()) { 8758 if (atFirstArg) { 8759 atFirstArg = false; 8760 usesPositionalArgs = FS.usesPositionalArg(); 8761 } 8762 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8763 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8764 startSpecifier, specifierLen); 8765 return false; 8766 } 8767 } 8768 8769 // Check if the field with is non-zero. 8770 const OptionalAmount &Amt = FS.getFieldWidth(); 8771 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8772 if (Amt.getConstantAmount() == 0) { 8773 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8774 Amt.getConstantLength()); 8775 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8776 getLocationOfByte(Amt.getStart()), 8777 /*IsStringLocation*/true, R, 8778 FixItHint::CreateRemoval(R)); 8779 } 8780 } 8781 8782 if (!FS.consumesDataArgument()) { 8783 // FIXME: Technically specifying a precision or field width here 8784 // makes no sense. Worth issuing a warning at some point. 8785 return true; 8786 } 8787 8788 // Consume the argument. 8789 unsigned argIndex = FS.getArgIndex(); 8790 if (argIndex < NumDataArgs) { 8791 // The check to see if the argIndex is valid will come later. 8792 // We set the bit here because we may exit early from this 8793 // function if we encounter some other error. 8794 CoveredArgs.set(argIndex); 8795 } 8796 8797 // Check the length modifier is valid with the given conversion specifier. 8798 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8799 S.getLangOpts())) 8800 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8801 diag::warn_format_nonsensical_length); 8802 else if (!FS.hasStandardLengthModifier()) 8803 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8804 else if (!FS.hasStandardLengthConversionCombination()) 8805 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8806 diag::warn_format_non_standard_conversion_spec); 8807 8808 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8809 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8810 8811 // The remaining checks depend on the data arguments. 8812 if (HasVAListArg) 8813 return true; 8814 8815 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8816 return false; 8817 8818 // Check that the argument type matches the format specifier. 8819 const Expr *Ex = getDataArg(argIndex); 8820 if (!Ex) 8821 return true; 8822 8823 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8824 8825 if (!AT.isValid()) { 8826 return true; 8827 } 8828 8829 analyze_format_string::ArgType::MatchKind Match = 8830 AT.matchesType(S.Context, Ex->getType()); 8831 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8832 if (Match == analyze_format_string::ArgType::Match) 8833 return true; 8834 8835 ScanfSpecifier fixedFS = FS; 8836 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8837 S.getLangOpts(), S.Context); 8838 8839 unsigned Diag = 8840 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8841 : diag::warn_format_conversion_argument_type_mismatch; 8842 8843 if (Success) { 8844 // Get the fix string from the fixed format specifier. 8845 SmallString<128> buf; 8846 llvm::raw_svector_ostream os(buf); 8847 fixedFS.toString(os); 8848 8849 EmitFormatDiagnostic( 8850 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8851 << Ex->getType() << false << Ex->getSourceRange(), 8852 Ex->getBeginLoc(), 8853 /*IsStringLocation*/ false, 8854 getSpecifierRange(startSpecifier, specifierLen), 8855 FixItHint::CreateReplacement( 8856 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8857 } else { 8858 EmitFormatDiagnostic(S.PDiag(Diag) 8859 << AT.getRepresentativeTypeName(S.Context) 8860 << Ex->getType() << false << Ex->getSourceRange(), 8861 Ex->getBeginLoc(), 8862 /*IsStringLocation*/ false, 8863 getSpecifierRange(startSpecifier, specifierLen)); 8864 } 8865 8866 return true; 8867 } 8868 8869 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8870 const Expr *OrigFormatExpr, 8871 ArrayRef<const Expr *> Args, 8872 bool HasVAListArg, unsigned format_idx, 8873 unsigned firstDataArg, 8874 Sema::FormatStringType Type, 8875 bool inFunctionCall, 8876 Sema::VariadicCallType CallType, 8877 llvm::SmallBitVector &CheckedVarArgs, 8878 UncoveredArgHandler &UncoveredArg, 8879 bool IgnoreStringsWithoutSpecifiers) { 8880 // CHECK: is the format string a wide literal? 8881 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8882 CheckFormatHandler::EmitFormatDiagnostic( 8883 S, inFunctionCall, Args[format_idx], 8884 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8885 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8886 return; 8887 } 8888 8889 // Str - The format string. NOTE: this is NOT null-terminated! 8890 StringRef StrRef = FExpr->getString(); 8891 const char *Str = StrRef.data(); 8892 // Account for cases where the string literal is truncated in a declaration. 8893 const ConstantArrayType *T = 8894 S.Context.getAsConstantArrayType(FExpr->getType()); 8895 assert(T && "String literal not of constant array type!"); 8896 size_t TypeSize = T->getSize().getZExtValue(); 8897 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8898 const unsigned numDataArgs = Args.size() - firstDataArg; 8899 8900 if (IgnoreStringsWithoutSpecifiers && 8901 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8902 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8903 return; 8904 8905 // Emit a warning if the string literal is truncated and does not contain an 8906 // embedded null character. 8907 if (TypeSize <= StrRef.size() && 8908 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8909 CheckFormatHandler::EmitFormatDiagnostic( 8910 S, inFunctionCall, Args[format_idx], 8911 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8912 FExpr->getBeginLoc(), 8913 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8914 return; 8915 } 8916 8917 // CHECK: empty format string? 8918 if (StrLen == 0 && numDataArgs > 0) { 8919 CheckFormatHandler::EmitFormatDiagnostic( 8920 S, inFunctionCall, Args[format_idx], 8921 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8922 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8923 return; 8924 } 8925 8926 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8927 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8928 Type == Sema::FST_OSTrace) { 8929 CheckPrintfHandler H( 8930 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8931 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8932 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8933 CheckedVarArgs, UncoveredArg); 8934 8935 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8936 S.getLangOpts(), 8937 S.Context.getTargetInfo(), 8938 Type == Sema::FST_FreeBSDKPrintf)) 8939 H.DoneProcessing(); 8940 } else if (Type == Sema::FST_Scanf) { 8941 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8942 numDataArgs, Str, HasVAListArg, Args, format_idx, 8943 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8944 8945 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8946 S.getLangOpts(), 8947 S.Context.getTargetInfo())) 8948 H.DoneProcessing(); 8949 } // TODO: handle other formats 8950 } 8951 8952 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8953 // Str - The format string. NOTE: this is NOT null-terminated! 8954 StringRef StrRef = FExpr->getString(); 8955 const char *Str = StrRef.data(); 8956 // Account for cases where the string literal is truncated in a declaration. 8957 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8958 assert(T && "String literal not of constant array type!"); 8959 size_t TypeSize = T->getSize().getZExtValue(); 8960 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8961 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8962 getLangOpts(), 8963 Context.getTargetInfo()); 8964 } 8965 8966 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8967 8968 // Returns the related absolute value function that is larger, of 0 if one 8969 // does not exist. 8970 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8971 switch (AbsFunction) { 8972 default: 8973 return 0; 8974 8975 case Builtin::BI__builtin_abs: 8976 return Builtin::BI__builtin_labs; 8977 case Builtin::BI__builtin_labs: 8978 return Builtin::BI__builtin_llabs; 8979 case Builtin::BI__builtin_llabs: 8980 return 0; 8981 8982 case Builtin::BI__builtin_fabsf: 8983 return Builtin::BI__builtin_fabs; 8984 case Builtin::BI__builtin_fabs: 8985 return Builtin::BI__builtin_fabsl; 8986 case Builtin::BI__builtin_fabsl: 8987 return 0; 8988 8989 case Builtin::BI__builtin_cabsf: 8990 return Builtin::BI__builtin_cabs; 8991 case Builtin::BI__builtin_cabs: 8992 return Builtin::BI__builtin_cabsl; 8993 case Builtin::BI__builtin_cabsl: 8994 return 0; 8995 8996 case Builtin::BIabs: 8997 return Builtin::BIlabs; 8998 case Builtin::BIlabs: 8999 return Builtin::BIllabs; 9000 case Builtin::BIllabs: 9001 return 0; 9002 9003 case Builtin::BIfabsf: 9004 return Builtin::BIfabs; 9005 case Builtin::BIfabs: 9006 return Builtin::BIfabsl; 9007 case Builtin::BIfabsl: 9008 return 0; 9009 9010 case Builtin::BIcabsf: 9011 return Builtin::BIcabs; 9012 case Builtin::BIcabs: 9013 return Builtin::BIcabsl; 9014 case Builtin::BIcabsl: 9015 return 0; 9016 } 9017 } 9018 9019 // Returns the argument type of the absolute value function. 9020 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9021 unsigned AbsType) { 9022 if (AbsType == 0) 9023 return QualType(); 9024 9025 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9026 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9027 if (Error != ASTContext::GE_None) 9028 return QualType(); 9029 9030 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9031 if (!FT) 9032 return QualType(); 9033 9034 if (FT->getNumParams() != 1) 9035 return QualType(); 9036 9037 return FT->getParamType(0); 9038 } 9039 9040 // Returns the best absolute value function, or zero, based on type and 9041 // current absolute value function. 9042 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9043 unsigned AbsFunctionKind) { 9044 unsigned BestKind = 0; 9045 uint64_t ArgSize = Context.getTypeSize(ArgType); 9046 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9047 Kind = getLargerAbsoluteValueFunction(Kind)) { 9048 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9049 if (Context.getTypeSize(ParamType) >= ArgSize) { 9050 if (BestKind == 0) 9051 BestKind = Kind; 9052 else if (Context.hasSameType(ParamType, ArgType)) { 9053 BestKind = Kind; 9054 break; 9055 } 9056 } 9057 } 9058 return BestKind; 9059 } 9060 9061 enum AbsoluteValueKind { 9062 AVK_Integer, 9063 AVK_Floating, 9064 AVK_Complex 9065 }; 9066 9067 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9068 if (T->isIntegralOrEnumerationType()) 9069 return AVK_Integer; 9070 if (T->isRealFloatingType()) 9071 return AVK_Floating; 9072 if (T->isAnyComplexType()) 9073 return AVK_Complex; 9074 9075 llvm_unreachable("Type not integer, floating, or complex"); 9076 } 9077 9078 // Changes the absolute value function to a different type. Preserves whether 9079 // the function is a builtin. 9080 static unsigned changeAbsFunction(unsigned AbsKind, 9081 AbsoluteValueKind ValueKind) { 9082 switch (ValueKind) { 9083 case AVK_Integer: 9084 switch (AbsKind) { 9085 default: 9086 return 0; 9087 case Builtin::BI__builtin_fabsf: 9088 case Builtin::BI__builtin_fabs: 9089 case Builtin::BI__builtin_fabsl: 9090 case Builtin::BI__builtin_cabsf: 9091 case Builtin::BI__builtin_cabs: 9092 case Builtin::BI__builtin_cabsl: 9093 return Builtin::BI__builtin_abs; 9094 case Builtin::BIfabsf: 9095 case Builtin::BIfabs: 9096 case Builtin::BIfabsl: 9097 case Builtin::BIcabsf: 9098 case Builtin::BIcabs: 9099 case Builtin::BIcabsl: 9100 return Builtin::BIabs; 9101 } 9102 case AVK_Floating: 9103 switch (AbsKind) { 9104 default: 9105 return 0; 9106 case Builtin::BI__builtin_abs: 9107 case Builtin::BI__builtin_labs: 9108 case Builtin::BI__builtin_llabs: 9109 case Builtin::BI__builtin_cabsf: 9110 case Builtin::BI__builtin_cabs: 9111 case Builtin::BI__builtin_cabsl: 9112 return Builtin::BI__builtin_fabsf; 9113 case Builtin::BIabs: 9114 case Builtin::BIlabs: 9115 case Builtin::BIllabs: 9116 case Builtin::BIcabsf: 9117 case Builtin::BIcabs: 9118 case Builtin::BIcabsl: 9119 return Builtin::BIfabsf; 9120 } 9121 case AVK_Complex: 9122 switch (AbsKind) { 9123 default: 9124 return 0; 9125 case Builtin::BI__builtin_abs: 9126 case Builtin::BI__builtin_labs: 9127 case Builtin::BI__builtin_llabs: 9128 case Builtin::BI__builtin_fabsf: 9129 case Builtin::BI__builtin_fabs: 9130 case Builtin::BI__builtin_fabsl: 9131 return Builtin::BI__builtin_cabsf; 9132 case Builtin::BIabs: 9133 case Builtin::BIlabs: 9134 case Builtin::BIllabs: 9135 case Builtin::BIfabsf: 9136 case Builtin::BIfabs: 9137 case Builtin::BIfabsl: 9138 return Builtin::BIcabsf; 9139 } 9140 } 9141 llvm_unreachable("Unable to convert function"); 9142 } 9143 9144 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9145 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9146 if (!FnInfo) 9147 return 0; 9148 9149 switch (FDecl->getBuiltinID()) { 9150 default: 9151 return 0; 9152 case Builtin::BI__builtin_abs: 9153 case Builtin::BI__builtin_fabs: 9154 case Builtin::BI__builtin_fabsf: 9155 case Builtin::BI__builtin_fabsl: 9156 case Builtin::BI__builtin_labs: 9157 case Builtin::BI__builtin_llabs: 9158 case Builtin::BI__builtin_cabs: 9159 case Builtin::BI__builtin_cabsf: 9160 case Builtin::BI__builtin_cabsl: 9161 case Builtin::BIabs: 9162 case Builtin::BIlabs: 9163 case Builtin::BIllabs: 9164 case Builtin::BIfabs: 9165 case Builtin::BIfabsf: 9166 case Builtin::BIfabsl: 9167 case Builtin::BIcabs: 9168 case Builtin::BIcabsf: 9169 case Builtin::BIcabsl: 9170 return FDecl->getBuiltinID(); 9171 } 9172 llvm_unreachable("Unknown Builtin type"); 9173 } 9174 9175 // If the replacement is valid, emit a note with replacement function. 9176 // Additionally, suggest including the proper header if not already included. 9177 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9178 unsigned AbsKind, QualType ArgType) { 9179 bool EmitHeaderHint = true; 9180 const char *HeaderName = nullptr; 9181 const char *FunctionName = nullptr; 9182 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9183 FunctionName = "std::abs"; 9184 if (ArgType->isIntegralOrEnumerationType()) { 9185 HeaderName = "cstdlib"; 9186 } else if (ArgType->isRealFloatingType()) { 9187 HeaderName = "cmath"; 9188 } else { 9189 llvm_unreachable("Invalid Type"); 9190 } 9191 9192 // Lookup all std::abs 9193 if (NamespaceDecl *Std = S.getStdNamespace()) { 9194 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9195 R.suppressDiagnostics(); 9196 S.LookupQualifiedName(R, Std); 9197 9198 for (const auto *I : R) { 9199 const FunctionDecl *FDecl = nullptr; 9200 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9201 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9202 } else { 9203 FDecl = dyn_cast<FunctionDecl>(I); 9204 } 9205 if (!FDecl) 9206 continue; 9207 9208 // Found std::abs(), check that they are the right ones. 9209 if (FDecl->getNumParams() != 1) 9210 continue; 9211 9212 // Check that the parameter type can handle the argument. 9213 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9214 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9215 S.Context.getTypeSize(ArgType) <= 9216 S.Context.getTypeSize(ParamType)) { 9217 // Found a function, don't need the header hint. 9218 EmitHeaderHint = false; 9219 break; 9220 } 9221 } 9222 } 9223 } else { 9224 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9225 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9226 9227 if (HeaderName) { 9228 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9229 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9230 R.suppressDiagnostics(); 9231 S.LookupName(R, S.getCurScope()); 9232 9233 if (R.isSingleResult()) { 9234 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9235 if (FD && FD->getBuiltinID() == AbsKind) { 9236 EmitHeaderHint = false; 9237 } else { 9238 return; 9239 } 9240 } else if (!R.empty()) { 9241 return; 9242 } 9243 } 9244 } 9245 9246 S.Diag(Loc, diag::note_replace_abs_function) 9247 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9248 9249 if (!HeaderName) 9250 return; 9251 9252 if (!EmitHeaderHint) 9253 return; 9254 9255 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9256 << FunctionName; 9257 } 9258 9259 template <std::size_t StrLen> 9260 static bool IsStdFunction(const FunctionDecl *FDecl, 9261 const char (&Str)[StrLen]) { 9262 if (!FDecl) 9263 return false; 9264 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9265 return false; 9266 if (!FDecl->isInStdNamespace()) 9267 return false; 9268 9269 return true; 9270 } 9271 9272 // Warn when using the wrong abs() function. 9273 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9274 const FunctionDecl *FDecl) { 9275 if (Call->getNumArgs() != 1) 9276 return; 9277 9278 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9279 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9280 if (AbsKind == 0 && !IsStdAbs) 9281 return; 9282 9283 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9284 QualType ParamType = Call->getArg(0)->getType(); 9285 9286 // Unsigned types cannot be negative. Suggest removing the absolute value 9287 // function call. 9288 if (ArgType->isUnsignedIntegerType()) { 9289 const char *FunctionName = 9290 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9291 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9292 Diag(Call->getExprLoc(), diag::note_remove_abs) 9293 << FunctionName 9294 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9295 return; 9296 } 9297 9298 // Taking the absolute value of a pointer is very suspicious, they probably 9299 // wanted to index into an array, dereference a pointer, call a function, etc. 9300 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9301 unsigned DiagType = 0; 9302 if (ArgType->isFunctionType()) 9303 DiagType = 1; 9304 else if (ArgType->isArrayType()) 9305 DiagType = 2; 9306 9307 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9308 return; 9309 } 9310 9311 // std::abs has overloads which prevent most of the absolute value problems 9312 // from occurring. 9313 if (IsStdAbs) 9314 return; 9315 9316 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9317 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9318 9319 // The argument and parameter are the same kind. Check if they are the right 9320 // size. 9321 if (ArgValueKind == ParamValueKind) { 9322 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9323 return; 9324 9325 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9326 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9327 << FDecl << ArgType << ParamType; 9328 9329 if (NewAbsKind == 0) 9330 return; 9331 9332 emitReplacement(*this, Call->getExprLoc(), 9333 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9334 return; 9335 } 9336 9337 // ArgValueKind != ParamValueKind 9338 // The wrong type of absolute value function was used. Attempt to find the 9339 // proper one. 9340 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9341 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9342 if (NewAbsKind == 0) 9343 return; 9344 9345 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9346 << FDecl << ParamValueKind << ArgValueKind; 9347 9348 emitReplacement(*this, Call->getExprLoc(), 9349 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9350 } 9351 9352 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9353 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9354 const FunctionDecl *FDecl) { 9355 if (!Call || !FDecl) return; 9356 9357 // Ignore template specializations and macros. 9358 if (inTemplateInstantiation()) return; 9359 if (Call->getExprLoc().isMacroID()) return; 9360 9361 // Only care about the one template argument, two function parameter std::max 9362 if (Call->getNumArgs() != 2) return; 9363 if (!IsStdFunction(FDecl, "max")) return; 9364 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9365 if (!ArgList) return; 9366 if (ArgList->size() != 1) return; 9367 9368 // Check that template type argument is unsigned integer. 9369 const auto& TA = ArgList->get(0); 9370 if (TA.getKind() != TemplateArgument::Type) return; 9371 QualType ArgType = TA.getAsType(); 9372 if (!ArgType->isUnsignedIntegerType()) return; 9373 9374 // See if either argument is a literal zero. 9375 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9376 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9377 if (!MTE) return false; 9378 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9379 if (!Num) return false; 9380 if (Num->getValue() != 0) return false; 9381 return true; 9382 }; 9383 9384 const Expr *FirstArg = Call->getArg(0); 9385 const Expr *SecondArg = Call->getArg(1); 9386 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9387 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9388 9389 // Only warn when exactly one argument is zero. 9390 if (IsFirstArgZero == IsSecondArgZero) return; 9391 9392 SourceRange FirstRange = FirstArg->getSourceRange(); 9393 SourceRange SecondRange = SecondArg->getSourceRange(); 9394 9395 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9396 9397 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9398 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9399 9400 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9401 SourceRange RemovalRange; 9402 if (IsFirstArgZero) { 9403 RemovalRange = SourceRange(FirstRange.getBegin(), 9404 SecondRange.getBegin().getLocWithOffset(-1)); 9405 } else { 9406 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9407 SecondRange.getEnd()); 9408 } 9409 9410 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9411 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9412 << FixItHint::CreateRemoval(RemovalRange); 9413 } 9414 9415 //===--- CHECK: Standard memory functions ---------------------------------===// 9416 9417 /// Takes the expression passed to the size_t parameter of functions 9418 /// such as memcmp, strncat, etc and warns if it's a comparison. 9419 /// 9420 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9421 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9422 IdentifierInfo *FnName, 9423 SourceLocation FnLoc, 9424 SourceLocation RParenLoc) { 9425 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9426 if (!Size) 9427 return false; 9428 9429 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9430 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9431 return false; 9432 9433 SourceRange SizeRange = Size->getSourceRange(); 9434 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9435 << SizeRange << FnName; 9436 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9437 << FnName 9438 << FixItHint::CreateInsertion( 9439 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9440 << FixItHint::CreateRemoval(RParenLoc); 9441 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9442 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9443 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9444 ")"); 9445 9446 return true; 9447 } 9448 9449 /// Determine whether the given type is or contains a dynamic class type 9450 /// (e.g., whether it has a vtable). 9451 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9452 bool &IsContained) { 9453 // Look through array types while ignoring qualifiers. 9454 const Type *Ty = T->getBaseElementTypeUnsafe(); 9455 IsContained = false; 9456 9457 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9458 RD = RD ? RD->getDefinition() : nullptr; 9459 if (!RD || RD->isInvalidDecl()) 9460 return nullptr; 9461 9462 if (RD->isDynamicClass()) 9463 return RD; 9464 9465 // Check all the fields. If any bases were dynamic, the class is dynamic. 9466 // It's impossible for a class to transitively contain itself by value, so 9467 // infinite recursion is impossible. 9468 for (auto *FD : RD->fields()) { 9469 bool SubContained; 9470 if (const CXXRecordDecl *ContainedRD = 9471 getContainedDynamicClass(FD->getType(), SubContained)) { 9472 IsContained = true; 9473 return ContainedRD; 9474 } 9475 } 9476 9477 return nullptr; 9478 } 9479 9480 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9481 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9482 if (Unary->getKind() == UETT_SizeOf) 9483 return Unary; 9484 return nullptr; 9485 } 9486 9487 /// If E is a sizeof expression, returns its argument expression, 9488 /// otherwise returns NULL. 9489 static const Expr *getSizeOfExprArg(const Expr *E) { 9490 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9491 if (!SizeOf->isArgumentType()) 9492 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9493 return nullptr; 9494 } 9495 9496 /// If E is a sizeof expression, returns its argument type. 9497 static QualType getSizeOfArgType(const Expr *E) { 9498 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9499 return SizeOf->getTypeOfArgument(); 9500 return QualType(); 9501 } 9502 9503 namespace { 9504 9505 struct SearchNonTrivialToInitializeField 9506 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9507 using Super = 9508 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9509 9510 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9511 9512 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9513 SourceLocation SL) { 9514 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9515 asDerived().visitArray(PDIK, AT, SL); 9516 return; 9517 } 9518 9519 Super::visitWithKind(PDIK, FT, SL); 9520 } 9521 9522 void visitARCStrong(QualType FT, SourceLocation SL) { 9523 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9524 } 9525 void visitARCWeak(QualType FT, SourceLocation SL) { 9526 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9527 } 9528 void visitStruct(QualType FT, SourceLocation SL) { 9529 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9530 visit(FD->getType(), FD->getLocation()); 9531 } 9532 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9533 const ArrayType *AT, SourceLocation SL) { 9534 visit(getContext().getBaseElementType(AT), SL); 9535 } 9536 void visitTrivial(QualType FT, SourceLocation SL) {} 9537 9538 static void diag(QualType RT, const Expr *E, Sema &S) { 9539 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9540 } 9541 9542 ASTContext &getContext() { return S.getASTContext(); } 9543 9544 const Expr *E; 9545 Sema &S; 9546 }; 9547 9548 struct SearchNonTrivialToCopyField 9549 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9550 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9551 9552 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9553 9554 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9555 SourceLocation SL) { 9556 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9557 asDerived().visitArray(PCK, AT, SL); 9558 return; 9559 } 9560 9561 Super::visitWithKind(PCK, FT, SL); 9562 } 9563 9564 void visitARCStrong(QualType FT, SourceLocation SL) { 9565 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9566 } 9567 void visitARCWeak(QualType FT, SourceLocation SL) { 9568 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9569 } 9570 void visitStruct(QualType FT, SourceLocation SL) { 9571 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9572 visit(FD->getType(), FD->getLocation()); 9573 } 9574 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9575 SourceLocation SL) { 9576 visit(getContext().getBaseElementType(AT), SL); 9577 } 9578 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9579 SourceLocation SL) {} 9580 void visitTrivial(QualType FT, SourceLocation SL) {} 9581 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9582 9583 static void diag(QualType RT, const Expr *E, Sema &S) { 9584 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9585 } 9586 9587 ASTContext &getContext() { return S.getASTContext(); } 9588 9589 const Expr *E; 9590 Sema &S; 9591 }; 9592 9593 } 9594 9595 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9596 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9597 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9598 9599 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9600 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9601 return false; 9602 9603 return doesExprLikelyComputeSize(BO->getLHS()) || 9604 doesExprLikelyComputeSize(BO->getRHS()); 9605 } 9606 9607 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9608 } 9609 9610 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9611 /// 9612 /// \code 9613 /// #define MACRO 0 9614 /// foo(MACRO); 9615 /// foo(0); 9616 /// \endcode 9617 /// 9618 /// This should return true for the first call to foo, but not for the second 9619 /// (regardless of whether foo is a macro or function). 9620 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9621 SourceLocation CallLoc, 9622 SourceLocation ArgLoc) { 9623 if (!CallLoc.isMacroID()) 9624 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9625 9626 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9627 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9628 } 9629 9630 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9631 /// last two arguments transposed. 9632 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9633 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9634 return; 9635 9636 const Expr *SizeArg = 9637 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9638 9639 auto isLiteralZero = [](const Expr *E) { 9640 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9641 }; 9642 9643 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9644 SourceLocation CallLoc = Call->getRParenLoc(); 9645 SourceManager &SM = S.getSourceManager(); 9646 if (isLiteralZero(SizeArg) && 9647 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9648 9649 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9650 9651 // Some platforms #define bzero to __builtin_memset. See if this is the 9652 // case, and if so, emit a better diagnostic. 9653 if (BId == Builtin::BIbzero || 9654 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9655 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9656 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9657 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9658 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9659 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9660 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9661 } 9662 return; 9663 } 9664 9665 // If the second argument to a memset is a sizeof expression and the third 9666 // isn't, this is also likely an error. This should catch 9667 // 'memset(buf, sizeof(buf), 0xff)'. 9668 if (BId == Builtin::BImemset && 9669 doesExprLikelyComputeSize(Call->getArg(1)) && 9670 !doesExprLikelyComputeSize(Call->getArg(2))) { 9671 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9672 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9673 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9674 return; 9675 } 9676 } 9677 9678 /// Check for dangerous or invalid arguments to memset(). 9679 /// 9680 /// This issues warnings on known problematic, dangerous or unspecified 9681 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9682 /// function calls. 9683 /// 9684 /// \param Call The call expression to diagnose. 9685 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9686 unsigned BId, 9687 IdentifierInfo *FnName) { 9688 assert(BId != 0); 9689 9690 // It is possible to have a non-standard definition of memset. Validate 9691 // we have enough arguments, and if not, abort further checking. 9692 unsigned ExpectedNumArgs = 9693 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9694 if (Call->getNumArgs() < ExpectedNumArgs) 9695 return; 9696 9697 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9698 BId == Builtin::BIstrndup ? 1 : 2); 9699 unsigned LenArg = 9700 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9701 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9702 9703 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9704 Call->getBeginLoc(), Call->getRParenLoc())) 9705 return; 9706 9707 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9708 CheckMemaccessSize(*this, BId, Call); 9709 9710 // We have special checking when the length is a sizeof expression. 9711 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9712 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9713 llvm::FoldingSetNodeID SizeOfArgID; 9714 9715 // Although widely used, 'bzero' is not a standard function. Be more strict 9716 // with the argument types before allowing diagnostics and only allow the 9717 // form bzero(ptr, sizeof(...)). 9718 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9719 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9720 return; 9721 9722 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9723 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9724 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9725 9726 QualType DestTy = Dest->getType(); 9727 QualType PointeeTy; 9728 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9729 PointeeTy = DestPtrTy->getPointeeType(); 9730 9731 // Never warn about void type pointers. This can be used to suppress 9732 // false positives. 9733 if (PointeeTy->isVoidType()) 9734 continue; 9735 9736 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9737 // actually comparing the expressions for equality. Because computing the 9738 // expression IDs can be expensive, we only do this if the diagnostic is 9739 // enabled. 9740 if (SizeOfArg && 9741 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9742 SizeOfArg->getExprLoc())) { 9743 // We only compute IDs for expressions if the warning is enabled, and 9744 // cache the sizeof arg's ID. 9745 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9746 SizeOfArg->Profile(SizeOfArgID, Context, true); 9747 llvm::FoldingSetNodeID DestID; 9748 Dest->Profile(DestID, Context, true); 9749 if (DestID == SizeOfArgID) { 9750 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9751 // over sizeof(src) as well. 9752 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9753 StringRef ReadableName = FnName->getName(); 9754 9755 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9756 if (UnaryOp->getOpcode() == UO_AddrOf) 9757 ActionIdx = 1; // If its an address-of operator, just remove it. 9758 if (!PointeeTy->isIncompleteType() && 9759 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9760 ActionIdx = 2; // If the pointee's size is sizeof(char), 9761 // suggest an explicit length. 9762 9763 // If the function is defined as a builtin macro, do not show macro 9764 // expansion. 9765 SourceLocation SL = SizeOfArg->getExprLoc(); 9766 SourceRange DSR = Dest->getSourceRange(); 9767 SourceRange SSR = SizeOfArg->getSourceRange(); 9768 SourceManager &SM = getSourceManager(); 9769 9770 if (SM.isMacroArgExpansion(SL)) { 9771 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9772 SL = SM.getSpellingLoc(SL); 9773 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9774 SM.getSpellingLoc(DSR.getEnd())); 9775 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9776 SM.getSpellingLoc(SSR.getEnd())); 9777 } 9778 9779 DiagRuntimeBehavior(SL, SizeOfArg, 9780 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9781 << ReadableName 9782 << PointeeTy 9783 << DestTy 9784 << DSR 9785 << SSR); 9786 DiagRuntimeBehavior(SL, SizeOfArg, 9787 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9788 << ActionIdx 9789 << SSR); 9790 9791 break; 9792 } 9793 } 9794 9795 // Also check for cases where the sizeof argument is the exact same 9796 // type as the memory argument, and where it points to a user-defined 9797 // record type. 9798 if (SizeOfArgTy != QualType()) { 9799 if (PointeeTy->isRecordType() && 9800 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9801 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9802 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9803 << FnName << SizeOfArgTy << ArgIdx 9804 << PointeeTy << Dest->getSourceRange() 9805 << LenExpr->getSourceRange()); 9806 break; 9807 } 9808 } 9809 } else if (DestTy->isArrayType()) { 9810 PointeeTy = DestTy; 9811 } 9812 9813 if (PointeeTy == QualType()) 9814 continue; 9815 9816 // Always complain about dynamic classes. 9817 bool IsContained; 9818 if (const CXXRecordDecl *ContainedRD = 9819 getContainedDynamicClass(PointeeTy, IsContained)) { 9820 9821 unsigned OperationType = 0; 9822 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9823 // "overwritten" if we're warning about the destination for any call 9824 // but memcmp; otherwise a verb appropriate to the call. 9825 if (ArgIdx != 0 || IsCmp) { 9826 if (BId == Builtin::BImemcpy) 9827 OperationType = 1; 9828 else if(BId == Builtin::BImemmove) 9829 OperationType = 2; 9830 else if (IsCmp) 9831 OperationType = 3; 9832 } 9833 9834 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9835 PDiag(diag::warn_dyn_class_memaccess) 9836 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9837 << IsContained << ContainedRD << OperationType 9838 << Call->getCallee()->getSourceRange()); 9839 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9840 BId != Builtin::BImemset) 9841 DiagRuntimeBehavior( 9842 Dest->getExprLoc(), Dest, 9843 PDiag(diag::warn_arc_object_memaccess) 9844 << ArgIdx << FnName << PointeeTy 9845 << Call->getCallee()->getSourceRange()); 9846 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9847 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9848 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9849 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9850 PDiag(diag::warn_cstruct_memaccess) 9851 << ArgIdx << FnName << PointeeTy << 0); 9852 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9853 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9854 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9855 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9856 PDiag(diag::warn_cstruct_memaccess) 9857 << ArgIdx << FnName << PointeeTy << 1); 9858 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9859 } else { 9860 continue; 9861 } 9862 } else 9863 continue; 9864 9865 DiagRuntimeBehavior( 9866 Dest->getExprLoc(), Dest, 9867 PDiag(diag::note_bad_memaccess_silence) 9868 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9869 break; 9870 } 9871 } 9872 9873 // A little helper routine: ignore addition and subtraction of integer literals. 9874 // This intentionally does not ignore all integer constant expressions because 9875 // we don't want to remove sizeof(). 9876 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9877 Ex = Ex->IgnoreParenCasts(); 9878 9879 while (true) { 9880 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9881 if (!BO || !BO->isAdditiveOp()) 9882 break; 9883 9884 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9885 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9886 9887 if (isa<IntegerLiteral>(RHS)) 9888 Ex = LHS; 9889 else if (isa<IntegerLiteral>(LHS)) 9890 Ex = RHS; 9891 else 9892 break; 9893 } 9894 9895 return Ex; 9896 } 9897 9898 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9899 ASTContext &Context) { 9900 // Only handle constant-sized or VLAs, but not flexible members. 9901 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9902 // Only issue the FIXIT for arrays of size > 1. 9903 if (CAT->getSize().getSExtValue() <= 1) 9904 return false; 9905 } else if (!Ty->isVariableArrayType()) { 9906 return false; 9907 } 9908 return true; 9909 } 9910 9911 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9912 // be the size of the source, instead of the destination. 9913 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9914 IdentifierInfo *FnName) { 9915 9916 // Don't crash if the user has the wrong number of arguments 9917 unsigned NumArgs = Call->getNumArgs(); 9918 if ((NumArgs != 3) && (NumArgs != 4)) 9919 return; 9920 9921 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9922 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9923 const Expr *CompareWithSrc = nullptr; 9924 9925 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9926 Call->getBeginLoc(), Call->getRParenLoc())) 9927 return; 9928 9929 // Look for 'strlcpy(dst, x, sizeof(x))' 9930 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9931 CompareWithSrc = Ex; 9932 else { 9933 // Look for 'strlcpy(dst, x, strlen(x))' 9934 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9935 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9936 SizeCall->getNumArgs() == 1) 9937 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9938 } 9939 } 9940 9941 if (!CompareWithSrc) 9942 return; 9943 9944 // Determine if the argument to sizeof/strlen is equal to the source 9945 // argument. In principle there's all kinds of things you could do 9946 // here, for instance creating an == expression and evaluating it with 9947 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9948 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9949 if (!SrcArgDRE) 9950 return; 9951 9952 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9953 if (!CompareWithSrcDRE || 9954 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9955 return; 9956 9957 const Expr *OriginalSizeArg = Call->getArg(2); 9958 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9959 << OriginalSizeArg->getSourceRange() << FnName; 9960 9961 // Output a FIXIT hint if the destination is an array (rather than a 9962 // pointer to an array). This could be enhanced to handle some 9963 // pointers if we know the actual size, like if DstArg is 'array+2' 9964 // we could say 'sizeof(array)-2'. 9965 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9966 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9967 return; 9968 9969 SmallString<128> sizeString; 9970 llvm::raw_svector_ostream OS(sizeString); 9971 OS << "sizeof("; 9972 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9973 OS << ")"; 9974 9975 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9976 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9977 OS.str()); 9978 } 9979 9980 /// Check if two expressions refer to the same declaration. 9981 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9982 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9983 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9984 return D1->getDecl() == D2->getDecl(); 9985 return false; 9986 } 9987 9988 static const Expr *getStrlenExprArg(const Expr *E) { 9989 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9990 const FunctionDecl *FD = CE->getDirectCallee(); 9991 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9992 return nullptr; 9993 return CE->getArg(0)->IgnoreParenCasts(); 9994 } 9995 return nullptr; 9996 } 9997 9998 // Warn on anti-patterns as the 'size' argument to strncat. 9999 // The correct size argument should look like following: 10000 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10001 void Sema::CheckStrncatArguments(const CallExpr *CE, 10002 IdentifierInfo *FnName) { 10003 // Don't crash if the user has the wrong number of arguments. 10004 if (CE->getNumArgs() < 3) 10005 return; 10006 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10007 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10008 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10009 10010 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10011 CE->getRParenLoc())) 10012 return; 10013 10014 // Identify common expressions, which are wrongly used as the size argument 10015 // to strncat and may lead to buffer overflows. 10016 unsigned PatternType = 0; 10017 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10018 // - sizeof(dst) 10019 if (referToTheSameDecl(SizeOfArg, DstArg)) 10020 PatternType = 1; 10021 // - sizeof(src) 10022 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10023 PatternType = 2; 10024 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10025 if (BE->getOpcode() == BO_Sub) { 10026 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10027 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10028 // - sizeof(dst) - strlen(dst) 10029 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10030 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10031 PatternType = 1; 10032 // - sizeof(src) - (anything) 10033 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10034 PatternType = 2; 10035 } 10036 } 10037 10038 if (PatternType == 0) 10039 return; 10040 10041 // Generate the diagnostic. 10042 SourceLocation SL = LenArg->getBeginLoc(); 10043 SourceRange SR = LenArg->getSourceRange(); 10044 SourceManager &SM = getSourceManager(); 10045 10046 // If the function is defined as a builtin macro, do not show macro expansion. 10047 if (SM.isMacroArgExpansion(SL)) { 10048 SL = SM.getSpellingLoc(SL); 10049 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10050 SM.getSpellingLoc(SR.getEnd())); 10051 } 10052 10053 // Check if the destination is an array (rather than a pointer to an array). 10054 QualType DstTy = DstArg->getType(); 10055 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10056 Context); 10057 if (!isKnownSizeArray) { 10058 if (PatternType == 1) 10059 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10060 else 10061 Diag(SL, diag::warn_strncat_src_size) << SR; 10062 return; 10063 } 10064 10065 if (PatternType == 1) 10066 Diag(SL, diag::warn_strncat_large_size) << SR; 10067 else 10068 Diag(SL, diag::warn_strncat_src_size) << SR; 10069 10070 SmallString<128> sizeString; 10071 llvm::raw_svector_ostream OS(sizeString); 10072 OS << "sizeof("; 10073 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10074 OS << ") - "; 10075 OS << "strlen("; 10076 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10077 OS << ") - 1"; 10078 10079 Diag(SL, diag::note_strncat_wrong_size) 10080 << FixItHint::CreateReplacement(SR, OS.str()); 10081 } 10082 10083 void 10084 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10085 SourceLocation ReturnLoc, 10086 bool isObjCMethod, 10087 const AttrVec *Attrs, 10088 const FunctionDecl *FD) { 10089 // Check if the return value is null but should not be. 10090 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10091 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10092 CheckNonNullExpr(*this, RetValExp)) 10093 Diag(ReturnLoc, diag::warn_null_ret) 10094 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10095 10096 // C++11 [basic.stc.dynamic.allocation]p4: 10097 // If an allocation function declared with a non-throwing 10098 // exception-specification fails to allocate storage, it shall return 10099 // a null pointer. Any other allocation function that fails to allocate 10100 // storage shall indicate failure only by throwing an exception [...] 10101 if (FD) { 10102 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10103 if (Op == OO_New || Op == OO_Array_New) { 10104 const FunctionProtoType *Proto 10105 = FD->getType()->castAs<FunctionProtoType>(); 10106 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10107 CheckNonNullExpr(*this, RetValExp)) 10108 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10109 << FD << getLangOpts().CPlusPlus11; 10110 } 10111 } 10112 } 10113 10114 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10115 10116 /// Check for comparisons of floating point operands using != and ==. 10117 /// Issue a warning if these are no self-comparisons, as they are not likely 10118 /// to do what the programmer intended. 10119 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10120 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10121 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10122 10123 // Special case: check for x == x (which is OK). 10124 // Do not emit warnings for such cases. 10125 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10126 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10127 if (DRL->getDecl() == DRR->getDecl()) 10128 return; 10129 10130 // Special case: check for comparisons against literals that can be exactly 10131 // represented by APFloat. In such cases, do not emit a warning. This 10132 // is a heuristic: often comparison against such literals are used to 10133 // detect if a value in a variable has not changed. This clearly can 10134 // lead to false negatives. 10135 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10136 if (FLL->isExact()) 10137 return; 10138 } else 10139 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10140 if (FLR->isExact()) 10141 return; 10142 10143 // Check for comparisons with builtin types. 10144 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10145 if (CL->getBuiltinCallee()) 10146 return; 10147 10148 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10149 if (CR->getBuiltinCallee()) 10150 return; 10151 10152 // Emit the diagnostic. 10153 Diag(Loc, diag::warn_floatingpoint_eq) 10154 << LHS->getSourceRange() << RHS->getSourceRange(); 10155 } 10156 10157 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10158 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10159 10160 namespace { 10161 10162 /// Structure recording the 'active' range of an integer-valued 10163 /// expression. 10164 struct IntRange { 10165 /// The number of bits active in the int. 10166 unsigned Width; 10167 10168 /// True if the int is known not to have negative values. 10169 bool NonNegative; 10170 10171 IntRange(unsigned Width, bool NonNegative) 10172 : Width(Width), NonNegative(NonNegative) {} 10173 10174 /// Returns the range of the bool type. 10175 static IntRange forBoolType() { 10176 return IntRange(1, true); 10177 } 10178 10179 /// Returns the range of an opaque value of the given integral type. 10180 static IntRange forValueOfType(ASTContext &C, QualType T) { 10181 return forValueOfCanonicalType(C, 10182 T->getCanonicalTypeInternal().getTypePtr()); 10183 } 10184 10185 /// Returns the range of an opaque value of a canonical integral type. 10186 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10187 assert(T->isCanonicalUnqualified()); 10188 10189 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10190 T = VT->getElementType().getTypePtr(); 10191 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10192 T = CT->getElementType().getTypePtr(); 10193 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10194 T = AT->getValueType().getTypePtr(); 10195 10196 if (!C.getLangOpts().CPlusPlus) { 10197 // For enum types in C code, use the underlying datatype. 10198 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10199 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10200 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10201 // For enum types in C++, use the known bit width of the enumerators. 10202 EnumDecl *Enum = ET->getDecl(); 10203 // In C++11, enums can have a fixed underlying type. Use this type to 10204 // compute the range. 10205 if (Enum->isFixed()) { 10206 return IntRange(C.getIntWidth(QualType(T, 0)), 10207 !ET->isSignedIntegerOrEnumerationType()); 10208 } 10209 10210 unsigned NumPositive = Enum->getNumPositiveBits(); 10211 unsigned NumNegative = Enum->getNumNegativeBits(); 10212 10213 if (NumNegative == 0) 10214 return IntRange(NumPositive, true/*NonNegative*/); 10215 else 10216 return IntRange(std::max(NumPositive + 1, NumNegative), 10217 false/*NonNegative*/); 10218 } 10219 10220 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10221 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10222 10223 const BuiltinType *BT = cast<BuiltinType>(T); 10224 assert(BT->isInteger()); 10225 10226 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10227 } 10228 10229 /// Returns the "target" range of a canonical integral type, i.e. 10230 /// the range of values expressible in the type. 10231 /// 10232 /// This matches forValueOfCanonicalType except that enums have the 10233 /// full range of their type, not the range of their enumerators. 10234 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10235 assert(T->isCanonicalUnqualified()); 10236 10237 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10238 T = VT->getElementType().getTypePtr(); 10239 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10240 T = CT->getElementType().getTypePtr(); 10241 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10242 T = AT->getValueType().getTypePtr(); 10243 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10244 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10245 10246 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10247 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10248 10249 const BuiltinType *BT = cast<BuiltinType>(T); 10250 assert(BT->isInteger()); 10251 10252 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10253 } 10254 10255 /// Returns the supremum of two ranges: i.e. their conservative merge. 10256 static IntRange join(IntRange L, IntRange R) { 10257 return IntRange(std::max(L.Width, R.Width), 10258 L.NonNegative && R.NonNegative); 10259 } 10260 10261 /// Returns the infinum of two ranges: i.e. their aggressive merge. 10262 static IntRange meet(IntRange L, IntRange R) { 10263 return IntRange(std::min(L.Width, R.Width), 10264 L.NonNegative || R.NonNegative); 10265 } 10266 }; 10267 10268 } // namespace 10269 10270 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10271 unsigned MaxWidth) { 10272 if (value.isSigned() && value.isNegative()) 10273 return IntRange(value.getMinSignedBits(), false); 10274 10275 if (value.getBitWidth() > MaxWidth) 10276 value = value.trunc(MaxWidth); 10277 10278 // isNonNegative() just checks the sign bit without considering 10279 // signedness. 10280 return IntRange(value.getActiveBits(), true); 10281 } 10282 10283 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10284 unsigned MaxWidth) { 10285 if (result.isInt()) 10286 return GetValueRange(C, result.getInt(), MaxWidth); 10287 10288 if (result.isVector()) { 10289 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10290 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10291 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10292 R = IntRange::join(R, El); 10293 } 10294 return R; 10295 } 10296 10297 if (result.isComplexInt()) { 10298 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10299 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10300 return IntRange::join(R, I); 10301 } 10302 10303 // This can happen with lossless casts to intptr_t of "based" lvalues. 10304 // Assume it might use arbitrary bits. 10305 // FIXME: The only reason we need to pass the type in here is to get 10306 // the sign right on this one case. It would be nice if APValue 10307 // preserved this. 10308 assert(result.isLValue() || result.isAddrLabelDiff()); 10309 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10310 } 10311 10312 static QualType GetExprType(const Expr *E) { 10313 QualType Ty = E->getType(); 10314 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10315 Ty = AtomicRHS->getValueType(); 10316 return Ty; 10317 } 10318 10319 /// Pseudo-evaluate the given integer expression, estimating the 10320 /// range of values it might take. 10321 /// 10322 /// \param MaxWidth - the width to which the value will be truncated 10323 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10324 bool InConstantContext) { 10325 E = E->IgnoreParens(); 10326 10327 // Try a full evaluation first. 10328 Expr::EvalResult result; 10329 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10330 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10331 10332 // I think we only want to look through implicit casts here; if the 10333 // user has an explicit widening cast, we should treat the value as 10334 // being of the new, wider type. 10335 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10336 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10337 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 10338 10339 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10340 10341 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10342 CE->getCastKind() == CK_BooleanToSignedIntegral; 10343 10344 // Assume that non-integer casts can span the full range of the type. 10345 if (!isIntegerCast) 10346 return OutputTypeRange; 10347 10348 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10349 std::min(MaxWidth, OutputTypeRange.Width), 10350 InConstantContext); 10351 10352 // Bail out if the subexpr's range is as wide as the cast type. 10353 if (SubRange.Width >= OutputTypeRange.Width) 10354 return OutputTypeRange; 10355 10356 // Otherwise, we take the smaller width, and we're non-negative if 10357 // either the output type or the subexpr is. 10358 return IntRange(SubRange.Width, 10359 SubRange.NonNegative || OutputTypeRange.NonNegative); 10360 } 10361 10362 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10363 // If we can fold the condition, just take that operand. 10364 bool CondResult; 10365 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10366 return GetExprRange(C, 10367 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10368 MaxWidth, InConstantContext); 10369 10370 // Otherwise, conservatively merge. 10371 IntRange L = 10372 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 10373 IntRange R = 10374 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 10375 return IntRange::join(L, R); 10376 } 10377 10378 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10379 switch (BO->getOpcode()) { 10380 case BO_Cmp: 10381 llvm_unreachable("builtin <=> should have class type"); 10382 10383 // Boolean-valued operations are single-bit and positive. 10384 case BO_LAnd: 10385 case BO_LOr: 10386 case BO_LT: 10387 case BO_GT: 10388 case BO_LE: 10389 case BO_GE: 10390 case BO_EQ: 10391 case BO_NE: 10392 return IntRange::forBoolType(); 10393 10394 // The type of the assignments is the type of the LHS, so the RHS 10395 // is not necessarily the same type. 10396 case BO_MulAssign: 10397 case BO_DivAssign: 10398 case BO_RemAssign: 10399 case BO_AddAssign: 10400 case BO_SubAssign: 10401 case BO_XorAssign: 10402 case BO_OrAssign: 10403 // TODO: bitfields? 10404 return IntRange::forValueOfType(C, GetExprType(E)); 10405 10406 // Simple assignments just pass through the RHS, which will have 10407 // been coerced to the LHS type. 10408 case BO_Assign: 10409 // TODO: bitfields? 10410 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10411 10412 // Operations with opaque sources are black-listed. 10413 case BO_PtrMemD: 10414 case BO_PtrMemI: 10415 return IntRange::forValueOfType(C, GetExprType(E)); 10416 10417 // Bitwise-and uses the *infinum* of the two source ranges. 10418 case BO_And: 10419 case BO_AndAssign: 10420 return IntRange::meet( 10421 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10422 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10423 10424 // Left shift gets black-listed based on a judgement call. 10425 case BO_Shl: 10426 // ...except that we want to treat '1 << (blah)' as logically 10427 // positive. It's an important idiom. 10428 if (IntegerLiteral *I 10429 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10430 if (I->getValue() == 1) { 10431 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10432 return IntRange(R.Width, /*NonNegative*/ true); 10433 } 10434 } 10435 LLVM_FALLTHROUGH; 10436 10437 case BO_ShlAssign: 10438 return IntRange::forValueOfType(C, GetExprType(E)); 10439 10440 // Right shift by a constant can narrow its left argument. 10441 case BO_Shr: 10442 case BO_ShrAssign: { 10443 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10444 10445 // If the shift amount is a positive constant, drop the width by 10446 // that much. 10447 if (Optional<llvm::APSInt> shift = 10448 BO->getRHS()->getIntegerConstantExpr(C)) { 10449 if (shift->isNonNegative()) { 10450 unsigned zext = shift->getZExtValue(); 10451 if (zext >= L.Width) 10452 L.Width = (L.NonNegative ? 0 : 1); 10453 else 10454 L.Width -= zext; 10455 } 10456 } 10457 10458 return L; 10459 } 10460 10461 // Comma acts as its right operand. 10462 case BO_Comma: 10463 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10464 10465 // Black-list pointer subtractions. 10466 case BO_Sub: 10467 if (BO->getLHS()->getType()->isPointerType()) 10468 return IntRange::forValueOfType(C, GetExprType(E)); 10469 break; 10470 10471 // The width of a division result is mostly determined by the size 10472 // of the LHS. 10473 case BO_Div: { 10474 // Don't 'pre-truncate' the operands. 10475 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10476 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10477 10478 // If the divisor is constant, use that. 10479 if (Optional<llvm::APSInt> divisor = 10480 BO->getRHS()->getIntegerConstantExpr(C)) { 10481 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 10482 if (log2 >= L.Width) 10483 L.Width = (L.NonNegative ? 0 : 1); 10484 else 10485 L.Width = std::min(L.Width - log2, MaxWidth); 10486 return L; 10487 } 10488 10489 // Otherwise, just use the LHS's width. 10490 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10491 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10492 } 10493 10494 // The result of a remainder can't be larger than the result of 10495 // either side. 10496 case BO_Rem: { 10497 // Don't 'pre-truncate' the operands. 10498 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10499 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10500 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10501 10502 IntRange meet = IntRange::meet(L, R); 10503 meet.Width = std::min(meet.Width, MaxWidth); 10504 return meet; 10505 } 10506 10507 // The default behavior is okay for these. 10508 case BO_Mul: 10509 case BO_Add: 10510 case BO_Xor: 10511 case BO_Or: 10512 break; 10513 } 10514 10515 // The default case is to treat the operation as if it were closed 10516 // on the narrowest type that encompasses both operands. 10517 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10518 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10519 return IntRange::join(L, R); 10520 } 10521 10522 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10523 switch (UO->getOpcode()) { 10524 // Boolean-valued operations are white-listed. 10525 case UO_LNot: 10526 return IntRange::forBoolType(); 10527 10528 // Operations with opaque sources are black-listed. 10529 case UO_Deref: 10530 case UO_AddrOf: // should be impossible 10531 return IntRange::forValueOfType(C, GetExprType(E)); 10532 10533 default: 10534 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10535 } 10536 } 10537 10538 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10539 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10540 10541 if (const auto *BitField = E->getSourceBitField()) 10542 return IntRange(BitField->getBitWidthValue(C), 10543 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10544 10545 return IntRange::forValueOfType(C, GetExprType(E)); 10546 } 10547 10548 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10549 bool InConstantContext) { 10550 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10551 } 10552 10553 /// Checks whether the given value, which currently has the given 10554 /// source semantics, has the same value when coerced through the 10555 /// target semantics. 10556 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10557 const llvm::fltSemantics &Src, 10558 const llvm::fltSemantics &Tgt) { 10559 llvm::APFloat truncated = value; 10560 10561 bool ignored; 10562 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10563 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10564 10565 return truncated.bitwiseIsEqual(value); 10566 } 10567 10568 /// Checks whether the given value, which currently has the given 10569 /// source semantics, has the same value when coerced through the 10570 /// target semantics. 10571 /// 10572 /// The value might be a vector of floats (or a complex number). 10573 static bool IsSameFloatAfterCast(const APValue &value, 10574 const llvm::fltSemantics &Src, 10575 const llvm::fltSemantics &Tgt) { 10576 if (value.isFloat()) 10577 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10578 10579 if (value.isVector()) { 10580 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10581 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10582 return false; 10583 return true; 10584 } 10585 10586 assert(value.isComplexFloat()); 10587 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10588 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10589 } 10590 10591 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10592 bool IsListInit = false); 10593 10594 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10595 // Suppress cases where we are comparing against an enum constant. 10596 if (const DeclRefExpr *DR = 10597 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10598 if (isa<EnumConstantDecl>(DR->getDecl())) 10599 return true; 10600 10601 // Suppress cases where the value is expanded from a macro, unless that macro 10602 // is how a language represents a boolean literal. This is the case in both C 10603 // and Objective-C. 10604 SourceLocation BeginLoc = E->getBeginLoc(); 10605 if (BeginLoc.isMacroID()) { 10606 StringRef MacroName = Lexer::getImmediateMacroName( 10607 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10608 return MacroName != "YES" && MacroName != "NO" && 10609 MacroName != "true" && MacroName != "false"; 10610 } 10611 10612 return false; 10613 } 10614 10615 static bool isKnownToHaveUnsignedValue(Expr *E) { 10616 return E->getType()->isIntegerType() && 10617 (!E->getType()->isSignedIntegerType() || 10618 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10619 } 10620 10621 namespace { 10622 /// The promoted range of values of a type. In general this has the 10623 /// following structure: 10624 /// 10625 /// |-----------| . . . |-----------| 10626 /// ^ ^ ^ ^ 10627 /// Min HoleMin HoleMax Max 10628 /// 10629 /// ... where there is only a hole if a signed type is promoted to unsigned 10630 /// (in which case Min and Max are the smallest and largest representable 10631 /// values). 10632 struct PromotedRange { 10633 // Min, or HoleMax if there is a hole. 10634 llvm::APSInt PromotedMin; 10635 // Max, or HoleMin if there is a hole. 10636 llvm::APSInt PromotedMax; 10637 10638 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10639 if (R.Width == 0) 10640 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10641 else if (R.Width >= BitWidth && !Unsigned) { 10642 // Promotion made the type *narrower*. This happens when promoting 10643 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10644 // Treat all values of 'signed int' as being in range for now. 10645 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10646 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10647 } else { 10648 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10649 .extOrTrunc(BitWidth); 10650 PromotedMin.setIsUnsigned(Unsigned); 10651 10652 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10653 .extOrTrunc(BitWidth); 10654 PromotedMax.setIsUnsigned(Unsigned); 10655 } 10656 } 10657 10658 // Determine whether this range is contiguous (has no hole). 10659 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10660 10661 // Where a constant value is within the range. 10662 enum ComparisonResult { 10663 LT = 0x1, 10664 LE = 0x2, 10665 GT = 0x4, 10666 GE = 0x8, 10667 EQ = 0x10, 10668 NE = 0x20, 10669 InRangeFlag = 0x40, 10670 10671 Less = LE | LT | NE, 10672 Min = LE | InRangeFlag, 10673 InRange = InRangeFlag, 10674 Max = GE | InRangeFlag, 10675 Greater = GE | GT | NE, 10676 10677 OnlyValue = LE | GE | EQ | InRangeFlag, 10678 InHole = NE 10679 }; 10680 10681 ComparisonResult compare(const llvm::APSInt &Value) const { 10682 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10683 Value.isUnsigned() == PromotedMin.isUnsigned()); 10684 if (!isContiguous()) { 10685 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10686 if (Value.isMinValue()) return Min; 10687 if (Value.isMaxValue()) return Max; 10688 if (Value >= PromotedMin) return InRange; 10689 if (Value <= PromotedMax) return InRange; 10690 return InHole; 10691 } 10692 10693 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10694 case -1: return Less; 10695 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10696 case 1: 10697 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10698 case -1: return InRange; 10699 case 0: return Max; 10700 case 1: return Greater; 10701 } 10702 } 10703 10704 llvm_unreachable("impossible compare result"); 10705 } 10706 10707 static llvm::Optional<StringRef> 10708 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10709 if (Op == BO_Cmp) { 10710 ComparisonResult LTFlag = LT, GTFlag = GT; 10711 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10712 10713 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10714 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10715 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10716 return llvm::None; 10717 } 10718 10719 ComparisonResult TrueFlag, FalseFlag; 10720 if (Op == BO_EQ) { 10721 TrueFlag = EQ; 10722 FalseFlag = NE; 10723 } else if (Op == BO_NE) { 10724 TrueFlag = NE; 10725 FalseFlag = EQ; 10726 } else { 10727 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10728 TrueFlag = LT; 10729 FalseFlag = GE; 10730 } else { 10731 TrueFlag = GT; 10732 FalseFlag = LE; 10733 } 10734 if (Op == BO_GE || Op == BO_LE) 10735 std::swap(TrueFlag, FalseFlag); 10736 } 10737 if (R & TrueFlag) 10738 return StringRef("true"); 10739 if (R & FalseFlag) 10740 return StringRef("false"); 10741 return llvm::None; 10742 } 10743 }; 10744 } 10745 10746 static bool HasEnumType(Expr *E) { 10747 // Strip off implicit integral promotions. 10748 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10749 if (ICE->getCastKind() != CK_IntegralCast && 10750 ICE->getCastKind() != CK_NoOp) 10751 break; 10752 E = ICE->getSubExpr(); 10753 } 10754 10755 return E->getType()->isEnumeralType(); 10756 } 10757 10758 static int classifyConstantValue(Expr *Constant) { 10759 // The values of this enumeration are used in the diagnostics 10760 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10761 enum ConstantValueKind { 10762 Miscellaneous = 0, 10763 LiteralTrue, 10764 LiteralFalse 10765 }; 10766 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10767 return BL->getValue() ? ConstantValueKind::LiteralTrue 10768 : ConstantValueKind::LiteralFalse; 10769 return ConstantValueKind::Miscellaneous; 10770 } 10771 10772 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10773 Expr *Constant, Expr *Other, 10774 const llvm::APSInt &Value, 10775 bool RhsConstant) { 10776 if (S.inTemplateInstantiation()) 10777 return false; 10778 10779 Expr *OriginalOther = Other; 10780 10781 Constant = Constant->IgnoreParenImpCasts(); 10782 Other = Other->IgnoreParenImpCasts(); 10783 10784 // Suppress warnings on tautological comparisons between values of the same 10785 // enumeration type. There are only two ways we could warn on this: 10786 // - If the constant is outside the range of representable values of 10787 // the enumeration. In such a case, we should warn about the cast 10788 // to enumeration type, not about the comparison. 10789 // - If the constant is the maximum / minimum in-range value. For an 10790 // enumeratin type, such comparisons can be meaningful and useful. 10791 if (Constant->getType()->isEnumeralType() && 10792 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10793 return false; 10794 10795 // TODO: Investigate using GetExprRange() to get tighter bounds 10796 // on the bit ranges. 10797 QualType OtherT = Other->getType(); 10798 if (const auto *AT = OtherT->getAs<AtomicType>()) 10799 OtherT = AT->getValueType(); 10800 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10801 10802 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10803 // (Namely, macOS). 10804 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10805 S.NSAPIObj->isObjCBOOLType(OtherT) && 10806 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10807 10808 // Whether we're treating Other as being a bool because of the form of 10809 // expression despite it having another type (typically 'int' in C). 10810 bool OtherIsBooleanDespiteType = 10811 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10812 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10813 OtherRange = IntRange::forBoolType(); 10814 10815 // Determine the promoted range of the other type and see if a comparison of 10816 // the constant against that range is tautological. 10817 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10818 Value.isUnsigned()); 10819 auto Cmp = OtherPromotedRange.compare(Value); 10820 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10821 if (!Result) 10822 return false; 10823 10824 // Suppress the diagnostic for an in-range comparison if the constant comes 10825 // from a macro or enumerator. We don't want to diagnose 10826 // 10827 // some_long_value <= INT_MAX 10828 // 10829 // when sizeof(int) == sizeof(long). 10830 bool InRange = Cmp & PromotedRange::InRangeFlag; 10831 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10832 return false; 10833 10834 // If this is a comparison to an enum constant, include that 10835 // constant in the diagnostic. 10836 const EnumConstantDecl *ED = nullptr; 10837 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10838 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10839 10840 // Should be enough for uint128 (39 decimal digits) 10841 SmallString<64> PrettySourceValue; 10842 llvm::raw_svector_ostream OS(PrettySourceValue); 10843 if (ED) { 10844 OS << '\'' << *ED << "' (" << Value << ")"; 10845 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10846 Constant->IgnoreParenImpCasts())) { 10847 OS << (BL->getValue() ? "YES" : "NO"); 10848 } else { 10849 OS << Value; 10850 } 10851 10852 if (IsObjCSignedCharBool) { 10853 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10854 S.PDiag(diag::warn_tautological_compare_objc_bool) 10855 << OS.str() << *Result); 10856 return true; 10857 } 10858 10859 // FIXME: We use a somewhat different formatting for the in-range cases and 10860 // cases involving boolean values for historical reasons. We should pick a 10861 // consistent way of presenting these diagnostics. 10862 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10863 10864 S.DiagRuntimeBehavior( 10865 E->getOperatorLoc(), E, 10866 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10867 : diag::warn_tautological_bool_compare) 10868 << OS.str() << classifyConstantValue(Constant) << OtherT 10869 << OtherIsBooleanDespiteType << *Result 10870 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10871 } else { 10872 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10873 ? (HasEnumType(OriginalOther) 10874 ? diag::warn_unsigned_enum_always_true_comparison 10875 : diag::warn_unsigned_always_true_comparison) 10876 : diag::warn_tautological_constant_compare; 10877 10878 S.Diag(E->getOperatorLoc(), Diag) 10879 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10880 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10881 } 10882 10883 return true; 10884 } 10885 10886 /// Analyze the operands of the given comparison. Implements the 10887 /// fallback case from AnalyzeComparison. 10888 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10889 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10890 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10891 } 10892 10893 /// Implements -Wsign-compare. 10894 /// 10895 /// \param E the binary operator to check for warnings 10896 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10897 // The type the comparison is being performed in. 10898 QualType T = E->getLHS()->getType(); 10899 10900 // Only analyze comparison operators where both sides have been converted to 10901 // the same type. 10902 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10903 return AnalyzeImpConvsInComparison(S, E); 10904 10905 // Don't analyze value-dependent comparisons directly. 10906 if (E->isValueDependent()) 10907 return AnalyzeImpConvsInComparison(S, E); 10908 10909 Expr *LHS = E->getLHS(); 10910 Expr *RHS = E->getRHS(); 10911 10912 if (T->isIntegralType(S.Context)) { 10913 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 10914 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 10915 10916 // We don't care about expressions whose result is a constant. 10917 if (RHSValue && LHSValue) 10918 return AnalyzeImpConvsInComparison(S, E); 10919 10920 // We only care about expressions where just one side is literal 10921 if ((bool)RHSValue ^ (bool)LHSValue) { 10922 // Is the constant on the RHS or LHS? 10923 const bool RhsConstant = (bool)RHSValue; 10924 Expr *Const = RhsConstant ? RHS : LHS; 10925 Expr *Other = RhsConstant ? LHS : RHS; 10926 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 10927 10928 // Check whether an integer constant comparison results in a value 10929 // of 'true' or 'false'. 10930 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10931 return AnalyzeImpConvsInComparison(S, E); 10932 } 10933 } 10934 10935 if (!T->hasUnsignedIntegerRepresentation()) { 10936 // We don't do anything special if this isn't an unsigned integral 10937 // comparison: we're only interested in integral comparisons, and 10938 // signed comparisons only happen in cases we don't care to warn about. 10939 return AnalyzeImpConvsInComparison(S, E); 10940 } 10941 10942 LHS = LHS->IgnoreParenImpCasts(); 10943 RHS = RHS->IgnoreParenImpCasts(); 10944 10945 if (!S.getLangOpts().CPlusPlus) { 10946 // Avoid warning about comparison of integers with different signs when 10947 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10948 // the type of `E`. 10949 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10950 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10951 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10952 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10953 } 10954 10955 // Check to see if one of the (unmodified) operands is of different 10956 // signedness. 10957 Expr *signedOperand, *unsignedOperand; 10958 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10959 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10960 "unsigned comparison between two signed integer expressions?"); 10961 signedOperand = LHS; 10962 unsignedOperand = RHS; 10963 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10964 signedOperand = RHS; 10965 unsignedOperand = LHS; 10966 } else { 10967 return AnalyzeImpConvsInComparison(S, E); 10968 } 10969 10970 // Otherwise, calculate the effective range of the signed operand. 10971 IntRange signedRange = 10972 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10973 10974 // Go ahead and analyze implicit conversions in the operands. Note 10975 // that we skip the implicit conversions on both sides. 10976 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10977 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10978 10979 // If the signed range is non-negative, -Wsign-compare won't fire. 10980 if (signedRange.NonNegative) 10981 return; 10982 10983 // For (in)equality comparisons, if the unsigned operand is a 10984 // constant which cannot collide with a overflowed signed operand, 10985 // then reinterpreting the signed operand as unsigned will not 10986 // change the result of the comparison. 10987 if (E->isEqualityOp()) { 10988 unsigned comparisonWidth = S.Context.getIntWidth(T); 10989 IntRange unsignedRange = 10990 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10991 10992 // We should never be unable to prove that the unsigned operand is 10993 // non-negative. 10994 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10995 10996 if (unsignedRange.Width < comparisonWidth) 10997 return; 10998 } 10999 11000 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11001 S.PDiag(diag::warn_mixed_sign_comparison) 11002 << LHS->getType() << RHS->getType() 11003 << LHS->getSourceRange() << RHS->getSourceRange()); 11004 } 11005 11006 /// Analyzes an attempt to assign the given value to a bitfield. 11007 /// 11008 /// Returns true if there was something fishy about the attempt. 11009 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11010 SourceLocation InitLoc) { 11011 assert(Bitfield->isBitField()); 11012 if (Bitfield->isInvalidDecl()) 11013 return false; 11014 11015 // White-list bool bitfields. 11016 QualType BitfieldType = Bitfield->getType(); 11017 if (BitfieldType->isBooleanType()) 11018 return false; 11019 11020 if (BitfieldType->isEnumeralType()) { 11021 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11022 // If the underlying enum type was not explicitly specified as an unsigned 11023 // type and the enum contain only positive values, MSVC++ will cause an 11024 // inconsistency by storing this as a signed type. 11025 if (S.getLangOpts().CPlusPlus11 && 11026 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11027 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11028 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11029 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11030 << BitfieldEnumDecl->getNameAsString(); 11031 } 11032 } 11033 11034 if (Bitfield->getType()->isBooleanType()) 11035 return false; 11036 11037 // Ignore value- or type-dependent expressions. 11038 if (Bitfield->getBitWidth()->isValueDependent() || 11039 Bitfield->getBitWidth()->isTypeDependent() || 11040 Init->isValueDependent() || 11041 Init->isTypeDependent()) 11042 return false; 11043 11044 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11045 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11046 11047 Expr::EvalResult Result; 11048 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11049 Expr::SE_AllowSideEffects)) { 11050 // The RHS is not constant. If the RHS has an enum type, make sure the 11051 // bitfield is wide enough to hold all the values of the enum without 11052 // truncation. 11053 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11054 EnumDecl *ED = EnumTy->getDecl(); 11055 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11056 11057 // Enum types are implicitly signed on Windows, so check if there are any 11058 // negative enumerators to see if the enum was intended to be signed or 11059 // not. 11060 bool SignedEnum = ED->getNumNegativeBits() > 0; 11061 11062 // Check for surprising sign changes when assigning enum values to a 11063 // bitfield of different signedness. If the bitfield is signed and we 11064 // have exactly the right number of bits to store this unsigned enum, 11065 // suggest changing the enum to an unsigned type. This typically happens 11066 // on Windows where unfixed enums always use an underlying type of 'int'. 11067 unsigned DiagID = 0; 11068 if (SignedEnum && !SignedBitfield) { 11069 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11070 } else if (SignedBitfield && !SignedEnum && 11071 ED->getNumPositiveBits() == FieldWidth) { 11072 DiagID = diag::warn_signed_bitfield_enum_conversion; 11073 } 11074 11075 if (DiagID) { 11076 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11077 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11078 SourceRange TypeRange = 11079 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11080 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11081 << SignedEnum << TypeRange; 11082 } 11083 11084 // Compute the required bitwidth. If the enum has negative values, we need 11085 // one more bit than the normal number of positive bits to represent the 11086 // sign bit. 11087 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11088 ED->getNumNegativeBits()) 11089 : ED->getNumPositiveBits(); 11090 11091 // Check the bitwidth. 11092 if (BitsNeeded > FieldWidth) { 11093 Expr *WidthExpr = Bitfield->getBitWidth(); 11094 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11095 << Bitfield << ED; 11096 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11097 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11098 } 11099 } 11100 11101 return false; 11102 } 11103 11104 llvm::APSInt Value = Result.Val.getInt(); 11105 11106 unsigned OriginalWidth = Value.getBitWidth(); 11107 11108 if (!Value.isSigned() || Value.isNegative()) 11109 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11110 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11111 OriginalWidth = Value.getMinSignedBits(); 11112 11113 if (OriginalWidth <= FieldWidth) 11114 return false; 11115 11116 // Compute the value which the bitfield will contain. 11117 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11118 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11119 11120 // Check whether the stored value is equal to the original value. 11121 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11122 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11123 return false; 11124 11125 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11126 // therefore don't strictly fit into a signed bitfield of width 1. 11127 if (FieldWidth == 1 && Value == 1) 11128 return false; 11129 11130 std::string PrettyValue = Value.toString(10); 11131 std::string PrettyTrunc = TruncatedValue.toString(10); 11132 11133 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11134 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11135 << Init->getSourceRange(); 11136 11137 return true; 11138 } 11139 11140 /// Analyze the given simple or compound assignment for warning-worthy 11141 /// operations. 11142 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11143 // Just recurse on the LHS. 11144 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11145 11146 // We want to recurse on the RHS as normal unless we're assigning to 11147 // a bitfield. 11148 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11149 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11150 E->getOperatorLoc())) { 11151 // Recurse, ignoring any implicit conversions on the RHS. 11152 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11153 E->getOperatorLoc()); 11154 } 11155 } 11156 11157 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11158 11159 // Diagnose implicitly sequentially-consistent atomic assignment. 11160 if (E->getLHS()->getType()->isAtomicType()) 11161 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11162 } 11163 11164 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11165 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11166 SourceLocation CContext, unsigned diag, 11167 bool pruneControlFlow = false) { 11168 if (pruneControlFlow) { 11169 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11170 S.PDiag(diag) 11171 << SourceType << T << E->getSourceRange() 11172 << SourceRange(CContext)); 11173 return; 11174 } 11175 S.Diag(E->getExprLoc(), diag) 11176 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11177 } 11178 11179 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11180 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11181 SourceLocation CContext, 11182 unsigned diag, bool pruneControlFlow = false) { 11183 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11184 } 11185 11186 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11187 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11188 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11189 } 11190 11191 static void adornObjCBoolConversionDiagWithTernaryFixit( 11192 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11193 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11194 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11195 Ignored = OVE->getSourceExpr(); 11196 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11197 isa<BinaryOperator>(Ignored) || 11198 isa<CXXOperatorCallExpr>(Ignored); 11199 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11200 if (NeedsParens) 11201 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11202 << FixItHint::CreateInsertion(EndLoc, ")"); 11203 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11204 } 11205 11206 /// Diagnose an implicit cast from a floating point value to an integer value. 11207 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11208 SourceLocation CContext) { 11209 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11210 const bool PruneWarnings = S.inTemplateInstantiation(); 11211 11212 Expr *InnerE = E->IgnoreParenImpCasts(); 11213 // We also want to warn on, e.g., "int i = -1.234" 11214 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11215 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11216 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11217 11218 const bool IsLiteral = 11219 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11220 11221 llvm::APFloat Value(0.0); 11222 bool IsConstant = 11223 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11224 if (!IsConstant) { 11225 if (isObjCSignedCharBool(S, T)) { 11226 return adornObjCBoolConversionDiagWithTernaryFixit( 11227 S, E, 11228 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11229 << E->getType()); 11230 } 11231 11232 return DiagnoseImpCast(S, E, T, CContext, 11233 diag::warn_impcast_float_integer, PruneWarnings); 11234 } 11235 11236 bool isExact = false; 11237 11238 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11239 T->hasUnsignedIntegerRepresentation()); 11240 llvm::APFloat::opStatus Result = Value.convertToInteger( 11241 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11242 11243 // FIXME: Force the precision of the source value down so we don't print 11244 // digits which are usually useless (we don't really care here if we 11245 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11246 // would automatically print the shortest representation, but it's a bit 11247 // tricky to implement. 11248 SmallString<16> PrettySourceValue; 11249 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11250 precision = (precision * 59 + 195) / 196; 11251 Value.toString(PrettySourceValue, precision); 11252 11253 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11254 return adornObjCBoolConversionDiagWithTernaryFixit( 11255 S, E, 11256 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11257 << PrettySourceValue); 11258 } 11259 11260 if (Result == llvm::APFloat::opOK && isExact) { 11261 if (IsLiteral) return; 11262 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11263 PruneWarnings); 11264 } 11265 11266 // Conversion of a floating-point value to a non-bool integer where the 11267 // integral part cannot be represented by the integer type is undefined. 11268 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11269 return DiagnoseImpCast( 11270 S, E, T, CContext, 11271 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11272 : diag::warn_impcast_float_to_integer_out_of_range, 11273 PruneWarnings); 11274 11275 unsigned DiagID = 0; 11276 if (IsLiteral) { 11277 // Warn on floating point literal to integer. 11278 DiagID = diag::warn_impcast_literal_float_to_integer; 11279 } else if (IntegerValue == 0) { 11280 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11281 return DiagnoseImpCast(S, E, T, CContext, 11282 diag::warn_impcast_float_integer, PruneWarnings); 11283 } 11284 // Warn on non-zero to zero conversion. 11285 DiagID = diag::warn_impcast_float_to_integer_zero; 11286 } else { 11287 if (IntegerValue.isUnsigned()) { 11288 if (!IntegerValue.isMaxValue()) { 11289 return DiagnoseImpCast(S, E, T, CContext, 11290 diag::warn_impcast_float_integer, PruneWarnings); 11291 } 11292 } else { // IntegerValue.isSigned() 11293 if (!IntegerValue.isMaxSignedValue() && 11294 !IntegerValue.isMinSignedValue()) { 11295 return DiagnoseImpCast(S, E, T, CContext, 11296 diag::warn_impcast_float_integer, PruneWarnings); 11297 } 11298 } 11299 // Warn on evaluatable floating point expression to integer conversion. 11300 DiagID = diag::warn_impcast_float_to_integer; 11301 } 11302 11303 SmallString<16> PrettyTargetValue; 11304 if (IsBool) 11305 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11306 else 11307 IntegerValue.toString(PrettyTargetValue); 11308 11309 if (PruneWarnings) { 11310 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11311 S.PDiag(DiagID) 11312 << E->getType() << T.getUnqualifiedType() 11313 << PrettySourceValue << PrettyTargetValue 11314 << E->getSourceRange() << SourceRange(CContext)); 11315 } else { 11316 S.Diag(E->getExprLoc(), DiagID) 11317 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11318 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11319 } 11320 } 11321 11322 /// Analyze the given compound assignment for the possible losing of 11323 /// floating-point precision. 11324 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11325 assert(isa<CompoundAssignOperator>(E) && 11326 "Must be compound assignment operation"); 11327 // Recurse on the LHS and RHS in here 11328 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11329 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11330 11331 if (E->getLHS()->getType()->isAtomicType()) 11332 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11333 11334 // Now check the outermost expression 11335 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11336 const auto *RBT = cast<CompoundAssignOperator>(E) 11337 ->getComputationResultType() 11338 ->getAs<BuiltinType>(); 11339 11340 // The below checks assume source is floating point. 11341 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11342 11343 // If source is floating point but target is an integer. 11344 if (ResultBT->isInteger()) 11345 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11346 E->getExprLoc(), diag::warn_impcast_float_integer); 11347 11348 if (!ResultBT->isFloatingPoint()) 11349 return; 11350 11351 // If both source and target are floating points, warn about losing precision. 11352 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11353 QualType(ResultBT, 0), QualType(RBT, 0)); 11354 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11355 // warn about dropping FP rank. 11356 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11357 diag::warn_impcast_float_result_precision); 11358 } 11359 11360 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11361 IntRange Range) { 11362 if (!Range.Width) return "0"; 11363 11364 llvm::APSInt ValueInRange = Value; 11365 ValueInRange.setIsSigned(!Range.NonNegative); 11366 ValueInRange = ValueInRange.trunc(Range.Width); 11367 return ValueInRange.toString(10); 11368 } 11369 11370 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11371 if (!isa<ImplicitCastExpr>(Ex)) 11372 return false; 11373 11374 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11375 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11376 const Type *Source = 11377 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11378 if (Target->isDependentType()) 11379 return false; 11380 11381 const BuiltinType *FloatCandidateBT = 11382 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11383 const Type *BoolCandidateType = ToBool ? Target : Source; 11384 11385 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11386 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11387 } 11388 11389 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11390 SourceLocation CC) { 11391 unsigned NumArgs = TheCall->getNumArgs(); 11392 for (unsigned i = 0; i < NumArgs; ++i) { 11393 Expr *CurrA = TheCall->getArg(i); 11394 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11395 continue; 11396 11397 bool IsSwapped = ((i > 0) && 11398 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11399 IsSwapped |= ((i < (NumArgs - 1)) && 11400 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11401 if (IsSwapped) { 11402 // Warn on this floating-point to bool conversion. 11403 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11404 CurrA->getType(), CC, 11405 diag::warn_impcast_floating_point_to_bool); 11406 } 11407 } 11408 } 11409 11410 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11411 SourceLocation CC) { 11412 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11413 E->getExprLoc())) 11414 return; 11415 11416 // Don't warn on functions which have return type nullptr_t. 11417 if (isa<CallExpr>(E)) 11418 return; 11419 11420 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11421 const Expr::NullPointerConstantKind NullKind = 11422 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11423 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11424 return; 11425 11426 // Return if target type is a safe conversion. 11427 if (T->isAnyPointerType() || T->isBlockPointerType() || 11428 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11429 return; 11430 11431 SourceLocation Loc = E->getSourceRange().getBegin(); 11432 11433 // Venture through the macro stacks to get to the source of macro arguments. 11434 // The new location is a better location than the complete location that was 11435 // passed in. 11436 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11437 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11438 11439 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11440 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11441 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11442 Loc, S.SourceMgr, S.getLangOpts()); 11443 if (MacroName == "NULL") 11444 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11445 } 11446 11447 // Only warn if the null and context location are in the same macro expansion. 11448 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11449 return; 11450 11451 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11452 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11453 << FixItHint::CreateReplacement(Loc, 11454 S.getFixItZeroLiteralForType(T, Loc)); 11455 } 11456 11457 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11458 ObjCArrayLiteral *ArrayLiteral); 11459 11460 static void 11461 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11462 ObjCDictionaryLiteral *DictionaryLiteral); 11463 11464 /// Check a single element within a collection literal against the 11465 /// target element type. 11466 static void checkObjCCollectionLiteralElement(Sema &S, 11467 QualType TargetElementType, 11468 Expr *Element, 11469 unsigned ElementKind) { 11470 // Skip a bitcast to 'id' or qualified 'id'. 11471 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11472 if (ICE->getCastKind() == CK_BitCast && 11473 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11474 Element = ICE->getSubExpr(); 11475 } 11476 11477 QualType ElementType = Element->getType(); 11478 ExprResult ElementResult(Element); 11479 if (ElementType->getAs<ObjCObjectPointerType>() && 11480 S.CheckSingleAssignmentConstraints(TargetElementType, 11481 ElementResult, 11482 false, false) 11483 != Sema::Compatible) { 11484 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11485 << ElementType << ElementKind << TargetElementType 11486 << Element->getSourceRange(); 11487 } 11488 11489 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11490 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11491 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11492 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11493 } 11494 11495 /// Check an Objective-C array literal being converted to the given 11496 /// target type. 11497 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11498 ObjCArrayLiteral *ArrayLiteral) { 11499 if (!S.NSArrayDecl) 11500 return; 11501 11502 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11503 if (!TargetObjCPtr) 11504 return; 11505 11506 if (TargetObjCPtr->isUnspecialized() || 11507 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11508 != S.NSArrayDecl->getCanonicalDecl()) 11509 return; 11510 11511 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11512 if (TypeArgs.size() != 1) 11513 return; 11514 11515 QualType TargetElementType = TypeArgs[0]; 11516 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11517 checkObjCCollectionLiteralElement(S, TargetElementType, 11518 ArrayLiteral->getElement(I), 11519 0); 11520 } 11521 } 11522 11523 /// Check an Objective-C dictionary literal being converted to the given 11524 /// target type. 11525 static void 11526 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11527 ObjCDictionaryLiteral *DictionaryLiteral) { 11528 if (!S.NSDictionaryDecl) 11529 return; 11530 11531 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11532 if (!TargetObjCPtr) 11533 return; 11534 11535 if (TargetObjCPtr->isUnspecialized() || 11536 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11537 != S.NSDictionaryDecl->getCanonicalDecl()) 11538 return; 11539 11540 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11541 if (TypeArgs.size() != 2) 11542 return; 11543 11544 QualType TargetKeyType = TypeArgs[0]; 11545 QualType TargetObjectType = TypeArgs[1]; 11546 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11547 auto Element = DictionaryLiteral->getKeyValueElement(I); 11548 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11549 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11550 } 11551 } 11552 11553 // Helper function to filter out cases for constant width constant conversion. 11554 // Don't warn on char array initialization or for non-decimal values. 11555 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11556 SourceLocation CC) { 11557 // If initializing from a constant, and the constant starts with '0', 11558 // then it is a binary, octal, or hexadecimal. Allow these constants 11559 // to fill all the bits, even if there is a sign change. 11560 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11561 const char FirstLiteralCharacter = 11562 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11563 if (FirstLiteralCharacter == '0') 11564 return false; 11565 } 11566 11567 // If the CC location points to a '{', and the type is char, then assume 11568 // assume it is an array initialization. 11569 if (CC.isValid() && T->isCharType()) { 11570 const char FirstContextCharacter = 11571 S.getSourceManager().getCharacterData(CC)[0]; 11572 if (FirstContextCharacter == '{') 11573 return false; 11574 } 11575 11576 return true; 11577 } 11578 11579 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11580 const auto *IL = dyn_cast<IntegerLiteral>(E); 11581 if (!IL) { 11582 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11583 if (UO->getOpcode() == UO_Minus) 11584 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11585 } 11586 } 11587 11588 return IL; 11589 } 11590 11591 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11592 E = E->IgnoreParenImpCasts(); 11593 SourceLocation ExprLoc = E->getExprLoc(); 11594 11595 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11596 BinaryOperator::Opcode Opc = BO->getOpcode(); 11597 Expr::EvalResult Result; 11598 // Do not diagnose unsigned shifts. 11599 if (Opc == BO_Shl) { 11600 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11601 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11602 if (LHS && LHS->getValue() == 0) 11603 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11604 else if (!E->isValueDependent() && LHS && RHS && 11605 RHS->getValue().isNonNegative() && 11606 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11607 S.Diag(ExprLoc, diag::warn_left_shift_always) 11608 << (Result.Val.getInt() != 0); 11609 else if (E->getType()->isSignedIntegerType()) 11610 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11611 } 11612 } 11613 11614 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11615 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11616 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11617 if (!LHS || !RHS) 11618 return; 11619 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11620 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11621 // Do not diagnose common idioms. 11622 return; 11623 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11624 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11625 } 11626 } 11627 11628 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11629 SourceLocation CC, 11630 bool *ICContext = nullptr, 11631 bool IsListInit = false) { 11632 if (E->isTypeDependent() || E->isValueDependent()) return; 11633 11634 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11635 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11636 if (Source == Target) return; 11637 if (Target->isDependentType()) return; 11638 11639 // If the conversion context location is invalid don't complain. We also 11640 // don't want to emit a warning if the issue occurs from the expansion of 11641 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11642 // delay this check as long as possible. Once we detect we are in that 11643 // scenario, we just return. 11644 if (CC.isInvalid()) 11645 return; 11646 11647 if (Source->isAtomicType()) 11648 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11649 11650 // Diagnose implicit casts to bool. 11651 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11652 if (isa<StringLiteral>(E)) 11653 // Warn on string literal to bool. Checks for string literals in logical 11654 // and expressions, for instance, assert(0 && "error here"), are 11655 // prevented by a check in AnalyzeImplicitConversions(). 11656 return DiagnoseImpCast(S, E, T, CC, 11657 diag::warn_impcast_string_literal_to_bool); 11658 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11659 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11660 // This covers the literal expressions that evaluate to Objective-C 11661 // objects. 11662 return DiagnoseImpCast(S, E, T, CC, 11663 diag::warn_impcast_objective_c_literal_to_bool); 11664 } 11665 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11666 // Warn on pointer to bool conversion that is always true. 11667 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11668 SourceRange(CC)); 11669 } 11670 } 11671 11672 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11673 // is a typedef for signed char (macOS), then that constant value has to be 1 11674 // or 0. 11675 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11676 Expr::EvalResult Result; 11677 if (E->EvaluateAsInt(Result, S.getASTContext(), 11678 Expr::SE_AllowSideEffects)) { 11679 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11680 adornObjCBoolConversionDiagWithTernaryFixit( 11681 S, E, 11682 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11683 << Result.Val.getInt().toString(10)); 11684 } 11685 return; 11686 } 11687 } 11688 11689 // Check implicit casts from Objective-C collection literals to specialized 11690 // collection types, e.g., NSArray<NSString *> *. 11691 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11692 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11693 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11694 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11695 11696 // Strip vector types. 11697 if (isa<VectorType>(Source)) { 11698 if (!isa<VectorType>(Target)) { 11699 if (S.SourceMgr.isInSystemMacro(CC)) 11700 return; 11701 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11702 } 11703 11704 // If the vector cast is cast between two vectors of the same size, it is 11705 // a bitcast, not a conversion. 11706 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11707 return; 11708 11709 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11710 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11711 } 11712 if (auto VecTy = dyn_cast<VectorType>(Target)) 11713 Target = VecTy->getElementType().getTypePtr(); 11714 11715 // Strip complex types. 11716 if (isa<ComplexType>(Source)) { 11717 if (!isa<ComplexType>(Target)) { 11718 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11719 return; 11720 11721 return DiagnoseImpCast(S, E, T, CC, 11722 S.getLangOpts().CPlusPlus 11723 ? diag::err_impcast_complex_scalar 11724 : diag::warn_impcast_complex_scalar); 11725 } 11726 11727 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11728 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11729 } 11730 11731 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11732 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11733 11734 // If the source is floating point... 11735 if (SourceBT && SourceBT->isFloatingPoint()) { 11736 // ...and the target is floating point... 11737 if (TargetBT && TargetBT->isFloatingPoint()) { 11738 // ...then warn if we're dropping FP rank. 11739 11740 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11741 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11742 if (Order > 0) { 11743 // Don't warn about float constants that are precisely 11744 // representable in the target type. 11745 Expr::EvalResult result; 11746 if (E->EvaluateAsRValue(result, S.Context)) { 11747 // Value might be a float, a float vector, or a float complex. 11748 if (IsSameFloatAfterCast(result.Val, 11749 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11750 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11751 return; 11752 } 11753 11754 if (S.SourceMgr.isInSystemMacro(CC)) 11755 return; 11756 11757 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11758 } 11759 // ... or possibly if we're increasing rank, too 11760 else if (Order < 0) { 11761 if (S.SourceMgr.isInSystemMacro(CC)) 11762 return; 11763 11764 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11765 } 11766 return; 11767 } 11768 11769 // If the target is integral, always warn. 11770 if (TargetBT && TargetBT->isInteger()) { 11771 if (S.SourceMgr.isInSystemMacro(CC)) 11772 return; 11773 11774 DiagnoseFloatingImpCast(S, E, T, CC); 11775 } 11776 11777 // Detect the case where a call result is converted from floating-point to 11778 // to bool, and the final argument to the call is converted from bool, to 11779 // discover this typo: 11780 // 11781 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11782 // 11783 // FIXME: This is an incredibly special case; is there some more general 11784 // way to detect this class of misplaced-parentheses bug? 11785 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11786 // Check last argument of function call to see if it is an 11787 // implicit cast from a type matching the type the result 11788 // is being cast to. 11789 CallExpr *CEx = cast<CallExpr>(E); 11790 if (unsigned NumArgs = CEx->getNumArgs()) { 11791 Expr *LastA = CEx->getArg(NumArgs - 1); 11792 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11793 if (isa<ImplicitCastExpr>(LastA) && 11794 InnerE->getType()->isBooleanType()) { 11795 // Warn on this floating-point to bool conversion 11796 DiagnoseImpCast(S, E, T, CC, 11797 diag::warn_impcast_floating_point_to_bool); 11798 } 11799 } 11800 } 11801 return; 11802 } 11803 11804 // Valid casts involving fixed point types should be accounted for here. 11805 if (Source->isFixedPointType()) { 11806 if (Target->isUnsaturatedFixedPointType()) { 11807 Expr::EvalResult Result; 11808 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11809 S.isConstantEvaluated())) { 11810 APFixedPoint Value = Result.Val.getFixedPoint(); 11811 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11812 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11813 if (Value > MaxVal || Value < MinVal) { 11814 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11815 S.PDiag(diag::warn_impcast_fixed_point_range) 11816 << Value.toString() << T 11817 << E->getSourceRange() 11818 << clang::SourceRange(CC)); 11819 return; 11820 } 11821 } 11822 } else if (Target->isIntegerType()) { 11823 Expr::EvalResult Result; 11824 if (!S.isConstantEvaluated() && 11825 E->EvaluateAsFixedPoint(Result, S.Context, 11826 Expr::SE_AllowSideEffects)) { 11827 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11828 11829 bool Overflowed; 11830 llvm::APSInt IntResult = FXResult.convertToInt( 11831 S.Context.getIntWidth(T), 11832 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11833 11834 if (Overflowed) { 11835 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11836 S.PDiag(diag::warn_impcast_fixed_point_range) 11837 << FXResult.toString() << T 11838 << E->getSourceRange() 11839 << clang::SourceRange(CC)); 11840 return; 11841 } 11842 } 11843 } 11844 } else if (Target->isUnsaturatedFixedPointType()) { 11845 if (Source->isIntegerType()) { 11846 Expr::EvalResult Result; 11847 if (!S.isConstantEvaluated() && 11848 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11849 llvm::APSInt Value = Result.Val.getInt(); 11850 11851 bool Overflowed; 11852 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11853 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11854 11855 if (Overflowed) { 11856 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11857 S.PDiag(diag::warn_impcast_fixed_point_range) 11858 << Value.toString(/*Radix=*/10) << T 11859 << E->getSourceRange() 11860 << clang::SourceRange(CC)); 11861 return; 11862 } 11863 } 11864 } 11865 } 11866 11867 // If we are casting an integer type to a floating point type without 11868 // initialization-list syntax, we might lose accuracy if the floating 11869 // point type has a narrower significand than the integer type. 11870 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11871 TargetBT->isFloatingType() && !IsListInit) { 11872 // Determine the number of precision bits in the source integer type. 11873 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11874 unsigned int SourcePrecision = SourceRange.Width; 11875 11876 // Determine the number of precision bits in the 11877 // target floating point type. 11878 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11879 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11880 11881 if (SourcePrecision > 0 && TargetPrecision > 0 && 11882 SourcePrecision > TargetPrecision) { 11883 11884 if (Optional<llvm::APSInt> SourceInt = 11885 E->getIntegerConstantExpr(S.Context)) { 11886 // If the source integer is a constant, convert it to the target 11887 // floating point type. Issue a warning if the value changes 11888 // during the whole conversion. 11889 llvm::APFloat TargetFloatValue( 11890 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11891 llvm::APFloat::opStatus ConversionStatus = 11892 TargetFloatValue.convertFromAPInt( 11893 *SourceInt, SourceBT->isSignedInteger(), 11894 llvm::APFloat::rmNearestTiesToEven); 11895 11896 if (ConversionStatus != llvm::APFloat::opOK) { 11897 std::string PrettySourceValue = SourceInt->toString(10); 11898 SmallString<32> PrettyTargetValue; 11899 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11900 11901 S.DiagRuntimeBehavior( 11902 E->getExprLoc(), E, 11903 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11904 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11905 << E->getSourceRange() << clang::SourceRange(CC)); 11906 } 11907 } else { 11908 // Otherwise, the implicit conversion may lose precision. 11909 DiagnoseImpCast(S, E, T, CC, 11910 diag::warn_impcast_integer_float_precision); 11911 } 11912 } 11913 } 11914 11915 DiagnoseNullConversion(S, E, T, CC); 11916 11917 S.DiscardMisalignedMemberAddress(Target, E); 11918 11919 if (Target->isBooleanType()) 11920 DiagnoseIntInBoolContext(S, E); 11921 11922 if (!Source->isIntegerType() || !Target->isIntegerType()) 11923 return; 11924 11925 // TODO: remove this early return once the false positives for constant->bool 11926 // in templates, macros, etc, are reduced or removed. 11927 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11928 return; 11929 11930 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11931 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11932 return adornObjCBoolConversionDiagWithTernaryFixit( 11933 S, E, 11934 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11935 << E->getType()); 11936 } 11937 11938 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11939 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11940 11941 if (SourceRange.Width > TargetRange.Width) { 11942 // If the source is a constant, use a default-on diagnostic. 11943 // TODO: this should happen for bitfield stores, too. 11944 Expr::EvalResult Result; 11945 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11946 S.isConstantEvaluated())) { 11947 llvm::APSInt Value(32); 11948 Value = Result.Val.getInt(); 11949 11950 if (S.SourceMgr.isInSystemMacro(CC)) 11951 return; 11952 11953 std::string PrettySourceValue = Value.toString(10); 11954 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11955 11956 S.DiagRuntimeBehavior( 11957 E->getExprLoc(), E, 11958 S.PDiag(diag::warn_impcast_integer_precision_constant) 11959 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11960 << E->getSourceRange() << clang::SourceRange(CC)); 11961 return; 11962 } 11963 11964 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11965 if (S.SourceMgr.isInSystemMacro(CC)) 11966 return; 11967 11968 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11969 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11970 /* pruneControlFlow */ true); 11971 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11972 } 11973 11974 if (TargetRange.Width > SourceRange.Width) { 11975 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11976 if (UO->getOpcode() == UO_Minus) 11977 if (Source->isUnsignedIntegerType()) { 11978 if (Target->isUnsignedIntegerType()) 11979 return DiagnoseImpCast(S, E, T, CC, 11980 diag::warn_impcast_high_order_zero_bits); 11981 if (Target->isSignedIntegerType()) 11982 return DiagnoseImpCast(S, E, T, CC, 11983 diag::warn_impcast_nonnegative_result); 11984 } 11985 } 11986 11987 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11988 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11989 // Warn when doing a signed to signed conversion, warn if the positive 11990 // source value is exactly the width of the target type, which will 11991 // cause a negative value to be stored. 11992 11993 Expr::EvalResult Result; 11994 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11995 !S.SourceMgr.isInSystemMacro(CC)) { 11996 llvm::APSInt Value = Result.Val.getInt(); 11997 if (isSameWidthConstantConversion(S, E, T, CC)) { 11998 std::string PrettySourceValue = Value.toString(10); 11999 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12000 12001 S.DiagRuntimeBehavior( 12002 E->getExprLoc(), E, 12003 S.PDiag(diag::warn_impcast_integer_precision_constant) 12004 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12005 << E->getSourceRange() << clang::SourceRange(CC)); 12006 return; 12007 } 12008 } 12009 12010 // Fall through for non-constants to give a sign conversion warning. 12011 } 12012 12013 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 12014 (!TargetRange.NonNegative && SourceRange.NonNegative && 12015 SourceRange.Width == TargetRange.Width)) { 12016 if (S.SourceMgr.isInSystemMacro(CC)) 12017 return; 12018 12019 unsigned DiagID = diag::warn_impcast_integer_sign; 12020 12021 // Traditionally, gcc has warned about this under -Wsign-compare. 12022 // We also want to warn about it in -Wconversion. 12023 // So if -Wconversion is off, use a completely identical diagnostic 12024 // in the sign-compare group. 12025 // The conditional-checking code will 12026 if (ICContext) { 12027 DiagID = diag::warn_impcast_integer_sign_conditional; 12028 *ICContext = true; 12029 } 12030 12031 return DiagnoseImpCast(S, E, T, CC, DiagID); 12032 } 12033 12034 // Diagnose conversions between different enumeration types. 12035 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12036 // type, to give us better diagnostics. 12037 QualType SourceType = E->getType(); 12038 if (!S.getLangOpts().CPlusPlus) { 12039 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12040 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12041 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12042 SourceType = S.Context.getTypeDeclType(Enum); 12043 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12044 } 12045 } 12046 12047 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12048 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12049 if (SourceEnum->getDecl()->hasNameForLinkage() && 12050 TargetEnum->getDecl()->hasNameForLinkage() && 12051 SourceEnum != TargetEnum) { 12052 if (S.SourceMgr.isInSystemMacro(CC)) 12053 return; 12054 12055 return DiagnoseImpCast(S, E, SourceType, T, CC, 12056 diag::warn_impcast_different_enum_types); 12057 } 12058 } 12059 12060 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12061 SourceLocation CC, QualType T); 12062 12063 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12064 SourceLocation CC, bool &ICContext) { 12065 E = E->IgnoreParenImpCasts(); 12066 12067 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12068 return CheckConditionalOperator(S, CO, CC, T); 12069 12070 AnalyzeImplicitConversions(S, E, CC); 12071 if (E->getType() != T) 12072 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12073 } 12074 12075 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12076 SourceLocation CC, QualType T) { 12077 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12078 12079 Expr *TrueExpr = E->getTrueExpr(); 12080 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12081 TrueExpr = BCO->getCommon(); 12082 12083 bool Suspicious = false; 12084 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12085 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12086 12087 if (T->isBooleanType()) 12088 DiagnoseIntInBoolContext(S, E); 12089 12090 // If -Wconversion would have warned about either of the candidates 12091 // for a signedness conversion to the context type... 12092 if (!Suspicious) return; 12093 12094 // ...but it's currently ignored... 12095 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12096 return; 12097 12098 // ...then check whether it would have warned about either of the 12099 // candidates for a signedness conversion to the condition type. 12100 if (E->getType() == T) return; 12101 12102 Suspicious = false; 12103 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12104 E->getType(), CC, &Suspicious); 12105 if (!Suspicious) 12106 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12107 E->getType(), CC, &Suspicious); 12108 } 12109 12110 /// Check conversion of given expression to boolean. 12111 /// Input argument E is a logical expression. 12112 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12113 if (S.getLangOpts().Bool) 12114 return; 12115 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12116 return; 12117 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12118 } 12119 12120 namespace { 12121 struct AnalyzeImplicitConversionsWorkItem { 12122 Expr *E; 12123 SourceLocation CC; 12124 bool IsListInit; 12125 }; 12126 } 12127 12128 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12129 /// that should be visited are added to WorkList. 12130 static void AnalyzeImplicitConversions( 12131 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12132 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12133 Expr *OrigE = Item.E; 12134 SourceLocation CC = Item.CC; 12135 12136 QualType T = OrigE->getType(); 12137 Expr *E = OrigE->IgnoreParenImpCasts(); 12138 12139 // Propagate whether we are in a C++ list initialization expression. 12140 // If so, we do not issue warnings for implicit int-float conversion 12141 // precision loss, because C++11 narrowing already handles it. 12142 bool IsListInit = Item.IsListInit || 12143 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12144 12145 if (E->isTypeDependent() || E->isValueDependent()) 12146 return; 12147 12148 Expr *SourceExpr = E; 12149 // Examine, but don't traverse into the source expression of an 12150 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12151 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12152 // evaluate it in the context of checking the specific conversion to T though. 12153 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12154 if (auto *Src = OVE->getSourceExpr()) 12155 SourceExpr = Src; 12156 12157 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12158 if (UO->getOpcode() == UO_Not && 12159 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12160 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12161 << OrigE->getSourceRange() << T->isBooleanType() 12162 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12163 12164 // For conditional operators, we analyze the arguments as if they 12165 // were being fed directly into the output. 12166 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12167 CheckConditionalOperator(S, CO, CC, T); 12168 return; 12169 } 12170 12171 // Check implicit argument conversions for function calls. 12172 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12173 CheckImplicitArgumentConversions(S, Call, CC); 12174 12175 // Go ahead and check any implicit conversions we might have skipped. 12176 // The non-canonical typecheck is just an optimization; 12177 // CheckImplicitConversion will filter out dead implicit conversions. 12178 if (SourceExpr->getType() != T) 12179 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12180 12181 // Now continue drilling into this expression. 12182 12183 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12184 // The bound subexpressions in a PseudoObjectExpr are not reachable 12185 // as transitive children. 12186 // FIXME: Use a more uniform representation for this. 12187 for (auto *SE : POE->semantics()) 12188 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12189 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12190 } 12191 12192 // Skip past explicit casts. 12193 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12194 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12195 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12196 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12197 WorkList.push_back({E, CC, IsListInit}); 12198 return; 12199 } 12200 12201 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12202 // Do a somewhat different check with comparison operators. 12203 if (BO->isComparisonOp()) 12204 return AnalyzeComparison(S, BO); 12205 12206 // And with simple assignments. 12207 if (BO->getOpcode() == BO_Assign) 12208 return AnalyzeAssignment(S, BO); 12209 // And with compound assignments. 12210 if (BO->isAssignmentOp()) 12211 return AnalyzeCompoundAssignment(S, BO); 12212 } 12213 12214 // These break the otherwise-useful invariant below. Fortunately, 12215 // we don't really need to recurse into them, because any internal 12216 // expressions should have been analyzed already when they were 12217 // built into statements. 12218 if (isa<StmtExpr>(E)) return; 12219 12220 // Don't descend into unevaluated contexts. 12221 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12222 12223 // Now just recurse over the expression's children. 12224 CC = E->getExprLoc(); 12225 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12226 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12227 for (Stmt *SubStmt : E->children()) { 12228 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12229 if (!ChildExpr) 12230 continue; 12231 12232 if (IsLogicalAndOperator && 12233 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12234 // Ignore checking string literals that are in logical and operators. 12235 // This is a common pattern for asserts. 12236 continue; 12237 WorkList.push_back({ChildExpr, CC, IsListInit}); 12238 } 12239 12240 if (BO && BO->isLogicalOp()) { 12241 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12242 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12243 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12244 12245 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12246 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12247 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12248 } 12249 12250 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12251 if (U->getOpcode() == UO_LNot) { 12252 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12253 } else if (U->getOpcode() != UO_AddrOf) { 12254 if (U->getSubExpr()->getType()->isAtomicType()) 12255 S.Diag(U->getSubExpr()->getBeginLoc(), 12256 diag::warn_atomic_implicit_seq_cst); 12257 } 12258 } 12259 } 12260 12261 /// AnalyzeImplicitConversions - Find and report any interesting 12262 /// implicit conversions in the given expression. There are a couple 12263 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12264 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12265 bool IsListInit/*= false*/) { 12266 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12267 WorkList.push_back({OrigE, CC, IsListInit}); 12268 while (!WorkList.empty()) 12269 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12270 } 12271 12272 /// Diagnose integer type and any valid implicit conversion to it. 12273 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12274 // Taking into account implicit conversions, 12275 // allow any integer. 12276 if (!E->getType()->isIntegerType()) { 12277 S.Diag(E->getBeginLoc(), 12278 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12279 return true; 12280 } 12281 // Potentially emit standard warnings for implicit conversions if enabled 12282 // using -Wconversion. 12283 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12284 return false; 12285 } 12286 12287 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12288 // Returns true when emitting a warning about taking the address of a reference. 12289 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12290 const PartialDiagnostic &PD) { 12291 E = E->IgnoreParenImpCasts(); 12292 12293 const FunctionDecl *FD = nullptr; 12294 12295 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12296 if (!DRE->getDecl()->getType()->isReferenceType()) 12297 return false; 12298 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12299 if (!M->getMemberDecl()->getType()->isReferenceType()) 12300 return false; 12301 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12302 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12303 return false; 12304 FD = Call->getDirectCallee(); 12305 } else { 12306 return false; 12307 } 12308 12309 SemaRef.Diag(E->getExprLoc(), PD); 12310 12311 // If possible, point to location of function. 12312 if (FD) { 12313 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12314 } 12315 12316 return true; 12317 } 12318 12319 // Returns true if the SourceLocation is expanded from any macro body. 12320 // Returns false if the SourceLocation is invalid, is from not in a macro 12321 // expansion, or is from expanded from a top-level macro argument. 12322 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12323 if (Loc.isInvalid()) 12324 return false; 12325 12326 while (Loc.isMacroID()) { 12327 if (SM.isMacroBodyExpansion(Loc)) 12328 return true; 12329 Loc = SM.getImmediateMacroCallerLoc(Loc); 12330 } 12331 12332 return false; 12333 } 12334 12335 /// Diagnose pointers that are always non-null. 12336 /// \param E the expression containing the pointer 12337 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12338 /// compared to a null pointer 12339 /// \param IsEqual True when the comparison is equal to a null pointer 12340 /// \param Range Extra SourceRange to highlight in the diagnostic 12341 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12342 Expr::NullPointerConstantKind NullKind, 12343 bool IsEqual, SourceRange Range) { 12344 if (!E) 12345 return; 12346 12347 // Don't warn inside macros. 12348 if (E->getExprLoc().isMacroID()) { 12349 const SourceManager &SM = getSourceManager(); 12350 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12351 IsInAnyMacroBody(SM, Range.getBegin())) 12352 return; 12353 } 12354 E = E->IgnoreImpCasts(); 12355 12356 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12357 12358 if (isa<CXXThisExpr>(E)) { 12359 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12360 : diag::warn_this_bool_conversion; 12361 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12362 return; 12363 } 12364 12365 bool IsAddressOf = false; 12366 12367 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12368 if (UO->getOpcode() != UO_AddrOf) 12369 return; 12370 IsAddressOf = true; 12371 E = UO->getSubExpr(); 12372 } 12373 12374 if (IsAddressOf) { 12375 unsigned DiagID = IsCompare 12376 ? diag::warn_address_of_reference_null_compare 12377 : diag::warn_address_of_reference_bool_conversion; 12378 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12379 << IsEqual; 12380 if (CheckForReference(*this, E, PD)) { 12381 return; 12382 } 12383 } 12384 12385 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12386 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12387 std::string Str; 12388 llvm::raw_string_ostream S(Str); 12389 E->printPretty(S, nullptr, getPrintingPolicy()); 12390 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12391 : diag::warn_cast_nonnull_to_bool; 12392 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12393 << E->getSourceRange() << Range << IsEqual; 12394 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12395 }; 12396 12397 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12398 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12399 if (auto *Callee = Call->getDirectCallee()) { 12400 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12401 ComplainAboutNonnullParamOrCall(A); 12402 return; 12403 } 12404 } 12405 } 12406 12407 // Expect to find a single Decl. Skip anything more complicated. 12408 ValueDecl *D = nullptr; 12409 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12410 D = R->getDecl(); 12411 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12412 D = M->getMemberDecl(); 12413 } 12414 12415 // Weak Decls can be null. 12416 if (!D || D->isWeak()) 12417 return; 12418 12419 // Check for parameter decl with nonnull attribute 12420 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12421 if (getCurFunction() && 12422 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12423 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12424 ComplainAboutNonnullParamOrCall(A); 12425 return; 12426 } 12427 12428 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12429 // Skip function template not specialized yet. 12430 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12431 return; 12432 auto ParamIter = llvm::find(FD->parameters(), PV); 12433 assert(ParamIter != FD->param_end()); 12434 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12435 12436 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12437 if (!NonNull->args_size()) { 12438 ComplainAboutNonnullParamOrCall(NonNull); 12439 return; 12440 } 12441 12442 for (const ParamIdx &ArgNo : NonNull->args()) { 12443 if (ArgNo.getASTIndex() == ParamNo) { 12444 ComplainAboutNonnullParamOrCall(NonNull); 12445 return; 12446 } 12447 } 12448 } 12449 } 12450 } 12451 } 12452 12453 QualType T = D->getType(); 12454 const bool IsArray = T->isArrayType(); 12455 const bool IsFunction = T->isFunctionType(); 12456 12457 // Address of function is used to silence the function warning. 12458 if (IsAddressOf && IsFunction) { 12459 return; 12460 } 12461 12462 // Found nothing. 12463 if (!IsAddressOf && !IsFunction && !IsArray) 12464 return; 12465 12466 // Pretty print the expression for the diagnostic. 12467 std::string Str; 12468 llvm::raw_string_ostream S(Str); 12469 E->printPretty(S, nullptr, getPrintingPolicy()); 12470 12471 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12472 : diag::warn_impcast_pointer_to_bool; 12473 enum { 12474 AddressOf, 12475 FunctionPointer, 12476 ArrayPointer 12477 } DiagType; 12478 if (IsAddressOf) 12479 DiagType = AddressOf; 12480 else if (IsFunction) 12481 DiagType = FunctionPointer; 12482 else if (IsArray) 12483 DiagType = ArrayPointer; 12484 else 12485 llvm_unreachable("Could not determine diagnostic."); 12486 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12487 << Range << IsEqual; 12488 12489 if (!IsFunction) 12490 return; 12491 12492 // Suggest '&' to silence the function warning. 12493 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12494 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12495 12496 // Check to see if '()' fixit should be emitted. 12497 QualType ReturnType; 12498 UnresolvedSet<4> NonTemplateOverloads; 12499 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12500 if (ReturnType.isNull()) 12501 return; 12502 12503 if (IsCompare) { 12504 // There are two cases here. If there is null constant, the only suggest 12505 // for a pointer return type. If the null is 0, then suggest if the return 12506 // type is a pointer or an integer type. 12507 if (!ReturnType->isPointerType()) { 12508 if (NullKind == Expr::NPCK_ZeroExpression || 12509 NullKind == Expr::NPCK_ZeroLiteral) { 12510 if (!ReturnType->isIntegerType()) 12511 return; 12512 } else { 12513 return; 12514 } 12515 } 12516 } else { // !IsCompare 12517 // For function to bool, only suggest if the function pointer has bool 12518 // return type. 12519 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12520 return; 12521 } 12522 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12523 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12524 } 12525 12526 /// Diagnoses "dangerous" implicit conversions within the given 12527 /// expression (which is a full expression). Implements -Wconversion 12528 /// and -Wsign-compare. 12529 /// 12530 /// \param CC the "context" location of the implicit conversion, i.e. 12531 /// the most location of the syntactic entity requiring the implicit 12532 /// conversion 12533 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12534 // Don't diagnose in unevaluated contexts. 12535 if (isUnevaluatedContext()) 12536 return; 12537 12538 // Don't diagnose for value- or type-dependent expressions. 12539 if (E->isTypeDependent() || E->isValueDependent()) 12540 return; 12541 12542 // Check for array bounds violations in cases where the check isn't triggered 12543 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12544 // ArraySubscriptExpr is on the RHS of a variable initialization. 12545 CheckArrayAccess(E); 12546 12547 // This is not the right CC for (e.g.) a variable initialization. 12548 AnalyzeImplicitConversions(*this, E, CC); 12549 } 12550 12551 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12552 /// Input argument E is a logical expression. 12553 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12554 ::CheckBoolLikeConversion(*this, E, CC); 12555 } 12556 12557 /// Diagnose when expression is an integer constant expression and its evaluation 12558 /// results in integer overflow 12559 void Sema::CheckForIntOverflow (Expr *E) { 12560 // Use a work list to deal with nested struct initializers. 12561 SmallVector<Expr *, 2> Exprs(1, E); 12562 12563 do { 12564 Expr *OriginalE = Exprs.pop_back_val(); 12565 Expr *E = OriginalE->IgnoreParenCasts(); 12566 12567 if (isa<BinaryOperator>(E)) { 12568 E->EvaluateForOverflow(Context); 12569 continue; 12570 } 12571 12572 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12573 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12574 else if (isa<ObjCBoxedExpr>(OriginalE)) 12575 E->EvaluateForOverflow(Context); 12576 else if (auto Call = dyn_cast<CallExpr>(E)) 12577 Exprs.append(Call->arg_begin(), Call->arg_end()); 12578 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12579 Exprs.append(Message->arg_begin(), Message->arg_end()); 12580 } while (!Exprs.empty()); 12581 } 12582 12583 namespace { 12584 12585 /// Visitor for expressions which looks for unsequenced operations on the 12586 /// same object. 12587 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12588 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12589 12590 /// A tree of sequenced regions within an expression. Two regions are 12591 /// unsequenced if one is an ancestor or a descendent of the other. When we 12592 /// finish processing an expression with sequencing, such as a comma 12593 /// expression, we fold its tree nodes into its parent, since they are 12594 /// unsequenced with respect to nodes we will visit later. 12595 class SequenceTree { 12596 struct Value { 12597 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12598 unsigned Parent : 31; 12599 unsigned Merged : 1; 12600 }; 12601 SmallVector<Value, 8> Values; 12602 12603 public: 12604 /// A region within an expression which may be sequenced with respect 12605 /// to some other region. 12606 class Seq { 12607 friend class SequenceTree; 12608 12609 unsigned Index; 12610 12611 explicit Seq(unsigned N) : Index(N) {} 12612 12613 public: 12614 Seq() : Index(0) {} 12615 }; 12616 12617 SequenceTree() { Values.push_back(Value(0)); } 12618 Seq root() const { return Seq(0); } 12619 12620 /// Create a new sequence of operations, which is an unsequenced 12621 /// subset of \p Parent. This sequence of operations is sequenced with 12622 /// respect to other children of \p Parent. 12623 Seq allocate(Seq Parent) { 12624 Values.push_back(Value(Parent.Index)); 12625 return Seq(Values.size() - 1); 12626 } 12627 12628 /// Merge a sequence of operations into its parent. 12629 void merge(Seq S) { 12630 Values[S.Index].Merged = true; 12631 } 12632 12633 /// Determine whether two operations are unsequenced. This operation 12634 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12635 /// should have been merged into its parent as appropriate. 12636 bool isUnsequenced(Seq Cur, Seq Old) { 12637 unsigned C = representative(Cur.Index); 12638 unsigned Target = representative(Old.Index); 12639 while (C >= Target) { 12640 if (C == Target) 12641 return true; 12642 C = Values[C].Parent; 12643 } 12644 return false; 12645 } 12646 12647 private: 12648 /// Pick a representative for a sequence. 12649 unsigned representative(unsigned K) { 12650 if (Values[K].Merged) 12651 // Perform path compression as we go. 12652 return Values[K].Parent = representative(Values[K].Parent); 12653 return K; 12654 } 12655 }; 12656 12657 /// An object for which we can track unsequenced uses. 12658 using Object = const NamedDecl *; 12659 12660 /// Different flavors of object usage which we track. We only track the 12661 /// least-sequenced usage of each kind. 12662 enum UsageKind { 12663 /// A read of an object. Multiple unsequenced reads are OK. 12664 UK_Use, 12665 12666 /// A modification of an object which is sequenced before the value 12667 /// computation of the expression, such as ++n in C++. 12668 UK_ModAsValue, 12669 12670 /// A modification of an object which is not sequenced before the value 12671 /// computation of the expression, such as n++. 12672 UK_ModAsSideEffect, 12673 12674 UK_Count = UK_ModAsSideEffect + 1 12675 }; 12676 12677 /// Bundle together a sequencing region and the expression corresponding 12678 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12679 struct Usage { 12680 const Expr *UsageExpr; 12681 SequenceTree::Seq Seq; 12682 12683 Usage() : UsageExpr(nullptr), Seq() {} 12684 }; 12685 12686 struct UsageInfo { 12687 Usage Uses[UK_Count]; 12688 12689 /// Have we issued a diagnostic for this object already? 12690 bool Diagnosed; 12691 12692 UsageInfo() : Uses(), Diagnosed(false) {} 12693 }; 12694 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12695 12696 Sema &SemaRef; 12697 12698 /// Sequenced regions within the expression. 12699 SequenceTree Tree; 12700 12701 /// Declaration modifications and references which we have seen. 12702 UsageInfoMap UsageMap; 12703 12704 /// The region we are currently within. 12705 SequenceTree::Seq Region; 12706 12707 /// Filled in with declarations which were modified as a side-effect 12708 /// (that is, post-increment operations). 12709 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12710 12711 /// Expressions to check later. We defer checking these to reduce 12712 /// stack usage. 12713 SmallVectorImpl<const Expr *> &WorkList; 12714 12715 /// RAII object wrapping the visitation of a sequenced subexpression of an 12716 /// expression. At the end of this process, the side-effects of the evaluation 12717 /// become sequenced with respect to the value computation of the result, so 12718 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12719 /// UK_ModAsValue. 12720 struct SequencedSubexpression { 12721 SequencedSubexpression(SequenceChecker &Self) 12722 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12723 Self.ModAsSideEffect = &ModAsSideEffect; 12724 } 12725 12726 ~SequencedSubexpression() { 12727 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12728 // Add a new usage with usage kind UK_ModAsValue, and then restore 12729 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12730 // the previous one was empty). 12731 UsageInfo &UI = Self.UsageMap[M.first]; 12732 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12733 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12734 SideEffectUsage = M.second; 12735 } 12736 Self.ModAsSideEffect = OldModAsSideEffect; 12737 } 12738 12739 SequenceChecker &Self; 12740 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12741 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12742 }; 12743 12744 /// RAII object wrapping the visitation of a subexpression which we might 12745 /// choose to evaluate as a constant. If any subexpression is evaluated and 12746 /// found to be non-constant, this allows us to suppress the evaluation of 12747 /// the outer expression. 12748 class EvaluationTracker { 12749 public: 12750 EvaluationTracker(SequenceChecker &Self) 12751 : Self(Self), Prev(Self.EvalTracker) { 12752 Self.EvalTracker = this; 12753 } 12754 12755 ~EvaluationTracker() { 12756 Self.EvalTracker = Prev; 12757 if (Prev) 12758 Prev->EvalOK &= EvalOK; 12759 } 12760 12761 bool evaluate(const Expr *E, bool &Result) { 12762 if (!EvalOK || E->isValueDependent()) 12763 return false; 12764 EvalOK = E->EvaluateAsBooleanCondition( 12765 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12766 return EvalOK; 12767 } 12768 12769 private: 12770 SequenceChecker &Self; 12771 EvaluationTracker *Prev; 12772 bool EvalOK = true; 12773 } *EvalTracker = nullptr; 12774 12775 /// Find the object which is produced by the specified expression, 12776 /// if any. 12777 Object getObject(const Expr *E, bool Mod) const { 12778 E = E->IgnoreParenCasts(); 12779 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12780 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12781 return getObject(UO->getSubExpr(), Mod); 12782 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12783 if (BO->getOpcode() == BO_Comma) 12784 return getObject(BO->getRHS(), Mod); 12785 if (Mod && BO->isAssignmentOp()) 12786 return getObject(BO->getLHS(), Mod); 12787 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12788 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12789 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12790 return ME->getMemberDecl(); 12791 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12792 // FIXME: If this is a reference, map through to its value. 12793 return DRE->getDecl(); 12794 return nullptr; 12795 } 12796 12797 /// Note that an object \p O was modified or used by an expression 12798 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12799 /// the object \p O as obtained via the \p UsageMap. 12800 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12801 // Get the old usage for the given object and usage kind. 12802 Usage &U = UI.Uses[UK]; 12803 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12804 // If we have a modification as side effect and are in a sequenced 12805 // subexpression, save the old Usage so that we can restore it later 12806 // in SequencedSubexpression::~SequencedSubexpression. 12807 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12808 ModAsSideEffect->push_back(std::make_pair(O, U)); 12809 // Then record the new usage with the current sequencing region. 12810 U.UsageExpr = UsageExpr; 12811 U.Seq = Region; 12812 } 12813 } 12814 12815 /// Check whether a modification or use of an object \p O in an expression 12816 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12817 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12818 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12819 /// usage and false we are checking for a mod-use unsequenced usage. 12820 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12821 UsageKind OtherKind, bool IsModMod) { 12822 if (UI.Diagnosed) 12823 return; 12824 12825 const Usage &U = UI.Uses[OtherKind]; 12826 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12827 return; 12828 12829 const Expr *Mod = U.UsageExpr; 12830 const Expr *ModOrUse = UsageExpr; 12831 if (OtherKind == UK_Use) 12832 std::swap(Mod, ModOrUse); 12833 12834 SemaRef.DiagRuntimeBehavior( 12835 Mod->getExprLoc(), {Mod, ModOrUse}, 12836 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12837 : diag::warn_unsequenced_mod_use) 12838 << O << SourceRange(ModOrUse->getExprLoc())); 12839 UI.Diagnosed = true; 12840 } 12841 12842 // A note on note{Pre, Post}{Use, Mod}: 12843 // 12844 // (It helps to follow the algorithm with an expression such as 12845 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12846 // operations before C++17 and both are well-defined in C++17). 12847 // 12848 // When visiting a node which uses/modify an object we first call notePreUse 12849 // or notePreMod before visiting its sub-expression(s). At this point the 12850 // children of the current node have not yet been visited and so the eventual 12851 // uses/modifications resulting from the children of the current node have not 12852 // been recorded yet. 12853 // 12854 // We then visit the children of the current node. After that notePostUse or 12855 // notePostMod is called. These will 1) detect an unsequenced modification 12856 // as side effect (as in "k++ + k") and 2) add a new usage with the 12857 // appropriate usage kind. 12858 // 12859 // We also have to be careful that some operation sequences modification as 12860 // side effect as well (for example: || or ,). To account for this we wrap 12861 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12862 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12863 // which record usages which are modifications as side effect, and then 12864 // downgrade them (or more accurately restore the previous usage which was a 12865 // modification as side effect) when exiting the scope of the sequenced 12866 // subexpression. 12867 12868 void notePreUse(Object O, const Expr *UseExpr) { 12869 UsageInfo &UI = UsageMap[O]; 12870 // Uses conflict with other modifications. 12871 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12872 } 12873 12874 void notePostUse(Object O, const Expr *UseExpr) { 12875 UsageInfo &UI = UsageMap[O]; 12876 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12877 /*IsModMod=*/false); 12878 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12879 } 12880 12881 void notePreMod(Object O, const Expr *ModExpr) { 12882 UsageInfo &UI = UsageMap[O]; 12883 // Modifications conflict with other modifications and with uses. 12884 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12885 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12886 } 12887 12888 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12889 UsageInfo &UI = UsageMap[O]; 12890 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12891 /*IsModMod=*/true); 12892 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12893 } 12894 12895 public: 12896 SequenceChecker(Sema &S, const Expr *E, 12897 SmallVectorImpl<const Expr *> &WorkList) 12898 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12899 Visit(E); 12900 // Silence a -Wunused-private-field since WorkList is now unused. 12901 // TODO: Evaluate if it can be used, and if not remove it. 12902 (void)this->WorkList; 12903 } 12904 12905 void VisitStmt(const Stmt *S) { 12906 // Skip all statements which aren't expressions for now. 12907 } 12908 12909 void VisitExpr(const Expr *E) { 12910 // By default, just recurse to evaluated subexpressions. 12911 Base::VisitStmt(E); 12912 } 12913 12914 void VisitCastExpr(const CastExpr *E) { 12915 Object O = Object(); 12916 if (E->getCastKind() == CK_LValueToRValue) 12917 O = getObject(E->getSubExpr(), false); 12918 12919 if (O) 12920 notePreUse(O, E); 12921 VisitExpr(E); 12922 if (O) 12923 notePostUse(O, E); 12924 } 12925 12926 void VisitSequencedExpressions(const Expr *SequencedBefore, 12927 const Expr *SequencedAfter) { 12928 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12929 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12930 SequenceTree::Seq OldRegion = Region; 12931 12932 { 12933 SequencedSubexpression SeqBefore(*this); 12934 Region = BeforeRegion; 12935 Visit(SequencedBefore); 12936 } 12937 12938 Region = AfterRegion; 12939 Visit(SequencedAfter); 12940 12941 Region = OldRegion; 12942 12943 Tree.merge(BeforeRegion); 12944 Tree.merge(AfterRegion); 12945 } 12946 12947 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12948 // C++17 [expr.sub]p1: 12949 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12950 // expression E1 is sequenced before the expression E2. 12951 if (SemaRef.getLangOpts().CPlusPlus17) 12952 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12953 else { 12954 Visit(ASE->getLHS()); 12955 Visit(ASE->getRHS()); 12956 } 12957 } 12958 12959 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12960 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12961 void VisitBinPtrMem(const BinaryOperator *BO) { 12962 // C++17 [expr.mptr.oper]p4: 12963 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12964 // the expression E1 is sequenced before the expression E2. 12965 if (SemaRef.getLangOpts().CPlusPlus17) 12966 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12967 else { 12968 Visit(BO->getLHS()); 12969 Visit(BO->getRHS()); 12970 } 12971 } 12972 12973 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12974 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12975 void VisitBinShlShr(const BinaryOperator *BO) { 12976 // C++17 [expr.shift]p4: 12977 // The expression E1 is sequenced before the expression E2. 12978 if (SemaRef.getLangOpts().CPlusPlus17) 12979 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12980 else { 12981 Visit(BO->getLHS()); 12982 Visit(BO->getRHS()); 12983 } 12984 } 12985 12986 void VisitBinComma(const BinaryOperator *BO) { 12987 // C++11 [expr.comma]p1: 12988 // Every value computation and side effect associated with the left 12989 // expression is sequenced before every value computation and side 12990 // effect associated with the right expression. 12991 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12992 } 12993 12994 void VisitBinAssign(const BinaryOperator *BO) { 12995 SequenceTree::Seq RHSRegion; 12996 SequenceTree::Seq LHSRegion; 12997 if (SemaRef.getLangOpts().CPlusPlus17) { 12998 RHSRegion = Tree.allocate(Region); 12999 LHSRegion = Tree.allocate(Region); 13000 } else { 13001 RHSRegion = Region; 13002 LHSRegion = Region; 13003 } 13004 SequenceTree::Seq OldRegion = Region; 13005 13006 // C++11 [expr.ass]p1: 13007 // [...] the assignment is sequenced after the value computation 13008 // of the right and left operands, [...] 13009 // 13010 // so check it before inspecting the operands and update the 13011 // map afterwards. 13012 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13013 if (O) 13014 notePreMod(O, BO); 13015 13016 if (SemaRef.getLangOpts().CPlusPlus17) { 13017 // C++17 [expr.ass]p1: 13018 // [...] The right operand is sequenced before the left operand. [...] 13019 { 13020 SequencedSubexpression SeqBefore(*this); 13021 Region = RHSRegion; 13022 Visit(BO->getRHS()); 13023 } 13024 13025 Region = LHSRegion; 13026 Visit(BO->getLHS()); 13027 13028 if (O && isa<CompoundAssignOperator>(BO)) 13029 notePostUse(O, BO); 13030 13031 } else { 13032 // C++11 does not specify any sequencing between the LHS and RHS. 13033 Region = LHSRegion; 13034 Visit(BO->getLHS()); 13035 13036 if (O && isa<CompoundAssignOperator>(BO)) 13037 notePostUse(O, BO); 13038 13039 Region = RHSRegion; 13040 Visit(BO->getRHS()); 13041 } 13042 13043 // C++11 [expr.ass]p1: 13044 // the assignment is sequenced [...] before the value computation of the 13045 // assignment expression. 13046 // C11 6.5.16/3 has no such rule. 13047 Region = OldRegion; 13048 if (O) 13049 notePostMod(O, BO, 13050 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13051 : UK_ModAsSideEffect); 13052 if (SemaRef.getLangOpts().CPlusPlus17) { 13053 Tree.merge(RHSRegion); 13054 Tree.merge(LHSRegion); 13055 } 13056 } 13057 13058 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13059 VisitBinAssign(CAO); 13060 } 13061 13062 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13063 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13064 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13065 Object O = getObject(UO->getSubExpr(), true); 13066 if (!O) 13067 return VisitExpr(UO); 13068 13069 notePreMod(O, UO); 13070 Visit(UO->getSubExpr()); 13071 // C++11 [expr.pre.incr]p1: 13072 // the expression ++x is equivalent to x+=1 13073 notePostMod(O, UO, 13074 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13075 : UK_ModAsSideEffect); 13076 } 13077 13078 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13079 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13080 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13081 Object O = getObject(UO->getSubExpr(), true); 13082 if (!O) 13083 return VisitExpr(UO); 13084 13085 notePreMod(O, UO); 13086 Visit(UO->getSubExpr()); 13087 notePostMod(O, UO, UK_ModAsSideEffect); 13088 } 13089 13090 void VisitBinLOr(const BinaryOperator *BO) { 13091 // C++11 [expr.log.or]p2: 13092 // If the second expression is evaluated, every value computation and 13093 // side effect associated with the first expression is sequenced before 13094 // every value computation and side effect associated with the 13095 // second expression. 13096 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13097 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13098 SequenceTree::Seq OldRegion = Region; 13099 13100 EvaluationTracker Eval(*this); 13101 { 13102 SequencedSubexpression Sequenced(*this); 13103 Region = LHSRegion; 13104 Visit(BO->getLHS()); 13105 } 13106 13107 // C++11 [expr.log.or]p1: 13108 // [...] the second operand is not evaluated if the first operand 13109 // evaluates to true. 13110 bool EvalResult = false; 13111 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13112 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13113 if (ShouldVisitRHS) { 13114 Region = RHSRegion; 13115 Visit(BO->getRHS()); 13116 } 13117 13118 Region = OldRegion; 13119 Tree.merge(LHSRegion); 13120 Tree.merge(RHSRegion); 13121 } 13122 13123 void VisitBinLAnd(const BinaryOperator *BO) { 13124 // C++11 [expr.log.and]p2: 13125 // If the second expression is evaluated, every value computation and 13126 // side effect associated with the first expression is sequenced before 13127 // every value computation and side effect associated with the 13128 // second expression. 13129 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13130 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13131 SequenceTree::Seq OldRegion = Region; 13132 13133 EvaluationTracker Eval(*this); 13134 { 13135 SequencedSubexpression Sequenced(*this); 13136 Region = LHSRegion; 13137 Visit(BO->getLHS()); 13138 } 13139 13140 // C++11 [expr.log.and]p1: 13141 // [...] the second operand is not evaluated if the first operand is false. 13142 bool EvalResult = false; 13143 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13144 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13145 if (ShouldVisitRHS) { 13146 Region = RHSRegion; 13147 Visit(BO->getRHS()); 13148 } 13149 13150 Region = OldRegion; 13151 Tree.merge(LHSRegion); 13152 Tree.merge(RHSRegion); 13153 } 13154 13155 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13156 // C++11 [expr.cond]p1: 13157 // [...] Every value computation and side effect associated with the first 13158 // expression is sequenced before every value computation and side effect 13159 // associated with the second or third expression. 13160 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13161 13162 // No sequencing is specified between the true and false expression. 13163 // However since exactly one of both is going to be evaluated we can 13164 // consider them to be sequenced. This is needed to avoid warning on 13165 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13166 // both the true and false expressions because we can't evaluate x. 13167 // This will still allow us to detect an expression like (pre C++17) 13168 // "(x ? y += 1 : y += 2) = y". 13169 // 13170 // We don't wrap the visitation of the true and false expression with 13171 // SequencedSubexpression because we don't want to downgrade modifications 13172 // as side effect in the true and false expressions after the visition 13173 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13174 // not warn between the two "y++", but we should warn between the "y++" 13175 // and the "y". 13176 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13177 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13178 SequenceTree::Seq OldRegion = Region; 13179 13180 EvaluationTracker Eval(*this); 13181 { 13182 SequencedSubexpression Sequenced(*this); 13183 Region = ConditionRegion; 13184 Visit(CO->getCond()); 13185 } 13186 13187 // C++11 [expr.cond]p1: 13188 // [...] The first expression is contextually converted to bool (Clause 4). 13189 // It is evaluated and if it is true, the result of the conditional 13190 // expression is the value of the second expression, otherwise that of the 13191 // third expression. Only one of the second and third expressions is 13192 // evaluated. [...] 13193 bool EvalResult = false; 13194 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13195 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13196 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13197 if (ShouldVisitTrueExpr) { 13198 Region = TrueRegion; 13199 Visit(CO->getTrueExpr()); 13200 } 13201 if (ShouldVisitFalseExpr) { 13202 Region = FalseRegion; 13203 Visit(CO->getFalseExpr()); 13204 } 13205 13206 Region = OldRegion; 13207 Tree.merge(ConditionRegion); 13208 Tree.merge(TrueRegion); 13209 Tree.merge(FalseRegion); 13210 } 13211 13212 void VisitCallExpr(const CallExpr *CE) { 13213 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13214 13215 if (CE->isUnevaluatedBuiltinCall(Context)) 13216 return; 13217 13218 // C++11 [intro.execution]p15: 13219 // When calling a function [...], every value computation and side effect 13220 // associated with any argument expression, or with the postfix expression 13221 // designating the called function, is sequenced before execution of every 13222 // expression or statement in the body of the function [and thus before 13223 // the value computation of its result]. 13224 SequencedSubexpression Sequenced(*this); 13225 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13226 // C++17 [expr.call]p5 13227 // The postfix-expression is sequenced before each expression in the 13228 // expression-list and any default argument. [...] 13229 SequenceTree::Seq CalleeRegion; 13230 SequenceTree::Seq OtherRegion; 13231 if (SemaRef.getLangOpts().CPlusPlus17) { 13232 CalleeRegion = Tree.allocate(Region); 13233 OtherRegion = Tree.allocate(Region); 13234 } else { 13235 CalleeRegion = Region; 13236 OtherRegion = Region; 13237 } 13238 SequenceTree::Seq OldRegion = Region; 13239 13240 // Visit the callee expression first. 13241 Region = CalleeRegion; 13242 if (SemaRef.getLangOpts().CPlusPlus17) { 13243 SequencedSubexpression Sequenced(*this); 13244 Visit(CE->getCallee()); 13245 } else { 13246 Visit(CE->getCallee()); 13247 } 13248 13249 // Then visit the argument expressions. 13250 Region = OtherRegion; 13251 for (const Expr *Argument : CE->arguments()) 13252 Visit(Argument); 13253 13254 Region = OldRegion; 13255 if (SemaRef.getLangOpts().CPlusPlus17) { 13256 Tree.merge(CalleeRegion); 13257 Tree.merge(OtherRegion); 13258 } 13259 }); 13260 } 13261 13262 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13263 // C++17 [over.match.oper]p2: 13264 // [...] the operator notation is first transformed to the equivalent 13265 // function-call notation as summarized in Table 12 (where @ denotes one 13266 // of the operators covered in the specified subclause). However, the 13267 // operands are sequenced in the order prescribed for the built-in 13268 // operator (Clause 8). 13269 // 13270 // From the above only overloaded binary operators and overloaded call 13271 // operators have sequencing rules in C++17 that we need to handle 13272 // separately. 13273 if (!SemaRef.getLangOpts().CPlusPlus17 || 13274 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13275 return VisitCallExpr(CXXOCE); 13276 13277 enum { 13278 NoSequencing, 13279 LHSBeforeRHS, 13280 RHSBeforeLHS, 13281 LHSBeforeRest 13282 } SequencingKind; 13283 switch (CXXOCE->getOperator()) { 13284 case OO_Equal: 13285 case OO_PlusEqual: 13286 case OO_MinusEqual: 13287 case OO_StarEqual: 13288 case OO_SlashEqual: 13289 case OO_PercentEqual: 13290 case OO_CaretEqual: 13291 case OO_AmpEqual: 13292 case OO_PipeEqual: 13293 case OO_LessLessEqual: 13294 case OO_GreaterGreaterEqual: 13295 SequencingKind = RHSBeforeLHS; 13296 break; 13297 13298 case OO_LessLess: 13299 case OO_GreaterGreater: 13300 case OO_AmpAmp: 13301 case OO_PipePipe: 13302 case OO_Comma: 13303 case OO_ArrowStar: 13304 case OO_Subscript: 13305 SequencingKind = LHSBeforeRHS; 13306 break; 13307 13308 case OO_Call: 13309 SequencingKind = LHSBeforeRest; 13310 break; 13311 13312 default: 13313 SequencingKind = NoSequencing; 13314 break; 13315 } 13316 13317 if (SequencingKind == NoSequencing) 13318 return VisitCallExpr(CXXOCE); 13319 13320 // This is a call, so all subexpressions are sequenced before the result. 13321 SequencedSubexpression Sequenced(*this); 13322 13323 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13324 assert(SemaRef.getLangOpts().CPlusPlus17 && 13325 "Should only get there with C++17 and above!"); 13326 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13327 "Should only get there with an overloaded binary operator" 13328 " or an overloaded call operator!"); 13329 13330 if (SequencingKind == LHSBeforeRest) { 13331 assert(CXXOCE->getOperator() == OO_Call && 13332 "We should only have an overloaded call operator here!"); 13333 13334 // This is very similar to VisitCallExpr, except that we only have the 13335 // C++17 case. The postfix-expression is the first argument of the 13336 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13337 // are in the following arguments. 13338 // 13339 // Note that we intentionally do not visit the callee expression since 13340 // it is just a decayed reference to a function. 13341 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13342 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13343 SequenceTree::Seq OldRegion = Region; 13344 13345 assert(CXXOCE->getNumArgs() >= 1 && 13346 "An overloaded call operator must have at least one argument" 13347 " for the postfix-expression!"); 13348 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13349 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13350 CXXOCE->getNumArgs() - 1); 13351 13352 // Visit the postfix-expression first. 13353 { 13354 Region = PostfixExprRegion; 13355 SequencedSubexpression Sequenced(*this); 13356 Visit(PostfixExpr); 13357 } 13358 13359 // Then visit the argument expressions. 13360 Region = ArgsRegion; 13361 for (const Expr *Arg : Args) 13362 Visit(Arg); 13363 13364 Region = OldRegion; 13365 Tree.merge(PostfixExprRegion); 13366 Tree.merge(ArgsRegion); 13367 } else { 13368 assert(CXXOCE->getNumArgs() == 2 && 13369 "Should only have two arguments here!"); 13370 assert((SequencingKind == LHSBeforeRHS || 13371 SequencingKind == RHSBeforeLHS) && 13372 "Unexpected sequencing kind!"); 13373 13374 // We do not visit the callee expression since it is just a decayed 13375 // reference to a function. 13376 const Expr *E1 = CXXOCE->getArg(0); 13377 const Expr *E2 = CXXOCE->getArg(1); 13378 if (SequencingKind == RHSBeforeLHS) 13379 std::swap(E1, E2); 13380 13381 return VisitSequencedExpressions(E1, E2); 13382 } 13383 }); 13384 } 13385 13386 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13387 // This is a call, so all subexpressions are sequenced before the result. 13388 SequencedSubexpression Sequenced(*this); 13389 13390 if (!CCE->isListInitialization()) 13391 return VisitExpr(CCE); 13392 13393 // In C++11, list initializations are sequenced. 13394 SmallVector<SequenceTree::Seq, 32> Elts; 13395 SequenceTree::Seq Parent = Region; 13396 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13397 E = CCE->arg_end(); 13398 I != E; ++I) { 13399 Region = Tree.allocate(Parent); 13400 Elts.push_back(Region); 13401 Visit(*I); 13402 } 13403 13404 // Forget that the initializers are sequenced. 13405 Region = Parent; 13406 for (unsigned I = 0; I < Elts.size(); ++I) 13407 Tree.merge(Elts[I]); 13408 } 13409 13410 void VisitInitListExpr(const InitListExpr *ILE) { 13411 if (!SemaRef.getLangOpts().CPlusPlus11) 13412 return VisitExpr(ILE); 13413 13414 // In C++11, list initializations are sequenced. 13415 SmallVector<SequenceTree::Seq, 32> Elts; 13416 SequenceTree::Seq Parent = Region; 13417 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13418 const Expr *E = ILE->getInit(I); 13419 if (!E) 13420 continue; 13421 Region = Tree.allocate(Parent); 13422 Elts.push_back(Region); 13423 Visit(E); 13424 } 13425 13426 // Forget that the initializers are sequenced. 13427 Region = Parent; 13428 for (unsigned I = 0; I < Elts.size(); ++I) 13429 Tree.merge(Elts[I]); 13430 } 13431 }; 13432 13433 } // namespace 13434 13435 void Sema::CheckUnsequencedOperations(const Expr *E) { 13436 SmallVector<const Expr *, 8> WorkList; 13437 WorkList.push_back(E); 13438 while (!WorkList.empty()) { 13439 const Expr *Item = WorkList.pop_back_val(); 13440 SequenceChecker(*this, Item, WorkList); 13441 } 13442 } 13443 13444 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13445 bool IsConstexpr) { 13446 llvm::SaveAndRestore<bool> ConstantContext( 13447 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13448 CheckImplicitConversions(E, CheckLoc); 13449 if (!E->isInstantiationDependent()) 13450 CheckUnsequencedOperations(E); 13451 if (!IsConstexpr && !E->isValueDependent()) 13452 CheckForIntOverflow(E); 13453 DiagnoseMisalignedMembers(); 13454 } 13455 13456 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13457 FieldDecl *BitField, 13458 Expr *Init) { 13459 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13460 } 13461 13462 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13463 SourceLocation Loc) { 13464 if (!PType->isVariablyModifiedType()) 13465 return; 13466 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13467 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13468 return; 13469 } 13470 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13471 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13472 return; 13473 } 13474 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13475 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13476 return; 13477 } 13478 13479 const ArrayType *AT = S.Context.getAsArrayType(PType); 13480 if (!AT) 13481 return; 13482 13483 if (AT->getSizeModifier() != ArrayType::Star) { 13484 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13485 return; 13486 } 13487 13488 S.Diag(Loc, diag::err_array_star_in_function_definition); 13489 } 13490 13491 /// CheckParmsForFunctionDef - Check that the parameters of the given 13492 /// function are appropriate for the definition of a function. This 13493 /// takes care of any checks that cannot be performed on the 13494 /// declaration itself, e.g., that the types of each of the function 13495 /// parameters are complete. 13496 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13497 bool CheckParameterNames) { 13498 bool HasInvalidParm = false; 13499 for (ParmVarDecl *Param : Parameters) { 13500 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13501 // function declarator that is part of a function definition of 13502 // that function shall not have incomplete type. 13503 // 13504 // This is also C++ [dcl.fct]p6. 13505 if (!Param->isInvalidDecl() && 13506 RequireCompleteType(Param->getLocation(), Param->getType(), 13507 diag::err_typecheck_decl_incomplete_type)) { 13508 Param->setInvalidDecl(); 13509 HasInvalidParm = true; 13510 } 13511 13512 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13513 // declaration of each parameter shall include an identifier. 13514 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13515 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13516 // Diagnose this as an extension in C17 and earlier. 13517 if (!getLangOpts().C2x) 13518 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13519 } 13520 13521 // C99 6.7.5.3p12: 13522 // If the function declarator is not part of a definition of that 13523 // function, parameters may have incomplete type and may use the [*] 13524 // notation in their sequences of declarator specifiers to specify 13525 // variable length array types. 13526 QualType PType = Param->getOriginalType(); 13527 // FIXME: This diagnostic should point the '[*]' if source-location 13528 // information is added for it. 13529 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13530 13531 // If the parameter is a c++ class type and it has to be destructed in the 13532 // callee function, declare the destructor so that it can be called by the 13533 // callee function. Do not perform any direct access check on the dtor here. 13534 if (!Param->isInvalidDecl()) { 13535 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13536 if (!ClassDecl->isInvalidDecl() && 13537 !ClassDecl->hasIrrelevantDestructor() && 13538 !ClassDecl->isDependentContext() && 13539 ClassDecl->isParamDestroyedInCallee()) { 13540 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13541 MarkFunctionReferenced(Param->getLocation(), Destructor); 13542 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13543 } 13544 } 13545 } 13546 13547 // Parameters with the pass_object_size attribute only need to be marked 13548 // constant at function definitions. Because we lack information about 13549 // whether we're on a declaration or definition when we're instantiating the 13550 // attribute, we need to check for constness here. 13551 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13552 if (!Param->getType().isConstQualified()) 13553 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13554 << Attr->getSpelling() << 1; 13555 13556 // Check for parameter names shadowing fields from the class. 13557 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13558 // The owning context for the parameter should be the function, but we 13559 // want to see if this function's declaration context is a record. 13560 DeclContext *DC = Param->getDeclContext(); 13561 if (DC && DC->isFunctionOrMethod()) { 13562 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13563 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13564 RD, /*DeclIsField*/ false); 13565 } 13566 } 13567 } 13568 13569 return HasInvalidParm; 13570 } 13571 13572 Optional<std::pair<CharUnits, CharUnits>> 13573 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 13574 13575 /// Compute the alignment and offset of the base class object given the 13576 /// derived-to-base cast expression and the alignment and offset of the derived 13577 /// class object. 13578 static std::pair<CharUnits, CharUnits> 13579 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 13580 CharUnits BaseAlignment, CharUnits Offset, 13581 ASTContext &Ctx) { 13582 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 13583 ++PathI) { 13584 const CXXBaseSpecifier *Base = *PathI; 13585 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 13586 if (Base->isVirtual()) { 13587 // The complete object may have a lower alignment than the non-virtual 13588 // alignment of the base, in which case the base may be misaligned. Choose 13589 // the smaller of the non-virtual alignment and BaseAlignment, which is a 13590 // conservative lower bound of the complete object alignment. 13591 CharUnits NonVirtualAlignment = 13592 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 13593 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 13594 Offset = CharUnits::Zero(); 13595 } else { 13596 const ASTRecordLayout &RL = 13597 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 13598 Offset += RL.getBaseClassOffset(BaseDecl); 13599 } 13600 DerivedType = Base->getType(); 13601 } 13602 13603 return std::make_pair(BaseAlignment, Offset); 13604 } 13605 13606 /// Compute the alignment and offset of a binary additive operator. 13607 static Optional<std::pair<CharUnits, CharUnits>> 13608 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 13609 bool IsSub, ASTContext &Ctx) { 13610 QualType PointeeType = PtrE->getType()->getPointeeType(); 13611 13612 if (!PointeeType->isConstantSizeType()) 13613 return llvm::None; 13614 13615 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 13616 13617 if (!P) 13618 return llvm::None; 13619 13620 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 13621 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 13622 CharUnits Offset = EltSize * IdxRes->getExtValue(); 13623 if (IsSub) 13624 Offset = -Offset; 13625 return std::make_pair(P->first, P->second + Offset); 13626 } 13627 13628 // If the integer expression isn't a constant expression, compute the lower 13629 // bound of the alignment using the alignment and offset of the pointer 13630 // expression and the element size. 13631 return std::make_pair( 13632 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 13633 CharUnits::Zero()); 13634 } 13635 13636 /// This helper function takes an lvalue expression and returns the alignment of 13637 /// a VarDecl and a constant offset from the VarDecl. 13638 Optional<std::pair<CharUnits, CharUnits>> 13639 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 13640 E = E->IgnoreParens(); 13641 switch (E->getStmtClass()) { 13642 default: 13643 break; 13644 case Stmt::CStyleCastExprClass: 13645 case Stmt::CXXStaticCastExprClass: 13646 case Stmt::ImplicitCastExprClass: { 13647 auto *CE = cast<CastExpr>(E); 13648 const Expr *From = CE->getSubExpr(); 13649 switch (CE->getCastKind()) { 13650 default: 13651 break; 13652 case CK_NoOp: 13653 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13654 case CK_UncheckedDerivedToBase: 13655 case CK_DerivedToBase: { 13656 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13657 if (!P) 13658 break; 13659 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 13660 P->second, Ctx); 13661 } 13662 } 13663 break; 13664 } 13665 case Stmt::ArraySubscriptExprClass: { 13666 auto *ASE = cast<ArraySubscriptExpr>(E); 13667 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 13668 false, Ctx); 13669 } 13670 case Stmt::DeclRefExprClass: { 13671 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 13672 // FIXME: If VD is captured by copy or is an escaping __block variable, 13673 // use the alignment of VD's type. 13674 if (!VD->getType()->isReferenceType()) 13675 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 13676 if (VD->hasInit()) 13677 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 13678 } 13679 break; 13680 } 13681 case Stmt::MemberExprClass: { 13682 auto *ME = cast<MemberExpr>(E); 13683 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 13684 if (!FD || FD->getType()->isReferenceType()) 13685 break; 13686 Optional<std::pair<CharUnits, CharUnits>> P; 13687 if (ME->isArrow()) 13688 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 13689 else 13690 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 13691 if (!P) 13692 break; 13693 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 13694 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 13695 return std::make_pair(P->first, 13696 P->second + CharUnits::fromQuantity(Offset)); 13697 } 13698 case Stmt::UnaryOperatorClass: { 13699 auto *UO = cast<UnaryOperator>(E); 13700 switch (UO->getOpcode()) { 13701 default: 13702 break; 13703 case UO_Deref: 13704 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 13705 } 13706 break; 13707 } 13708 case Stmt::BinaryOperatorClass: { 13709 auto *BO = cast<BinaryOperator>(E); 13710 auto Opcode = BO->getOpcode(); 13711 switch (Opcode) { 13712 default: 13713 break; 13714 case BO_Comma: 13715 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 13716 } 13717 break; 13718 } 13719 } 13720 return llvm::None; 13721 } 13722 13723 /// This helper function takes a pointer expression and returns the alignment of 13724 /// a VarDecl and a constant offset from the VarDecl. 13725 Optional<std::pair<CharUnits, CharUnits>> 13726 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 13727 E = E->IgnoreParens(); 13728 switch (E->getStmtClass()) { 13729 default: 13730 break; 13731 case Stmt::CStyleCastExprClass: 13732 case Stmt::CXXStaticCastExprClass: 13733 case Stmt::ImplicitCastExprClass: { 13734 auto *CE = cast<CastExpr>(E); 13735 const Expr *From = CE->getSubExpr(); 13736 switch (CE->getCastKind()) { 13737 default: 13738 break; 13739 case CK_NoOp: 13740 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13741 case CK_ArrayToPointerDecay: 13742 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13743 case CK_UncheckedDerivedToBase: 13744 case CK_DerivedToBase: { 13745 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13746 if (!P) 13747 break; 13748 return getDerivedToBaseAlignmentAndOffset( 13749 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 13750 } 13751 } 13752 break; 13753 } 13754 case Stmt::CXXThisExprClass: { 13755 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 13756 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 13757 return std::make_pair(Alignment, CharUnits::Zero()); 13758 } 13759 case Stmt::UnaryOperatorClass: { 13760 auto *UO = cast<UnaryOperator>(E); 13761 if (UO->getOpcode() == UO_AddrOf) 13762 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 13763 break; 13764 } 13765 case Stmt::BinaryOperatorClass: { 13766 auto *BO = cast<BinaryOperator>(E); 13767 auto Opcode = BO->getOpcode(); 13768 switch (Opcode) { 13769 default: 13770 break; 13771 case BO_Add: 13772 case BO_Sub: { 13773 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 13774 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 13775 std::swap(LHS, RHS); 13776 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 13777 Ctx); 13778 } 13779 case BO_Comma: 13780 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 13781 } 13782 break; 13783 } 13784 } 13785 return llvm::None; 13786 } 13787 13788 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 13789 // See if we can compute the alignment of a VarDecl and an offset from it. 13790 Optional<std::pair<CharUnits, CharUnits>> P = 13791 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 13792 13793 if (P) 13794 return P->first.alignmentAtOffset(P->second); 13795 13796 // If that failed, return the type's alignment. 13797 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 13798 } 13799 13800 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13801 /// pointer cast increases the alignment requirements. 13802 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13803 // This is actually a lot of work to potentially be doing on every 13804 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13805 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13806 return; 13807 13808 // Ignore dependent types. 13809 if (T->isDependentType() || Op->getType()->isDependentType()) 13810 return; 13811 13812 // Require that the destination be a pointer type. 13813 const PointerType *DestPtr = T->getAs<PointerType>(); 13814 if (!DestPtr) return; 13815 13816 // If the destination has alignment 1, we're done. 13817 QualType DestPointee = DestPtr->getPointeeType(); 13818 if (DestPointee->isIncompleteType()) return; 13819 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13820 if (DestAlign.isOne()) return; 13821 13822 // Require that the source be a pointer type. 13823 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13824 if (!SrcPtr) return; 13825 QualType SrcPointee = SrcPtr->getPointeeType(); 13826 13827 // Explicitly allow casts from cv void*. We already implicitly 13828 // allowed casts to cv void*, since they have alignment 1. 13829 // Also allow casts involving incomplete types, which implicitly 13830 // includes 'void'. 13831 if (SrcPointee->isIncompleteType()) return; 13832 13833 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 13834 13835 if (SrcAlign >= DestAlign) return; 13836 13837 Diag(TRange.getBegin(), diag::warn_cast_align) 13838 << Op->getType() << T 13839 << static_cast<unsigned>(SrcAlign.getQuantity()) 13840 << static_cast<unsigned>(DestAlign.getQuantity()) 13841 << TRange << Op->getSourceRange(); 13842 } 13843 13844 /// Check whether this array fits the idiom of a size-one tail padded 13845 /// array member of a struct. 13846 /// 13847 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13848 /// commonly used to emulate flexible arrays in C89 code. 13849 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13850 const NamedDecl *ND) { 13851 if (Size != 1 || !ND) return false; 13852 13853 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13854 if (!FD) return false; 13855 13856 // Don't consider sizes resulting from macro expansions or template argument 13857 // substitution to form C89 tail-padded arrays. 13858 13859 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13860 while (TInfo) { 13861 TypeLoc TL = TInfo->getTypeLoc(); 13862 // Look through typedefs. 13863 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13864 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13865 TInfo = TDL->getTypeSourceInfo(); 13866 continue; 13867 } 13868 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13869 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13870 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13871 return false; 13872 } 13873 break; 13874 } 13875 13876 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13877 if (!RD) return false; 13878 if (RD->isUnion()) return false; 13879 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13880 if (!CRD->isStandardLayout()) return false; 13881 } 13882 13883 // See if this is the last field decl in the record. 13884 const Decl *D = FD; 13885 while ((D = D->getNextDeclInContext())) 13886 if (isa<FieldDecl>(D)) 13887 return false; 13888 return true; 13889 } 13890 13891 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13892 const ArraySubscriptExpr *ASE, 13893 bool AllowOnePastEnd, bool IndexNegated) { 13894 // Already diagnosed by the constant evaluator. 13895 if (isConstantEvaluated()) 13896 return; 13897 13898 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13899 if (IndexExpr->isValueDependent()) 13900 return; 13901 13902 const Type *EffectiveType = 13903 BaseExpr->getType()->getPointeeOrArrayElementType(); 13904 BaseExpr = BaseExpr->IgnoreParenCasts(); 13905 const ConstantArrayType *ArrayTy = 13906 Context.getAsConstantArrayType(BaseExpr->getType()); 13907 13908 if (!ArrayTy) 13909 return; 13910 13911 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13912 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13913 return; 13914 13915 Expr::EvalResult Result; 13916 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13917 return; 13918 13919 llvm::APSInt index = Result.Val.getInt(); 13920 if (IndexNegated) 13921 index = -index; 13922 13923 const NamedDecl *ND = nullptr; 13924 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13925 ND = DRE->getDecl(); 13926 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13927 ND = ME->getMemberDecl(); 13928 13929 if (index.isUnsigned() || !index.isNegative()) { 13930 // It is possible that the type of the base expression after 13931 // IgnoreParenCasts is incomplete, even though the type of the base 13932 // expression before IgnoreParenCasts is complete (see PR39746 for an 13933 // example). In this case we have no information about whether the array 13934 // access exceeds the array bounds. However we can still diagnose an array 13935 // access which precedes the array bounds. 13936 if (BaseType->isIncompleteType()) 13937 return; 13938 13939 llvm::APInt size = ArrayTy->getSize(); 13940 if (!size.isStrictlyPositive()) 13941 return; 13942 13943 if (BaseType != EffectiveType) { 13944 // Make sure we're comparing apples to apples when comparing index to size 13945 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13946 uint64_t array_typesize = Context.getTypeSize(BaseType); 13947 // Handle ptrarith_typesize being zero, such as when casting to void* 13948 if (!ptrarith_typesize) ptrarith_typesize = 1; 13949 if (ptrarith_typesize != array_typesize) { 13950 // There's a cast to a different size type involved 13951 uint64_t ratio = array_typesize / ptrarith_typesize; 13952 // TODO: Be smarter about handling cases where array_typesize is not a 13953 // multiple of ptrarith_typesize 13954 if (ptrarith_typesize * ratio == array_typesize) 13955 size *= llvm::APInt(size.getBitWidth(), ratio); 13956 } 13957 } 13958 13959 if (size.getBitWidth() > index.getBitWidth()) 13960 index = index.zext(size.getBitWidth()); 13961 else if (size.getBitWidth() < index.getBitWidth()) 13962 size = size.zext(index.getBitWidth()); 13963 13964 // For array subscripting the index must be less than size, but for pointer 13965 // arithmetic also allow the index (offset) to be equal to size since 13966 // computing the next address after the end of the array is legal and 13967 // commonly done e.g. in C++ iterators and range-based for loops. 13968 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13969 return; 13970 13971 // Also don't warn for arrays of size 1 which are members of some 13972 // structure. These are often used to approximate flexible arrays in C89 13973 // code. 13974 if (IsTailPaddedMemberArray(*this, size, ND)) 13975 return; 13976 13977 // Suppress the warning if the subscript expression (as identified by the 13978 // ']' location) and the index expression are both from macro expansions 13979 // within a system header. 13980 if (ASE) { 13981 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13982 ASE->getRBracketLoc()); 13983 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13984 SourceLocation IndexLoc = 13985 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13986 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13987 return; 13988 } 13989 } 13990 13991 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13992 if (ASE) 13993 DiagID = diag::warn_array_index_exceeds_bounds; 13994 13995 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13996 PDiag(DiagID) << index.toString(10, true) 13997 << size.toString(10, true) 13998 << (unsigned)size.getLimitedValue(~0U) 13999 << IndexExpr->getSourceRange()); 14000 } else { 14001 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14002 if (!ASE) { 14003 DiagID = diag::warn_ptr_arith_precedes_bounds; 14004 if (index.isNegative()) index = -index; 14005 } 14006 14007 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14008 PDiag(DiagID) << index.toString(10, true) 14009 << IndexExpr->getSourceRange()); 14010 } 14011 14012 if (!ND) { 14013 // Try harder to find a NamedDecl to point at in the note. 14014 while (const ArraySubscriptExpr *ASE = 14015 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14016 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14017 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14018 ND = DRE->getDecl(); 14019 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14020 ND = ME->getMemberDecl(); 14021 } 14022 14023 if (ND) 14024 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14025 PDiag(diag::note_array_declared_here) << ND); 14026 } 14027 14028 void Sema::CheckArrayAccess(const Expr *expr) { 14029 int AllowOnePastEnd = 0; 14030 while (expr) { 14031 expr = expr->IgnoreParenImpCasts(); 14032 switch (expr->getStmtClass()) { 14033 case Stmt::ArraySubscriptExprClass: { 14034 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14035 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14036 AllowOnePastEnd > 0); 14037 expr = ASE->getBase(); 14038 break; 14039 } 14040 case Stmt::MemberExprClass: { 14041 expr = cast<MemberExpr>(expr)->getBase(); 14042 break; 14043 } 14044 case Stmt::OMPArraySectionExprClass: { 14045 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 14046 if (ASE->getLowerBound()) 14047 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 14048 /*ASE=*/nullptr, AllowOnePastEnd > 0); 14049 return; 14050 } 14051 case Stmt::UnaryOperatorClass: { 14052 // Only unwrap the * and & unary operators 14053 const UnaryOperator *UO = cast<UnaryOperator>(expr); 14054 expr = UO->getSubExpr(); 14055 switch (UO->getOpcode()) { 14056 case UO_AddrOf: 14057 AllowOnePastEnd++; 14058 break; 14059 case UO_Deref: 14060 AllowOnePastEnd--; 14061 break; 14062 default: 14063 return; 14064 } 14065 break; 14066 } 14067 case Stmt::ConditionalOperatorClass: { 14068 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14069 if (const Expr *lhs = cond->getLHS()) 14070 CheckArrayAccess(lhs); 14071 if (const Expr *rhs = cond->getRHS()) 14072 CheckArrayAccess(rhs); 14073 return; 14074 } 14075 case Stmt::CXXOperatorCallExprClass: { 14076 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14077 for (const auto *Arg : OCE->arguments()) 14078 CheckArrayAccess(Arg); 14079 return; 14080 } 14081 default: 14082 return; 14083 } 14084 } 14085 } 14086 14087 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14088 14089 namespace { 14090 14091 struct RetainCycleOwner { 14092 VarDecl *Variable = nullptr; 14093 SourceRange Range; 14094 SourceLocation Loc; 14095 bool Indirect = false; 14096 14097 RetainCycleOwner() = default; 14098 14099 void setLocsFrom(Expr *e) { 14100 Loc = e->getExprLoc(); 14101 Range = e->getSourceRange(); 14102 } 14103 }; 14104 14105 } // namespace 14106 14107 /// Consider whether capturing the given variable can possibly lead to 14108 /// a retain cycle. 14109 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14110 // In ARC, it's captured strongly iff the variable has __strong 14111 // lifetime. In MRR, it's captured strongly if the variable is 14112 // __block and has an appropriate type. 14113 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14114 return false; 14115 14116 owner.Variable = var; 14117 if (ref) 14118 owner.setLocsFrom(ref); 14119 return true; 14120 } 14121 14122 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14123 while (true) { 14124 e = e->IgnoreParens(); 14125 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14126 switch (cast->getCastKind()) { 14127 case CK_BitCast: 14128 case CK_LValueBitCast: 14129 case CK_LValueToRValue: 14130 case CK_ARCReclaimReturnedObject: 14131 e = cast->getSubExpr(); 14132 continue; 14133 14134 default: 14135 return false; 14136 } 14137 } 14138 14139 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14140 ObjCIvarDecl *ivar = ref->getDecl(); 14141 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14142 return false; 14143 14144 // Try to find a retain cycle in the base. 14145 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14146 return false; 14147 14148 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14149 owner.Indirect = true; 14150 return true; 14151 } 14152 14153 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14154 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14155 if (!var) return false; 14156 return considerVariable(var, ref, owner); 14157 } 14158 14159 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14160 if (member->isArrow()) return false; 14161 14162 // Don't count this as an indirect ownership. 14163 e = member->getBase(); 14164 continue; 14165 } 14166 14167 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14168 // Only pay attention to pseudo-objects on property references. 14169 ObjCPropertyRefExpr *pre 14170 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14171 ->IgnoreParens()); 14172 if (!pre) return false; 14173 if (pre->isImplicitProperty()) return false; 14174 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14175 if (!property->isRetaining() && 14176 !(property->getPropertyIvarDecl() && 14177 property->getPropertyIvarDecl()->getType() 14178 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14179 return false; 14180 14181 owner.Indirect = true; 14182 if (pre->isSuperReceiver()) { 14183 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14184 if (!owner.Variable) 14185 return false; 14186 owner.Loc = pre->getLocation(); 14187 owner.Range = pre->getSourceRange(); 14188 return true; 14189 } 14190 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14191 ->getSourceExpr()); 14192 continue; 14193 } 14194 14195 // Array ivars? 14196 14197 return false; 14198 } 14199 } 14200 14201 namespace { 14202 14203 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14204 ASTContext &Context; 14205 VarDecl *Variable; 14206 Expr *Capturer = nullptr; 14207 bool VarWillBeReased = false; 14208 14209 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14210 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14211 Context(Context), Variable(variable) {} 14212 14213 void VisitDeclRefExpr(DeclRefExpr *ref) { 14214 if (ref->getDecl() == Variable && !Capturer) 14215 Capturer = ref; 14216 } 14217 14218 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14219 if (Capturer) return; 14220 Visit(ref->getBase()); 14221 if (Capturer && ref->isFreeIvar()) 14222 Capturer = ref; 14223 } 14224 14225 void VisitBlockExpr(BlockExpr *block) { 14226 // Look inside nested blocks 14227 if (block->getBlockDecl()->capturesVariable(Variable)) 14228 Visit(block->getBlockDecl()->getBody()); 14229 } 14230 14231 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14232 if (Capturer) return; 14233 if (OVE->getSourceExpr()) 14234 Visit(OVE->getSourceExpr()); 14235 } 14236 14237 void VisitBinaryOperator(BinaryOperator *BinOp) { 14238 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14239 return; 14240 Expr *LHS = BinOp->getLHS(); 14241 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14242 if (DRE->getDecl() != Variable) 14243 return; 14244 if (Expr *RHS = BinOp->getRHS()) { 14245 RHS = RHS->IgnoreParenCasts(); 14246 Optional<llvm::APSInt> Value; 14247 VarWillBeReased = 14248 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14249 *Value == 0); 14250 } 14251 } 14252 } 14253 }; 14254 14255 } // namespace 14256 14257 /// Check whether the given argument is a block which captures a 14258 /// variable. 14259 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14260 assert(owner.Variable && owner.Loc.isValid()); 14261 14262 e = e->IgnoreParenCasts(); 14263 14264 // Look through [^{...} copy] and Block_copy(^{...}). 14265 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14266 Selector Cmd = ME->getSelector(); 14267 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14268 e = ME->getInstanceReceiver(); 14269 if (!e) 14270 return nullptr; 14271 e = e->IgnoreParenCasts(); 14272 } 14273 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14274 if (CE->getNumArgs() == 1) { 14275 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14276 if (Fn) { 14277 const IdentifierInfo *FnI = Fn->getIdentifier(); 14278 if (FnI && FnI->isStr("_Block_copy")) { 14279 e = CE->getArg(0)->IgnoreParenCasts(); 14280 } 14281 } 14282 } 14283 } 14284 14285 BlockExpr *block = dyn_cast<BlockExpr>(e); 14286 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14287 return nullptr; 14288 14289 FindCaptureVisitor visitor(S.Context, owner.Variable); 14290 visitor.Visit(block->getBlockDecl()->getBody()); 14291 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14292 } 14293 14294 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14295 RetainCycleOwner &owner) { 14296 assert(capturer); 14297 assert(owner.Variable && owner.Loc.isValid()); 14298 14299 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14300 << owner.Variable << capturer->getSourceRange(); 14301 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14302 << owner.Indirect << owner.Range; 14303 } 14304 14305 /// Check for a keyword selector that starts with the word 'add' or 14306 /// 'set'. 14307 static bool isSetterLikeSelector(Selector sel) { 14308 if (sel.isUnarySelector()) return false; 14309 14310 StringRef str = sel.getNameForSlot(0); 14311 while (!str.empty() && str.front() == '_') str = str.substr(1); 14312 if (str.startswith("set")) 14313 str = str.substr(3); 14314 else if (str.startswith("add")) { 14315 // Specially allow 'addOperationWithBlock:'. 14316 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14317 return false; 14318 str = str.substr(3); 14319 } 14320 else 14321 return false; 14322 14323 if (str.empty()) return true; 14324 return !isLowercase(str.front()); 14325 } 14326 14327 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14328 ObjCMessageExpr *Message) { 14329 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14330 Message->getReceiverInterface(), 14331 NSAPI::ClassId_NSMutableArray); 14332 if (!IsMutableArray) { 14333 return None; 14334 } 14335 14336 Selector Sel = Message->getSelector(); 14337 14338 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14339 S.NSAPIObj->getNSArrayMethodKind(Sel); 14340 if (!MKOpt) { 14341 return None; 14342 } 14343 14344 NSAPI::NSArrayMethodKind MK = *MKOpt; 14345 14346 switch (MK) { 14347 case NSAPI::NSMutableArr_addObject: 14348 case NSAPI::NSMutableArr_insertObjectAtIndex: 14349 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14350 return 0; 14351 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14352 return 1; 14353 14354 default: 14355 return None; 14356 } 14357 14358 return None; 14359 } 14360 14361 static 14362 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14363 ObjCMessageExpr *Message) { 14364 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14365 Message->getReceiverInterface(), 14366 NSAPI::ClassId_NSMutableDictionary); 14367 if (!IsMutableDictionary) { 14368 return None; 14369 } 14370 14371 Selector Sel = Message->getSelector(); 14372 14373 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14374 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14375 if (!MKOpt) { 14376 return None; 14377 } 14378 14379 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14380 14381 switch (MK) { 14382 case NSAPI::NSMutableDict_setObjectForKey: 14383 case NSAPI::NSMutableDict_setValueForKey: 14384 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14385 return 0; 14386 14387 default: 14388 return None; 14389 } 14390 14391 return None; 14392 } 14393 14394 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14395 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14396 Message->getReceiverInterface(), 14397 NSAPI::ClassId_NSMutableSet); 14398 14399 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14400 Message->getReceiverInterface(), 14401 NSAPI::ClassId_NSMutableOrderedSet); 14402 if (!IsMutableSet && !IsMutableOrderedSet) { 14403 return None; 14404 } 14405 14406 Selector Sel = Message->getSelector(); 14407 14408 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14409 if (!MKOpt) { 14410 return None; 14411 } 14412 14413 NSAPI::NSSetMethodKind MK = *MKOpt; 14414 14415 switch (MK) { 14416 case NSAPI::NSMutableSet_addObject: 14417 case NSAPI::NSOrderedSet_setObjectAtIndex: 14418 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14419 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14420 return 0; 14421 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14422 return 1; 14423 } 14424 14425 return None; 14426 } 14427 14428 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14429 if (!Message->isInstanceMessage()) { 14430 return; 14431 } 14432 14433 Optional<int> ArgOpt; 14434 14435 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14436 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14437 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14438 return; 14439 } 14440 14441 int ArgIndex = *ArgOpt; 14442 14443 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14444 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14445 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14446 } 14447 14448 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14449 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14450 if (ArgRE->isObjCSelfExpr()) { 14451 Diag(Message->getSourceRange().getBegin(), 14452 diag::warn_objc_circular_container) 14453 << ArgRE->getDecl() << StringRef("'super'"); 14454 } 14455 } 14456 } else { 14457 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14458 14459 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14460 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14461 } 14462 14463 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14464 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14465 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14466 ValueDecl *Decl = ReceiverRE->getDecl(); 14467 Diag(Message->getSourceRange().getBegin(), 14468 diag::warn_objc_circular_container) 14469 << Decl << Decl; 14470 if (!ArgRE->isObjCSelfExpr()) { 14471 Diag(Decl->getLocation(), 14472 diag::note_objc_circular_container_declared_here) 14473 << Decl; 14474 } 14475 } 14476 } 14477 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14478 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14479 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14480 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14481 Diag(Message->getSourceRange().getBegin(), 14482 diag::warn_objc_circular_container) 14483 << Decl << Decl; 14484 Diag(Decl->getLocation(), 14485 diag::note_objc_circular_container_declared_here) 14486 << Decl; 14487 } 14488 } 14489 } 14490 } 14491 } 14492 14493 /// Check a message send to see if it's likely to cause a retain cycle. 14494 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14495 // Only check instance methods whose selector looks like a setter. 14496 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14497 return; 14498 14499 // Try to find a variable that the receiver is strongly owned by. 14500 RetainCycleOwner owner; 14501 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14502 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14503 return; 14504 } else { 14505 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14506 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14507 owner.Loc = msg->getSuperLoc(); 14508 owner.Range = msg->getSuperLoc(); 14509 } 14510 14511 // Check whether the receiver is captured by any of the arguments. 14512 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14513 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14514 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14515 // noescape blocks should not be retained by the method. 14516 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14517 continue; 14518 return diagnoseRetainCycle(*this, capturer, owner); 14519 } 14520 } 14521 } 14522 14523 /// Check a property assign to see if it's likely to cause a retain cycle. 14524 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14525 RetainCycleOwner owner; 14526 if (!findRetainCycleOwner(*this, receiver, owner)) 14527 return; 14528 14529 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14530 diagnoseRetainCycle(*this, capturer, owner); 14531 } 14532 14533 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14534 RetainCycleOwner Owner; 14535 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14536 return; 14537 14538 // Because we don't have an expression for the variable, we have to set the 14539 // location explicitly here. 14540 Owner.Loc = Var->getLocation(); 14541 Owner.Range = Var->getSourceRange(); 14542 14543 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14544 diagnoseRetainCycle(*this, Capturer, Owner); 14545 } 14546 14547 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14548 Expr *RHS, bool isProperty) { 14549 // Check if RHS is an Objective-C object literal, which also can get 14550 // immediately zapped in a weak reference. Note that we explicitly 14551 // allow ObjCStringLiterals, since those are designed to never really die. 14552 RHS = RHS->IgnoreParenImpCasts(); 14553 14554 // This enum needs to match with the 'select' in 14555 // warn_objc_arc_literal_assign (off-by-1). 14556 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14557 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14558 return false; 14559 14560 S.Diag(Loc, diag::warn_arc_literal_assign) 14561 << (unsigned) Kind 14562 << (isProperty ? 0 : 1) 14563 << RHS->getSourceRange(); 14564 14565 return true; 14566 } 14567 14568 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14569 Qualifiers::ObjCLifetime LT, 14570 Expr *RHS, bool isProperty) { 14571 // Strip off any implicit cast added to get to the one ARC-specific. 14572 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14573 if (cast->getCastKind() == CK_ARCConsumeObject) { 14574 S.Diag(Loc, diag::warn_arc_retained_assign) 14575 << (LT == Qualifiers::OCL_ExplicitNone) 14576 << (isProperty ? 0 : 1) 14577 << RHS->getSourceRange(); 14578 return true; 14579 } 14580 RHS = cast->getSubExpr(); 14581 } 14582 14583 if (LT == Qualifiers::OCL_Weak && 14584 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14585 return true; 14586 14587 return false; 14588 } 14589 14590 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14591 QualType LHS, Expr *RHS) { 14592 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14593 14594 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14595 return false; 14596 14597 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14598 return true; 14599 14600 return false; 14601 } 14602 14603 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14604 Expr *LHS, Expr *RHS) { 14605 QualType LHSType; 14606 // PropertyRef on LHS type need be directly obtained from 14607 // its declaration as it has a PseudoType. 14608 ObjCPropertyRefExpr *PRE 14609 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14610 if (PRE && !PRE->isImplicitProperty()) { 14611 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14612 if (PD) 14613 LHSType = PD->getType(); 14614 } 14615 14616 if (LHSType.isNull()) 14617 LHSType = LHS->getType(); 14618 14619 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14620 14621 if (LT == Qualifiers::OCL_Weak) { 14622 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14623 getCurFunction()->markSafeWeakUse(LHS); 14624 } 14625 14626 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14627 return; 14628 14629 // FIXME. Check for other life times. 14630 if (LT != Qualifiers::OCL_None) 14631 return; 14632 14633 if (PRE) { 14634 if (PRE->isImplicitProperty()) 14635 return; 14636 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14637 if (!PD) 14638 return; 14639 14640 unsigned Attributes = PD->getPropertyAttributes(); 14641 if (Attributes & ObjCPropertyAttribute::kind_assign) { 14642 // when 'assign' attribute was not explicitly specified 14643 // by user, ignore it and rely on property type itself 14644 // for lifetime info. 14645 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14646 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 14647 LHSType->isObjCRetainableType()) 14648 return; 14649 14650 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14651 if (cast->getCastKind() == CK_ARCConsumeObject) { 14652 Diag(Loc, diag::warn_arc_retained_property_assign) 14653 << RHS->getSourceRange(); 14654 return; 14655 } 14656 RHS = cast->getSubExpr(); 14657 } 14658 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 14659 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14660 return; 14661 } 14662 } 14663 } 14664 14665 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14666 14667 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14668 SourceLocation StmtLoc, 14669 const NullStmt *Body) { 14670 // Do not warn if the body is a macro that expands to nothing, e.g: 14671 // 14672 // #define CALL(x) 14673 // if (condition) 14674 // CALL(0); 14675 if (Body->hasLeadingEmptyMacro()) 14676 return false; 14677 14678 // Get line numbers of statement and body. 14679 bool StmtLineInvalid; 14680 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14681 &StmtLineInvalid); 14682 if (StmtLineInvalid) 14683 return false; 14684 14685 bool BodyLineInvalid; 14686 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14687 &BodyLineInvalid); 14688 if (BodyLineInvalid) 14689 return false; 14690 14691 // Warn if null statement and body are on the same line. 14692 if (StmtLine != BodyLine) 14693 return false; 14694 14695 return true; 14696 } 14697 14698 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14699 const Stmt *Body, 14700 unsigned DiagID) { 14701 // Since this is a syntactic check, don't emit diagnostic for template 14702 // instantiations, this just adds noise. 14703 if (CurrentInstantiationScope) 14704 return; 14705 14706 // The body should be a null statement. 14707 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14708 if (!NBody) 14709 return; 14710 14711 // Do the usual checks. 14712 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14713 return; 14714 14715 Diag(NBody->getSemiLoc(), DiagID); 14716 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14717 } 14718 14719 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14720 const Stmt *PossibleBody) { 14721 assert(!CurrentInstantiationScope); // Ensured by caller 14722 14723 SourceLocation StmtLoc; 14724 const Stmt *Body; 14725 unsigned DiagID; 14726 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14727 StmtLoc = FS->getRParenLoc(); 14728 Body = FS->getBody(); 14729 DiagID = diag::warn_empty_for_body; 14730 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14731 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14732 Body = WS->getBody(); 14733 DiagID = diag::warn_empty_while_body; 14734 } else 14735 return; // Neither `for' nor `while'. 14736 14737 // The body should be a null statement. 14738 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14739 if (!NBody) 14740 return; 14741 14742 // Skip expensive checks if diagnostic is disabled. 14743 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14744 return; 14745 14746 // Do the usual checks. 14747 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14748 return; 14749 14750 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14751 // noise level low, emit diagnostics only if for/while is followed by a 14752 // CompoundStmt, e.g.: 14753 // for (int i = 0; i < n; i++); 14754 // { 14755 // a(i); 14756 // } 14757 // or if for/while is followed by a statement with more indentation 14758 // than for/while itself: 14759 // for (int i = 0; i < n; i++); 14760 // a(i); 14761 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14762 if (!ProbableTypo) { 14763 bool BodyColInvalid; 14764 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14765 PossibleBody->getBeginLoc(), &BodyColInvalid); 14766 if (BodyColInvalid) 14767 return; 14768 14769 bool StmtColInvalid; 14770 unsigned StmtCol = 14771 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14772 if (StmtColInvalid) 14773 return; 14774 14775 if (BodyCol > StmtCol) 14776 ProbableTypo = true; 14777 } 14778 14779 if (ProbableTypo) { 14780 Diag(NBody->getSemiLoc(), DiagID); 14781 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14782 } 14783 } 14784 14785 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14786 14787 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14788 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14789 SourceLocation OpLoc) { 14790 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14791 return; 14792 14793 if (inTemplateInstantiation()) 14794 return; 14795 14796 // Strip parens and casts away. 14797 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14798 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14799 14800 // Check for a call expression 14801 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14802 if (!CE || CE->getNumArgs() != 1) 14803 return; 14804 14805 // Check for a call to std::move 14806 if (!CE->isCallToStdMove()) 14807 return; 14808 14809 // Get argument from std::move 14810 RHSExpr = CE->getArg(0); 14811 14812 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14813 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14814 14815 // Two DeclRefExpr's, check that the decls are the same. 14816 if (LHSDeclRef && RHSDeclRef) { 14817 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14818 return; 14819 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14820 RHSDeclRef->getDecl()->getCanonicalDecl()) 14821 return; 14822 14823 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14824 << LHSExpr->getSourceRange() 14825 << RHSExpr->getSourceRange(); 14826 return; 14827 } 14828 14829 // Member variables require a different approach to check for self moves. 14830 // MemberExpr's are the same if every nested MemberExpr refers to the same 14831 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14832 // the base Expr's are CXXThisExpr's. 14833 const Expr *LHSBase = LHSExpr; 14834 const Expr *RHSBase = RHSExpr; 14835 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14836 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14837 if (!LHSME || !RHSME) 14838 return; 14839 14840 while (LHSME && RHSME) { 14841 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14842 RHSME->getMemberDecl()->getCanonicalDecl()) 14843 return; 14844 14845 LHSBase = LHSME->getBase(); 14846 RHSBase = RHSME->getBase(); 14847 LHSME = dyn_cast<MemberExpr>(LHSBase); 14848 RHSME = dyn_cast<MemberExpr>(RHSBase); 14849 } 14850 14851 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14852 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14853 if (LHSDeclRef && RHSDeclRef) { 14854 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14855 return; 14856 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14857 RHSDeclRef->getDecl()->getCanonicalDecl()) 14858 return; 14859 14860 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14861 << LHSExpr->getSourceRange() 14862 << RHSExpr->getSourceRange(); 14863 return; 14864 } 14865 14866 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14867 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14868 << LHSExpr->getSourceRange() 14869 << RHSExpr->getSourceRange(); 14870 } 14871 14872 //===--- Layout compatibility ----------------------------------------------// 14873 14874 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14875 14876 /// Check if two enumeration types are layout-compatible. 14877 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14878 // C++11 [dcl.enum] p8: 14879 // Two enumeration types are layout-compatible if they have the same 14880 // underlying type. 14881 return ED1->isComplete() && ED2->isComplete() && 14882 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14883 } 14884 14885 /// Check if two fields are layout-compatible. 14886 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14887 FieldDecl *Field2) { 14888 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14889 return false; 14890 14891 if (Field1->isBitField() != Field2->isBitField()) 14892 return false; 14893 14894 if (Field1->isBitField()) { 14895 // Make sure that the bit-fields are the same length. 14896 unsigned Bits1 = Field1->getBitWidthValue(C); 14897 unsigned Bits2 = Field2->getBitWidthValue(C); 14898 14899 if (Bits1 != Bits2) 14900 return false; 14901 } 14902 14903 return true; 14904 } 14905 14906 /// Check if two standard-layout structs are layout-compatible. 14907 /// (C++11 [class.mem] p17) 14908 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14909 RecordDecl *RD2) { 14910 // If both records are C++ classes, check that base classes match. 14911 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14912 // If one of records is a CXXRecordDecl we are in C++ mode, 14913 // thus the other one is a CXXRecordDecl, too. 14914 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14915 // Check number of base classes. 14916 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14917 return false; 14918 14919 // Check the base classes. 14920 for (CXXRecordDecl::base_class_const_iterator 14921 Base1 = D1CXX->bases_begin(), 14922 BaseEnd1 = D1CXX->bases_end(), 14923 Base2 = D2CXX->bases_begin(); 14924 Base1 != BaseEnd1; 14925 ++Base1, ++Base2) { 14926 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14927 return false; 14928 } 14929 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14930 // If only RD2 is a C++ class, it should have zero base classes. 14931 if (D2CXX->getNumBases() > 0) 14932 return false; 14933 } 14934 14935 // Check the fields. 14936 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14937 Field2End = RD2->field_end(), 14938 Field1 = RD1->field_begin(), 14939 Field1End = RD1->field_end(); 14940 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14941 if (!isLayoutCompatible(C, *Field1, *Field2)) 14942 return false; 14943 } 14944 if (Field1 != Field1End || Field2 != Field2End) 14945 return false; 14946 14947 return true; 14948 } 14949 14950 /// Check if two standard-layout unions are layout-compatible. 14951 /// (C++11 [class.mem] p18) 14952 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14953 RecordDecl *RD2) { 14954 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14955 for (auto *Field2 : RD2->fields()) 14956 UnmatchedFields.insert(Field2); 14957 14958 for (auto *Field1 : RD1->fields()) { 14959 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14960 I = UnmatchedFields.begin(), 14961 E = UnmatchedFields.end(); 14962 14963 for ( ; I != E; ++I) { 14964 if (isLayoutCompatible(C, Field1, *I)) { 14965 bool Result = UnmatchedFields.erase(*I); 14966 (void) Result; 14967 assert(Result); 14968 break; 14969 } 14970 } 14971 if (I == E) 14972 return false; 14973 } 14974 14975 return UnmatchedFields.empty(); 14976 } 14977 14978 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14979 RecordDecl *RD2) { 14980 if (RD1->isUnion() != RD2->isUnion()) 14981 return false; 14982 14983 if (RD1->isUnion()) 14984 return isLayoutCompatibleUnion(C, RD1, RD2); 14985 else 14986 return isLayoutCompatibleStruct(C, RD1, RD2); 14987 } 14988 14989 /// Check if two types are layout-compatible in C++11 sense. 14990 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14991 if (T1.isNull() || T2.isNull()) 14992 return false; 14993 14994 // C++11 [basic.types] p11: 14995 // If two types T1 and T2 are the same type, then T1 and T2 are 14996 // layout-compatible types. 14997 if (C.hasSameType(T1, T2)) 14998 return true; 14999 15000 T1 = T1.getCanonicalType().getUnqualifiedType(); 15001 T2 = T2.getCanonicalType().getUnqualifiedType(); 15002 15003 const Type::TypeClass TC1 = T1->getTypeClass(); 15004 const Type::TypeClass TC2 = T2->getTypeClass(); 15005 15006 if (TC1 != TC2) 15007 return false; 15008 15009 if (TC1 == Type::Enum) { 15010 return isLayoutCompatible(C, 15011 cast<EnumType>(T1)->getDecl(), 15012 cast<EnumType>(T2)->getDecl()); 15013 } else if (TC1 == Type::Record) { 15014 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15015 return false; 15016 15017 return isLayoutCompatible(C, 15018 cast<RecordType>(T1)->getDecl(), 15019 cast<RecordType>(T2)->getDecl()); 15020 } 15021 15022 return false; 15023 } 15024 15025 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15026 15027 /// Given a type tag expression find the type tag itself. 15028 /// 15029 /// \param TypeExpr Type tag expression, as it appears in user's code. 15030 /// 15031 /// \param VD Declaration of an identifier that appears in a type tag. 15032 /// 15033 /// \param MagicValue Type tag magic value. 15034 /// 15035 /// \param isConstantEvaluated wether the evalaution should be performed in 15036 15037 /// constant context. 15038 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15039 const ValueDecl **VD, uint64_t *MagicValue, 15040 bool isConstantEvaluated) { 15041 while(true) { 15042 if (!TypeExpr) 15043 return false; 15044 15045 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 15046 15047 switch (TypeExpr->getStmtClass()) { 15048 case Stmt::UnaryOperatorClass: { 15049 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 15050 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 15051 TypeExpr = UO->getSubExpr(); 15052 continue; 15053 } 15054 return false; 15055 } 15056 15057 case Stmt::DeclRefExprClass: { 15058 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15059 *VD = DRE->getDecl(); 15060 return true; 15061 } 15062 15063 case Stmt::IntegerLiteralClass: { 15064 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15065 llvm::APInt MagicValueAPInt = IL->getValue(); 15066 if (MagicValueAPInt.getActiveBits() <= 64) { 15067 *MagicValue = MagicValueAPInt.getZExtValue(); 15068 return true; 15069 } else 15070 return false; 15071 } 15072 15073 case Stmt::BinaryConditionalOperatorClass: 15074 case Stmt::ConditionalOperatorClass: { 15075 const AbstractConditionalOperator *ACO = 15076 cast<AbstractConditionalOperator>(TypeExpr); 15077 bool Result; 15078 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15079 isConstantEvaluated)) { 15080 if (Result) 15081 TypeExpr = ACO->getTrueExpr(); 15082 else 15083 TypeExpr = ACO->getFalseExpr(); 15084 continue; 15085 } 15086 return false; 15087 } 15088 15089 case Stmt::BinaryOperatorClass: { 15090 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15091 if (BO->getOpcode() == BO_Comma) { 15092 TypeExpr = BO->getRHS(); 15093 continue; 15094 } 15095 return false; 15096 } 15097 15098 default: 15099 return false; 15100 } 15101 } 15102 } 15103 15104 /// Retrieve the C type corresponding to type tag TypeExpr. 15105 /// 15106 /// \param TypeExpr Expression that specifies a type tag. 15107 /// 15108 /// \param MagicValues Registered magic values. 15109 /// 15110 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15111 /// kind. 15112 /// 15113 /// \param TypeInfo Information about the corresponding C type. 15114 /// 15115 /// \param isConstantEvaluated wether the evalaution should be performed in 15116 /// constant context. 15117 /// 15118 /// \returns true if the corresponding C type was found. 15119 static bool GetMatchingCType( 15120 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15121 const ASTContext &Ctx, 15122 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15123 *MagicValues, 15124 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15125 bool isConstantEvaluated) { 15126 FoundWrongKind = false; 15127 15128 // Variable declaration that has type_tag_for_datatype attribute. 15129 const ValueDecl *VD = nullptr; 15130 15131 uint64_t MagicValue; 15132 15133 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15134 return false; 15135 15136 if (VD) { 15137 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15138 if (I->getArgumentKind() != ArgumentKind) { 15139 FoundWrongKind = true; 15140 return false; 15141 } 15142 TypeInfo.Type = I->getMatchingCType(); 15143 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15144 TypeInfo.MustBeNull = I->getMustBeNull(); 15145 return true; 15146 } 15147 return false; 15148 } 15149 15150 if (!MagicValues) 15151 return false; 15152 15153 llvm::DenseMap<Sema::TypeTagMagicValue, 15154 Sema::TypeTagData>::const_iterator I = 15155 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15156 if (I == MagicValues->end()) 15157 return false; 15158 15159 TypeInfo = I->second; 15160 return true; 15161 } 15162 15163 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15164 uint64_t MagicValue, QualType Type, 15165 bool LayoutCompatible, 15166 bool MustBeNull) { 15167 if (!TypeTagForDatatypeMagicValues) 15168 TypeTagForDatatypeMagicValues.reset( 15169 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15170 15171 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15172 (*TypeTagForDatatypeMagicValues)[Magic] = 15173 TypeTagData(Type, LayoutCompatible, MustBeNull); 15174 } 15175 15176 static bool IsSameCharType(QualType T1, QualType T2) { 15177 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15178 if (!BT1) 15179 return false; 15180 15181 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15182 if (!BT2) 15183 return false; 15184 15185 BuiltinType::Kind T1Kind = BT1->getKind(); 15186 BuiltinType::Kind T2Kind = BT2->getKind(); 15187 15188 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15189 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15190 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15191 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15192 } 15193 15194 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15195 const ArrayRef<const Expr *> ExprArgs, 15196 SourceLocation CallSiteLoc) { 15197 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15198 bool IsPointerAttr = Attr->getIsPointer(); 15199 15200 // Retrieve the argument representing the 'type_tag'. 15201 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15202 if (TypeTagIdxAST >= ExprArgs.size()) { 15203 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15204 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15205 return; 15206 } 15207 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15208 bool FoundWrongKind; 15209 TypeTagData TypeInfo; 15210 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15211 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15212 TypeInfo, isConstantEvaluated())) { 15213 if (FoundWrongKind) 15214 Diag(TypeTagExpr->getExprLoc(), 15215 diag::warn_type_tag_for_datatype_wrong_kind) 15216 << TypeTagExpr->getSourceRange(); 15217 return; 15218 } 15219 15220 // Retrieve the argument representing the 'arg_idx'. 15221 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15222 if (ArgumentIdxAST >= ExprArgs.size()) { 15223 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15224 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15225 return; 15226 } 15227 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15228 if (IsPointerAttr) { 15229 // Skip implicit cast of pointer to `void *' (as a function argument). 15230 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15231 if (ICE->getType()->isVoidPointerType() && 15232 ICE->getCastKind() == CK_BitCast) 15233 ArgumentExpr = ICE->getSubExpr(); 15234 } 15235 QualType ArgumentType = ArgumentExpr->getType(); 15236 15237 // Passing a `void*' pointer shouldn't trigger a warning. 15238 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15239 return; 15240 15241 if (TypeInfo.MustBeNull) { 15242 // Type tag with matching void type requires a null pointer. 15243 if (!ArgumentExpr->isNullPointerConstant(Context, 15244 Expr::NPC_ValueDependentIsNotNull)) { 15245 Diag(ArgumentExpr->getExprLoc(), 15246 diag::warn_type_safety_null_pointer_required) 15247 << ArgumentKind->getName() 15248 << ArgumentExpr->getSourceRange() 15249 << TypeTagExpr->getSourceRange(); 15250 } 15251 return; 15252 } 15253 15254 QualType RequiredType = TypeInfo.Type; 15255 if (IsPointerAttr) 15256 RequiredType = Context.getPointerType(RequiredType); 15257 15258 bool mismatch = false; 15259 if (!TypeInfo.LayoutCompatible) { 15260 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15261 15262 // C++11 [basic.fundamental] p1: 15263 // Plain char, signed char, and unsigned char are three distinct types. 15264 // 15265 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15266 // char' depending on the current char signedness mode. 15267 if (mismatch) 15268 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15269 RequiredType->getPointeeType())) || 15270 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15271 mismatch = false; 15272 } else 15273 if (IsPointerAttr) 15274 mismatch = !isLayoutCompatible(Context, 15275 ArgumentType->getPointeeType(), 15276 RequiredType->getPointeeType()); 15277 else 15278 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15279 15280 if (mismatch) 15281 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15282 << ArgumentType << ArgumentKind 15283 << TypeInfo.LayoutCompatible << RequiredType 15284 << ArgumentExpr->getSourceRange() 15285 << TypeTagExpr->getSourceRange(); 15286 } 15287 15288 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15289 CharUnits Alignment) { 15290 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15291 } 15292 15293 void Sema::DiagnoseMisalignedMembers() { 15294 for (MisalignedMember &m : MisalignedMembers) { 15295 const NamedDecl *ND = m.RD; 15296 if (ND->getName().empty()) { 15297 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15298 ND = TD; 15299 } 15300 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15301 << m.MD << ND << m.E->getSourceRange(); 15302 } 15303 MisalignedMembers.clear(); 15304 } 15305 15306 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15307 E = E->IgnoreParens(); 15308 if (!T->isPointerType() && !T->isIntegerType()) 15309 return; 15310 if (isa<UnaryOperator>(E) && 15311 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15312 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15313 if (isa<MemberExpr>(Op)) { 15314 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15315 if (MA != MisalignedMembers.end() && 15316 (T->isIntegerType() || 15317 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15318 Context.getTypeAlignInChars( 15319 T->getPointeeType()) <= MA->Alignment)))) 15320 MisalignedMembers.erase(MA); 15321 } 15322 } 15323 } 15324 15325 void Sema::RefersToMemberWithReducedAlignment( 15326 Expr *E, 15327 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15328 Action) { 15329 const auto *ME = dyn_cast<MemberExpr>(E); 15330 if (!ME) 15331 return; 15332 15333 // No need to check expressions with an __unaligned-qualified type. 15334 if (E->getType().getQualifiers().hasUnaligned()) 15335 return; 15336 15337 // For a chain of MemberExpr like "a.b.c.d" this list 15338 // will keep FieldDecl's like [d, c, b]. 15339 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15340 const MemberExpr *TopME = nullptr; 15341 bool AnyIsPacked = false; 15342 do { 15343 QualType BaseType = ME->getBase()->getType(); 15344 if (BaseType->isDependentType()) 15345 return; 15346 if (ME->isArrow()) 15347 BaseType = BaseType->getPointeeType(); 15348 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15349 if (RD->isInvalidDecl()) 15350 return; 15351 15352 ValueDecl *MD = ME->getMemberDecl(); 15353 auto *FD = dyn_cast<FieldDecl>(MD); 15354 // We do not care about non-data members. 15355 if (!FD || FD->isInvalidDecl()) 15356 return; 15357 15358 AnyIsPacked = 15359 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15360 ReverseMemberChain.push_back(FD); 15361 15362 TopME = ME; 15363 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15364 } while (ME); 15365 assert(TopME && "We did not compute a topmost MemberExpr!"); 15366 15367 // Not the scope of this diagnostic. 15368 if (!AnyIsPacked) 15369 return; 15370 15371 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15372 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15373 // TODO: The innermost base of the member expression may be too complicated. 15374 // For now, just disregard these cases. This is left for future 15375 // improvement. 15376 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15377 return; 15378 15379 // Alignment expected by the whole expression. 15380 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15381 15382 // No need to do anything else with this case. 15383 if (ExpectedAlignment.isOne()) 15384 return; 15385 15386 // Synthesize offset of the whole access. 15387 CharUnits Offset; 15388 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15389 I++) { 15390 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15391 } 15392 15393 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15394 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15395 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15396 15397 // The base expression of the innermost MemberExpr may give 15398 // stronger guarantees than the class containing the member. 15399 if (DRE && !TopME->isArrow()) { 15400 const ValueDecl *VD = DRE->getDecl(); 15401 if (!VD->getType()->isReferenceType()) 15402 CompleteObjectAlignment = 15403 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15404 } 15405 15406 // Check if the synthesized offset fulfills the alignment. 15407 if (Offset % ExpectedAlignment != 0 || 15408 // It may fulfill the offset it but the effective alignment may still be 15409 // lower than the expected expression alignment. 15410 CompleteObjectAlignment < ExpectedAlignment) { 15411 // If this happens, we want to determine a sensible culprit of this. 15412 // Intuitively, watching the chain of member expressions from right to 15413 // left, we start with the required alignment (as required by the field 15414 // type) but some packed attribute in that chain has reduced the alignment. 15415 // It may happen that another packed structure increases it again. But if 15416 // we are here such increase has not been enough. So pointing the first 15417 // FieldDecl that either is packed or else its RecordDecl is, 15418 // seems reasonable. 15419 FieldDecl *FD = nullptr; 15420 CharUnits Alignment; 15421 for (FieldDecl *FDI : ReverseMemberChain) { 15422 if (FDI->hasAttr<PackedAttr>() || 15423 FDI->getParent()->hasAttr<PackedAttr>()) { 15424 FD = FDI; 15425 Alignment = std::min( 15426 Context.getTypeAlignInChars(FD->getType()), 15427 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15428 break; 15429 } 15430 } 15431 assert(FD && "We did not find a packed FieldDecl!"); 15432 Action(E, FD->getParent(), FD, Alignment); 15433 } 15434 } 15435 15436 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15437 using namespace std::placeholders; 15438 15439 RefersToMemberWithReducedAlignment( 15440 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15441 _2, _3, _4)); 15442 } 15443 15444 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15445 ExprResult CallResult) { 15446 if (checkArgCount(*this, TheCall, 1)) 15447 return ExprError(); 15448 15449 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15450 if (MatrixArg.isInvalid()) 15451 return MatrixArg; 15452 Expr *Matrix = MatrixArg.get(); 15453 15454 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15455 if (!MType) { 15456 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 15457 return ExprError(); 15458 } 15459 15460 // Create returned matrix type by swapping rows and columns of the argument 15461 // matrix type. 15462 QualType ResultType = Context.getConstantMatrixType( 15463 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15464 15465 // Change the return type to the type of the returned matrix. 15466 TheCall->setType(ResultType); 15467 15468 // Update call argument to use the possibly converted matrix argument. 15469 TheCall->setArg(0, Matrix); 15470 return CallResult; 15471 } 15472 15473 // Get and verify the matrix dimensions. 15474 static llvm::Optional<unsigned> 15475 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 15476 SourceLocation ErrorPos; 15477 Optional<llvm::APSInt> Value = 15478 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 15479 if (!Value) { 15480 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 15481 << Name; 15482 return {}; 15483 } 15484 uint64_t Dim = Value->getZExtValue(); 15485 if (!ConstantMatrixType::isDimensionValid(Dim)) { 15486 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 15487 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 15488 return {}; 15489 } 15490 return Dim; 15491 } 15492 15493 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 15494 ExprResult CallResult) { 15495 if (!getLangOpts().MatrixTypes) { 15496 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 15497 return ExprError(); 15498 } 15499 15500 if (checkArgCount(*this, TheCall, 4)) 15501 return ExprError(); 15502 15503 unsigned PtrArgIdx = 0; 15504 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15505 Expr *RowsExpr = TheCall->getArg(1); 15506 Expr *ColumnsExpr = TheCall->getArg(2); 15507 Expr *StrideExpr = TheCall->getArg(3); 15508 15509 bool ArgError = false; 15510 15511 // Check pointer argument. 15512 { 15513 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15514 if (PtrConv.isInvalid()) 15515 return PtrConv; 15516 PtrExpr = PtrConv.get(); 15517 TheCall->setArg(0, PtrExpr); 15518 if (PtrExpr->isTypeDependent()) { 15519 TheCall->setType(Context.DependentTy); 15520 return TheCall; 15521 } 15522 } 15523 15524 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15525 QualType ElementTy; 15526 if (!PtrTy) { 15527 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15528 << PtrArgIdx + 1; 15529 ArgError = true; 15530 } else { 15531 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 15532 15533 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 15534 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15535 << PtrArgIdx + 1; 15536 ArgError = true; 15537 } 15538 } 15539 15540 // Apply default Lvalue conversions and convert the expression to size_t. 15541 auto ApplyArgumentConversions = [this](Expr *E) { 15542 ExprResult Conv = DefaultLvalueConversion(E); 15543 if (Conv.isInvalid()) 15544 return Conv; 15545 15546 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 15547 }; 15548 15549 // Apply conversion to row and column expressions. 15550 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 15551 if (!RowsConv.isInvalid()) { 15552 RowsExpr = RowsConv.get(); 15553 TheCall->setArg(1, RowsExpr); 15554 } else 15555 RowsExpr = nullptr; 15556 15557 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 15558 if (!ColumnsConv.isInvalid()) { 15559 ColumnsExpr = ColumnsConv.get(); 15560 TheCall->setArg(2, ColumnsExpr); 15561 } else 15562 ColumnsExpr = nullptr; 15563 15564 // If any any part of the result matrix type is still pending, just use 15565 // Context.DependentTy, until all parts are resolved. 15566 if ((RowsExpr && RowsExpr->isTypeDependent()) || 15567 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 15568 TheCall->setType(Context.DependentTy); 15569 return CallResult; 15570 } 15571 15572 // Check row and column dimenions. 15573 llvm::Optional<unsigned> MaybeRows; 15574 if (RowsExpr) 15575 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 15576 15577 llvm::Optional<unsigned> MaybeColumns; 15578 if (ColumnsExpr) 15579 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 15580 15581 // Check stride argument. 15582 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 15583 if (StrideConv.isInvalid()) 15584 return ExprError(); 15585 StrideExpr = StrideConv.get(); 15586 TheCall->setArg(3, StrideExpr); 15587 15588 if (MaybeRows) { 15589 if (Optional<llvm::APSInt> Value = 15590 StrideExpr->getIntegerConstantExpr(Context)) { 15591 uint64_t Stride = Value->getZExtValue(); 15592 if (Stride < *MaybeRows) { 15593 Diag(StrideExpr->getBeginLoc(), 15594 diag::err_builtin_matrix_stride_too_small); 15595 ArgError = true; 15596 } 15597 } 15598 } 15599 15600 if (ArgError || !MaybeRows || !MaybeColumns) 15601 return ExprError(); 15602 15603 TheCall->setType( 15604 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 15605 return CallResult; 15606 } 15607 15608 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 15609 ExprResult CallResult) { 15610 if (checkArgCount(*this, TheCall, 3)) 15611 return ExprError(); 15612 15613 unsigned PtrArgIdx = 1; 15614 Expr *MatrixExpr = TheCall->getArg(0); 15615 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15616 Expr *StrideExpr = TheCall->getArg(2); 15617 15618 bool ArgError = false; 15619 15620 { 15621 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 15622 if (MatrixConv.isInvalid()) 15623 return MatrixConv; 15624 MatrixExpr = MatrixConv.get(); 15625 TheCall->setArg(0, MatrixExpr); 15626 } 15627 if (MatrixExpr->isTypeDependent()) { 15628 TheCall->setType(Context.DependentTy); 15629 return TheCall; 15630 } 15631 15632 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 15633 if (!MatrixTy) { 15634 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 15635 ArgError = true; 15636 } 15637 15638 { 15639 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15640 if (PtrConv.isInvalid()) 15641 return PtrConv; 15642 PtrExpr = PtrConv.get(); 15643 TheCall->setArg(1, PtrExpr); 15644 if (PtrExpr->isTypeDependent()) { 15645 TheCall->setType(Context.DependentTy); 15646 return TheCall; 15647 } 15648 } 15649 15650 // Check pointer argument. 15651 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15652 if (!PtrTy) { 15653 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15654 << PtrArgIdx + 1; 15655 ArgError = true; 15656 } else { 15657 QualType ElementTy = PtrTy->getPointeeType(); 15658 if (ElementTy.isConstQualified()) { 15659 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 15660 ArgError = true; 15661 } 15662 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 15663 if (MatrixTy && 15664 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 15665 Diag(PtrExpr->getBeginLoc(), 15666 diag::err_builtin_matrix_pointer_arg_mismatch) 15667 << ElementTy << MatrixTy->getElementType(); 15668 ArgError = true; 15669 } 15670 } 15671 15672 // Apply default Lvalue conversions and convert the stride expression to 15673 // size_t. 15674 { 15675 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 15676 if (StrideConv.isInvalid()) 15677 return StrideConv; 15678 15679 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 15680 if (StrideConv.isInvalid()) 15681 return StrideConv; 15682 StrideExpr = StrideConv.get(); 15683 TheCall->setArg(2, StrideExpr); 15684 } 15685 15686 // Check stride argument. 15687 if (MatrixTy) { 15688 if (Optional<llvm::APSInt> Value = 15689 StrideExpr->getIntegerConstantExpr(Context)) { 15690 uint64_t Stride = Value->getZExtValue(); 15691 if (Stride < MatrixTy->getNumRows()) { 15692 Diag(StrideExpr->getBeginLoc(), 15693 diag::err_builtin_matrix_stride_too_small); 15694 ArgError = true; 15695 } 15696 } 15697 } 15698 15699 if (ArgError) 15700 return ExprError(); 15701 15702 return CallResult; 15703 } 15704