1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cstddef> 95 #include <cstdint> 96 #include <functional> 97 #include <limits> 98 #include <string> 99 #include <tuple> 100 #include <utility> 101 102 using namespace clang; 103 using namespace sema; 104 105 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 106 unsigned ByteNo) const { 107 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 108 Context.getTargetInfo()); 109 } 110 111 /// Checks that a call expression's argument count is the desired number. 112 /// This is useful when doing custom type-checking. Returns true on error. 113 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 114 unsigned argCount = call->getNumArgs(); 115 if (argCount == desiredArgCount) return false; 116 117 if (argCount < desiredArgCount) 118 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 119 << 0 /*function call*/ << desiredArgCount << argCount 120 << call->getSourceRange(); 121 122 // Highlight all the excess arguments. 123 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 124 call->getArg(argCount - 1)->getEndLoc()); 125 126 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 127 << 0 /*function call*/ << desiredArgCount << argCount 128 << call->getArg(1)->getSourceRange(); 129 } 130 131 /// Check that the first argument to __builtin_annotation is an integer 132 /// and the second argument is a non-wide string literal. 133 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 134 if (checkArgCount(S, TheCall, 2)) 135 return true; 136 137 // First argument should be an integer. 138 Expr *ValArg = TheCall->getArg(0); 139 QualType Ty = ValArg->getType(); 140 if (!Ty->isIntegerType()) { 141 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 142 << ValArg->getSourceRange(); 143 return true; 144 } 145 146 // Second argument should be a constant string. 147 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 148 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 149 if (!Literal || !Literal->isAscii()) { 150 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 151 << StrArg->getSourceRange(); 152 return true; 153 } 154 155 TheCall->setType(Ty); 156 return false; 157 } 158 159 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 160 // We need at least one argument. 161 if (TheCall->getNumArgs() < 1) { 162 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 163 << 0 << 1 << TheCall->getNumArgs() 164 << TheCall->getCallee()->getSourceRange(); 165 return true; 166 } 167 168 // All arguments should be wide string literals. 169 for (Expr *Arg : TheCall->arguments()) { 170 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 171 if (!Literal || !Literal->isWide()) { 172 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 173 << Arg->getSourceRange(); 174 return true; 175 } 176 } 177 178 return false; 179 } 180 181 /// Check that the argument to __builtin_addressof is a glvalue, and set the 182 /// result type to the corresponding pointer type. 183 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 184 if (checkArgCount(S, TheCall, 1)) 185 return true; 186 187 ExprResult Arg(TheCall->getArg(0)); 188 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 189 if (ResultType.isNull()) 190 return true; 191 192 TheCall->setArg(0, Arg.get()); 193 TheCall->setType(ResultType); 194 return false; 195 } 196 197 /// Check the number of arguments and set the result type to 198 /// the argument type. 199 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 200 if (checkArgCount(S, TheCall, 1)) 201 return true; 202 203 TheCall->setType(TheCall->getArg(0)->getType()); 204 return false; 205 } 206 207 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 208 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 209 /// type (but not a function pointer) and that the alignment is a power-of-two. 210 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 211 if (checkArgCount(S, TheCall, 2)) 212 return true; 213 214 clang::Expr *Source = TheCall->getArg(0); 215 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 216 217 auto IsValidIntegerType = [](QualType Ty) { 218 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 219 }; 220 QualType SrcTy = Source->getType(); 221 // We should also be able to use it with arrays (but not functions!). 222 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 223 SrcTy = S.Context.getDecayedType(SrcTy); 224 } 225 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 226 SrcTy->isFunctionPointerType()) { 227 // FIXME: this is not quite the right error message since we don't allow 228 // floating point types, or member pointers. 229 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 230 << SrcTy; 231 return true; 232 } 233 234 clang::Expr *AlignOp = TheCall->getArg(1); 235 if (!IsValidIntegerType(AlignOp->getType())) { 236 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 237 << AlignOp->getType(); 238 return true; 239 } 240 Expr::EvalResult AlignResult; 241 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 242 // We can't check validity of alignment if it is value dependent. 243 if (!AlignOp->isValueDependent() && 244 AlignOp->EvaluateAsInt(AlignResult, S.Context, 245 Expr::SE_AllowSideEffects)) { 246 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 247 llvm::APSInt MaxValue( 248 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 249 if (AlignValue < 1) { 250 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 251 return true; 252 } 253 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 254 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 255 << MaxValue.toString(10); 256 return true; 257 } 258 if (!AlignValue.isPowerOf2()) { 259 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 260 return true; 261 } 262 if (AlignValue == 1) { 263 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 264 << IsBooleanAlignBuiltin; 265 } 266 } 267 268 ExprResult SrcArg = S.PerformCopyInitialization( 269 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 270 SourceLocation(), Source); 271 if (SrcArg.isInvalid()) 272 return true; 273 TheCall->setArg(0, SrcArg.get()); 274 ExprResult AlignArg = 275 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 276 S.Context, AlignOp->getType(), false), 277 SourceLocation(), AlignOp); 278 if (AlignArg.isInvalid()) 279 return true; 280 TheCall->setArg(1, AlignArg.get()); 281 // For align_up/align_down, the return type is the same as the (potentially 282 // decayed) argument type including qualifiers. For is_aligned(), the result 283 // is always bool. 284 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 285 return false; 286 } 287 288 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 289 unsigned BuiltinID) { 290 if (checkArgCount(S, TheCall, 3)) 291 return true; 292 293 // First two arguments should be integers. 294 for (unsigned I = 0; I < 2; ++I) { 295 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 296 if (Arg.isInvalid()) return true; 297 TheCall->setArg(I, Arg.get()); 298 299 QualType Ty = Arg.get()->getType(); 300 if (!Ty->isIntegerType()) { 301 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 302 << Ty << Arg.get()->getSourceRange(); 303 return true; 304 } 305 } 306 307 // Third argument should be a pointer to a non-const integer. 308 // IRGen correctly handles volatile, restrict, and address spaces, and 309 // the other qualifiers aren't possible. 310 { 311 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 312 if (Arg.isInvalid()) return true; 313 TheCall->setArg(2, Arg.get()); 314 315 QualType Ty = Arg.get()->getType(); 316 const auto *PtrTy = Ty->getAs<PointerType>(); 317 if (!PtrTy || 318 !PtrTy->getPointeeType()->isIntegerType() || 319 PtrTy->getPointeeType().isConstQualified()) { 320 S.Diag(Arg.get()->getBeginLoc(), 321 diag::err_overflow_builtin_must_be_ptr_int) 322 << Ty << Arg.get()->getSourceRange(); 323 return true; 324 } 325 } 326 327 // Disallow signed ExtIntType args larger than 128 bits to mul function until 328 // we improve backend support. 329 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 330 for (unsigned I = 0; I < 3; ++I) { 331 const auto Arg = TheCall->getArg(I); 332 // Third argument will be a pointer. 333 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 334 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 335 S.getASTContext().getIntWidth(Ty) > 128) 336 return S.Diag(Arg->getBeginLoc(), 337 diag::err_overflow_builtin_ext_int_max_size) 338 << 128; 339 } 340 } 341 342 return false; 343 } 344 345 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 346 if (checkArgCount(S, BuiltinCall, 2)) 347 return true; 348 349 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 350 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 351 Expr *Call = BuiltinCall->getArg(0); 352 Expr *Chain = BuiltinCall->getArg(1); 353 354 if (Call->getStmtClass() != Stmt::CallExprClass) { 355 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 356 << Call->getSourceRange(); 357 return true; 358 } 359 360 auto CE = cast<CallExpr>(Call); 361 if (CE->getCallee()->getType()->isBlockPointerType()) { 362 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 363 << Call->getSourceRange(); 364 return true; 365 } 366 367 const Decl *TargetDecl = CE->getCalleeDecl(); 368 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 369 if (FD->getBuiltinID()) { 370 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 371 << Call->getSourceRange(); 372 return true; 373 } 374 375 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 376 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 377 << Call->getSourceRange(); 378 return true; 379 } 380 381 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 382 if (ChainResult.isInvalid()) 383 return true; 384 if (!ChainResult.get()->getType()->isPointerType()) { 385 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 386 << Chain->getSourceRange(); 387 return true; 388 } 389 390 QualType ReturnTy = CE->getCallReturnType(S.Context); 391 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 392 QualType BuiltinTy = S.Context.getFunctionType( 393 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 394 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 395 396 Builtin = 397 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 398 399 BuiltinCall->setType(CE->getType()); 400 BuiltinCall->setValueKind(CE->getValueKind()); 401 BuiltinCall->setObjectKind(CE->getObjectKind()); 402 BuiltinCall->setCallee(Builtin); 403 BuiltinCall->setArg(1, ChainResult.get()); 404 405 return false; 406 } 407 408 namespace { 409 410 class EstimateSizeFormatHandler 411 : public analyze_format_string::FormatStringHandler { 412 size_t Size; 413 414 public: 415 EstimateSizeFormatHandler(StringRef Format) 416 : Size(std::min(Format.find(0), Format.size()) + 417 1 /* null byte always written by sprintf */) {} 418 419 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 420 const char *, unsigned SpecifierLen) override { 421 422 const size_t FieldWidth = computeFieldWidth(FS); 423 const size_t Precision = computePrecision(FS); 424 425 // The actual format. 426 switch (FS.getConversionSpecifier().getKind()) { 427 // Just a char. 428 case analyze_format_string::ConversionSpecifier::cArg: 429 case analyze_format_string::ConversionSpecifier::CArg: 430 Size += std::max(FieldWidth, (size_t)1); 431 break; 432 // Just an integer. 433 case analyze_format_string::ConversionSpecifier::dArg: 434 case analyze_format_string::ConversionSpecifier::DArg: 435 case analyze_format_string::ConversionSpecifier::iArg: 436 case analyze_format_string::ConversionSpecifier::oArg: 437 case analyze_format_string::ConversionSpecifier::OArg: 438 case analyze_format_string::ConversionSpecifier::uArg: 439 case analyze_format_string::ConversionSpecifier::UArg: 440 case analyze_format_string::ConversionSpecifier::xArg: 441 case analyze_format_string::ConversionSpecifier::XArg: 442 Size += std::max(FieldWidth, Precision); 443 break; 444 445 // %g style conversion switches between %f or %e style dynamically. 446 // %f always takes less space, so default to it. 447 case analyze_format_string::ConversionSpecifier::gArg: 448 case analyze_format_string::ConversionSpecifier::GArg: 449 450 // Floating point number in the form '[+]ddd.ddd'. 451 case analyze_format_string::ConversionSpecifier::fArg: 452 case analyze_format_string::ConversionSpecifier::FArg: 453 Size += std::max(FieldWidth, 1 /* integer part */ + 454 (Precision ? 1 + Precision 455 : 0) /* period + decimal */); 456 break; 457 458 // Floating point number in the form '[-]d.ddde[+-]dd'. 459 case analyze_format_string::ConversionSpecifier::eArg: 460 case analyze_format_string::ConversionSpecifier::EArg: 461 Size += 462 std::max(FieldWidth, 463 1 /* integer part */ + 464 (Precision ? 1 + Precision : 0) /* period + decimal */ + 465 1 /* e or E letter */ + 2 /* exponent */); 466 break; 467 468 // Floating point number in the form '[-]0xh.hhhhp±dd'. 469 case analyze_format_string::ConversionSpecifier::aArg: 470 case analyze_format_string::ConversionSpecifier::AArg: 471 Size += 472 std::max(FieldWidth, 473 2 /* 0x */ + 1 /* integer part */ + 474 (Precision ? 1 + Precision : 0) /* period + decimal */ + 475 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 476 break; 477 478 // Just a string. 479 case analyze_format_string::ConversionSpecifier::sArg: 480 case analyze_format_string::ConversionSpecifier::SArg: 481 Size += FieldWidth; 482 break; 483 484 // Just a pointer in the form '0xddd'. 485 case analyze_format_string::ConversionSpecifier::pArg: 486 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 487 break; 488 489 // A plain percent. 490 case analyze_format_string::ConversionSpecifier::PercentArg: 491 Size += 1; 492 break; 493 494 default: 495 break; 496 } 497 498 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 499 500 if (FS.hasAlternativeForm()) { 501 switch (FS.getConversionSpecifier().getKind()) { 502 default: 503 break; 504 // Force a leading '0'. 505 case analyze_format_string::ConversionSpecifier::oArg: 506 Size += 1; 507 break; 508 // Force a leading '0x'. 509 case analyze_format_string::ConversionSpecifier::xArg: 510 case analyze_format_string::ConversionSpecifier::XArg: 511 Size += 2; 512 break; 513 // Force a period '.' before decimal, even if precision is 0. 514 case analyze_format_string::ConversionSpecifier::aArg: 515 case analyze_format_string::ConversionSpecifier::AArg: 516 case analyze_format_string::ConversionSpecifier::eArg: 517 case analyze_format_string::ConversionSpecifier::EArg: 518 case analyze_format_string::ConversionSpecifier::fArg: 519 case analyze_format_string::ConversionSpecifier::FArg: 520 case analyze_format_string::ConversionSpecifier::gArg: 521 case analyze_format_string::ConversionSpecifier::GArg: 522 Size += (Precision ? 0 : 1); 523 break; 524 } 525 } 526 assert(SpecifierLen <= Size && "no underflow"); 527 Size -= SpecifierLen; 528 return true; 529 } 530 531 size_t getSizeLowerBound() const { return Size; } 532 533 private: 534 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 535 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 536 size_t FieldWidth = 0; 537 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 538 FieldWidth = FW.getConstantAmount(); 539 return FieldWidth; 540 } 541 542 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 543 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 544 size_t Precision = 0; 545 546 // See man 3 printf for default precision value based on the specifier. 547 switch (FW.getHowSpecified()) { 548 case analyze_format_string::OptionalAmount::NotSpecified: 549 switch (FS.getConversionSpecifier().getKind()) { 550 default: 551 break; 552 case analyze_format_string::ConversionSpecifier::dArg: // %d 553 case analyze_format_string::ConversionSpecifier::DArg: // %D 554 case analyze_format_string::ConversionSpecifier::iArg: // %i 555 Precision = 1; 556 break; 557 case analyze_format_string::ConversionSpecifier::oArg: // %d 558 case analyze_format_string::ConversionSpecifier::OArg: // %D 559 case analyze_format_string::ConversionSpecifier::uArg: // %d 560 case analyze_format_string::ConversionSpecifier::UArg: // %D 561 case analyze_format_string::ConversionSpecifier::xArg: // %d 562 case analyze_format_string::ConversionSpecifier::XArg: // %D 563 Precision = 1; 564 break; 565 case analyze_format_string::ConversionSpecifier::fArg: // %f 566 case analyze_format_string::ConversionSpecifier::FArg: // %F 567 case analyze_format_string::ConversionSpecifier::eArg: // %e 568 case analyze_format_string::ConversionSpecifier::EArg: // %E 569 case analyze_format_string::ConversionSpecifier::gArg: // %g 570 case analyze_format_string::ConversionSpecifier::GArg: // %G 571 Precision = 6; 572 break; 573 case analyze_format_string::ConversionSpecifier::pArg: // %d 574 Precision = 1; 575 break; 576 } 577 break; 578 case analyze_format_string::OptionalAmount::Constant: 579 Precision = FW.getConstantAmount(); 580 break; 581 default: 582 break; 583 } 584 return Precision; 585 } 586 }; 587 588 } // namespace 589 590 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 591 /// __builtin_*_chk function, then use the object size argument specified in the 592 /// source. Otherwise, infer the object size using __builtin_object_size. 593 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 594 CallExpr *TheCall) { 595 // FIXME: There are some more useful checks we could be doing here: 596 // - Evaluate strlen of strcpy arguments, use as object size. 597 598 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 599 isConstantEvaluated()) 600 return; 601 602 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 603 if (!BuiltinID) 604 return; 605 606 const TargetInfo &TI = getASTContext().getTargetInfo(); 607 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 608 609 unsigned DiagID = 0; 610 bool IsChkVariant = false; 611 Optional<llvm::APSInt> UsedSize; 612 unsigned SizeIndex, ObjectIndex; 613 switch (BuiltinID) { 614 default: 615 return; 616 case Builtin::BIsprintf: 617 case Builtin::BI__builtin___sprintf_chk: { 618 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 619 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 620 621 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 622 623 if (!Format->isAscii() && !Format->isUTF8()) 624 return; 625 626 StringRef FormatStrRef = Format->getString(); 627 EstimateSizeFormatHandler H(FormatStrRef); 628 const char *FormatBytes = FormatStrRef.data(); 629 const ConstantArrayType *T = 630 Context.getAsConstantArrayType(Format->getType()); 631 assert(T && "String literal not of constant array type!"); 632 size_t TypeSize = T->getSize().getZExtValue(); 633 634 // In case there's a null byte somewhere. 635 size_t StrLen = 636 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 637 if (!analyze_format_string::ParsePrintfString( 638 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 639 Context.getTargetInfo(), false)) { 640 DiagID = diag::warn_fortify_source_format_overflow; 641 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 642 .extOrTrunc(SizeTypeWidth); 643 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 644 IsChkVariant = true; 645 ObjectIndex = 2; 646 } else { 647 IsChkVariant = false; 648 ObjectIndex = 0; 649 } 650 break; 651 } 652 } 653 return; 654 } 655 case Builtin::BI__builtin___memcpy_chk: 656 case Builtin::BI__builtin___memmove_chk: 657 case Builtin::BI__builtin___memset_chk: 658 case Builtin::BI__builtin___strlcat_chk: 659 case Builtin::BI__builtin___strlcpy_chk: 660 case Builtin::BI__builtin___strncat_chk: 661 case Builtin::BI__builtin___strncpy_chk: 662 case Builtin::BI__builtin___stpncpy_chk: 663 case Builtin::BI__builtin___memccpy_chk: 664 case Builtin::BI__builtin___mempcpy_chk: { 665 DiagID = diag::warn_builtin_chk_overflow; 666 IsChkVariant = true; 667 SizeIndex = TheCall->getNumArgs() - 2; 668 ObjectIndex = TheCall->getNumArgs() - 1; 669 break; 670 } 671 672 case Builtin::BI__builtin___snprintf_chk: 673 case Builtin::BI__builtin___vsnprintf_chk: { 674 DiagID = diag::warn_builtin_chk_overflow; 675 IsChkVariant = true; 676 SizeIndex = 1; 677 ObjectIndex = 3; 678 break; 679 } 680 681 case Builtin::BIstrncat: 682 case Builtin::BI__builtin_strncat: 683 case Builtin::BIstrncpy: 684 case Builtin::BI__builtin_strncpy: 685 case Builtin::BIstpncpy: 686 case Builtin::BI__builtin_stpncpy: { 687 // Whether these functions overflow depends on the runtime strlen of the 688 // string, not just the buffer size, so emitting the "always overflow" 689 // diagnostic isn't quite right. We should still diagnose passing a buffer 690 // size larger than the destination buffer though; this is a runtime abort 691 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 692 DiagID = diag::warn_fortify_source_size_mismatch; 693 SizeIndex = TheCall->getNumArgs() - 1; 694 ObjectIndex = 0; 695 break; 696 } 697 698 case Builtin::BImemcpy: 699 case Builtin::BI__builtin_memcpy: 700 case Builtin::BImemmove: 701 case Builtin::BI__builtin_memmove: 702 case Builtin::BImemset: 703 case Builtin::BI__builtin_memset: 704 case Builtin::BImempcpy: 705 case Builtin::BI__builtin_mempcpy: { 706 DiagID = diag::warn_fortify_source_overflow; 707 SizeIndex = TheCall->getNumArgs() - 1; 708 ObjectIndex = 0; 709 break; 710 } 711 case Builtin::BIsnprintf: 712 case Builtin::BI__builtin_snprintf: 713 case Builtin::BIvsnprintf: 714 case Builtin::BI__builtin_vsnprintf: { 715 DiagID = diag::warn_fortify_source_size_mismatch; 716 SizeIndex = 1; 717 ObjectIndex = 0; 718 break; 719 } 720 } 721 722 llvm::APSInt ObjectSize; 723 // For __builtin___*_chk, the object size is explicitly provided by the caller 724 // (usually using __builtin_object_size). Use that value to check this call. 725 if (IsChkVariant) { 726 Expr::EvalResult Result; 727 Expr *SizeArg = TheCall->getArg(ObjectIndex); 728 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 729 return; 730 ObjectSize = Result.Val.getInt(); 731 732 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 733 } else { 734 // If the parameter has a pass_object_size attribute, then we should use its 735 // (potentially) more strict checking mode. Otherwise, conservatively assume 736 // type 0. 737 int BOSType = 0; 738 if (const auto *POS = 739 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 740 BOSType = POS->getType(); 741 742 Expr *ObjArg = TheCall->getArg(ObjectIndex); 743 uint64_t Result; 744 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 745 return; 746 // Get the object size in the target's size_t width. 747 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 748 } 749 750 // Evaluate the number of bytes of the object that this call will use. 751 if (!UsedSize) { 752 Expr::EvalResult Result; 753 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 754 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 755 return; 756 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 757 } 758 759 if (UsedSize.getValue().ule(ObjectSize)) 760 return; 761 762 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 763 // Skim off the details of whichever builtin was called to produce a better 764 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 765 if (IsChkVariant) { 766 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 767 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 768 } else if (FunctionName.startswith("__builtin_")) { 769 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 770 } 771 772 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 773 PDiag(DiagID) 774 << FunctionName << ObjectSize.toString(/*Radix=*/10) 775 << UsedSize.getValue().toString(/*Radix=*/10)); 776 } 777 778 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 779 Scope::ScopeFlags NeededScopeFlags, 780 unsigned DiagID) { 781 // Scopes aren't available during instantiation. Fortunately, builtin 782 // functions cannot be template args so they cannot be formed through template 783 // instantiation. Therefore checking once during the parse is sufficient. 784 if (SemaRef.inTemplateInstantiation()) 785 return false; 786 787 Scope *S = SemaRef.getCurScope(); 788 while (S && !S->isSEHExceptScope()) 789 S = S->getParent(); 790 if (!S || !(S->getFlags() & NeededScopeFlags)) { 791 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 792 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 793 << DRE->getDecl()->getIdentifier(); 794 return true; 795 } 796 797 return false; 798 } 799 800 static inline bool isBlockPointer(Expr *Arg) { 801 return Arg->getType()->isBlockPointerType(); 802 } 803 804 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 805 /// void*, which is a requirement of device side enqueue. 806 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 807 const BlockPointerType *BPT = 808 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 809 ArrayRef<QualType> Params = 810 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 811 unsigned ArgCounter = 0; 812 bool IllegalParams = false; 813 // Iterate through the block parameters until either one is found that is not 814 // a local void*, or the block is valid. 815 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 816 I != E; ++I, ++ArgCounter) { 817 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 818 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 819 LangAS::opencl_local) { 820 // Get the location of the error. If a block literal has been passed 821 // (BlockExpr) then we can point straight to the offending argument, 822 // else we just point to the variable reference. 823 SourceLocation ErrorLoc; 824 if (isa<BlockExpr>(BlockArg)) { 825 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 826 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 827 } else if (isa<DeclRefExpr>(BlockArg)) { 828 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 829 } 830 S.Diag(ErrorLoc, 831 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 832 IllegalParams = true; 833 } 834 } 835 836 return IllegalParams; 837 } 838 839 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 840 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 841 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 842 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 843 return true; 844 } 845 return false; 846 } 847 848 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 849 if (checkArgCount(S, TheCall, 2)) 850 return true; 851 852 if (checkOpenCLSubgroupExt(S, TheCall)) 853 return true; 854 855 // First argument is an ndrange_t type. 856 Expr *NDRangeArg = TheCall->getArg(0); 857 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 858 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 859 << TheCall->getDirectCallee() << "'ndrange_t'"; 860 return true; 861 } 862 863 Expr *BlockArg = TheCall->getArg(1); 864 if (!isBlockPointer(BlockArg)) { 865 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 866 << TheCall->getDirectCallee() << "block"; 867 return true; 868 } 869 return checkOpenCLBlockArgs(S, BlockArg); 870 } 871 872 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 873 /// get_kernel_work_group_size 874 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 875 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 876 if (checkArgCount(S, TheCall, 1)) 877 return true; 878 879 Expr *BlockArg = TheCall->getArg(0); 880 if (!isBlockPointer(BlockArg)) { 881 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 882 << TheCall->getDirectCallee() << "block"; 883 return true; 884 } 885 return checkOpenCLBlockArgs(S, BlockArg); 886 } 887 888 /// Diagnose integer type and any valid implicit conversion to it. 889 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 890 const QualType &IntType); 891 892 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 893 unsigned Start, unsigned End) { 894 bool IllegalParams = false; 895 for (unsigned I = Start; I <= End; ++I) 896 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 897 S.Context.getSizeType()); 898 return IllegalParams; 899 } 900 901 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 902 /// 'local void*' parameter of passed block. 903 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 904 Expr *BlockArg, 905 unsigned NumNonVarArgs) { 906 const BlockPointerType *BPT = 907 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 908 unsigned NumBlockParams = 909 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 910 unsigned TotalNumArgs = TheCall->getNumArgs(); 911 912 // For each argument passed to the block, a corresponding uint needs to 913 // be passed to describe the size of the local memory. 914 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 915 S.Diag(TheCall->getBeginLoc(), 916 diag::err_opencl_enqueue_kernel_local_size_args); 917 return true; 918 } 919 920 // Check that the sizes of the local memory are specified by integers. 921 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 922 TotalNumArgs - 1); 923 } 924 925 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 926 /// overload formats specified in Table 6.13.17.1. 927 /// int enqueue_kernel(queue_t queue, 928 /// kernel_enqueue_flags_t flags, 929 /// const ndrange_t ndrange, 930 /// void (^block)(void)) 931 /// int enqueue_kernel(queue_t queue, 932 /// kernel_enqueue_flags_t flags, 933 /// const ndrange_t ndrange, 934 /// uint num_events_in_wait_list, 935 /// clk_event_t *event_wait_list, 936 /// clk_event_t *event_ret, 937 /// void (^block)(void)) 938 /// int enqueue_kernel(queue_t queue, 939 /// kernel_enqueue_flags_t flags, 940 /// const ndrange_t ndrange, 941 /// void (^block)(local void*, ...), 942 /// uint size0, ...) 943 /// int enqueue_kernel(queue_t queue, 944 /// kernel_enqueue_flags_t flags, 945 /// const ndrange_t ndrange, 946 /// uint num_events_in_wait_list, 947 /// clk_event_t *event_wait_list, 948 /// clk_event_t *event_ret, 949 /// void (^block)(local void*, ...), 950 /// uint size0, ...) 951 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 952 unsigned NumArgs = TheCall->getNumArgs(); 953 954 if (NumArgs < 4) { 955 S.Diag(TheCall->getBeginLoc(), 956 diag::err_typecheck_call_too_few_args_at_least) 957 << 0 << 4 << NumArgs; 958 return true; 959 } 960 961 Expr *Arg0 = TheCall->getArg(0); 962 Expr *Arg1 = TheCall->getArg(1); 963 Expr *Arg2 = TheCall->getArg(2); 964 Expr *Arg3 = TheCall->getArg(3); 965 966 // First argument always needs to be a queue_t type. 967 if (!Arg0->getType()->isQueueT()) { 968 S.Diag(TheCall->getArg(0)->getBeginLoc(), 969 diag::err_opencl_builtin_expected_type) 970 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 971 return true; 972 } 973 974 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 975 if (!Arg1->getType()->isIntegerType()) { 976 S.Diag(TheCall->getArg(1)->getBeginLoc(), 977 diag::err_opencl_builtin_expected_type) 978 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 979 return true; 980 } 981 982 // Third argument is always an ndrange_t type. 983 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 984 S.Diag(TheCall->getArg(2)->getBeginLoc(), 985 diag::err_opencl_builtin_expected_type) 986 << TheCall->getDirectCallee() << "'ndrange_t'"; 987 return true; 988 } 989 990 // With four arguments, there is only one form that the function could be 991 // called in: no events and no variable arguments. 992 if (NumArgs == 4) { 993 // check that the last argument is the right block type. 994 if (!isBlockPointer(Arg3)) { 995 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 996 << TheCall->getDirectCallee() << "block"; 997 return true; 998 } 999 // we have a block type, check the prototype 1000 const BlockPointerType *BPT = 1001 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1002 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1003 S.Diag(Arg3->getBeginLoc(), 1004 diag::err_opencl_enqueue_kernel_blocks_no_args); 1005 return true; 1006 } 1007 return false; 1008 } 1009 // we can have block + varargs. 1010 if (isBlockPointer(Arg3)) 1011 return (checkOpenCLBlockArgs(S, Arg3) || 1012 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1013 // last two cases with either exactly 7 args or 7 args and varargs. 1014 if (NumArgs >= 7) { 1015 // check common block argument. 1016 Expr *Arg6 = TheCall->getArg(6); 1017 if (!isBlockPointer(Arg6)) { 1018 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1019 << TheCall->getDirectCallee() << "block"; 1020 return true; 1021 } 1022 if (checkOpenCLBlockArgs(S, Arg6)) 1023 return true; 1024 1025 // Forth argument has to be any integer type. 1026 if (!Arg3->getType()->isIntegerType()) { 1027 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1028 diag::err_opencl_builtin_expected_type) 1029 << TheCall->getDirectCallee() << "integer"; 1030 return true; 1031 } 1032 // check remaining common arguments. 1033 Expr *Arg4 = TheCall->getArg(4); 1034 Expr *Arg5 = TheCall->getArg(5); 1035 1036 // Fifth argument is always passed as a pointer to clk_event_t. 1037 if (!Arg4->isNullPointerConstant(S.Context, 1038 Expr::NPC_ValueDependentIsNotNull) && 1039 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1040 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1041 diag::err_opencl_builtin_expected_type) 1042 << TheCall->getDirectCallee() 1043 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1044 return true; 1045 } 1046 1047 // Sixth argument is always passed as a pointer to clk_event_t. 1048 if (!Arg5->isNullPointerConstant(S.Context, 1049 Expr::NPC_ValueDependentIsNotNull) && 1050 !(Arg5->getType()->isPointerType() && 1051 Arg5->getType()->getPointeeType()->isClkEventT())) { 1052 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1053 diag::err_opencl_builtin_expected_type) 1054 << TheCall->getDirectCallee() 1055 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1056 return true; 1057 } 1058 1059 if (NumArgs == 7) 1060 return false; 1061 1062 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1063 } 1064 1065 // None of the specific case has been detected, give generic error 1066 S.Diag(TheCall->getBeginLoc(), 1067 diag::err_opencl_enqueue_kernel_incorrect_args); 1068 return true; 1069 } 1070 1071 /// Returns OpenCL access qual. 1072 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1073 return D->getAttr<OpenCLAccessAttr>(); 1074 } 1075 1076 /// Returns true if pipe element type is different from the pointer. 1077 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1078 const Expr *Arg0 = Call->getArg(0); 1079 // First argument type should always be pipe. 1080 if (!Arg0->getType()->isPipeType()) { 1081 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1082 << Call->getDirectCallee() << Arg0->getSourceRange(); 1083 return true; 1084 } 1085 OpenCLAccessAttr *AccessQual = 1086 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1087 // Validates the access qualifier is compatible with the call. 1088 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1089 // read_only and write_only, and assumed to be read_only if no qualifier is 1090 // specified. 1091 switch (Call->getDirectCallee()->getBuiltinID()) { 1092 case Builtin::BIread_pipe: 1093 case Builtin::BIreserve_read_pipe: 1094 case Builtin::BIcommit_read_pipe: 1095 case Builtin::BIwork_group_reserve_read_pipe: 1096 case Builtin::BIsub_group_reserve_read_pipe: 1097 case Builtin::BIwork_group_commit_read_pipe: 1098 case Builtin::BIsub_group_commit_read_pipe: 1099 if (!(!AccessQual || AccessQual->isReadOnly())) { 1100 S.Diag(Arg0->getBeginLoc(), 1101 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1102 << "read_only" << Arg0->getSourceRange(); 1103 return true; 1104 } 1105 break; 1106 case Builtin::BIwrite_pipe: 1107 case Builtin::BIreserve_write_pipe: 1108 case Builtin::BIcommit_write_pipe: 1109 case Builtin::BIwork_group_reserve_write_pipe: 1110 case Builtin::BIsub_group_reserve_write_pipe: 1111 case Builtin::BIwork_group_commit_write_pipe: 1112 case Builtin::BIsub_group_commit_write_pipe: 1113 if (!(AccessQual && AccessQual->isWriteOnly())) { 1114 S.Diag(Arg0->getBeginLoc(), 1115 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1116 << "write_only" << Arg0->getSourceRange(); 1117 return true; 1118 } 1119 break; 1120 default: 1121 break; 1122 } 1123 return false; 1124 } 1125 1126 /// Returns true if pipe element type is different from the pointer. 1127 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1128 const Expr *Arg0 = Call->getArg(0); 1129 const Expr *ArgIdx = Call->getArg(Idx); 1130 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1131 const QualType EltTy = PipeTy->getElementType(); 1132 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1133 // The Idx argument should be a pointer and the type of the pointer and 1134 // the type of pipe element should also be the same. 1135 if (!ArgTy || 1136 !S.Context.hasSameType( 1137 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1138 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1139 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1140 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1141 return true; 1142 } 1143 return false; 1144 } 1145 1146 // Performs semantic analysis for the read/write_pipe call. 1147 // \param S Reference to the semantic analyzer. 1148 // \param Call A pointer to the builtin call. 1149 // \return True if a semantic error has been found, false otherwise. 1150 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1151 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1152 // functions have two forms. 1153 switch (Call->getNumArgs()) { 1154 case 2: 1155 if (checkOpenCLPipeArg(S, Call)) 1156 return true; 1157 // The call with 2 arguments should be 1158 // read/write_pipe(pipe T, T*). 1159 // Check packet type T. 1160 if (checkOpenCLPipePacketType(S, Call, 1)) 1161 return true; 1162 break; 1163 1164 case 4: { 1165 if (checkOpenCLPipeArg(S, Call)) 1166 return true; 1167 // The call with 4 arguments should be 1168 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1169 // Check reserve_id_t. 1170 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1171 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1172 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1173 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1174 return true; 1175 } 1176 1177 // Check the index. 1178 const Expr *Arg2 = Call->getArg(2); 1179 if (!Arg2->getType()->isIntegerType() && 1180 !Arg2->getType()->isUnsignedIntegerType()) { 1181 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1182 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1183 << Arg2->getType() << Arg2->getSourceRange(); 1184 return true; 1185 } 1186 1187 // Check packet type T. 1188 if (checkOpenCLPipePacketType(S, Call, 3)) 1189 return true; 1190 } break; 1191 default: 1192 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1193 << Call->getDirectCallee() << Call->getSourceRange(); 1194 return true; 1195 } 1196 1197 return false; 1198 } 1199 1200 // Performs a semantic analysis on the {work_group_/sub_group_ 1201 // /_}reserve_{read/write}_pipe 1202 // \param S Reference to the semantic analyzer. 1203 // \param Call The call to the builtin function to be analyzed. 1204 // \return True if a semantic error was found, false otherwise. 1205 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1206 if (checkArgCount(S, Call, 2)) 1207 return true; 1208 1209 if (checkOpenCLPipeArg(S, Call)) 1210 return true; 1211 1212 // Check the reserve size. 1213 if (!Call->getArg(1)->getType()->isIntegerType() && 1214 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1215 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1216 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1217 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1218 return true; 1219 } 1220 1221 // Since return type of reserve_read/write_pipe built-in function is 1222 // reserve_id_t, which is not defined in the builtin def file , we used int 1223 // as return type and need to override the return type of these functions. 1224 Call->setType(S.Context.OCLReserveIDTy); 1225 1226 return false; 1227 } 1228 1229 // Performs a semantic analysis on {work_group_/sub_group_ 1230 // /_}commit_{read/write}_pipe 1231 // \param S Reference to the semantic analyzer. 1232 // \param Call The call to the builtin function to be analyzed. 1233 // \return True if a semantic error was found, false otherwise. 1234 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1235 if (checkArgCount(S, Call, 2)) 1236 return true; 1237 1238 if (checkOpenCLPipeArg(S, Call)) 1239 return true; 1240 1241 // Check reserve_id_t. 1242 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1243 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1244 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1245 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1246 return true; 1247 } 1248 1249 return false; 1250 } 1251 1252 // Performs a semantic analysis on the call to built-in Pipe 1253 // Query Functions. 1254 // \param S Reference to the semantic analyzer. 1255 // \param Call The call to the builtin function to be analyzed. 1256 // \return True if a semantic error was found, false otherwise. 1257 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1258 if (checkArgCount(S, Call, 1)) 1259 return true; 1260 1261 if (!Call->getArg(0)->getType()->isPipeType()) { 1262 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1263 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1264 return true; 1265 } 1266 1267 return false; 1268 } 1269 1270 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1271 // Performs semantic analysis for the to_global/local/private call. 1272 // \param S Reference to the semantic analyzer. 1273 // \param BuiltinID ID of the builtin function. 1274 // \param Call A pointer to the builtin call. 1275 // \return True if a semantic error has been found, false otherwise. 1276 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1277 CallExpr *Call) { 1278 if (checkArgCount(S, Call, 1)) 1279 return true; 1280 1281 auto RT = Call->getArg(0)->getType(); 1282 if (!RT->isPointerType() || RT->getPointeeType() 1283 .getAddressSpace() == LangAS::opencl_constant) { 1284 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1285 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1286 return true; 1287 } 1288 1289 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1290 S.Diag(Call->getArg(0)->getBeginLoc(), 1291 diag::warn_opencl_generic_address_space_arg) 1292 << Call->getDirectCallee()->getNameInfo().getAsString() 1293 << Call->getArg(0)->getSourceRange(); 1294 } 1295 1296 RT = RT->getPointeeType(); 1297 auto Qual = RT.getQualifiers(); 1298 switch (BuiltinID) { 1299 case Builtin::BIto_global: 1300 Qual.setAddressSpace(LangAS::opencl_global); 1301 break; 1302 case Builtin::BIto_local: 1303 Qual.setAddressSpace(LangAS::opencl_local); 1304 break; 1305 case Builtin::BIto_private: 1306 Qual.setAddressSpace(LangAS::opencl_private); 1307 break; 1308 default: 1309 llvm_unreachable("Invalid builtin function"); 1310 } 1311 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1312 RT.getUnqualifiedType(), Qual))); 1313 1314 return false; 1315 } 1316 1317 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1318 if (checkArgCount(S, TheCall, 1)) 1319 return ExprError(); 1320 1321 // Compute __builtin_launder's parameter type from the argument. 1322 // The parameter type is: 1323 // * The type of the argument if it's not an array or function type, 1324 // Otherwise, 1325 // * The decayed argument type. 1326 QualType ParamTy = [&]() { 1327 QualType ArgTy = TheCall->getArg(0)->getType(); 1328 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1329 return S.Context.getPointerType(Ty->getElementType()); 1330 if (ArgTy->isFunctionType()) { 1331 return S.Context.getPointerType(ArgTy); 1332 } 1333 return ArgTy; 1334 }(); 1335 1336 TheCall->setType(ParamTy); 1337 1338 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1339 if (!ParamTy->isPointerType()) 1340 return 0; 1341 if (ParamTy->isFunctionPointerType()) 1342 return 1; 1343 if (ParamTy->isVoidPointerType()) 1344 return 2; 1345 return llvm::Optional<unsigned>{}; 1346 }(); 1347 if (DiagSelect.hasValue()) { 1348 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1349 << DiagSelect.getValue() << TheCall->getSourceRange(); 1350 return ExprError(); 1351 } 1352 1353 // We either have an incomplete class type, or we have a class template 1354 // whose instantiation has not been forced. Example: 1355 // 1356 // template <class T> struct Foo { T value; }; 1357 // Foo<int> *p = nullptr; 1358 // auto *d = __builtin_launder(p); 1359 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1360 diag::err_incomplete_type)) 1361 return ExprError(); 1362 1363 assert(ParamTy->getPointeeType()->isObjectType() && 1364 "Unhandled non-object pointer case"); 1365 1366 InitializedEntity Entity = 1367 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1368 ExprResult Arg = 1369 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1370 if (Arg.isInvalid()) 1371 return ExprError(); 1372 TheCall->setArg(0, Arg.get()); 1373 1374 return TheCall; 1375 } 1376 1377 // Emit an error and return true if the current architecture is not in the list 1378 // of supported architectures. 1379 static bool 1380 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1381 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1382 llvm::Triple::ArchType CurArch = 1383 S.getASTContext().getTargetInfo().getTriple().getArch(); 1384 if (llvm::is_contained(SupportedArchs, CurArch)) 1385 return false; 1386 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1387 << TheCall->getSourceRange(); 1388 return true; 1389 } 1390 1391 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1392 SourceLocation CallSiteLoc); 1393 1394 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1395 CallExpr *TheCall) { 1396 switch (TI.getTriple().getArch()) { 1397 default: 1398 // Some builtins don't require additional checking, so just consider these 1399 // acceptable. 1400 return false; 1401 case llvm::Triple::arm: 1402 case llvm::Triple::armeb: 1403 case llvm::Triple::thumb: 1404 case llvm::Triple::thumbeb: 1405 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1406 case llvm::Triple::aarch64: 1407 case llvm::Triple::aarch64_32: 1408 case llvm::Triple::aarch64_be: 1409 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1410 case llvm::Triple::bpfeb: 1411 case llvm::Triple::bpfel: 1412 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1413 case llvm::Triple::hexagon: 1414 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1415 case llvm::Triple::mips: 1416 case llvm::Triple::mipsel: 1417 case llvm::Triple::mips64: 1418 case llvm::Triple::mips64el: 1419 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1420 case llvm::Triple::systemz: 1421 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1422 case llvm::Triple::x86: 1423 case llvm::Triple::x86_64: 1424 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1425 case llvm::Triple::ppc: 1426 case llvm::Triple::ppcle: 1427 case llvm::Triple::ppc64: 1428 case llvm::Triple::ppc64le: 1429 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1430 case llvm::Triple::amdgcn: 1431 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1432 case llvm::Triple::riscv32: 1433 case llvm::Triple::riscv64: 1434 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1435 } 1436 } 1437 1438 ExprResult 1439 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1440 CallExpr *TheCall) { 1441 ExprResult TheCallResult(TheCall); 1442 1443 // Find out if any arguments are required to be integer constant expressions. 1444 unsigned ICEArguments = 0; 1445 ASTContext::GetBuiltinTypeError Error; 1446 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1447 if (Error != ASTContext::GE_None) 1448 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1449 1450 // If any arguments are required to be ICE's, check and diagnose. 1451 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1452 // Skip arguments not required to be ICE's. 1453 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1454 1455 llvm::APSInt Result; 1456 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1457 return true; 1458 ICEArguments &= ~(1 << ArgNo); 1459 } 1460 1461 switch (BuiltinID) { 1462 case Builtin::BI__builtin___CFStringMakeConstantString: 1463 assert(TheCall->getNumArgs() == 1 && 1464 "Wrong # arguments to builtin CFStringMakeConstantString"); 1465 if (CheckObjCString(TheCall->getArg(0))) 1466 return ExprError(); 1467 break; 1468 case Builtin::BI__builtin_ms_va_start: 1469 case Builtin::BI__builtin_stdarg_start: 1470 case Builtin::BI__builtin_va_start: 1471 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1472 return ExprError(); 1473 break; 1474 case Builtin::BI__va_start: { 1475 switch (Context.getTargetInfo().getTriple().getArch()) { 1476 case llvm::Triple::aarch64: 1477 case llvm::Triple::arm: 1478 case llvm::Triple::thumb: 1479 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1480 return ExprError(); 1481 break; 1482 default: 1483 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1484 return ExprError(); 1485 break; 1486 } 1487 break; 1488 } 1489 1490 // The acquire, release, and no fence variants are ARM and AArch64 only. 1491 case Builtin::BI_interlockedbittestandset_acq: 1492 case Builtin::BI_interlockedbittestandset_rel: 1493 case Builtin::BI_interlockedbittestandset_nf: 1494 case Builtin::BI_interlockedbittestandreset_acq: 1495 case Builtin::BI_interlockedbittestandreset_rel: 1496 case Builtin::BI_interlockedbittestandreset_nf: 1497 if (CheckBuiltinTargetSupport( 1498 *this, BuiltinID, TheCall, 1499 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1500 return ExprError(); 1501 break; 1502 1503 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1504 case Builtin::BI_bittest64: 1505 case Builtin::BI_bittestandcomplement64: 1506 case Builtin::BI_bittestandreset64: 1507 case Builtin::BI_bittestandset64: 1508 case Builtin::BI_interlockedbittestandreset64: 1509 case Builtin::BI_interlockedbittestandset64: 1510 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1511 {llvm::Triple::x86_64, llvm::Triple::arm, 1512 llvm::Triple::thumb, llvm::Triple::aarch64})) 1513 return ExprError(); 1514 break; 1515 1516 case Builtin::BI__builtin_isgreater: 1517 case Builtin::BI__builtin_isgreaterequal: 1518 case Builtin::BI__builtin_isless: 1519 case Builtin::BI__builtin_islessequal: 1520 case Builtin::BI__builtin_islessgreater: 1521 case Builtin::BI__builtin_isunordered: 1522 if (SemaBuiltinUnorderedCompare(TheCall)) 1523 return ExprError(); 1524 break; 1525 case Builtin::BI__builtin_fpclassify: 1526 if (SemaBuiltinFPClassification(TheCall, 6)) 1527 return ExprError(); 1528 break; 1529 case Builtin::BI__builtin_isfinite: 1530 case Builtin::BI__builtin_isinf: 1531 case Builtin::BI__builtin_isinf_sign: 1532 case Builtin::BI__builtin_isnan: 1533 case Builtin::BI__builtin_isnormal: 1534 case Builtin::BI__builtin_signbit: 1535 case Builtin::BI__builtin_signbitf: 1536 case Builtin::BI__builtin_signbitl: 1537 if (SemaBuiltinFPClassification(TheCall, 1)) 1538 return ExprError(); 1539 break; 1540 case Builtin::BI__builtin_shufflevector: 1541 return SemaBuiltinShuffleVector(TheCall); 1542 // TheCall will be freed by the smart pointer here, but that's fine, since 1543 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1544 case Builtin::BI__builtin_prefetch: 1545 if (SemaBuiltinPrefetch(TheCall)) 1546 return ExprError(); 1547 break; 1548 case Builtin::BI__builtin_alloca_with_align: 1549 if (SemaBuiltinAllocaWithAlign(TheCall)) 1550 return ExprError(); 1551 LLVM_FALLTHROUGH; 1552 case Builtin::BI__builtin_alloca: 1553 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1554 << TheCall->getDirectCallee(); 1555 break; 1556 case Builtin::BI__assume: 1557 case Builtin::BI__builtin_assume: 1558 if (SemaBuiltinAssume(TheCall)) 1559 return ExprError(); 1560 break; 1561 case Builtin::BI__builtin_assume_aligned: 1562 if (SemaBuiltinAssumeAligned(TheCall)) 1563 return ExprError(); 1564 break; 1565 case Builtin::BI__builtin_dynamic_object_size: 1566 case Builtin::BI__builtin_object_size: 1567 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1568 return ExprError(); 1569 break; 1570 case Builtin::BI__builtin_longjmp: 1571 if (SemaBuiltinLongjmp(TheCall)) 1572 return ExprError(); 1573 break; 1574 case Builtin::BI__builtin_setjmp: 1575 if (SemaBuiltinSetjmp(TheCall)) 1576 return ExprError(); 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, Context)) || 1823 !Eval.Val.isFloat()) { 1824 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1825 << ProbArg->getSourceRange(); 1826 for (const PartialDiagnosticAt &PDiag : Notes) 1827 Diag(PDiag.first, PDiag.second); 1828 return ExprError(); 1829 } 1830 llvm::APFloat Probability = Eval.Val.getFloat(); 1831 bool LoseInfo = false; 1832 Probability.convert(llvm::APFloat::IEEEdouble(), 1833 llvm::RoundingMode::Dynamic, &LoseInfo); 1834 if (!(Probability >= llvm::APFloat(0.0) && 1835 Probability <= llvm::APFloat(1.0))) { 1836 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1837 << ProbArg->getSourceRange(); 1838 return ExprError(); 1839 } 1840 break; 1841 } 1842 case Builtin::BI__builtin_preserve_access_index: 1843 if (SemaBuiltinPreserveAI(*this, TheCall)) 1844 return ExprError(); 1845 break; 1846 case Builtin::BI__builtin_call_with_static_chain: 1847 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1848 return ExprError(); 1849 break; 1850 case Builtin::BI__exception_code: 1851 case Builtin::BI_exception_code: 1852 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1853 diag::err_seh___except_block)) 1854 return ExprError(); 1855 break; 1856 case Builtin::BI__exception_info: 1857 case Builtin::BI_exception_info: 1858 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1859 diag::err_seh___except_filter)) 1860 return ExprError(); 1861 break; 1862 case Builtin::BI__GetExceptionInfo: 1863 if (checkArgCount(*this, TheCall, 1)) 1864 return ExprError(); 1865 1866 if (CheckCXXThrowOperand( 1867 TheCall->getBeginLoc(), 1868 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1869 TheCall)) 1870 return ExprError(); 1871 1872 TheCall->setType(Context.VoidPtrTy); 1873 break; 1874 // OpenCL v2.0, s6.13.16 - Pipe functions 1875 case Builtin::BIread_pipe: 1876 case Builtin::BIwrite_pipe: 1877 // Since those two functions are declared with var args, we need a semantic 1878 // check for the argument. 1879 if (SemaBuiltinRWPipe(*this, TheCall)) 1880 return ExprError(); 1881 break; 1882 case Builtin::BIreserve_read_pipe: 1883 case Builtin::BIreserve_write_pipe: 1884 case Builtin::BIwork_group_reserve_read_pipe: 1885 case Builtin::BIwork_group_reserve_write_pipe: 1886 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1887 return ExprError(); 1888 break; 1889 case Builtin::BIsub_group_reserve_read_pipe: 1890 case Builtin::BIsub_group_reserve_write_pipe: 1891 if (checkOpenCLSubgroupExt(*this, TheCall) || 1892 SemaBuiltinReserveRWPipe(*this, TheCall)) 1893 return ExprError(); 1894 break; 1895 case Builtin::BIcommit_read_pipe: 1896 case Builtin::BIcommit_write_pipe: 1897 case Builtin::BIwork_group_commit_read_pipe: 1898 case Builtin::BIwork_group_commit_write_pipe: 1899 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1900 return ExprError(); 1901 break; 1902 case Builtin::BIsub_group_commit_read_pipe: 1903 case Builtin::BIsub_group_commit_write_pipe: 1904 if (checkOpenCLSubgroupExt(*this, TheCall) || 1905 SemaBuiltinCommitRWPipe(*this, TheCall)) 1906 return ExprError(); 1907 break; 1908 case Builtin::BIget_pipe_num_packets: 1909 case Builtin::BIget_pipe_max_packets: 1910 if (SemaBuiltinPipePackets(*this, TheCall)) 1911 return ExprError(); 1912 break; 1913 case Builtin::BIto_global: 1914 case Builtin::BIto_local: 1915 case Builtin::BIto_private: 1916 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1917 return ExprError(); 1918 break; 1919 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1920 case Builtin::BIenqueue_kernel: 1921 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1922 return ExprError(); 1923 break; 1924 case Builtin::BIget_kernel_work_group_size: 1925 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1926 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1927 return ExprError(); 1928 break; 1929 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1930 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1931 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1932 return ExprError(); 1933 break; 1934 case Builtin::BI__builtin_os_log_format: 1935 Cleanup.setExprNeedsCleanups(true); 1936 LLVM_FALLTHROUGH; 1937 case Builtin::BI__builtin_os_log_format_buffer_size: 1938 if (SemaBuiltinOSLogFormat(TheCall)) 1939 return ExprError(); 1940 break; 1941 case Builtin::BI__builtin_frame_address: 1942 case Builtin::BI__builtin_return_address: { 1943 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1944 return ExprError(); 1945 1946 // -Wframe-address warning if non-zero passed to builtin 1947 // return/frame address. 1948 Expr::EvalResult Result; 1949 if (!TheCall->getArg(0)->isValueDependent() && 1950 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 isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2574 QualType VectorTy, QualType EltTy) { 2575 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2576 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2577 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2578 << Call->getSourceRange() << VectorEltTy << EltTy; 2579 return false; 2580 } 2581 return true; 2582 } 2583 2584 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2585 QualType ArgType = Arg->getType(); 2586 if (ArgType->getAsPlaceholderType()) 2587 return false; 2588 2589 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2590 // format: 2591 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2592 // 2. <type> var; 2593 // __builtin_preserve_type_info(var, flag); 2594 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2595 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2596 return false; 2597 2598 // Typedef type. 2599 if (ArgType->getAs<TypedefType>()) 2600 return true; 2601 2602 // Record type or Enum type. 2603 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2604 if (const auto *RT = Ty->getAs<RecordType>()) { 2605 if (!RT->getDecl()->getDeclName().isEmpty()) 2606 return true; 2607 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2608 if (!ET->getDecl()->getDeclName().isEmpty()) 2609 return true; 2610 } 2611 2612 return false; 2613 } 2614 2615 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2616 QualType ArgType = Arg->getType(); 2617 if (ArgType->getAsPlaceholderType()) 2618 return false; 2619 2620 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2621 // format: 2622 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2623 // flag); 2624 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2625 if (!UO) 2626 return false; 2627 2628 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2629 if (!CE) 2630 return false; 2631 if (CE->getCastKind() != CK_IntegralToPointer && 2632 CE->getCastKind() != CK_NullToPointer) 2633 return false; 2634 2635 // The integer must be from an EnumConstantDecl. 2636 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2637 if (!DR) 2638 return false; 2639 2640 const EnumConstantDecl *Enumerator = 2641 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2642 if (!Enumerator) 2643 return false; 2644 2645 // The type must be EnumType. 2646 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2647 const auto *ET = Ty->getAs<EnumType>(); 2648 if (!ET) 2649 return false; 2650 2651 // The enum value must be supported. 2652 for (auto *EDI : ET->getDecl()->enumerators()) { 2653 if (EDI == Enumerator) 2654 return true; 2655 } 2656 2657 return false; 2658 } 2659 2660 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2661 CallExpr *TheCall) { 2662 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2663 BuiltinID == BPF::BI__builtin_btf_type_id || 2664 BuiltinID == BPF::BI__builtin_preserve_type_info || 2665 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2666 "unexpected BPF builtin"); 2667 2668 if (checkArgCount(*this, TheCall, 2)) 2669 return true; 2670 2671 // The second argument needs to be a constant int 2672 Expr *Arg = TheCall->getArg(1); 2673 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2674 diag::kind kind; 2675 if (!Value) { 2676 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2677 kind = diag::err_preserve_field_info_not_const; 2678 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2679 kind = diag::err_btf_type_id_not_const; 2680 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2681 kind = diag::err_preserve_type_info_not_const; 2682 else 2683 kind = diag::err_preserve_enum_value_not_const; 2684 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2685 return true; 2686 } 2687 2688 // The first argument 2689 Arg = TheCall->getArg(0); 2690 bool InvalidArg = false; 2691 bool ReturnUnsignedInt = true; 2692 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2693 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2694 InvalidArg = true; 2695 kind = diag::err_preserve_field_info_not_field; 2696 } 2697 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2698 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2699 InvalidArg = true; 2700 kind = diag::err_preserve_type_info_invalid; 2701 } 2702 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2703 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2704 InvalidArg = true; 2705 kind = diag::err_preserve_enum_value_invalid; 2706 } 2707 ReturnUnsignedInt = false; 2708 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2709 ReturnUnsignedInt = false; 2710 } 2711 2712 if (InvalidArg) { 2713 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2714 return true; 2715 } 2716 2717 if (ReturnUnsignedInt) 2718 TheCall->setType(Context.UnsignedIntTy); 2719 else 2720 TheCall->setType(Context.UnsignedLongTy); 2721 return false; 2722 } 2723 2724 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2725 struct ArgInfo { 2726 uint8_t OpNum; 2727 bool IsSigned; 2728 uint8_t BitWidth; 2729 uint8_t Align; 2730 }; 2731 struct BuiltinInfo { 2732 unsigned BuiltinID; 2733 ArgInfo Infos[2]; 2734 }; 2735 2736 static BuiltinInfo Infos[] = { 2737 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2738 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2739 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2740 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2741 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2742 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2743 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2744 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2745 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2746 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2747 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2748 2749 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2750 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2760 2761 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2813 {{ 1, false, 6, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2821 {{ 1, false, 5, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2828 { 2, false, 5, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2830 { 2, false, 6, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2832 { 3, false, 5, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2834 { 3, false, 6, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2851 {{ 2, false, 4, 0 }, 2852 { 3, false, 5, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2854 {{ 2, false, 4, 0 }, 2855 { 3, false, 5, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2857 {{ 2, false, 4, 0 }, 2858 { 3, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2860 {{ 2, false, 4, 0 }, 2861 { 3, false, 5, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2873 { 2, false, 5, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2875 { 2, false, 6, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2885 {{ 1, false, 4, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2888 {{ 1, false, 4, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2909 {{ 3, false, 1, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2914 {{ 3, false, 1, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2919 {{ 3, false, 1, 0 }} }, 2920 }; 2921 2922 // Use a dynamically initialized static to sort the table exactly once on 2923 // first run. 2924 static const bool SortOnce = 2925 (llvm::sort(Infos, 2926 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2927 return LHS.BuiltinID < RHS.BuiltinID; 2928 }), 2929 true); 2930 (void)SortOnce; 2931 2932 const BuiltinInfo *F = llvm::partition_point( 2933 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2934 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2935 return false; 2936 2937 bool Error = false; 2938 2939 for (const ArgInfo &A : F->Infos) { 2940 // Ignore empty ArgInfo elements. 2941 if (A.BitWidth == 0) 2942 continue; 2943 2944 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2945 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2946 if (!A.Align) { 2947 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2948 } else { 2949 unsigned M = 1 << A.Align; 2950 Min *= M; 2951 Max *= M; 2952 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2953 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2954 } 2955 } 2956 return Error; 2957 } 2958 2959 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2960 CallExpr *TheCall) { 2961 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2962 } 2963 2964 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2965 unsigned BuiltinID, CallExpr *TheCall) { 2966 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2967 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2968 } 2969 2970 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2971 CallExpr *TheCall) { 2972 2973 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2974 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2975 if (!TI.hasFeature("dsp")) 2976 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2977 } 2978 2979 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2980 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2981 if (!TI.hasFeature("dspr2")) 2982 return Diag(TheCall->getBeginLoc(), 2983 diag::err_mips_builtin_requires_dspr2); 2984 } 2985 2986 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2987 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2988 if (!TI.hasFeature("msa")) 2989 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2990 } 2991 2992 return false; 2993 } 2994 2995 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2996 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2997 // ordering for DSP is unspecified. MSA is ordered by the data format used 2998 // by the underlying instruction i.e., df/m, df/n and then by size. 2999 // 3000 // FIXME: The size tests here should instead be tablegen'd along with the 3001 // definitions from include/clang/Basic/BuiltinsMips.def. 3002 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3003 // be too. 3004 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3005 unsigned i = 0, l = 0, u = 0, m = 0; 3006 switch (BuiltinID) { 3007 default: return false; 3008 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3009 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3010 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3011 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3012 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3013 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3014 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3015 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3016 // df/m field. 3017 // These intrinsics take an unsigned 3 bit immediate. 3018 case Mips::BI__builtin_msa_bclri_b: 3019 case Mips::BI__builtin_msa_bnegi_b: 3020 case Mips::BI__builtin_msa_bseti_b: 3021 case Mips::BI__builtin_msa_sat_s_b: 3022 case Mips::BI__builtin_msa_sat_u_b: 3023 case Mips::BI__builtin_msa_slli_b: 3024 case Mips::BI__builtin_msa_srai_b: 3025 case Mips::BI__builtin_msa_srari_b: 3026 case Mips::BI__builtin_msa_srli_b: 3027 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3028 case Mips::BI__builtin_msa_binsli_b: 3029 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3030 // These intrinsics take an unsigned 4 bit immediate. 3031 case Mips::BI__builtin_msa_bclri_h: 3032 case Mips::BI__builtin_msa_bnegi_h: 3033 case Mips::BI__builtin_msa_bseti_h: 3034 case Mips::BI__builtin_msa_sat_s_h: 3035 case Mips::BI__builtin_msa_sat_u_h: 3036 case Mips::BI__builtin_msa_slli_h: 3037 case Mips::BI__builtin_msa_srai_h: 3038 case Mips::BI__builtin_msa_srari_h: 3039 case Mips::BI__builtin_msa_srli_h: 3040 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3041 case Mips::BI__builtin_msa_binsli_h: 3042 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3043 // These intrinsics take an unsigned 5 bit immediate. 3044 // The first block of intrinsics actually have an unsigned 5 bit field, 3045 // not a df/n field. 3046 case Mips::BI__builtin_msa_cfcmsa: 3047 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3048 case Mips::BI__builtin_msa_clei_u_b: 3049 case Mips::BI__builtin_msa_clei_u_h: 3050 case Mips::BI__builtin_msa_clei_u_w: 3051 case Mips::BI__builtin_msa_clei_u_d: 3052 case Mips::BI__builtin_msa_clti_u_b: 3053 case Mips::BI__builtin_msa_clti_u_h: 3054 case Mips::BI__builtin_msa_clti_u_w: 3055 case Mips::BI__builtin_msa_clti_u_d: 3056 case Mips::BI__builtin_msa_maxi_u_b: 3057 case Mips::BI__builtin_msa_maxi_u_h: 3058 case Mips::BI__builtin_msa_maxi_u_w: 3059 case Mips::BI__builtin_msa_maxi_u_d: 3060 case Mips::BI__builtin_msa_mini_u_b: 3061 case Mips::BI__builtin_msa_mini_u_h: 3062 case Mips::BI__builtin_msa_mini_u_w: 3063 case Mips::BI__builtin_msa_mini_u_d: 3064 case Mips::BI__builtin_msa_addvi_b: 3065 case Mips::BI__builtin_msa_addvi_h: 3066 case Mips::BI__builtin_msa_addvi_w: 3067 case Mips::BI__builtin_msa_addvi_d: 3068 case Mips::BI__builtin_msa_bclri_w: 3069 case Mips::BI__builtin_msa_bnegi_w: 3070 case Mips::BI__builtin_msa_bseti_w: 3071 case Mips::BI__builtin_msa_sat_s_w: 3072 case Mips::BI__builtin_msa_sat_u_w: 3073 case Mips::BI__builtin_msa_slli_w: 3074 case Mips::BI__builtin_msa_srai_w: 3075 case Mips::BI__builtin_msa_srari_w: 3076 case Mips::BI__builtin_msa_srli_w: 3077 case Mips::BI__builtin_msa_srlri_w: 3078 case Mips::BI__builtin_msa_subvi_b: 3079 case Mips::BI__builtin_msa_subvi_h: 3080 case Mips::BI__builtin_msa_subvi_w: 3081 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3082 case Mips::BI__builtin_msa_binsli_w: 3083 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3084 // These intrinsics take an unsigned 6 bit immediate. 3085 case Mips::BI__builtin_msa_bclri_d: 3086 case Mips::BI__builtin_msa_bnegi_d: 3087 case Mips::BI__builtin_msa_bseti_d: 3088 case Mips::BI__builtin_msa_sat_s_d: 3089 case Mips::BI__builtin_msa_sat_u_d: 3090 case Mips::BI__builtin_msa_slli_d: 3091 case Mips::BI__builtin_msa_srai_d: 3092 case Mips::BI__builtin_msa_srari_d: 3093 case Mips::BI__builtin_msa_srli_d: 3094 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3095 case Mips::BI__builtin_msa_binsli_d: 3096 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3097 // These intrinsics take a signed 5 bit immediate. 3098 case Mips::BI__builtin_msa_ceqi_b: 3099 case Mips::BI__builtin_msa_ceqi_h: 3100 case Mips::BI__builtin_msa_ceqi_w: 3101 case Mips::BI__builtin_msa_ceqi_d: 3102 case Mips::BI__builtin_msa_clti_s_b: 3103 case Mips::BI__builtin_msa_clti_s_h: 3104 case Mips::BI__builtin_msa_clti_s_w: 3105 case Mips::BI__builtin_msa_clti_s_d: 3106 case Mips::BI__builtin_msa_clei_s_b: 3107 case Mips::BI__builtin_msa_clei_s_h: 3108 case Mips::BI__builtin_msa_clei_s_w: 3109 case Mips::BI__builtin_msa_clei_s_d: 3110 case Mips::BI__builtin_msa_maxi_s_b: 3111 case Mips::BI__builtin_msa_maxi_s_h: 3112 case Mips::BI__builtin_msa_maxi_s_w: 3113 case Mips::BI__builtin_msa_maxi_s_d: 3114 case Mips::BI__builtin_msa_mini_s_b: 3115 case Mips::BI__builtin_msa_mini_s_h: 3116 case Mips::BI__builtin_msa_mini_s_w: 3117 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3118 // These intrinsics take an unsigned 8 bit immediate. 3119 case Mips::BI__builtin_msa_andi_b: 3120 case Mips::BI__builtin_msa_nori_b: 3121 case Mips::BI__builtin_msa_ori_b: 3122 case Mips::BI__builtin_msa_shf_b: 3123 case Mips::BI__builtin_msa_shf_h: 3124 case Mips::BI__builtin_msa_shf_w: 3125 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3126 case Mips::BI__builtin_msa_bseli_b: 3127 case Mips::BI__builtin_msa_bmnzi_b: 3128 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3129 // df/n format 3130 // These intrinsics take an unsigned 4 bit immediate. 3131 case Mips::BI__builtin_msa_copy_s_b: 3132 case Mips::BI__builtin_msa_copy_u_b: 3133 case Mips::BI__builtin_msa_insve_b: 3134 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3135 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3136 // These intrinsics take an unsigned 3 bit immediate. 3137 case Mips::BI__builtin_msa_copy_s_h: 3138 case Mips::BI__builtin_msa_copy_u_h: 3139 case Mips::BI__builtin_msa_insve_h: 3140 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3141 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3142 // These intrinsics take an unsigned 2 bit immediate. 3143 case Mips::BI__builtin_msa_copy_s_w: 3144 case Mips::BI__builtin_msa_copy_u_w: 3145 case Mips::BI__builtin_msa_insve_w: 3146 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3147 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3148 // These intrinsics take an unsigned 1 bit immediate. 3149 case Mips::BI__builtin_msa_copy_s_d: 3150 case Mips::BI__builtin_msa_copy_u_d: 3151 case Mips::BI__builtin_msa_insve_d: 3152 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3153 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3154 // Memory offsets and immediate loads. 3155 // These intrinsics take a signed 10 bit immediate. 3156 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3157 case Mips::BI__builtin_msa_ldi_h: 3158 case Mips::BI__builtin_msa_ldi_w: 3159 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3160 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3161 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3162 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3163 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3164 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3165 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3166 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3167 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3168 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3169 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3170 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3171 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3172 } 3173 3174 if (!m) 3175 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3176 3177 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3178 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3179 } 3180 3181 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3182 /// advancing the pointer over the consumed characters. The decoded type is 3183 /// returned. If the decoded type represents a constant integer with a 3184 /// constraint on its value then Mask is set to that value. The type descriptors 3185 /// used in Str are specific to PPC MMA builtins and are documented in the file 3186 /// defining the PPC builtins. 3187 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3188 unsigned &Mask) { 3189 bool RequireICE = false; 3190 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3191 switch (*Str++) { 3192 case 'V': 3193 return Context.getVectorType(Context.UnsignedCharTy, 16, 3194 VectorType::VectorKind::AltiVecVector); 3195 case 'i': { 3196 char *End; 3197 unsigned size = strtoul(Str, &End, 10); 3198 assert(End != Str && "Missing constant parameter constraint"); 3199 Str = End; 3200 Mask = size; 3201 return Context.IntTy; 3202 } 3203 case 'W': { 3204 char *End; 3205 unsigned size = strtoul(Str, &End, 10); 3206 assert(End != Str && "Missing PowerPC MMA type size"); 3207 Str = End; 3208 QualType Type; 3209 switch (size) { 3210 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3211 case size: Type = Context.Id##Ty; break; 3212 #include "clang/Basic/PPCTypes.def" 3213 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3214 } 3215 bool CheckVectorArgs = false; 3216 while (!CheckVectorArgs) { 3217 switch (*Str++) { 3218 case '*': 3219 Type = Context.getPointerType(Type); 3220 break; 3221 case 'C': 3222 Type = Type.withConst(); 3223 break; 3224 default: 3225 CheckVectorArgs = true; 3226 --Str; 3227 break; 3228 } 3229 } 3230 return Type; 3231 } 3232 default: 3233 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3234 } 3235 } 3236 3237 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3238 CallExpr *TheCall) { 3239 unsigned i = 0, l = 0, u = 0; 3240 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3241 BuiltinID == PPC::BI__builtin_divdeu || 3242 BuiltinID == PPC::BI__builtin_bpermd; 3243 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3244 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3245 BuiltinID == PPC::BI__builtin_divweu || 3246 BuiltinID == PPC::BI__builtin_divde || 3247 BuiltinID == PPC::BI__builtin_divdeu; 3248 3249 if (Is64BitBltin && !IsTarget64Bit) 3250 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3251 << TheCall->getSourceRange(); 3252 3253 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3254 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3255 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3256 << TheCall->getSourceRange(); 3257 3258 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3259 if (!TI.hasFeature("vsx")) 3260 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3261 << TheCall->getSourceRange(); 3262 return false; 3263 }; 3264 3265 switch (BuiltinID) { 3266 default: return false; 3267 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3268 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3269 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3270 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3271 case PPC::BI__builtin_altivec_dss: 3272 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3273 case PPC::BI__builtin_tbegin: 3274 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3275 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3276 case PPC::BI__builtin_tabortwc: 3277 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3278 case PPC::BI__builtin_tabortwci: 3279 case PPC::BI__builtin_tabortdci: 3280 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3281 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3282 case PPC::BI__builtin_altivec_dst: 3283 case PPC::BI__builtin_altivec_dstt: 3284 case PPC::BI__builtin_altivec_dstst: 3285 case PPC::BI__builtin_altivec_dststt: 3286 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3287 case PPC::BI__builtin_vsx_xxpermdi: 3288 case PPC::BI__builtin_vsx_xxsldwi: 3289 return SemaBuiltinVSX(TheCall); 3290 case PPC::BI__builtin_unpack_vector_int128: 3291 return SemaVSXCheck(TheCall) || 3292 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3293 case PPC::BI__builtin_pack_vector_int128: 3294 return SemaVSXCheck(TheCall); 3295 case PPC::BI__builtin_altivec_vgnb: 3296 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3297 case PPC::BI__builtin_altivec_vec_replace_elt: 3298 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3299 QualType VecTy = TheCall->getArg(0)->getType(); 3300 QualType EltTy = TheCall->getArg(1)->getType(); 3301 unsigned Width = Context.getIntWidth(EltTy); 3302 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3303 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3304 } 3305 case PPC::BI__builtin_vsx_xxeval: 3306 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3307 case PPC::BI__builtin_altivec_vsldbi: 3308 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3309 case PPC::BI__builtin_altivec_vsrdbi: 3310 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3311 case PPC::BI__builtin_vsx_xxpermx: 3312 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3313 #define CUSTOM_BUILTIN(Name, Types, Acc) \ 3314 case PPC::BI__builtin_##Name: \ 3315 return SemaBuiltinPPCMMACall(TheCall, Types); 3316 #include "clang/Basic/BuiltinsPPC.def" 3317 } 3318 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3319 } 3320 3321 // Check if the given type is a non-pointer PPC MMA type. This function is used 3322 // in Sema to prevent invalid uses of restricted PPC MMA types. 3323 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3324 if (Type->isPointerType() || Type->isArrayType()) 3325 return false; 3326 3327 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3328 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3329 if (false 3330 #include "clang/Basic/PPCTypes.def" 3331 ) { 3332 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3333 return true; 3334 } 3335 return false; 3336 } 3337 3338 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3339 CallExpr *TheCall) { 3340 // position of memory order and scope arguments in the builtin 3341 unsigned OrderIndex, ScopeIndex; 3342 switch (BuiltinID) { 3343 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3344 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3345 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3346 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3347 OrderIndex = 2; 3348 ScopeIndex = 3; 3349 break; 3350 case AMDGPU::BI__builtin_amdgcn_fence: 3351 OrderIndex = 0; 3352 ScopeIndex = 1; 3353 break; 3354 default: 3355 return false; 3356 } 3357 3358 ExprResult Arg = TheCall->getArg(OrderIndex); 3359 auto ArgExpr = Arg.get(); 3360 Expr::EvalResult ArgResult; 3361 3362 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3363 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3364 << ArgExpr->getType(); 3365 int ord = ArgResult.Val.getInt().getZExtValue(); 3366 3367 // Check valididty of memory ordering as per C11 / C++11's memody model. 3368 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3369 case llvm::AtomicOrderingCABI::acquire: 3370 case llvm::AtomicOrderingCABI::release: 3371 case llvm::AtomicOrderingCABI::acq_rel: 3372 case llvm::AtomicOrderingCABI::seq_cst: 3373 break; 3374 default: { 3375 return Diag(ArgExpr->getBeginLoc(), 3376 diag::warn_atomic_op_has_invalid_memory_order) 3377 << ArgExpr->getSourceRange(); 3378 } 3379 } 3380 3381 Arg = TheCall->getArg(ScopeIndex); 3382 ArgExpr = Arg.get(); 3383 Expr::EvalResult ArgResult1; 3384 // Check that sync scope is a constant literal 3385 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3386 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3387 << ArgExpr->getType(); 3388 3389 return false; 3390 } 3391 3392 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3393 unsigned BuiltinID, 3394 CallExpr *TheCall) { 3395 // CodeGenFunction can also detect this, but this gives a better error 3396 // message. 3397 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3398 if (Features.find("experimental-v") != StringRef::npos && 3399 !TI.hasFeature("experimental-v")) 3400 return Diag(TheCall->getBeginLoc(), diag::err_riscvv_builtin_requires_v) 3401 << TheCall->getSourceRange(); 3402 3403 return false; 3404 } 3405 3406 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3407 CallExpr *TheCall) { 3408 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3409 Expr *Arg = TheCall->getArg(0); 3410 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3411 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3412 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3413 << Arg->getSourceRange(); 3414 } 3415 3416 // For intrinsics which take an immediate value as part of the instruction, 3417 // range check them here. 3418 unsigned i = 0, l = 0, u = 0; 3419 switch (BuiltinID) { 3420 default: return false; 3421 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3422 case SystemZ::BI__builtin_s390_verimb: 3423 case SystemZ::BI__builtin_s390_verimh: 3424 case SystemZ::BI__builtin_s390_verimf: 3425 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3426 case SystemZ::BI__builtin_s390_vfaeb: 3427 case SystemZ::BI__builtin_s390_vfaeh: 3428 case SystemZ::BI__builtin_s390_vfaef: 3429 case SystemZ::BI__builtin_s390_vfaebs: 3430 case SystemZ::BI__builtin_s390_vfaehs: 3431 case SystemZ::BI__builtin_s390_vfaefs: 3432 case SystemZ::BI__builtin_s390_vfaezb: 3433 case SystemZ::BI__builtin_s390_vfaezh: 3434 case SystemZ::BI__builtin_s390_vfaezf: 3435 case SystemZ::BI__builtin_s390_vfaezbs: 3436 case SystemZ::BI__builtin_s390_vfaezhs: 3437 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3438 case SystemZ::BI__builtin_s390_vfisb: 3439 case SystemZ::BI__builtin_s390_vfidb: 3440 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3441 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3442 case SystemZ::BI__builtin_s390_vftcisb: 3443 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3444 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3445 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3446 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3447 case SystemZ::BI__builtin_s390_vstrcb: 3448 case SystemZ::BI__builtin_s390_vstrch: 3449 case SystemZ::BI__builtin_s390_vstrcf: 3450 case SystemZ::BI__builtin_s390_vstrczb: 3451 case SystemZ::BI__builtin_s390_vstrczh: 3452 case SystemZ::BI__builtin_s390_vstrczf: 3453 case SystemZ::BI__builtin_s390_vstrcbs: 3454 case SystemZ::BI__builtin_s390_vstrchs: 3455 case SystemZ::BI__builtin_s390_vstrcfs: 3456 case SystemZ::BI__builtin_s390_vstrczbs: 3457 case SystemZ::BI__builtin_s390_vstrczhs: 3458 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3459 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3460 case SystemZ::BI__builtin_s390_vfminsb: 3461 case SystemZ::BI__builtin_s390_vfmaxsb: 3462 case SystemZ::BI__builtin_s390_vfmindb: 3463 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3464 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3465 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3466 } 3467 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3468 } 3469 3470 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3471 /// This checks that the target supports __builtin_cpu_supports and 3472 /// that the string argument is constant and valid. 3473 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3474 CallExpr *TheCall) { 3475 Expr *Arg = TheCall->getArg(0); 3476 3477 // Check if the argument is a string literal. 3478 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3479 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3480 << Arg->getSourceRange(); 3481 3482 // Check the contents of the string. 3483 StringRef Feature = 3484 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3485 if (!TI.validateCpuSupports(Feature)) 3486 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3487 << Arg->getSourceRange(); 3488 return false; 3489 } 3490 3491 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3492 /// This checks that the target supports __builtin_cpu_is and 3493 /// that the string argument is constant and valid. 3494 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3495 Expr *Arg = TheCall->getArg(0); 3496 3497 // Check if the argument is a string literal. 3498 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3499 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3500 << Arg->getSourceRange(); 3501 3502 // Check the contents of the string. 3503 StringRef Feature = 3504 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3505 if (!TI.validateCpuIs(Feature)) 3506 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3507 << Arg->getSourceRange(); 3508 return false; 3509 } 3510 3511 // Check if the rounding mode is legal. 3512 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3513 // Indicates if this instruction has rounding control or just SAE. 3514 bool HasRC = false; 3515 3516 unsigned ArgNum = 0; 3517 switch (BuiltinID) { 3518 default: 3519 return false; 3520 case X86::BI__builtin_ia32_vcvttsd2si32: 3521 case X86::BI__builtin_ia32_vcvttsd2si64: 3522 case X86::BI__builtin_ia32_vcvttsd2usi32: 3523 case X86::BI__builtin_ia32_vcvttsd2usi64: 3524 case X86::BI__builtin_ia32_vcvttss2si32: 3525 case X86::BI__builtin_ia32_vcvttss2si64: 3526 case X86::BI__builtin_ia32_vcvttss2usi32: 3527 case X86::BI__builtin_ia32_vcvttss2usi64: 3528 ArgNum = 1; 3529 break; 3530 case X86::BI__builtin_ia32_maxpd512: 3531 case X86::BI__builtin_ia32_maxps512: 3532 case X86::BI__builtin_ia32_minpd512: 3533 case X86::BI__builtin_ia32_minps512: 3534 ArgNum = 2; 3535 break; 3536 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3537 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3538 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3539 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3540 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3541 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3542 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3543 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3544 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3545 case X86::BI__builtin_ia32_exp2pd_mask: 3546 case X86::BI__builtin_ia32_exp2ps_mask: 3547 case X86::BI__builtin_ia32_getexppd512_mask: 3548 case X86::BI__builtin_ia32_getexpps512_mask: 3549 case X86::BI__builtin_ia32_rcp28pd_mask: 3550 case X86::BI__builtin_ia32_rcp28ps_mask: 3551 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3552 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3553 case X86::BI__builtin_ia32_vcomisd: 3554 case X86::BI__builtin_ia32_vcomiss: 3555 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3556 ArgNum = 3; 3557 break; 3558 case X86::BI__builtin_ia32_cmppd512_mask: 3559 case X86::BI__builtin_ia32_cmpps512_mask: 3560 case X86::BI__builtin_ia32_cmpsd_mask: 3561 case X86::BI__builtin_ia32_cmpss_mask: 3562 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3563 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3564 case X86::BI__builtin_ia32_getexpss128_round_mask: 3565 case X86::BI__builtin_ia32_getmantpd512_mask: 3566 case X86::BI__builtin_ia32_getmantps512_mask: 3567 case X86::BI__builtin_ia32_maxsd_round_mask: 3568 case X86::BI__builtin_ia32_maxss_round_mask: 3569 case X86::BI__builtin_ia32_minsd_round_mask: 3570 case X86::BI__builtin_ia32_minss_round_mask: 3571 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3572 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3573 case X86::BI__builtin_ia32_reducepd512_mask: 3574 case X86::BI__builtin_ia32_reduceps512_mask: 3575 case X86::BI__builtin_ia32_rndscalepd_mask: 3576 case X86::BI__builtin_ia32_rndscaleps_mask: 3577 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3578 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3579 ArgNum = 4; 3580 break; 3581 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3582 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3583 case X86::BI__builtin_ia32_fixupimmps512_mask: 3584 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3585 case X86::BI__builtin_ia32_fixupimmsd_mask: 3586 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3587 case X86::BI__builtin_ia32_fixupimmss_mask: 3588 case X86::BI__builtin_ia32_fixupimmss_maskz: 3589 case X86::BI__builtin_ia32_getmantsd_round_mask: 3590 case X86::BI__builtin_ia32_getmantss_round_mask: 3591 case X86::BI__builtin_ia32_rangepd512_mask: 3592 case X86::BI__builtin_ia32_rangeps512_mask: 3593 case X86::BI__builtin_ia32_rangesd128_round_mask: 3594 case X86::BI__builtin_ia32_rangess128_round_mask: 3595 case X86::BI__builtin_ia32_reducesd_mask: 3596 case X86::BI__builtin_ia32_reducess_mask: 3597 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3598 case X86::BI__builtin_ia32_rndscaless_round_mask: 3599 ArgNum = 5; 3600 break; 3601 case X86::BI__builtin_ia32_vcvtsd2si64: 3602 case X86::BI__builtin_ia32_vcvtsd2si32: 3603 case X86::BI__builtin_ia32_vcvtsd2usi32: 3604 case X86::BI__builtin_ia32_vcvtsd2usi64: 3605 case X86::BI__builtin_ia32_vcvtss2si32: 3606 case X86::BI__builtin_ia32_vcvtss2si64: 3607 case X86::BI__builtin_ia32_vcvtss2usi32: 3608 case X86::BI__builtin_ia32_vcvtss2usi64: 3609 case X86::BI__builtin_ia32_sqrtpd512: 3610 case X86::BI__builtin_ia32_sqrtps512: 3611 ArgNum = 1; 3612 HasRC = true; 3613 break; 3614 case X86::BI__builtin_ia32_addpd512: 3615 case X86::BI__builtin_ia32_addps512: 3616 case X86::BI__builtin_ia32_divpd512: 3617 case X86::BI__builtin_ia32_divps512: 3618 case X86::BI__builtin_ia32_mulpd512: 3619 case X86::BI__builtin_ia32_mulps512: 3620 case X86::BI__builtin_ia32_subpd512: 3621 case X86::BI__builtin_ia32_subps512: 3622 case X86::BI__builtin_ia32_cvtsi2sd64: 3623 case X86::BI__builtin_ia32_cvtsi2ss32: 3624 case X86::BI__builtin_ia32_cvtsi2ss64: 3625 case X86::BI__builtin_ia32_cvtusi2sd64: 3626 case X86::BI__builtin_ia32_cvtusi2ss32: 3627 case X86::BI__builtin_ia32_cvtusi2ss64: 3628 ArgNum = 2; 3629 HasRC = true; 3630 break; 3631 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3632 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3633 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3634 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3635 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3636 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3637 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3638 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3639 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3640 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3641 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3642 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3643 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3644 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3645 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3646 ArgNum = 3; 3647 HasRC = true; 3648 break; 3649 case X86::BI__builtin_ia32_addss_round_mask: 3650 case X86::BI__builtin_ia32_addsd_round_mask: 3651 case X86::BI__builtin_ia32_divss_round_mask: 3652 case X86::BI__builtin_ia32_divsd_round_mask: 3653 case X86::BI__builtin_ia32_mulss_round_mask: 3654 case X86::BI__builtin_ia32_mulsd_round_mask: 3655 case X86::BI__builtin_ia32_subss_round_mask: 3656 case X86::BI__builtin_ia32_subsd_round_mask: 3657 case X86::BI__builtin_ia32_scalefpd512_mask: 3658 case X86::BI__builtin_ia32_scalefps512_mask: 3659 case X86::BI__builtin_ia32_scalefsd_round_mask: 3660 case X86::BI__builtin_ia32_scalefss_round_mask: 3661 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3662 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3663 case X86::BI__builtin_ia32_sqrtss_round_mask: 3664 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3665 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3666 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3667 case X86::BI__builtin_ia32_vfmaddss3_mask: 3668 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3669 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3670 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3671 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3672 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3673 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3674 case X86::BI__builtin_ia32_vfmaddps512_mask: 3675 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3676 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3677 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3678 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3679 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3680 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3681 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3682 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3683 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3684 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3685 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3686 ArgNum = 4; 3687 HasRC = true; 3688 break; 3689 } 3690 3691 llvm::APSInt Result; 3692 3693 // We can't check the value of a dependent argument. 3694 Expr *Arg = TheCall->getArg(ArgNum); 3695 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3696 return false; 3697 3698 // Check constant-ness first. 3699 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3700 return true; 3701 3702 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3703 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3704 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3705 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3706 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3707 Result == 8/*ROUND_NO_EXC*/ || 3708 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3709 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3710 return false; 3711 3712 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3713 << Arg->getSourceRange(); 3714 } 3715 3716 // Check if the gather/scatter scale is legal. 3717 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3718 CallExpr *TheCall) { 3719 unsigned ArgNum = 0; 3720 switch (BuiltinID) { 3721 default: 3722 return false; 3723 case X86::BI__builtin_ia32_gatherpfdpd: 3724 case X86::BI__builtin_ia32_gatherpfdps: 3725 case X86::BI__builtin_ia32_gatherpfqpd: 3726 case X86::BI__builtin_ia32_gatherpfqps: 3727 case X86::BI__builtin_ia32_scatterpfdpd: 3728 case X86::BI__builtin_ia32_scatterpfdps: 3729 case X86::BI__builtin_ia32_scatterpfqpd: 3730 case X86::BI__builtin_ia32_scatterpfqps: 3731 ArgNum = 3; 3732 break; 3733 case X86::BI__builtin_ia32_gatherd_pd: 3734 case X86::BI__builtin_ia32_gatherd_pd256: 3735 case X86::BI__builtin_ia32_gatherq_pd: 3736 case X86::BI__builtin_ia32_gatherq_pd256: 3737 case X86::BI__builtin_ia32_gatherd_ps: 3738 case X86::BI__builtin_ia32_gatherd_ps256: 3739 case X86::BI__builtin_ia32_gatherq_ps: 3740 case X86::BI__builtin_ia32_gatherq_ps256: 3741 case X86::BI__builtin_ia32_gatherd_q: 3742 case X86::BI__builtin_ia32_gatherd_q256: 3743 case X86::BI__builtin_ia32_gatherq_q: 3744 case X86::BI__builtin_ia32_gatherq_q256: 3745 case X86::BI__builtin_ia32_gatherd_d: 3746 case X86::BI__builtin_ia32_gatherd_d256: 3747 case X86::BI__builtin_ia32_gatherq_d: 3748 case X86::BI__builtin_ia32_gatherq_d256: 3749 case X86::BI__builtin_ia32_gather3div2df: 3750 case X86::BI__builtin_ia32_gather3div2di: 3751 case X86::BI__builtin_ia32_gather3div4df: 3752 case X86::BI__builtin_ia32_gather3div4di: 3753 case X86::BI__builtin_ia32_gather3div4sf: 3754 case X86::BI__builtin_ia32_gather3div4si: 3755 case X86::BI__builtin_ia32_gather3div8sf: 3756 case X86::BI__builtin_ia32_gather3div8si: 3757 case X86::BI__builtin_ia32_gather3siv2df: 3758 case X86::BI__builtin_ia32_gather3siv2di: 3759 case X86::BI__builtin_ia32_gather3siv4df: 3760 case X86::BI__builtin_ia32_gather3siv4di: 3761 case X86::BI__builtin_ia32_gather3siv4sf: 3762 case X86::BI__builtin_ia32_gather3siv4si: 3763 case X86::BI__builtin_ia32_gather3siv8sf: 3764 case X86::BI__builtin_ia32_gather3siv8si: 3765 case X86::BI__builtin_ia32_gathersiv8df: 3766 case X86::BI__builtin_ia32_gathersiv16sf: 3767 case X86::BI__builtin_ia32_gatherdiv8df: 3768 case X86::BI__builtin_ia32_gatherdiv16sf: 3769 case X86::BI__builtin_ia32_gathersiv8di: 3770 case X86::BI__builtin_ia32_gathersiv16si: 3771 case X86::BI__builtin_ia32_gatherdiv8di: 3772 case X86::BI__builtin_ia32_gatherdiv16si: 3773 case X86::BI__builtin_ia32_scatterdiv2df: 3774 case X86::BI__builtin_ia32_scatterdiv2di: 3775 case X86::BI__builtin_ia32_scatterdiv4df: 3776 case X86::BI__builtin_ia32_scatterdiv4di: 3777 case X86::BI__builtin_ia32_scatterdiv4sf: 3778 case X86::BI__builtin_ia32_scatterdiv4si: 3779 case X86::BI__builtin_ia32_scatterdiv8sf: 3780 case X86::BI__builtin_ia32_scatterdiv8si: 3781 case X86::BI__builtin_ia32_scattersiv2df: 3782 case X86::BI__builtin_ia32_scattersiv2di: 3783 case X86::BI__builtin_ia32_scattersiv4df: 3784 case X86::BI__builtin_ia32_scattersiv4di: 3785 case X86::BI__builtin_ia32_scattersiv4sf: 3786 case X86::BI__builtin_ia32_scattersiv4si: 3787 case X86::BI__builtin_ia32_scattersiv8sf: 3788 case X86::BI__builtin_ia32_scattersiv8si: 3789 case X86::BI__builtin_ia32_scattersiv8df: 3790 case X86::BI__builtin_ia32_scattersiv16sf: 3791 case X86::BI__builtin_ia32_scatterdiv8df: 3792 case X86::BI__builtin_ia32_scatterdiv16sf: 3793 case X86::BI__builtin_ia32_scattersiv8di: 3794 case X86::BI__builtin_ia32_scattersiv16si: 3795 case X86::BI__builtin_ia32_scatterdiv8di: 3796 case X86::BI__builtin_ia32_scatterdiv16si: 3797 ArgNum = 4; 3798 break; 3799 } 3800 3801 llvm::APSInt Result; 3802 3803 // We can't check the value of a dependent argument. 3804 Expr *Arg = TheCall->getArg(ArgNum); 3805 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3806 return false; 3807 3808 // Check constant-ness first. 3809 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3810 return true; 3811 3812 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3813 return false; 3814 3815 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3816 << Arg->getSourceRange(); 3817 } 3818 3819 enum { TileRegLow = 0, TileRegHigh = 7 }; 3820 3821 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 3822 ArrayRef<int> ArgNums) { 3823 for (int ArgNum : ArgNums) { 3824 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 3825 return true; 3826 } 3827 return false; 3828 } 3829 3830 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 3831 ArrayRef<int> ArgNums) { 3832 // Because the max number of tile register is TileRegHigh + 1, so here we use 3833 // each bit to represent the usage of them in bitset. 3834 std::bitset<TileRegHigh + 1> ArgValues; 3835 for (int ArgNum : ArgNums) { 3836 Expr *Arg = TheCall->getArg(ArgNum); 3837 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3838 continue; 3839 3840 llvm::APSInt Result; 3841 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3842 return true; 3843 int ArgExtValue = Result.getExtValue(); 3844 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 3845 "Incorrect tile register num."); 3846 if (ArgValues.test(ArgExtValue)) 3847 return Diag(TheCall->getBeginLoc(), 3848 diag::err_x86_builtin_tile_arg_duplicate) 3849 << TheCall->getArg(ArgNum)->getSourceRange(); 3850 ArgValues.set(ArgExtValue); 3851 } 3852 return false; 3853 } 3854 3855 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 3856 ArrayRef<int> ArgNums) { 3857 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 3858 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 3859 } 3860 3861 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 3862 switch (BuiltinID) { 3863 default: 3864 return false; 3865 case X86::BI__builtin_ia32_tileloadd64: 3866 case X86::BI__builtin_ia32_tileloaddt164: 3867 case X86::BI__builtin_ia32_tilestored64: 3868 case X86::BI__builtin_ia32_tilezero: 3869 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 3870 case X86::BI__builtin_ia32_tdpbssd: 3871 case X86::BI__builtin_ia32_tdpbsud: 3872 case X86::BI__builtin_ia32_tdpbusd: 3873 case X86::BI__builtin_ia32_tdpbuud: 3874 case X86::BI__builtin_ia32_tdpbf16ps: 3875 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 3876 } 3877 } 3878 static bool isX86_32Builtin(unsigned BuiltinID) { 3879 // These builtins only work on x86-32 targets. 3880 switch (BuiltinID) { 3881 case X86::BI__builtin_ia32_readeflags_u32: 3882 case X86::BI__builtin_ia32_writeeflags_u32: 3883 return true; 3884 } 3885 3886 return false; 3887 } 3888 3889 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3890 CallExpr *TheCall) { 3891 if (BuiltinID == X86::BI__builtin_cpu_supports) 3892 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3893 3894 if (BuiltinID == X86::BI__builtin_cpu_is) 3895 return SemaBuiltinCpuIs(*this, TI, TheCall); 3896 3897 // Check for 32-bit only builtins on a 64-bit target. 3898 const llvm::Triple &TT = TI.getTriple(); 3899 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3900 return Diag(TheCall->getCallee()->getBeginLoc(), 3901 diag::err_32_bit_builtin_64_bit_tgt); 3902 3903 // If the intrinsic has rounding or SAE make sure its valid. 3904 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3905 return true; 3906 3907 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3908 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3909 return true; 3910 3911 // If the intrinsic has a tile arguments, make sure they are valid. 3912 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 3913 return true; 3914 3915 // For intrinsics which take an immediate value as part of the instruction, 3916 // range check them here. 3917 int i = 0, l = 0, u = 0; 3918 switch (BuiltinID) { 3919 default: 3920 return false; 3921 case X86::BI__builtin_ia32_vec_ext_v2si: 3922 case X86::BI__builtin_ia32_vec_ext_v2di: 3923 case X86::BI__builtin_ia32_vextractf128_pd256: 3924 case X86::BI__builtin_ia32_vextractf128_ps256: 3925 case X86::BI__builtin_ia32_vextractf128_si256: 3926 case X86::BI__builtin_ia32_extract128i256: 3927 case X86::BI__builtin_ia32_extractf64x4_mask: 3928 case X86::BI__builtin_ia32_extracti64x4_mask: 3929 case X86::BI__builtin_ia32_extractf32x8_mask: 3930 case X86::BI__builtin_ia32_extracti32x8_mask: 3931 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3932 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3933 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3934 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3935 i = 1; l = 0; u = 1; 3936 break; 3937 case X86::BI__builtin_ia32_vec_set_v2di: 3938 case X86::BI__builtin_ia32_vinsertf128_pd256: 3939 case X86::BI__builtin_ia32_vinsertf128_ps256: 3940 case X86::BI__builtin_ia32_vinsertf128_si256: 3941 case X86::BI__builtin_ia32_insert128i256: 3942 case X86::BI__builtin_ia32_insertf32x8: 3943 case X86::BI__builtin_ia32_inserti32x8: 3944 case X86::BI__builtin_ia32_insertf64x4: 3945 case X86::BI__builtin_ia32_inserti64x4: 3946 case X86::BI__builtin_ia32_insertf64x2_256: 3947 case X86::BI__builtin_ia32_inserti64x2_256: 3948 case X86::BI__builtin_ia32_insertf32x4_256: 3949 case X86::BI__builtin_ia32_inserti32x4_256: 3950 i = 2; l = 0; u = 1; 3951 break; 3952 case X86::BI__builtin_ia32_vpermilpd: 3953 case X86::BI__builtin_ia32_vec_ext_v4hi: 3954 case X86::BI__builtin_ia32_vec_ext_v4si: 3955 case X86::BI__builtin_ia32_vec_ext_v4sf: 3956 case X86::BI__builtin_ia32_vec_ext_v4di: 3957 case X86::BI__builtin_ia32_extractf32x4_mask: 3958 case X86::BI__builtin_ia32_extracti32x4_mask: 3959 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3960 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3961 i = 1; l = 0; u = 3; 3962 break; 3963 case X86::BI_mm_prefetch: 3964 case X86::BI__builtin_ia32_vec_ext_v8hi: 3965 case X86::BI__builtin_ia32_vec_ext_v8si: 3966 i = 1; l = 0; u = 7; 3967 break; 3968 case X86::BI__builtin_ia32_sha1rnds4: 3969 case X86::BI__builtin_ia32_blendpd: 3970 case X86::BI__builtin_ia32_shufpd: 3971 case X86::BI__builtin_ia32_vec_set_v4hi: 3972 case X86::BI__builtin_ia32_vec_set_v4si: 3973 case X86::BI__builtin_ia32_vec_set_v4di: 3974 case X86::BI__builtin_ia32_shuf_f32x4_256: 3975 case X86::BI__builtin_ia32_shuf_f64x2_256: 3976 case X86::BI__builtin_ia32_shuf_i32x4_256: 3977 case X86::BI__builtin_ia32_shuf_i64x2_256: 3978 case X86::BI__builtin_ia32_insertf64x2_512: 3979 case X86::BI__builtin_ia32_inserti64x2_512: 3980 case X86::BI__builtin_ia32_insertf32x4: 3981 case X86::BI__builtin_ia32_inserti32x4: 3982 i = 2; l = 0; u = 3; 3983 break; 3984 case X86::BI__builtin_ia32_vpermil2pd: 3985 case X86::BI__builtin_ia32_vpermil2pd256: 3986 case X86::BI__builtin_ia32_vpermil2ps: 3987 case X86::BI__builtin_ia32_vpermil2ps256: 3988 i = 3; l = 0; u = 3; 3989 break; 3990 case X86::BI__builtin_ia32_cmpb128_mask: 3991 case X86::BI__builtin_ia32_cmpw128_mask: 3992 case X86::BI__builtin_ia32_cmpd128_mask: 3993 case X86::BI__builtin_ia32_cmpq128_mask: 3994 case X86::BI__builtin_ia32_cmpb256_mask: 3995 case X86::BI__builtin_ia32_cmpw256_mask: 3996 case X86::BI__builtin_ia32_cmpd256_mask: 3997 case X86::BI__builtin_ia32_cmpq256_mask: 3998 case X86::BI__builtin_ia32_cmpb512_mask: 3999 case X86::BI__builtin_ia32_cmpw512_mask: 4000 case X86::BI__builtin_ia32_cmpd512_mask: 4001 case X86::BI__builtin_ia32_cmpq512_mask: 4002 case X86::BI__builtin_ia32_ucmpb128_mask: 4003 case X86::BI__builtin_ia32_ucmpw128_mask: 4004 case X86::BI__builtin_ia32_ucmpd128_mask: 4005 case X86::BI__builtin_ia32_ucmpq128_mask: 4006 case X86::BI__builtin_ia32_ucmpb256_mask: 4007 case X86::BI__builtin_ia32_ucmpw256_mask: 4008 case X86::BI__builtin_ia32_ucmpd256_mask: 4009 case X86::BI__builtin_ia32_ucmpq256_mask: 4010 case X86::BI__builtin_ia32_ucmpb512_mask: 4011 case X86::BI__builtin_ia32_ucmpw512_mask: 4012 case X86::BI__builtin_ia32_ucmpd512_mask: 4013 case X86::BI__builtin_ia32_ucmpq512_mask: 4014 case X86::BI__builtin_ia32_vpcomub: 4015 case X86::BI__builtin_ia32_vpcomuw: 4016 case X86::BI__builtin_ia32_vpcomud: 4017 case X86::BI__builtin_ia32_vpcomuq: 4018 case X86::BI__builtin_ia32_vpcomb: 4019 case X86::BI__builtin_ia32_vpcomw: 4020 case X86::BI__builtin_ia32_vpcomd: 4021 case X86::BI__builtin_ia32_vpcomq: 4022 case X86::BI__builtin_ia32_vec_set_v8hi: 4023 case X86::BI__builtin_ia32_vec_set_v8si: 4024 i = 2; l = 0; u = 7; 4025 break; 4026 case X86::BI__builtin_ia32_vpermilpd256: 4027 case X86::BI__builtin_ia32_roundps: 4028 case X86::BI__builtin_ia32_roundpd: 4029 case X86::BI__builtin_ia32_roundps256: 4030 case X86::BI__builtin_ia32_roundpd256: 4031 case X86::BI__builtin_ia32_getmantpd128_mask: 4032 case X86::BI__builtin_ia32_getmantpd256_mask: 4033 case X86::BI__builtin_ia32_getmantps128_mask: 4034 case X86::BI__builtin_ia32_getmantps256_mask: 4035 case X86::BI__builtin_ia32_getmantpd512_mask: 4036 case X86::BI__builtin_ia32_getmantps512_mask: 4037 case X86::BI__builtin_ia32_vec_ext_v16qi: 4038 case X86::BI__builtin_ia32_vec_ext_v16hi: 4039 i = 1; l = 0; u = 15; 4040 break; 4041 case X86::BI__builtin_ia32_pblendd128: 4042 case X86::BI__builtin_ia32_blendps: 4043 case X86::BI__builtin_ia32_blendpd256: 4044 case X86::BI__builtin_ia32_shufpd256: 4045 case X86::BI__builtin_ia32_roundss: 4046 case X86::BI__builtin_ia32_roundsd: 4047 case X86::BI__builtin_ia32_rangepd128_mask: 4048 case X86::BI__builtin_ia32_rangepd256_mask: 4049 case X86::BI__builtin_ia32_rangepd512_mask: 4050 case X86::BI__builtin_ia32_rangeps128_mask: 4051 case X86::BI__builtin_ia32_rangeps256_mask: 4052 case X86::BI__builtin_ia32_rangeps512_mask: 4053 case X86::BI__builtin_ia32_getmantsd_round_mask: 4054 case X86::BI__builtin_ia32_getmantss_round_mask: 4055 case X86::BI__builtin_ia32_vec_set_v16qi: 4056 case X86::BI__builtin_ia32_vec_set_v16hi: 4057 i = 2; l = 0; u = 15; 4058 break; 4059 case X86::BI__builtin_ia32_vec_ext_v32qi: 4060 i = 1; l = 0; u = 31; 4061 break; 4062 case X86::BI__builtin_ia32_cmpps: 4063 case X86::BI__builtin_ia32_cmpss: 4064 case X86::BI__builtin_ia32_cmppd: 4065 case X86::BI__builtin_ia32_cmpsd: 4066 case X86::BI__builtin_ia32_cmpps256: 4067 case X86::BI__builtin_ia32_cmppd256: 4068 case X86::BI__builtin_ia32_cmpps128_mask: 4069 case X86::BI__builtin_ia32_cmppd128_mask: 4070 case X86::BI__builtin_ia32_cmpps256_mask: 4071 case X86::BI__builtin_ia32_cmppd256_mask: 4072 case X86::BI__builtin_ia32_cmpps512_mask: 4073 case X86::BI__builtin_ia32_cmppd512_mask: 4074 case X86::BI__builtin_ia32_cmpsd_mask: 4075 case X86::BI__builtin_ia32_cmpss_mask: 4076 case X86::BI__builtin_ia32_vec_set_v32qi: 4077 i = 2; l = 0; u = 31; 4078 break; 4079 case X86::BI__builtin_ia32_permdf256: 4080 case X86::BI__builtin_ia32_permdi256: 4081 case X86::BI__builtin_ia32_permdf512: 4082 case X86::BI__builtin_ia32_permdi512: 4083 case X86::BI__builtin_ia32_vpermilps: 4084 case X86::BI__builtin_ia32_vpermilps256: 4085 case X86::BI__builtin_ia32_vpermilpd512: 4086 case X86::BI__builtin_ia32_vpermilps512: 4087 case X86::BI__builtin_ia32_pshufd: 4088 case X86::BI__builtin_ia32_pshufd256: 4089 case X86::BI__builtin_ia32_pshufd512: 4090 case X86::BI__builtin_ia32_pshufhw: 4091 case X86::BI__builtin_ia32_pshufhw256: 4092 case X86::BI__builtin_ia32_pshufhw512: 4093 case X86::BI__builtin_ia32_pshuflw: 4094 case X86::BI__builtin_ia32_pshuflw256: 4095 case X86::BI__builtin_ia32_pshuflw512: 4096 case X86::BI__builtin_ia32_vcvtps2ph: 4097 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4098 case X86::BI__builtin_ia32_vcvtps2ph256: 4099 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4100 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4101 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4102 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4103 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4104 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4105 case X86::BI__builtin_ia32_rndscaleps_mask: 4106 case X86::BI__builtin_ia32_rndscalepd_mask: 4107 case X86::BI__builtin_ia32_reducepd128_mask: 4108 case X86::BI__builtin_ia32_reducepd256_mask: 4109 case X86::BI__builtin_ia32_reducepd512_mask: 4110 case X86::BI__builtin_ia32_reduceps128_mask: 4111 case X86::BI__builtin_ia32_reduceps256_mask: 4112 case X86::BI__builtin_ia32_reduceps512_mask: 4113 case X86::BI__builtin_ia32_prold512: 4114 case X86::BI__builtin_ia32_prolq512: 4115 case X86::BI__builtin_ia32_prold128: 4116 case X86::BI__builtin_ia32_prold256: 4117 case X86::BI__builtin_ia32_prolq128: 4118 case X86::BI__builtin_ia32_prolq256: 4119 case X86::BI__builtin_ia32_prord512: 4120 case X86::BI__builtin_ia32_prorq512: 4121 case X86::BI__builtin_ia32_prord128: 4122 case X86::BI__builtin_ia32_prord256: 4123 case X86::BI__builtin_ia32_prorq128: 4124 case X86::BI__builtin_ia32_prorq256: 4125 case X86::BI__builtin_ia32_fpclasspd128_mask: 4126 case X86::BI__builtin_ia32_fpclasspd256_mask: 4127 case X86::BI__builtin_ia32_fpclassps128_mask: 4128 case X86::BI__builtin_ia32_fpclassps256_mask: 4129 case X86::BI__builtin_ia32_fpclassps512_mask: 4130 case X86::BI__builtin_ia32_fpclasspd512_mask: 4131 case X86::BI__builtin_ia32_fpclasssd_mask: 4132 case X86::BI__builtin_ia32_fpclassss_mask: 4133 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4134 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4135 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4136 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4137 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4138 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4139 case X86::BI__builtin_ia32_kshiftliqi: 4140 case X86::BI__builtin_ia32_kshiftlihi: 4141 case X86::BI__builtin_ia32_kshiftlisi: 4142 case X86::BI__builtin_ia32_kshiftlidi: 4143 case X86::BI__builtin_ia32_kshiftriqi: 4144 case X86::BI__builtin_ia32_kshiftrihi: 4145 case X86::BI__builtin_ia32_kshiftrisi: 4146 case X86::BI__builtin_ia32_kshiftridi: 4147 i = 1; l = 0; u = 255; 4148 break; 4149 case X86::BI__builtin_ia32_vperm2f128_pd256: 4150 case X86::BI__builtin_ia32_vperm2f128_ps256: 4151 case X86::BI__builtin_ia32_vperm2f128_si256: 4152 case X86::BI__builtin_ia32_permti256: 4153 case X86::BI__builtin_ia32_pblendw128: 4154 case X86::BI__builtin_ia32_pblendw256: 4155 case X86::BI__builtin_ia32_blendps256: 4156 case X86::BI__builtin_ia32_pblendd256: 4157 case X86::BI__builtin_ia32_palignr128: 4158 case X86::BI__builtin_ia32_palignr256: 4159 case X86::BI__builtin_ia32_palignr512: 4160 case X86::BI__builtin_ia32_alignq512: 4161 case X86::BI__builtin_ia32_alignd512: 4162 case X86::BI__builtin_ia32_alignd128: 4163 case X86::BI__builtin_ia32_alignd256: 4164 case X86::BI__builtin_ia32_alignq128: 4165 case X86::BI__builtin_ia32_alignq256: 4166 case X86::BI__builtin_ia32_vcomisd: 4167 case X86::BI__builtin_ia32_vcomiss: 4168 case X86::BI__builtin_ia32_shuf_f32x4: 4169 case X86::BI__builtin_ia32_shuf_f64x2: 4170 case X86::BI__builtin_ia32_shuf_i32x4: 4171 case X86::BI__builtin_ia32_shuf_i64x2: 4172 case X86::BI__builtin_ia32_shufpd512: 4173 case X86::BI__builtin_ia32_shufps: 4174 case X86::BI__builtin_ia32_shufps256: 4175 case X86::BI__builtin_ia32_shufps512: 4176 case X86::BI__builtin_ia32_dbpsadbw128: 4177 case X86::BI__builtin_ia32_dbpsadbw256: 4178 case X86::BI__builtin_ia32_dbpsadbw512: 4179 case X86::BI__builtin_ia32_vpshldd128: 4180 case X86::BI__builtin_ia32_vpshldd256: 4181 case X86::BI__builtin_ia32_vpshldd512: 4182 case X86::BI__builtin_ia32_vpshldq128: 4183 case X86::BI__builtin_ia32_vpshldq256: 4184 case X86::BI__builtin_ia32_vpshldq512: 4185 case X86::BI__builtin_ia32_vpshldw128: 4186 case X86::BI__builtin_ia32_vpshldw256: 4187 case X86::BI__builtin_ia32_vpshldw512: 4188 case X86::BI__builtin_ia32_vpshrdd128: 4189 case X86::BI__builtin_ia32_vpshrdd256: 4190 case X86::BI__builtin_ia32_vpshrdd512: 4191 case X86::BI__builtin_ia32_vpshrdq128: 4192 case X86::BI__builtin_ia32_vpshrdq256: 4193 case X86::BI__builtin_ia32_vpshrdq512: 4194 case X86::BI__builtin_ia32_vpshrdw128: 4195 case X86::BI__builtin_ia32_vpshrdw256: 4196 case X86::BI__builtin_ia32_vpshrdw512: 4197 i = 2; l = 0; u = 255; 4198 break; 4199 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4200 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4201 case X86::BI__builtin_ia32_fixupimmps512_mask: 4202 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4203 case X86::BI__builtin_ia32_fixupimmsd_mask: 4204 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4205 case X86::BI__builtin_ia32_fixupimmss_mask: 4206 case X86::BI__builtin_ia32_fixupimmss_maskz: 4207 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4208 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4209 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4210 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4211 case X86::BI__builtin_ia32_fixupimmps128_mask: 4212 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4213 case X86::BI__builtin_ia32_fixupimmps256_mask: 4214 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4215 case X86::BI__builtin_ia32_pternlogd512_mask: 4216 case X86::BI__builtin_ia32_pternlogd512_maskz: 4217 case X86::BI__builtin_ia32_pternlogq512_mask: 4218 case X86::BI__builtin_ia32_pternlogq512_maskz: 4219 case X86::BI__builtin_ia32_pternlogd128_mask: 4220 case X86::BI__builtin_ia32_pternlogd128_maskz: 4221 case X86::BI__builtin_ia32_pternlogd256_mask: 4222 case X86::BI__builtin_ia32_pternlogd256_maskz: 4223 case X86::BI__builtin_ia32_pternlogq128_mask: 4224 case X86::BI__builtin_ia32_pternlogq128_maskz: 4225 case X86::BI__builtin_ia32_pternlogq256_mask: 4226 case X86::BI__builtin_ia32_pternlogq256_maskz: 4227 i = 3; l = 0; u = 255; 4228 break; 4229 case X86::BI__builtin_ia32_gatherpfdpd: 4230 case X86::BI__builtin_ia32_gatherpfdps: 4231 case X86::BI__builtin_ia32_gatherpfqpd: 4232 case X86::BI__builtin_ia32_gatherpfqps: 4233 case X86::BI__builtin_ia32_scatterpfdpd: 4234 case X86::BI__builtin_ia32_scatterpfdps: 4235 case X86::BI__builtin_ia32_scatterpfqpd: 4236 case X86::BI__builtin_ia32_scatterpfqps: 4237 i = 4; l = 2; u = 3; 4238 break; 4239 case X86::BI__builtin_ia32_reducesd_mask: 4240 case X86::BI__builtin_ia32_reducess_mask: 4241 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4242 case X86::BI__builtin_ia32_rndscaless_round_mask: 4243 i = 4; l = 0; u = 255; 4244 break; 4245 } 4246 4247 // Note that we don't force a hard error on the range check here, allowing 4248 // template-generated or macro-generated dead code to potentially have out-of- 4249 // range values. These need to code generate, but don't need to necessarily 4250 // make any sense. We use a warning that defaults to an error. 4251 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4252 } 4253 4254 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4255 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4256 /// Returns true when the format fits the function and the FormatStringInfo has 4257 /// been populated. 4258 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4259 FormatStringInfo *FSI) { 4260 FSI->HasVAListArg = Format->getFirstArg() == 0; 4261 FSI->FormatIdx = Format->getFormatIdx() - 1; 4262 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4263 4264 // The way the format attribute works in GCC, the implicit this argument 4265 // of member functions is counted. However, it doesn't appear in our own 4266 // lists, so decrement format_idx in that case. 4267 if (IsCXXMember) { 4268 if(FSI->FormatIdx == 0) 4269 return false; 4270 --FSI->FormatIdx; 4271 if (FSI->FirstDataArg != 0) 4272 --FSI->FirstDataArg; 4273 } 4274 return true; 4275 } 4276 4277 /// Checks if a the given expression evaluates to null. 4278 /// 4279 /// Returns true if the value evaluates to null. 4280 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4281 // If the expression has non-null type, it doesn't evaluate to null. 4282 if (auto nullability 4283 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4284 if (*nullability == NullabilityKind::NonNull) 4285 return false; 4286 } 4287 4288 // As a special case, transparent unions initialized with zero are 4289 // considered null for the purposes of the nonnull attribute. 4290 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4291 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4292 if (const CompoundLiteralExpr *CLE = 4293 dyn_cast<CompoundLiteralExpr>(Expr)) 4294 if (const InitListExpr *ILE = 4295 dyn_cast<InitListExpr>(CLE->getInitializer())) 4296 Expr = ILE->getInit(0); 4297 } 4298 4299 bool Result; 4300 return (!Expr->isValueDependent() && 4301 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4302 !Result); 4303 } 4304 4305 static void CheckNonNullArgument(Sema &S, 4306 const Expr *ArgExpr, 4307 SourceLocation CallSiteLoc) { 4308 if (CheckNonNullExpr(S, ArgExpr)) 4309 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4310 S.PDiag(diag::warn_null_arg) 4311 << ArgExpr->getSourceRange()); 4312 } 4313 4314 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4315 FormatStringInfo FSI; 4316 if ((GetFormatStringType(Format) == FST_NSString) && 4317 getFormatStringInfo(Format, false, &FSI)) { 4318 Idx = FSI.FormatIdx; 4319 return true; 4320 } 4321 return false; 4322 } 4323 4324 /// Diagnose use of %s directive in an NSString which is being passed 4325 /// as formatting string to formatting method. 4326 static void 4327 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4328 const NamedDecl *FDecl, 4329 Expr **Args, 4330 unsigned NumArgs) { 4331 unsigned Idx = 0; 4332 bool Format = false; 4333 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4334 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4335 Idx = 2; 4336 Format = true; 4337 } 4338 else 4339 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4340 if (S.GetFormatNSStringIdx(I, Idx)) { 4341 Format = true; 4342 break; 4343 } 4344 } 4345 if (!Format || NumArgs <= Idx) 4346 return; 4347 const Expr *FormatExpr = Args[Idx]; 4348 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4349 FormatExpr = CSCE->getSubExpr(); 4350 const StringLiteral *FormatString; 4351 if (const ObjCStringLiteral *OSL = 4352 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4353 FormatString = OSL->getString(); 4354 else 4355 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4356 if (!FormatString) 4357 return; 4358 if (S.FormatStringHasSArg(FormatString)) { 4359 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4360 << "%s" << 1 << 1; 4361 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4362 << FDecl->getDeclName(); 4363 } 4364 } 4365 4366 /// Determine whether the given type has a non-null nullability annotation. 4367 static bool isNonNullType(ASTContext &ctx, QualType type) { 4368 if (auto nullability = type->getNullability(ctx)) 4369 return *nullability == NullabilityKind::NonNull; 4370 4371 return false; 4372 } 4373 4374 static void CheckNonNullArguments(Sema &S, 4375 const NamedDecl *FDecl, 4376 const FunctionProtoType *Proto, 4377 ArrayRef<const Expr *> Args, 4378 SourceLocation CallSiteLoc) { 4379 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4380 4381 // Already checked by by constant evaluator. 4382 if (S.isConstantEvaluated()) 4383 return; 4384 // Check the attributes attached to the method/function itself. 4385 llvm::SmallBitVector NonNullArgs; 4386 if (FDecl) { 4387 // Handle the nonnull attribute on the function/method declaration itself. 4388 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4389 if (!NonNull->args_size()) { 4390 // Easy case: all pointer arguments are nonnull. 4391 for (const auto *Arg : Args) 4392 if (S.isValidPointerAttrType(Arg->getType())) 4393 CheckNonNullArgument(S, Arg, CallSiteLoc); 4394 return; 4395 } 4396 4397 for (const ParamIdx &Idx : NonNull->args()) { 4398 unsigned IdxAST = Idx.getASTIndex(); 4399 if (IdxAST >= Args.size()) 4400 continue; 4401 if (NonNullArgs.empty()) 4402 NonNullArgs.resize(Args.size()); 4403 NonNullArgs.set(IdxAST); 4404 } 4405 } 4406 } 4407 4408 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4409 // Handle the nonnull attribute on the parameters of the 4410 // function/method. 4411 ArrayRef<ParmVarDecl*> parms; 4412 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4413 parms = FD->parameters(); 4414 else 4415 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4416 4417 unsigned ParamIndex = 0; 4418 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4419 I != E; ++I, ++ParamIndex) { 4420 const ParmVarDecl *PVD = *I; 4421 if (PVD->hasAttr<NonNullAttr>() || 4422 isNonNullType(S.Context, PVD->getType())) { 4423 if (NonNullArgs.empty()) 4424 NonNullArgs.resize(Args.size()); 4425 4426 NonNullArgs.set(ParamIndex); 4427 } 4428 } 4429 } else { 4430 // If we have a non-function, non-method declaration but no 4431 // function prototype, try to dig out the function prototype. 4432 if (!Proto) { 4433 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4434 QualType type = VD->getType().getNonReferenceType(); 4435 if (auto pointerType = type->getAs<PointerType>()) 4436 type = pointerType->getPointeeType(); 4437 else if (auto blockType = type->getAs<BlockPointerType>()) 4438 type = blockType->getPointeeType(); 4439 // FIXME: data member pointers? 4440 4441 // Dig out the function prototype, if there is one. 4442 Proto = type->getAs<FunctionProtoType>(); 4443 } 4444 } 4445 4446 // Fill in non-null argument information from the nullability 4447 // information on the parameter types (if we have them). 4448 if (Proto) { 4449 unsigned Index = 0; 4450 for (auto paramType : Proto->getParamTypes()) { 4451 if (isNonNullType(S.Context, paramType)) { 4452 if (NonNullArgs.empty()) 4453 NonNullArgs.resize(Args.size()); 4454 4455 NonNullArgs.set(Index); 4456 } 4457 4458 ++Index; 4459 } 4460 } 4461 } 4462 4463 // Check for non-null arguments. 4464 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4465 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4466 if (NonNullArgs[ArgIndex]) 4467 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4468 } 4469 } 4470 4471 /// Warn if a pointer or reference argument passed to a function points to an 4472 /// object that is less aligned than the parameter. This can happen when 4473 /// creating a typedef with a lower alignment than the original type and then 4474 /// calling functions defined in terms of the original type. 4475 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4476 StringRef ParamName, QualType ArgTy, 4477 QualType ParamTy) { 4478 4479 // If a function accepts a pointer or reference type 4480 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4481 return; 4482 4483 // If the parameter is a pointer type, get the pointee type for the 4484 // argument too. If the parameter is a reference type, don't try to get 4485 // the pointee type for the argument. 4486 if (ParamTy->isPointerType()) 4487 ArgTy = ArgTy->getPointeeType(); 4488 4489 // Remove reference or pointer 4490 ParamTy = ParamTy->getPointeeType(); 4491 4492 // Find expected alignment, and the actual alignment of the passed object. 4493 // getTypeAlignInChars requires complete types 4494 if (ParamTy->isIncompleteType() || ArgTy->isIncompleteType()) 4495 return; 4496 4497 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 4498 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 4499 4500 // If the argument is less aligned than the parameter, there is a 4501 // potential alignment issue. 4502 if (ArgAlign < ParamAlign) 4503 Diag(Loc, diag::warn_param_mismatched_alignment) 4504 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 4505 << ParamName << FDecl; 4506 } 4507 4508 /// Handles the checks for format strings, non-POD arguments to vararg 4509 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4510 /// attributes. 4511 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4512 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4513 bool IsMemberFunction, SourceLocation Loc, 4514 SourceRange Range, VariadicCallType CallType) { 4515 // FIXME: We should check as much as we can in the template definition. 4516 if (CurContext->isDependentContext()) 4517 return; 4518 4519 // Printf and scanf checking. 4520 llvm::SmallBitVector CheckedVarArgs; 4521 if (FDecl) { 4522 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4523 // Only create vector if there are format attributes. 4524 CheckedVarArgs.resize(Args.size()); 4525 4526 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4527 CheckedVarArgs); 4528 } 4529 } 4530 4531 // Refuse POD arguments that weren't caught by the format string 4532 // checks above. 4533 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4534 if (CallType != VariadicDoesNotApply && 4535 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4536 unsigned NumParams = Proto ? Proto->getNumParams() 4537 : FDecl && isa<FunctionDecl>(FDecl) 4538 ? cast<FunctionDecl>(FDecl)->getNumParams() 4539 : FDecl && isa<ObjCMethodDecl>(FDecl) 4540 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4541 : 0; 4542 4543 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4544 // Args[ArgIdx] can be null in malformed code. 4545 if (const Expr *Arg = Args[ArgIdx]) { 4546 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4547 checkVariadicArgument(Arg, CallType); 4548 } 4549 } 4550 } 4551 4552 if (FDecl || Proto) { 4553 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4554 4555 // Type safety checking. 4556 if (FDecl) { 4557 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4558 CheckArgumentWithTypeTag(I, Args, Loc); 4559 } 4560 } 4561 4562 // Check that passed arguments match the alignment of original arguments. 4563 // Try to get the missing prototype from the declaration. 4564 if (!Proto && FDecl) { 4565 const auto *FT = FDecl->getFunctionType(); 4566 if (isa_and_nonnull<FunctionProtoType>(FT)) 4567 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 4568 } 4569 if (Proto) { 4570 // For variadic functions, we may have more args than parameters. 4571 // For some K&R functions, we may have less args than parameters. 4572 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 4573 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 4574 // Args[ArgIdx] can be null in malformed code. 4575 if (const Expr *Arg = Args[ArgIdx]) { 4576 QualType ParamTy = Proto->getParamType(ArgIdx); 4577 QualType ArgTy = Arg->getType(); 4578 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 4579 ArgTy, ParamTy); 4580 } 4581 } 4582 } 4583 4584 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4585 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4586 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4587 if (!Arg->isValueDependent()) { 4588 Expr::EvalResult Align; 4589 if (Arg->EvaluateAsInt(Align, Context)) { 4590 const llvm::APSInt &I = Align.Val.getInt(); 4591 if (!I.isPowerOf2()) 4592 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4593 << Arg->getSourceRange(); 4594 4595 if (I > Sema::MaximumAlignment) 4596 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4597 << Arg->getSourceRange() << Sema::MaximumAlignment; 4598 } 4599 } 4600 } 4601 4602 if (FD) 4603 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4604 } 4605 4606 /// CheckConstructorCall - Check a constructor call for correctness and safety 4607 /// properties not enforced by the C type system. 4608 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 4609 ArrayRef<const Expr *> Args, 4610 const FunctionProtoType *Proto, 4611 SourceLocation Loc) { 4612 VariadicCallType CallType = 4613 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4614 4615 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 4616 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 4617 Context.getPointerType(Ctor->getThisObjectType())); 4618 4619 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4620 Loc, SourceRange(), CallType); 4621 } 4622 4623 /// CheckFunctionCall - Check a direct function call for various correctness 4624 /// and safety properties not strictly enforced by the C type system. 4625 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4626 const FunctionProtoType *Proto) { 4627 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4628 isa<CXXMethodDecl>(FDecl); 4629 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4630 IsMemberOperatorCall; 4631 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4632 TheCall->getCallee()); 4633 Expr** Args = TheCall->getArgs(); 4634 unsigned NumArgs = TheCall->getNumArgs(); 4635 4636 Expr *ImplicitThis = nullptr; 4637 if (IsMemberOperatorCall) { 4638 // If this is a call to a member operator, hide the first argument 4639 // from checkCall. 4640 // FIXME: Our choice of AST representation here is less than ideal. 4641 ImplicitThis = Args[0]; 4642 ++Args; 4643 --NumArgs; 4644 } else if (IsMemberFunction) 4645 ImplicitThis = 4646 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4647 4648 if (ImplicitThis) { 4649 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 4650 // used. 4651 QualType ThisType = ImplicitThis->getType(); 4652 if (!ThisType->isPointerType()) { 4653 assert(!ThisType->isReferenceType()); 4654 ThisType = Context.getPointerType(ThisType); 4655 } 4656 4657 QualType ThisTypeFromDecl = 4658 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 4659 4660 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 4661 ThisTypeFromDecl); 4662 } 4663 4664 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4665 IsMemberFunction, TheCall->getRParenLoc(), 4666 TheCall->getCallee()->getSourceRange(), CallType); 4667 4668 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4669 // None of the checks below are needed for functions that don't have 4670 // simple names (e.g., C++ conversion functions). 4671 if (!FnInfo) 4672 return false; 4673 4674 CheckTCBEnforcement(TheCall, FDecl); 4675 4676 CheckAbsoluteValueFunction(TheCall, FDecl); 4677 CheckMaxUnsignedZero(TheCall, FDecl); 4678 4679 if (getLangOpts().ObjC) 4680 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4681 4682 unsigned CMId = FDecl->getMemoryFunctionKind(); 4683 4684 // Handle memory setting and copying functions. 4685 switch (CMId) { 4686 case 0: 4687 return false; 4688 case Builtin::BIstrlcpy: // fallthrough 4689 case Builtin::BIstrlcat: 4690 CheckStrlcpycatArguments(TheCall, FnInfo); 4691 break; 4692 case Builtin::BIstrncat: 4693 CheckStrncatArguments(TheCall, FnInfo); 4694 break; 4695 case Builtin::BIfree: 4696 CheckFreeArguments(TheCall); 4697 break; 4698 default: 4699 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4700 } 4701 4702 return false; 4703 } 4704 4705 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4706 ArrayRef<const Expr *> Args) { 4707 VariadicCallType CallType = 4708 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4709 4710 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4711 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4712 CallType); 4713 4714 return false; 4715 } 4716 4717 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4718 const FunctionProtoType *Proto) { 4719 QualType Ty; 4720 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4721 Ty = V->getType().getNonReferenceType(); 4722 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4723 Ty = F->getType().getNonReferenceType(); 4724 else 4725 return false; 4726 4727 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4728 !Ty->isFunctionProtoType()) 4729 return false; 4730 4731 VariadicCallType CallType; 4732 if (!Proto || !Proto->isVariadic()) { 4733 CallType = VariadicDoesNotApply; 4734 } else if (Ty->isBlockPointerType()) { 4735 CallType = VariadicBlock; 4736 } else { // Ty->isFunctionPointerType() 4737 CallType = VariadicFunction; 4738 } 4739 4740 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4741 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4742 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4743 TheCall->getCallee()->getSourceRange(), CallType); 4744 4745 return false; 4746 } 4747 4748 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4749 /// such as function pointers returned from functions. 4750 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4751 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4752 TheCall->getCallee()); 4753 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4754 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4755 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4756 TheCall->getCallee()->getSourceRange(), CallType); 4757 4758 return false; 4759 } 4760 4761 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4762 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4763 return false; 4764 4765 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4766 switch (Op) { 4767 case AtomicExpr::AO__c11_atomic_init: 4768 case AtomicExpr::AO__opencl_atomic_init: 4769 llvm_unreachable("There is no ordering argument for an init"); 4770 4771 case AtomicExpr::AO__c11_atomic_load: 4772 case AtomicExpr::AO__opencl_atomic_load: 4773 case AtomicExpr::AO__atomic_load_n: 4774 case AtomicExpr::AO__atomic_load: 4775 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4776 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4777 4778 case AtomicExpr::AO__c11_atomic_store: 4779 case AtomicExpr::AO__opencl_atomic_store: 4780 case AtomicExpr::AO__atomic_store: 4781 case AtomicExpr::AO__atomic_store_n: 4782 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4783 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4784 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4785 4786 default: 4787 return true; 4788 } 4789 } 4790 4791 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4792 AtomicExpr::AtomicOp Op) { 4793 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4794 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4795 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4796 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4797 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4798 Op); 4799 } 4800 4801 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4802 SourceLocation RParenLoc, MultiExprArg Args, 4803 AtomicExpr::AtomicOp Op, 4804 AtomicArgumentOrder ArgOrder) { 4805 // All the non-OpenCL operations take one of the following forms. 4806 // The OpenCL operations take the __c11 forms with one extra argument for 4807 // synchronization scope. 4808 enum { 4809 // C __c11_atomic_init(A *, C) 4810 Init, 4811 4812 // C __c11_atomic_load(A *, int) 4813 Load, 4814 4815 // void __atomic_load(A *, CP, int) 4816 LoadCopy, 4817 4818 // void __atomic_store(A *, CP, int) 4819 Copy, 4820 4821 // C __c11_atomic_add(A *, M, int) 4822 Arithmetic, 4823 4824 // C __atomic_exchange_n(A *, CP, int) 4825 Xchg, 4826 4827 // void __atomic_exchange(A *, C *, CP, int) 4828 GNUXchg, 4829 4830 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4831 C11CmpXchg, 4832 4833 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4834 GNUCmpXchg 4835 } Form = Init; 4836 4837 const unsigned NumForm = GNUCmpXchg + 1; 4838 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4839 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4840 // where: 4841 // C is an appropriate type, 4842 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4843 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4844 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4845 // the int parameters are for orderings. 4846 4847 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4848 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4849 "need to update code for modified forms"); 4850 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4851 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4852 AtomicExpr::AO__atomic_load, 4853 "need to update code for modified C11 atomics"); 4854 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4855 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4856 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4857 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4858 IsOpenCL; 4859 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4860 Op == AtomicExpr::AO__atomic_store_n || 4861 Op == AtomicExpr::AO__atomic_exchange_n || 4862 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4863 bool IsAddSub = false; 4864 4865 switch (Op) { 4866 case AtomicExpr::AO__c11_atomic_init: 4867 case AtomicExpr::AO__opencl_atomic_init: 4868 Form = Init; 4869 break; 4870 4871 case AtomicExpr::AO__c11_atomic_load: 4872 case AtomicExpr::AO__opencl_atomic_load: 4873 case AtomicExpr::AO__atomic_load_n: 4874 Form = Load; 4875 break; 4876 4877 case AtomicExpr::AO__atomic_load: 4878 Form = LoadCopy; 4879 break; 4880 4881 case AtomicExpr::AO__c11_atomic_store: 4882 case AtomicExpr::AO__opencl_atomic_store: 4883 case AtomicExpr::AO__atomic_store: 4884 case AtomicExpr::AO__atomic_store_n: 4885 Form = Copy; 4886 break; 4887 4888 case AtomicExpr::AO__c11_atomic_fetch_add: 4889 case AtomicExpr::AO__c11_atomic_fetch_sub: 4890 case AtomicExpr::AO__opencl_atomic_fetch_add: 4891 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4892 case AtomicExpr::AO__atomic_fetch_add: 4893 case AtomicExpr::AO__atomic_fetch_sub: 4894 case AtomicExpr::AO__atomic_add_fetch: 4895 case AtomicExpr::AO__atomic_sub_fetch: 4896 IsAddSub = true; 4897 LLVM_FALLTHROUGH; 4898 case AtomicExpr::AO__c11_atomic_fetch_and: 4899 case AtomicExpr::AO__c11_atomic_fetch_or: 4900 case AtomicExpr::AO__c11_atomic_fetch_xor: 4901 case AtomicExpr::AO__opencl_atomic_fetch_and: 4902 case AtomicExpr::AO__opencl_atomic_fetch_or: 4903 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4904 case AtomicExpr::AO__atomic_fetch_and: 4905 case AtomicExpr::AO__atomic_fetch_or: 4906 case AtomicExpr::AO__atomic_fetch_xor: 4907 case AtomicExpr::AO__atomic_fetch_nand: 4908 case AtomicExpr::AO__atomic_and_fetch: 4909 case AtomicExpr::AO__atomic_or_fetch: 4910 case AtomicExpr::AO__atomic_xor_fetch: 4911 case AtomicExpr::AO__atomic_nand_fetch: 4912 case AtomicExpr::AO__c11_atomic_fetch_min: 4913 case AtomicExpr::AO__c11_atomic_fetch_max: 4914 case AtomicExpr::AO__opencl_atomic_fetch_min: 4915 case AtomicExpr::AO__opencl_atomic_fetch_max: 4916 case AtomicExpr::AO__atomic_min_fetch: 4917 case AtomicExpr::AO__atomic_max_fetch: 4918 case AtomicExpr::AO__atomic_fetch_min: 4919 case AtomicExpr::AO__atomic_fetch_max: 4920 Form = Arithmetic; 4921 break; 4922 4923 case AtomicExpr::AO__c11_atomic_exchange: 4924 case AtomicExpr::AO__opencl_atomic_exchange: 4925 case AtomicExpr::AO__atomic_exchange_n: 4926 Form = Xchg; 4927 break; 4928 4929 case AtomicExpr::AO__atomic_exchange: 4930 Form = GNUXchg; 4931 break; 4932 4933 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4934 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4935 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4936 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4937 Form = C11CmpXchg; 4938 break; 4939 4940 case AtomicExpr::AO__atomic_compare_exchange: 4941 case AtomicExpr::AO__atomic_compare_exchange_n: 4942 Form = GNUCmpXchg; 4943 break; 4944 } 4945 4946 unsigned AdjustedNumArgs = NumArgs[Form]; 4947 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4948 ++AdjustedNumArgs; 4949 // Check we have the right number of arguments. 4950 if (Args.size() < AdjustedNumArgs) { 4951 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4952 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4953 << ExprRange; 4954 return ExprError(); 4955 } else if (Args.size() > AdjustedNumArgs) { 4956 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4957 diag::err_typecheck_call_too_many_args) 4958 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4959 << ExprRange; 4960 return ExprError(); 4961 } 4962 4963 // Inspect the first argument of the atomic operation. 4964 Expr *Ptr = Args[0]; 4965 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4966 if (ConvertedPtr.isInvalid()) 4967 return ExprError(); 4968 4969 Ptr = ConvertedPtr.get(); 4970 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4971 if (!pointerType) { 4972 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4973 << Ptr->getType() << Ptr->getSourceRange(); 4974 return ExprError(); 4975 } 4976 4977 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4978 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4979 QualType ValType = AtomTy; // 'C' 4980 if (IsC11) { 4981 if (!AtomTy->isAtomicType()) { 4982 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4983 << Ptr->getType() << Ptr->getSourceRange(); 4984 return ExprError(); 4985 } 4986 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4987 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4988 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4989 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4990 << Ptr->getSourceRange(); 4991 return ExprError(); 4992 } 4993 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4994 } else if (Form != Load && Form != LoadCopy) { 4995 if (ValType.isConstQualified()) { 4996 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4997 << Ptr->getType() << Ptr->getSourceRange(); 4998 return ExprError(); 4999 } 5000 } 5001 5002 // For an arithmetic operation, the implied arithmetic must be well-formed. 5003 if (Form == Arithmetic) { 5004 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 5005 if (IsAddSub && !ValType->isIntegerType() 5006 && !ValType->isPointerType()) { 5007 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5008 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5009 return ExprError(); 5010 } 5011 if (!IsAddSub && !ValType->isIntegerType()) { 5012 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5013 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5014 return ExprError(); 5015 } 5016 if (IsC11 && ValType->isPointerType() && 5017 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5018 diag::err_incomplete_type)) { 5019 return ExprError(); 5020 } 5021 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5022 // For __atomic_*_n operations, the value type must be a scalar integral or 5023 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5024 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5025 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5026 return ExprError(); 5027 } 5028 5029 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5030 !AtomTy->isScalarType()) { 5031 // For GNU atomics, require a trivially-copyable type. This is not part of 5032 // the GNU atomics specification, but we enforce it for sanity. 5033 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5034 << Ptr->getType() << Ptr->getSourceRange(); 5035 return ExprError(); 5036 } 5037 5038 switch (ValType.getObjCLifetime()) { 5039 case Qualifiers::OCL_None: 5040 case Qualifiers::OCL_ExplicitNone: 5041 // okay 5042 break; 5043 5044 case Qualifiers::OCL_Weak: 5045 case Qualifiers::OCL_Strong: 5046 case Qualifiers::OCL_Autoreleasing: 5047 // FIXME: Can this happen? By this point, ValType should be known 5048 // to be trivially copyable. 5049 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5050 << ValType << Ptr->getSourceRange(); 5051 return ExprError(); 5052 } 5053 5054 // All atomic operations have an overload which takes a pointer to a volatile 5055 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5056 // into the result or the other operands. Similarly atomic_load takes a 5057 // pointer to a const 'A'. 5058 ValType.removeLocalVolatile(); 5059 ValType.removeLocalConst(); 5060 QualType ResultType = ValType; 5061 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5062 Form == Init) 5063 ResultType = Context.VoidTy; 5064 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5065 ResultType = Context.BoolTy; 5066 5067 // The type of a parameter passed 'by value'. In the GNU atomics, such 5068 // arguments are actually passed as pointers. 5069 QualType ByValType = ValType; // 'CP' 5070 bool IsPassedByAddress = false; 5071 if (!IsC11 && !IsN) { 5072 ByValType = Ptr->getType(); 5073 IsPassedByAddress = true; 5074 } 5075 5076 SmallVector<Expr *, 5> APIOrderedArgs; 5077 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5078 APIOrderedArgs.push_back(Args[0]); 5079 switch (Form) { 5080 case Init: 5081 case Load: 5082 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5083 break; 5084 case LoadCopy: 5085 case Copy: 5086 case Arithmetic: 5087 case Xchg: 5088 APIOrderedArgs.push_back(Args[2]); // Val1 5089 APIOrderedArgs.push_back(Args[1]); // Order 5090 break; 5091 case GNUXchg: 5092 APIOrderedArgs.push_back(Args[2]); // Val1 5093 APIOrderedArgs.push_back(Args[3]); // Val2 5094 APIOrderedArgs.push_back(Args[1]); // Order 5095 break; 5096 case C11CmpXchg: 5097 APIOrderedArgs.push_back(Args[2]); // Val1 5098 APIOrderedArgs.push_back(Args[4]); // Val2 5099 APIOrderedArgs.push_back(Args[1]); // Order 5100 APIOrderedArgs.push_back(Args[3]); // OrderFail 5101 break; 5102 case GNUCmpXchg: 5103 APIOrderedArgs.push_back(Args[2]); // Val1 5104 APIOrderedArgs.push_back(Args[4]); // Val2 5105 APIOrderedArgs.push_back(Args[5]); // Weak 5106 APIOrderedArgs.push_back(Args[1]); // Order 5107 APIOrderedArgs.push_back(Args[3]); // OrderFail 5108 break; 5109 } 5110 } else 5111 APIOrderedArgs.append(Args.begin(), Args.end()); 5112 5113 // The first argument's non-CV pointer type is used to deduce the type of 5114 // subsequent arguments, except for: 5115 // - weak flag (always converted to bool) 5116 // - memory order (always converted to int) 5117 // - scope (always converted to int) 5118 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5119 QualType Ty; 5120 if (i < NumVals[Form] + 1) { 5121 switch (i) { 5122 case 0: 5123 // The first argument is always a pointer. It has a fixed type. 5124 // It is always dereferenced, a nullptr is undefined. 5125 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5126 // Nothing else to do: we already know all we want about this pointer. 5127 continue; 5128 case 1: 5129 // The second argument is the non-atomic operand. For arithmetic, this 5130 // is always passed by value, and for a compare_exchange it is always 5131 // passed by address. For the rest, GNU uses by-address and C11 uses 5132 // by-value. 5133 assert(Form != Load); 5134 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 5135 Ty = ValType; 5136 else if (Form == Copy || Form == Xchg) { 5137 if (IsPassedByAddress) { 5138 // The value pointer is always dereferenced, a nullptr is undefined. 5139 CheckNonNullArgument(*this, APIOrderedArgs[i], 5140 ExprRange.getBegin()); 5141 } 5142 Ty = ByValType; 5143 } else if (Form == Arithmetic) 5144 Ty = Context.getPointerDiffType(); 5145 else { 5146 Expr *ValArg = APIOrderedArgs[i]; 5147 // The value pointer is always dereferenced, a nullptr is undefined. 5148 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5149 LangAS AS = LangAS::Default; 5150 // Keep address space of non-atomic pointer type. 5151 if (const PointerType *PtrTy = 5152 ValArg->getType()->getAs<PointerType>()) { 5153 AS = PtrTy->getPointeeType().getAddressSpace(); 5154 } 5155 Ty = Context.getPointerType( 5156 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5157 } 5158 break; 5159 case 2: 5160 // The third argument to compare_exchange / GNU exchange is the desired 5161 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5162 if (IsPassedByAddress) 5163 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5164 Ty = ByValType; 5165 break; 5166 case 3: 5167 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5168 Ty = Context.BoolTy; 5169 break; 5170 } 5171 } else { 5172 // The order(s) and scope are always converted to int. 5173 Ty = Context.IntTy; 5174 } 5175 5176 InitializedEntity Entity = 5177 InitializedEntity::InitializeParameter(Context, Ty, false); 5178 ExprResult Arg = APIOrderedArgs[i]; 5179 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5180 if (Arg.isInvalid()) 5181 return true; 5182 APIOrderedArgs[i] = Arg.get(); 5183 } 5184 5185 // Permute the arguments into a 'consistent' order. 5186 SmallVector<Expr*, 5> SubExprs; 5187 SubExprs.push_back(Ptr); 5188 switch (Form) { 5189 case Init: 5190 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5191 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5192 break; 5193 case Load: 5194 SubExprs.push_back(APIOrderedArgs[1]); // Order 5195 break; 5196 case LoadCopy: 5197 case Copy: 5198 case Arithmetic: 5199 case Xchg: 5200 SubExprs.push_back(APIOrderedArgs[2]); // Order 5201 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5202 break; 5203 case GNUXchg: 5204 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5205 SubExprs.push_back(APIOrderedArgs[3]); // Order 5206 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5207 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5208 break; 5209 case C11CmpXchg: 5210 SubExprs.push_back(APIOrderedArgs[3]); // Order 5211 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5212 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5213 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5214 break; 5215 case GNUCmpXchg: 5216 SubExprs.push_back(APIOrderedArgs[4]); // Order 5217 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5218 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5219 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5220 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5221 break; 5222 } 5223 5224 if (SubExprs.size() >= 2 && Form != Init) { 5225 if (Optional<llvm::APSInt> Result = 5226 SubExprs[1]->getIntegerConstantExpr(Context)) 5227 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5228 Diag(SubExprs[1]->getBeginLoc(), 5229 diag::warn_atomic_op_has_invalid_memory_order) 5230 << SubExprs[1]->getSourceRange(); 5231 } 5232 5233 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5234 auto *Scope = Args[Args.size() - 1]; 5235 if (Optional<llvm::APSInt> Result = 5236 Scope->getIntegerConstantExpr(Context)) { 5237 if (!ScopeModel->isValid(Result->getZExtValue())) 5238 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5239 << Scope->getSourceRange(); 5240 } 5241 SubExprs.push_back(Scope); 5242 } 5243 5244 AtomicExpr *AE = new (Context) 5245 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5246 5247 if ((Op == AtomicExpr::AO__c11_atomic_load || 5248 Op == AtomicExpr::AO__c11_atomic_store || 5249 Op == AtomicExpr::AO__opencl_atomic_load || 5250 Op == AtomicExpr::AO__opencl_atomic_store ) && 5251 Context.AtomicUsesUnsupportedLibcall(AE)) 5252 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5253 << ((Op == AtomicExpr::AO__c11_atomic_load || 5254 Op == AtomicExpr::AO__opencl_atomic_load) 5255 ? 0 5256 : 1); 5257 5258 if (ValType->isExtIntType()) { 5259 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5260 return ExprError(); 5261 } 5262 5263 return AE; 5264 } 5265 5266 /// checkBuiltinArgument - Given a call to a builtin function, perform 5267 /// normal type-checking on the given argument, updating the call in 5268 /// place. This is useful when a builtin function requires custom 5269 /// type-checking for some of its arguments but not necessarily all of 5270 /// them. 5271 /// 5272 /// Returns true on error. 5273 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5274 FunctionDecl *Fn = E->getDirectCallee(); 5275 assert(Fn && "builtin call without direct callee!"); 5276 5277 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5278 InitializedEntity Entity = 5279 InitializedEntity::InitializeParameter(S.Context, Param); 5280 5281 ExprResult Arg = E->getArg(0); 5282 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5283 if (Arg.isInvalid()) 5284 return true; 5285 5286 E->setArg(ArgIndex, Arg.get()); 5287 return false; 5288 } 5289 5290 /// We have a call to a function like __sync_fetch_and_add, which is an 5291 /// overloaded function based on the pointer type of its first argument. 5292 /// The main BuildCallExpr routines have already promoted the types of 5293 /// arguments because all of these calls are prototyped as void(...). 5294 /// 5295 /// This function goes through and does final semantic checking for these 5296 /// builtins, as well as generating any warnings. 5297 ExprResult 5298 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5299 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5300 Expr *Callee = TheCall->getCallee(); 5301 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5302 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5303 5304 // Ensure that we have at least one argument to do type inference from. 5305 if (TheCall->getNumArgs() < 1) { 5306 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5307 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5308 return ExprError(); 5309 } 5310 5311 // Inspect the first argument of the atomic builtin. This should always be 5312 // a pointer type, whose element is an integral scalar or pointer type. 5313 // Because it is a pointer type, we don't have to worry about any implicit 5314 // casts here. 5315 // FIXME: We don't allow floating point scalars as input. 5316 Expr *FirstArg = TheCall->getArg(0); 5317 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5318 if (FirstArgResult.isInvalid()) 5319 return ExprError(); 5320 FirstArg = FirstArgResult.get(); 5321 TheCall->setArg(0, FirstArg); 5322 5323 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5324 if (!pointerType) { 5325 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5326 << FirstArg->getType() << FirstArg->getSourceRange(); 5327 return ExprError(); 5328 } 5329 5330 QualType ValType = pointerType->getPointeeType(); 5331 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5332 !ValType->isBlockPointerType()) { 5333 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5334 << FirstArg->getType() << FirstArg->getSourceRange(); 5335 return ExprError(); 5336 } 5337 5338 if (ValType.isConstQualified()) { 5339 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5340 << FirstArg->getType() << FirstArg->getSourceRange(); 5341 return ExprError(); 5342 } 5343 5344 switch (ValType.getObjCLifetime()) { 5345 case Qualifiers::OCL_None: 5346 case Qualifiers::OCL_ExplicitNone: 5347 // okay 5348 break; 5349 5350 case Qualifiers::OCL_Weak: 5351 case Qualifiers::OCL_Strong: 5352 case Qualifiers::OCL_Autoreleasing: 5353 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5354 << ValType << FirstArg->getSourceRange(); 5355 return ExprError(); 5356 } 5357 5358 // Strip any qualifiers off ValType. 5359 ValType = ValType.getUnqualifiedType(); 5360 5361 // The majority of builtins return a value, but a few have special return 5362 // types, so allow them to override appropriately below. 5363 QualType ResultType = ValType; 5364 5365 // We need to figure out which concrete builtin this maps onto. For example, 5366 // __sync_fetch_and_add with a 2 byte object turns into 5367 // __sync_fetch_and_add_2. 5368 #define BUILTIN_ROW(x) \ 5369 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5370 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5371 5372 static const unsigned BuiltinIndices[][5] = { 5373 BUILTIN_ROW(__sync_fetch_and_add), 5374 BUILTIN_ROW(__sync_fetch_and_sub), 5375 BUILTIN_ROW(__sync_fetch_and_or), 5376 BUILTIN_ROW(__sync_fetch_and_and), 5377 BUILTIN_ROW(__sync_fetch_and_xor), 5378 BUILTIN_ROW(__sync_fetch_and_nand), 5379 5380 BUILTIN_ROW(__sync_add_and_fetch), 5381 BUILTIN_ROW(__sync_sub_and_fetch), 5382 BUILTIN_ROW(__sync_and_and_fetch), 5383 BUILTIN_ROW(__sync_or_and_fetch), 5384 BUILTIN_ROW(__sync_xor_and_fetch), 5385 BUILTIN_ROW(__sync_nand_and_fetch), 5386 5387 BUILTIN_ROW(__sync_val_compare_and_swap), 5388 BUILTIN_ROW(__sync_bool_compare_and_swap), 5389 BUILTIN_ROW(__sync_lock_test_and_set), 5390 BUILTIN_ROW(__sync_lock_release), 5391 BUILTIN_ROW(__sync_swap) 5392 }; 5393 #undef BUILTIN_ROW 5394 5395 // Determine the index of the size. 5396 unsigned SizeIndex; 5397 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5398 case 1: SizeIndex = 0; break; 5399 case 2: SizeIndex = 1; break; 5400 case 4: SizeIndex = 2; break; 5401 case 8: SizeIndex = 3; break; 5402 case 16: SizeIndex = 4; break; 5403 default: 5404 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5405 << FirstArg->getType() << FirstArg->getSourceRange(); 5406 return ExprError(); 5407 } 5408 5409 // Each of these builtins has one pointer argument, followed by some number of 5410 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5411 // that we ignore. Find out which row of BuiltinIndices to read from as well 5412 // as the number of fixed args. 5413 unsigned BuiltinID = FDecl->getBuiltinID(); 5414 unsigned BuiltinIndex, NumFixed = 1; 5415 bool WarnAboutSemanticsChange = false; 5416 switch (BuiltinID) { 5417 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5418 case Builtin::BI__sync_fetch_and_add: 5419 case Builtin::BI__sync_fetch_and_add_1: 5420 case Builtin::BI__sync_fetch_and_add_2: 5421 case Builtin::BI__sync_fetch_and_add_4: 5422 case Builtin::BI__sync_fetch_and_add_8: 5423 case Builtin::BI__sync_fetch_and_add_16: 5424 BuiltinIndex = 0; 5425 break; 5426 5427 case Builtin::BI__sync_fetch_and_sub: 5428 case Builtin::BI__sync_fetch_and_sub_1: 5429 case Builtin::BI__sync_fetch_and_sub_2: 5430 case Builtin::BI__sync_fetch_and_sub_4: 5431 case Builtin::BI__sync_fetch_and_sub_8: 5432 case Builtin::BI__sync_fetch_and_sub_16: 5433 BuiltinIndex = 1; 5434 break; 5435 5436 case Builtin::BI__sync_fetch_and_or: 5437 case Builtin::BI__sync_fetch_and_or_1: 5438 case Builtin::BI__sync_fetch_and_or_2: 5439 case Builtin::BI__sync_fetch_and_or_4: 5440 case Builtin::BI__sync_fetch_and_or_8: 5441 case Builtin::BI__sync_fetch_and_or_16: 5442 BuiltinIndex = 2; 5443 break; 5444 5445 case Builtin::BI__sync_fetch_and_and: 5446 case Builtin::BI__sync_fetch_and_and_1: 5447 case Builtin::BI__sync_fetch_and_and_2: 5448 case Builtin::BI__sync_fetch_and_and_4: 5449 case Builtin::BI__sync_fetch_and_and_8: 5450 case Builtin::BI__sync_fetch_and_and_16: 5451 BuiltinIndex = 3; 5452 break; 5453 5454 case Builtin::BI__sync_fetch_and_xor: 5455 case Builtin::BI__sync_fetch_and_xor_1: 5456 case Builtin::BI__sync_fetch_and_xor_2: 5457 case Builtin::BI__sync_fetch_and_xor_4: 5458 case Builtin::BI__sync_fetch_and_xor_8: 5459 case Builtin::BI__sync_fetch_and_xor_16: 5460 BuiltinIndex = 4; 5461 break; 5462 5463 case Builtin::BI__sync_fetch_and_nand: 5464 case Builtin::BI__sync_fetch_and_nand_1: 5465 case Builtin::BI__sync_fetch_and_nand_2: 5466 case Builtin::BI__sync_fetch_and_nand_4: 5467 case Builtin::BI__sync_fetch_and_nand_8: 5468 case Builtin::BI__sync_fetch_and_nand_16: 5469 BuiltinIndex = 5; 5470 WarnAboutSemanticsChange = true; 5471 break; 5472 5473 case Builtin::BI__sync_add_and_fetch: 5474 case Builtin::BI__sync_add_and_fetch_1: 5475 case Builtin::BI__sync_add_and_fetch_2: 5476 case Builtin::BI__sync_add_and_fetch_4: 5477 case Builtin::BI__sync_add_and_fetch_8: 5478 case Builtin::BI__sync_add_and_fetch_16: 5479 BuiltinIndex = 6; 5480 break; 5481 5482 case Builtin::BI__sync_sub_and_fetch: 5483 case Builtin::BI__sync_sub_and_fetch_1: 5484 case Builtin::BI__sync_sub_and_fetch_2: 5485 case Builtin::BI__sync_sub_and_fetch_4: 5486 case Builtin::BI__sync_sub_and_fetch_8: 5487 case Builtin::BI__sync_sub_and_fetch_16: 5488 BuiltinIndex = 7; 5489 break; 5490 5491 case Builtin::BI__sync_and_and_fetch: 5492 case Builtin::BI__sync_and_and_fetch_1: 5493 case Builtin::BI__sync_and_and_fetch_2: 5494 case Builtin::BI__sync_and_and_fetch_4: 5495 case Builtin::BI__sync_and_and_fetch_8: 5496 case Builtin::BI__sync_and_and_fetch_16: 5497 BuiltinIndex = 8; 5498 break; 5499 5500 case Builtin::BI__sync_or_and_fetch: 5501 case Builtin::BI__sync_or_and_fetch_1: 5502 case Builtin::BI__sync_or_and_fetch_2: 5503 case Builtin::BI__sync_or_and_fetch_4: 5504 case Builtin::BI__sync_or_and_fetch_8: 5505 case Builtin::BI__sync_or_and_fetch_16: 5506 BuiltinIndex = 9; 5507 break; 5508 5509 case Builtin::BI__sync_xor_and_fetch: 5510 case Builtin::BI__sync_xor_and_fetch_1: 5511 case Builtin::BI__sync_xor_and_fetch_2: 5512 case Builtin::BI__sync_xor_and_fetch_4: 5513 case Builtin::BI__sync_xor_and_fetch_8: 5514 case Builtin::BI__sync_xor_and_fetch_16: 5515 BuiltinIndex = 10; 5516 break; 5517 5518 case Builtin::BI__sync_nand_and_fetch: 5519 case Builtin::BI__sync_nand_and_fetch_1: 5520 case Builtin::BI__sync_nand_and_fetch_2: 5521 case Builtin::BI__sync_nand_and_fetch_4: 5522 case Builtin::BI__sync_nand_and_fetch_8: 5523 case Builtin::BI__sync_nand_and_fetch_16: 5524 BuiltinIndex = 11; 5525 WarnAboutSemanticsChange = true; 5526 break; 5527 5528 case Builtin::BI__sync_val_compare_and_swap: 5529 case Builtin::BI__sync_val_compare_and_swap_1: 5530 case Builtin::BI__sync_val_compare_and_swap_2: 5531 case Builtin::BI__sync_val_compare_and_swap_4: 5532 case Builtin::BI__sync_val_compare_and_swap_8: 5533 case Builtin::BI__sync_val_compare_and_swap_16: 5534 BuiltinIndex = 12; 5535 NumFixed = 2; 5536 break; 5537 5538 case Builtin::BI__sync_bool_compare_and_swap: 5539 case Builtin::BI__sync_bool_compare_and_swap_1: 5540 case Builtin::BI__sync_bool_compare_and_swap_2: 5541 case Builtin::BI__sync_bool_compare_and_swap_4: 5542 case Builtin::BI__sync_bool_compare_and_swap_8: 5543 case Builtin::BI__sync_bool_compare_and_swap_16: 5544 BuiltinIndex = 13; 5545 NumFixed = 2; 5546 ResultType = Context.BoolTy; 5547 break; 5548 5549 case Builtin::BI__sync_lock_test_and_set: 5550 case Builtin::BI__sync_lock_test_and_set_1: 5551 case Builtin::BI__sync_lock_test_and_set_2: 5552 case Builtin::BI__sync_lock_test_and_set_4: 5553 case Builtin::BI__sync_lock_test_and_set_8: 5554 case Builtin::BI__sync_lock_test_and_set_16: 5555 BuiltinIndex = 14; 5556 break; 5557 5558 case Builtin::BI__sync_lock_release: 5559 case Builtin::BI__sync_lock_release_1: 5560 case Builtin::BI__sync_lock_release_2: 5561 case Builtin::BI__sync_lock_release_4: 5562 case Builtin::BI__sync_lock_release_8: 5563 case Builtin::BI__sync_lock_release_16: 5564 BuiltinIndex = 15; 5565 NumFixed = 0; 5566 ResultType = Context.VoidTy; 5567 break; 5568 5569 case Builtin::BI__sync_swap: 5570 case Builtin::BI__sync_swap_1: 5571 case Builtin::BI__sync_swap_2: 5572 case Builtin::BI__sync_swap_4: 5573 case Builtin::BI__sync_swap_8: 5574 case Builtin::BI__sync_swap_16: 5575 BuiltinIndex = 16; 5576 break; 5577 } 5578 5579 // Now that we know how many fixed arguments we expect, first check that we 5580 // have at least that many. 5581 if (TheCall->getNumArgs() < 1+NumFixed) { 5582 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5583 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5584 << Callee->getSourceRange(); 5585 return ExprError(); 5586 } 5587 5588 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5589 << Callee->getSourceRange(); 5590 5591 if (WarnAboutSemanticsChange) { 5592 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5593 << Callee->getSourceRange(); 5594 } 5595 5596 // Get the decl for the concrete builtin from this, we can tell what the 5597 // concrete integer type we should convert to is. 5598 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5599 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5600 FunctionDecl *NewBuiltinDecl; 5601 if (NewBuiltinID == BuiltinID) 5602 NewBuiltinDecl = FDecl; 5603 else { 5604 // Perform builtin lookup to avoid redeclaring it. 5605 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5606 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5607 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5608 assert(Res.getFoundDecl()); 5609 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5610 if (!NewBuiltinDecl) 5611 return ExprError(); 5612 } 5613 5614 // The first argument --- the pointer --- has a fixed type; we 5615 // deduce the types of the rest of the arguments accordingly. Walk 5616 // the remaining arguments, converting them to the deduced value type. 5617 for (unsigned i = 0; i != NumFixed; ++i) { 5618 ExprResult Arg = TheCall->getArg(i+1); 5619 5620 // GCC does an implicit conversion to the pointer or integer ValType. This 5621 // can fail in some cases (1i -> int**), check for this error case now. 5622 // Initialize the argument. 5623 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5624 ValType, /*consume*/ false); 5625 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5626 if (Arg.isInvalid()) 5627 return ExprError(); 5628 5629 // Okay, we have something that *can* be converted to the right type. Check 5630 // to see if there is a potentially weird extension going on here. This can 5631 // happen when you do an atomic operation on something like an char* and 5632 // pass in 42. The 42 gets converted to char. This is even more strange 5633 // for things like 45.123 -> char, etc. 5634 // FIXME: Do this check. 5635 TheCall->setArg(i+1, Arg.get()); 5636 } 5637 5638 // Create a new DeclRefExpr to refer to the new decl. 5639 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5640 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5641 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5642 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5643 5644 // Set the callee in the CallExpr. 5645 // FIXME: This loses syntactic information. 5646 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5647 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5648 CK_BuiltinFnToFnPtr); 5649 TheCall->setCallee(PromotedCall.get()); 5650 5651 // Change the result type of the call to match the original value type. This 5652 // is arbitrary, but the codegen for these builtins ins design to handle it 5653 // gracefully. 5654 TheCall->setType(ResultType); 5655 5656 // Prohibit use of _ExtInt with atomic builtins. 5657 // The arguments would have already been converted to the first argument's 5658 // type, so only need to check the first argument. 5659 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5660 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5661 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5662 return ExprError(); 5663 } 5664 5665 return TheCallResult; 5666 } 5667 5668 /// SemaBuiltinNontemporalOverloaded - We have a call to 5669 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5670 /// overloaded function based on the pointer type of its last argument. 5671 /// 5672 /// This function goes through and does final semantic checking for these 5673 /// builtins. 5674 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5675 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5676 DeclRefExpr *DRE = 5677 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5678 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5679 unsigned BuiltinID = FDecl->getBuiltinID(); 5680 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5681 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5682 "Unexpected nontemporal load/store builtin!"); 5683 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5684 unsigned numArgs = isStore ? 2 : 1; 5685 5686 // Ensure that we have the proper number of arguments. 5687 if (checkArgCount(*this, TheCall, numArgs)) 5688 return ExprError(); 5689 5690 // Inspect the last argument of the nontemporal builtin. This should always 5691 // be a pointer type, from which we imply the type of the memory access. 5692 // Because it is a pointer type, we don't have to worry about any implicit 5693 // casts here. 5694 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5695 ExprResult PointerArgResult = 5696 DefaultFunctionArrayLvalueConversion(PointerArg); 5697 5698 if (PointerArgResult.isInvalid()) 5699 return ExprError(); 5700 PointerArg = PointerArgResult.get(); 5701 TheCall->setArg(numArgs - 1, PointerArg); 5702 5703 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5704 if (!pointerType) { 5705 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5706 << PointerArg->getType() << PointerArg->getSourceRange(); 5707 return ExprError(); 5708 } 5709 5710 QualType ValType = pointerType->getPointeeType(); 5711 5712 // Strip any qualifiers off ValType. 5713 ValType = ValType.getUnqualifiedType(); 5714 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5715 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5716 !ValType->isVectorType()) { 5717 Diag(DRE->getBeginLoc(), 5718 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5719 << PointerArg->getType() << PointerArg->getSourceRange(); 5720 return ExprError(); 5721 } 5722 5723 if (!isStore) { 5724 TheCall->setType(ValType); 5725 return TheCallResult; 5726 } 5727 5728 ExprResult ValArg = TheCall->getArg(0); 5729 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5730 Context, ValType, /*consume*/ false); 5731 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5732 if (ValArg.isInvalid()) 5733 return ExprError(); 5734 5735 TheCall->setArg(0, ValArg.get()); 5736 TheCall->setType(Context.VoidTy); 5737 return TheCallResult; 5738 } 5739 5740 /// CheckObjCString - Checks that the argument to the builtin 5741 /// CFString constructor is correct 5742 /// Note: It might also make sense to do the UTF-16 conversion here (would 5743 /// simplify the backend). 5744 bool Sema::CheckObjCString(Expr *Arg) { 5745 Arg = Arg->IgnoreParenCasts(); 5746 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5747 5748 if (!Literal || !Literal->isAscii()) { 5749 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5750 << Arg->getSourceRange(); 5751 return true; 5752 } 5753 5754 if (Literal->containsNonAsciiOrNull()) { 5755 StringRef String = Literal->getString(); 5756 unsigned NumBytes = String.size(); 5757 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5758 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5759 llvm::UTF16 *ToPtr = &ToBuf[0]; 5760 5761 llvm::ConversionResult Result = 5762 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5763 ToPtr + NumBytes, llvm::strictConversion); 5764 // Check for conversion failure. 5765 if (Result != llvm::conversionOK) 5766 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5767 << Arg->getSourceRange(); 5768 } 5769 return false; 5770 } 5771 5772 /// CheckObjCString - Checks that the format string argument to the os_log() 5773 /// and os_trace() functions is correct, and converts it to const char *. 5774 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5775 Arg = Arg->IgnoreParenCasts(); 5776 auto *Literal = dyn_cast<StringLiteral>(Arg); 5777 if (!Literal) { 5778 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5779 Literal = ObjcLiteral->getString(); 5780 } 5781 } 5782 5783 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5784 return ExprError( 5785 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5786 << Arg->getSourceRange()); 5787 } 5788 5789 ExprResult Result(Literal); 5790 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5791 InitializedEntity Entity = 5792 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5793 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5794 return Result; 5795 } 5796 5797 /// Check that the user is calling the appropriate va_start builtin for the 5798 /// target and calling convention. 5799 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5800 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5801 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5802 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5803 TT.getArch() == llvm::Triple::aarch64_32); 5804 bool IsWindows = TT.isOSWindows(); 5805 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5806 if (IsX64 || IsAArch64) { 5807 CallingConv CC = CC_C; 5808 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5809 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5810 if (IsMSVAStart) { 5811 // Don't allow this in System V ABI functions. 5812 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5813 return S.Diag(Fn->getBeginLoc(), 5814 diag::err_ms_va_start_used_in_sysv_function); 5815 } else { 5816 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5817 // On x64 Windows, don't allow this in System V ABI functions. 5818 // (Yes, that means there's no corresponding way to support variadic 5819 // System V ABI functions on Windows.) 5820 if ((IsWindows && CC == CC_X86_64SysV) || 5821 (!IsWindows && CC == CC_Win64)) 5822 return S.Diag(Fn->getBeginLoc(), 5823 diag::err_va_start_used_in_wrong_abi_function) 5824 << !IsWindows; 5825 } 5826 return false; 5827 } 5828 5829 if (IsMSVAStart) 5830 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5831 return false; 5832 } 5833 5834 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5835 ParmVarDecl **LastParam = nullptr) { 5836 // Determine whether the current function, block, or obj-c method is variadic 5837 // and get its parameter list. 5838 bool IsVariadic = false; 5839 ArrayRef<ParmVarDecl *> Params; 5840 DeclContext *Caller = S.CurContext; 5841 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5842 IsVariadic = Block->isVariadic(); 5843 Params = Block->parameters(); 5844 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5845 IsVariadic = FD->isVariadic(); 5846 Params = FD->parameters(); 5847 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5848 IsVariadic = MD->isVariadic(); 5849 // FIXME: This isn't correct for methods (results in bogus warning). 5850 Params = MD->parameters(); 5851 } else if (isa<CapturedDecl>(Caller)) { 5852 // We don't support va_start in a CapturedDecl. 5853 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5854 return true; 5855 } else { 5856 // This must be some other declcontext that parses exprs. 5857 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5858 return true; 5859 } 5860 5861 if (!IsVariadic) { 5862 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5863 return true; 5864 } 5865 5866 if (LastParam) 5867 *LastParam = Params.empty() ? nullptr : Params.back(); 5868 5869 return false; 5870 } 5871 5872 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5873 /// for validity. Emit an error and return true on failure; return false 5874 /// on success. 5875 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5876 Expr *Fn = TheCall->getCallee(); 5877 5878 if (checkVAStartABI(*this, BuiltinID, Fn)) 5879 return true; 5880 5881 if (checkArgCount(*this, TheCall, 2)) 5882 return true; 5883 5884 // Type-check the first argument normally. 5885 if (checkBuiltinArgument(*this, TheCall, 0)) 5886 return true; 5887 5888 // Check that the current function is variadic, and get its last parameter. 5889 ParmVarDecl *LastParam; 5890 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5891 return true; 5892 5893 // Verify that the second argument to the builtin is the last argument of the 5894 // current function or method. 5895 bool SecondArgIsLastNamedArgument = false; 5896 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5897 5898 // These are valid if SecondArgIsLastNamedArgument is false after the next 5899 // block. 5900 QualType Type; 5901 SourceLocation ParamLoc; 5902 bool IsCRegister = false; 5903 5904 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5905 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5906 SecondArgIsLastNamedArgument = PV == LastParam; 5907 5908 Type = PV->getType(); 5909 ParamLoc = PV->getLocation(); 5910 IsCRegister = 5911 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5912 } 5913 } 5914 5915 if (!SecondArgIsLastNamedArgument) 5916 Diag(TheCall->getArg(1)->getBeginLoc(), 5917 diag::warn_second_arg_of_va_start_not_last_named_param); 5918 else if (IsCRegister || Type->isReferenceType() || 5919 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5920 // Promotable integers are UB, but enumerations need a bit of 5921 // extra checking to see what their promotable type actually is. 5922 if (!Type->isPromotableIntegerType()) 5923 return false; 5924 if (!Type->isEnumeralType()) 5925 return true; 5926 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5927 return !(ED && 5928 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5929 }()) { 5930 unsigned Reason = 0; 5931 if (Type->isReferenceType()) Reason = 1; 5932 else if (IsCRegister) Reason = 2; 5933 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5934 Diag(ParamLoc, diag::note_parameter_type) << Type; 5935 } 5936 5937 TheCall->setType(Context.VoidTy); 5938 return false; 5939 } 5940 5941 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5942 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5943 // const char *named_addr); 5944 5945 Expr *Func = Call->getCallee(); 5946 5947 if (Call->getNumArgs() < 3) 5948 return Diag(Call->getEndLoc(), 5949 diag::err_typecheck_call_too_few_args_at_least) 5950 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5951 5952 // Type-check the first argument normally. 5953 if (checkBuiltinArgument(*this, Call, 0)) 5954 return true; 5955 5956 // Check that the current function is variadic. 5957 if (checkVAStartIsInVariadicFunction(*this, Func)) 5958 return true; 5959 5960 // __va_start on Windows does not validate the parameter qualifiers 5961 5962 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5963 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5964 5965 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5966 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5967 5968 const QualType &ConstCharPtrTy = 5969 Context.getPointerType(Context.CharTy.withConst()); 5970 if (!Arg1Ty->isPointerType() || 5971 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5972 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5973 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5974 << 0 /* qualifier difference */ 5975 << 3 /* parameter mismatch */ 5976 << 2 << Arg1->getType() << ConstCharPtrTy; 5977 5978 const QualType SizeTy = Context.getSizeType(); 5979 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5980 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5981 << Arg2->getType() << SizeTy << 1 /* different class */ 5982 << 0 /* qualifier difference */ 5983 << 3 /* parameter mismatch */ 5984 << 3 << Arg2->getType() << SizeTy; 5985 5986 return false; 5987 } 5988 5989 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5990 /// friends. This is declared to take (...), so we have to check everything. 5991 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5992 if (checkArgCount(*this, TheCall, 2)) 5993 return true; 5994 5995 ExprResult OrigArg0 = TheCall->getArg(0); 5996 ExprResult OrigArg1 = TheCall->getArg(1); 5997 5998 // Do standard promotions between the two arguments, returning their common 5999 // type. 6000 QualType Res = UsualArithmeticConversions( 6001 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6002 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6003 return true; 6004 6005 // Make sure any conversions are pushed back into the call; this is 6006 // type safe since unordered compare builtins are declared as "_Bool 6007 // foo(...)". 6008 TheCall->setArg(0, OrigArg0.get()); 6009 TheCall->setArg(1, OrigArg1.get()); 6010 6011 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6012 return false; 6013 6014 // If the common type isn't a real floating type, then the arguments were 6015 // invalid for this operation. 6016 if (Res.isNull() || !Res->isRealFloatingType()) 6017 return Diag(OrigArg0.get()->getBeginLoc(), 6018 diag::err_typecheck_call_invalid_ordered_compare) 6019 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6020 << SourceRange(OrigArg0.get()->getBeginLoc(), 6021 OrigArg1.get()->getEndLoc()); 6022 6023 return false; 6024 } 6025 6026 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6027 /// __builtin_isnan and friends. This is declared to take (...), so we have 6028 /// to check everything. We expect the last argument to be a floating point 6029 /// value. 6030 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6031 if (checkArgCount(*this, TheCall, NumArgs)) 6032 return true; 6033 6034 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6035 // on all preceding parameters just being int. Try all of those. 6036 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6037 Expr *Arg = TheCall->getArg(i); 6038 6039 if (Arg->isTypeDependent()) 6040 return false; 6041 6042 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6043 6044 if (Res.isInvalid()) 6045 return true; 6046 TheCall->setArg(i, Res.get()); 6047 } 6048 6049 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6050 6051 if (OrigArg->isTypeDependent()) 6052 return false; 6053 6054 // Usual Unary Conversions will convert half to float, which we want for 6055 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6056 // type how it is, but do normal L->Rvalue conversions. 6057 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6058 OrigArg = UsualUnaryConversions(OrigArg).get(); 6059 else 6060 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6061 TheCall->setArg(NumArgs - 1, OrigArg); 6062 6063 // This operation requires a non-_Complex floating-point number. 6064 if (!OrigArg->getType()->isRealFloatingType()) 6065 return Diag(OrigArg->getBeginLoc(), 6066 diag::err_typecheck_call_invalid_unary_fp) 6067 << OrigArg->getType() << OrigArg->getSourceRange(); 6068 6069 return false; 6070 } 6071 6072 /// Perform semantic analysis for a call to __builtin_complex. 6073 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6074 if (checkArgCount(*this, TheCall, 2)) 6075 return true; 6076 6077 bool Dependent = false; 6078 for (unsigned I = 0; I != 2; ++I) { 6079 Expr *Arg = TheCall->getArg(I); 6080 QualType T = Arg->getType(); 6081 if (T->isDependentType()) { 6082 Dependent = true; 6083 continue; 6084 } 6085 6086 // Despite supporting _Complex int, GCC requires a real floating point type 6087 // for the operands of __builtin_complex. 6088 if (!T->isRealFloatingType()) { 6089 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6090 << Arg->getType() << Arg->getSourceRange(); 6091 } 6092 6093 ExprResult Converted = DefaultLvalueConversion(Arg); 6094 if (Converted.isInvalid()) 6095 return true; 6096 TheCall->setArg(I, Converted.get()); 6097 } 6098 6099 if (Dependent) { 6100 TheCall->setType(Context.DependentTy); 6101 return false; 6102 } 6103 6104 Expr *Real = TheCall->getArg(0); 6105 Expr *Imag = TheCall->getArg(1); 6106 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6107 return Diag(Real->getBeginLoc(), 6108 diag::err_typecheck_call_different_arg_types) 6109 << Real->getType() << Imag->getType() 6110 << Real->getSourceRange() << Imag->getSourceRange(); 6111 } 6112 6113 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6114 // don't allow this builtin to form those types either. 6115 // FIXME: Should we allow these types? 6116 if (Real->getType()->isFloat16Type()) 6117 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6118 << "_Float16"; 6119 if (Real->getType()->isHalfType()) 6120 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6121 << "half"; 6122 6123 TheCall->setType(Context.getComplexType(Real->getType())); 6124 return false; 6125 } 6126 6127 // Customized Sema Checking for VSX builtins that have the following signature: 6128 // vector [...] builtinName(vector [...], vector [...], const int); 6129 // Which takes the same type of vectors (any legal vector type) for the first 6130 // two arguments and takes compile time constant for the third argument. 6131 // Example builtins are : 6132 // vector double vec_xxpermdi(vector double, vector double, int); 6133 // vector short vec_xxsldwi(vector short, vector short, int); 6134 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6135 unsigned ExpectedNumArgs = 3; 6136 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6137 return true; 6138 6139 // Check the third argument is a compile time constant 6140 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6141 return Diag(TheCall->getBeginLoc(), 6142 diag::err_vsx_builtin_nonconstant_argument) 6143 << 3 /* argument index */ << TheCall->getDirectCallee() 6144 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6145 TheCall->getArg(2)->getEndLoc()); 6146 6147 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6148 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6149 6150 // Check the type of argument 1 and argument 2 are vectors. 6151 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6152 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6153 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6154 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6155 << TheCall->getDirectCallee() 6156 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6157 TheCall->getArg(1)->getEndLoc()); 6158 } 6159 6160 // Check the first two arguments are the same type. 6161 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6162 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6163 << TheCall->getDirectCallee() 6164 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6165 TheCall->getArg(1)->getEndLoc()); 6166 } 6167 6168 // When default clang type checking is turned off and the customized type 6169 // checking is used, the returning type of the function must be explicitly 6170 // set. Otherwise it is _Bool by default. 6171 TheCall->setType(Arg1Ty); 6172 6173 return false; 6174 } 6175 6176 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6177 // This is declared to take (...), so we have to check everything. 6178 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6179 if (TheCall->getNumArgs() < 2) 6180 return ExprError(Diag(TheCall->getEndLoc(), 6181 diag::err_typecheck_call_too_few_args_at_least) 6182 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6183 << TheCall->getSourceRange()); 6184 6185 // Determine which of the following types of shufflevector we're checking: 6186 // 1) unary, vector mask: (lhs, mask) 6187 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6188 QualType resType = TheCall->getArg(0)->getType(); 6189 unsigned numElements = 0; 6190 6191 if (!TheCall->getArg(0)->isTypeDependent() && 6192 !TheCall->getArg(1)->isTypeDependent()) { 6193 QualType LHSType = TheCall->getArg(0)->getType(); 6194 QualType RHSType = TheCall->getArg(1)->getType(); 6195 6196 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6197 return ExprError( 6198 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6199 << TheCall->getDirectCallee() 6200 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6201 TheCall->getArg(1)->getEndLoc())); 6202 6203 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6204 unsigned numResElements = TheCall->getNumArgs() - 2; 6205 6206 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6207 // with mask. If so, verify that RHS is an integer vector type with the 6208 // same number of elts as lhs. 6209 if (TheCall->getNumArgs() == 2) { 6210 if (!RHSType->hasIntegerRepresentation() || 6211 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6212 return ExprError(Diag(TheCall->getBeginLoc(), 6213 diag::err_vec_builtin_incompatible_vector) 6214 << TheCall->getDirectCallee() 6215 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6216 TheCall->getArg(1)->getEndLoc())); 6217 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6218 return ExprError(Diag(TheCall->getBeginLoc(), 6219 diag::err_vec_builtin_incompatible_vector) 6220 << TheCall->getDirectCallee() 6221 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6222 TheCall->getArg(1)->getEndLoc())); 6223 } else if (numElements != numResElements) { 6224 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6225 resType = Context.getVectorType(eltType, numResElements, 6226 VectorType::GenericVector); 6227 } 6228 } 6229 6230 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6231 if (TheCall->getArg(i)->isTypeDependent() || 6232 TheCall->getArg(i)->isValueDependent()) 6233 continue; 6234 6235 Optional<llvm::APSInt> Result; 6236 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6237 return ExprError(Diag(TheCall->getBeginLoc(), 6238 diag::err_shufflevector_nonconstant_argument) 6239 << TheCall->getArg(i)->getSourceRange()); 6240 6241 // Allow -1 which will be translated to undef in the IR. 6242 if (Result->isSigned() && Result->isAllOnesValue()) 6243 continue; 6244 6245 if (Result->getActiveBits() > 64 || 6246 Result->getZExtValue() >= numElements * 2) 6247 return ExprError(Diag(TheCall->getBeginLoc(), 6248 diag::err_shufflevector_argument_too_large) 6249 << TheCall->getArg(i)->getSourceRange()); 6250 } 6251 6252 SmallVector<Expr*, 32> exprs; 6253 6254 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6255 exprs.push_back(TheCall->getArg(i)); 6256 TheCall->setArg(i, nullptr); 6257 } 6258 6259 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6260 TheCall->getCallee()->getBeginLoc(), 6261 TheCall->getRParenLoc()); 6262 } 6263 6264 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6265 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6266 SourceLocation BuiltinLoc, 6267 SourceLocation RParenLoc) { 6268 ExprValueKind VK = VK_RValue; 6269 ExprObjectKind OK = OK_Ordinary; 6270 QualType DstTy = TInfo->getType(); 6271 QualType SrcTy = E->getType(); 6272 6273 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6274 return ExprError(Diag(BuiltinLoc, 6275 diag::err_convertvector_non_vector) 6276 << E->getSourceRange()); 6277 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6278 return ExprError(Diag(BuiltinLoc, 6279 diag::err_convertvector_non_vector_type)); 6280 6281 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6282 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6283 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6284 if (SrcElts != DstElts) 6285 return ExprError(Diag(BuiltinLoc, 6286 diag::err_convertvector_incompatible_vector) 6287 << E->getSourceRange()); 6288 } 6289 6290 return new (Context) 6291 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6292 } 6293 6294 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6295 // This is declared to take (const void*, ...) and can take two 6296 // optional constant int args. 6297 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6298 unsigned NumArgs = TheCall->getNumArgs(); 6299 6300 if (NumArgs > 3) 6301 return Diag(TheCall->getEndLoc(), 6302 diag::err_typecheck_call_too_many_args_at_most) 6303 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6304 6305 // Argument 0 is checked for us and the remaining arguments must be 6306 // constant integers. 6307 for (unsigned i = 1; i != NumArgs; ++i) 6308 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6309 return true; 6310 6311 return false; 6312 } 6313 6314 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6315 // __assume does not evaluate its arguments, and should warn if its argument 6316 // has side effects. 6317 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6318 Expr *Arg = TheCall->getArg(0); 6319 if (Arg->isInstantiationDependent()) return false; 6320 6321 if (Arg->HasSideEffects(Context)) 6322 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6323 << Arg->getSourceRange() 6324 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6325 6326 return false; 6327 } 6328 6329 /// Handle __builtin_alloca_with_align. This is declared 6330 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6331 /// than 8. 6332 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6333 // The alignment must be a constant integer. 6334 Expr *Arg = TheCall->getArg(1); 6335 6336 // We can't check the value of a dependent argument. 6337 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6338 if (const auto *UE = 6339 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6340 if (UE->getKind() == UETT_AlignOf || 6341 UE->getKind() == UETT_PreferredAlignOf) 6342 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6343 << Arg->getSourceRange(); 6344 6345 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6346 6347 if (!Result.isPowerOf2()) 6348 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6349 << Arg->getSourceRange(); 6350 6351 if (Result < Context.getCharWidth()) 6352 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6353 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6354 6355 if (Result > std::numeric_limits<int32_t>::max()) 6356 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6357 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6358 } 6359 6360 return false; 6361 } 6362 6363 /// Handle __builtin_assume_aligned. This is declared 6364 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6365 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6366 unsigned NumArgs = TheCall->getNumArgs(); 6367 6368 if (NumArgs > 3) 6369 return Diag(TheCall->getEndLoc(), 6370 diag::err_typecheck_call_too_many_args_at_most) 6371 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6372 6373 // The alignment must be a constant integer. 6374 Expr *Arg = TheCall->getArg(1); 6375 6376 // We can't check the value of a dependent argument. 6377 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6378 llvm::APSInt Result; 6379 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6380 return true; 6381 6382 if (!Result.isPowerOf2()) 6383 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6384 << Arg->getSourceRange(); 6385 6386 if (Result > Sema::MaximumAlignment) 6387 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6388 << Arg->getSourceRange() << Sema::MaximumAlignment; 6389 } 6390 6391 if (NumArgs > 2) { 6392 ExprResult Arg(TheCall->getArg(2)); 6393 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6394 Context.getSizeType(), false); 6395 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6396 if (Arg.isInvalid()) return true; 6397 TheCall->setArg(2, Arg.get()); 6398 } 6399 6400 return false; 6401 } 6402 6403 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6404 unsigned BuiltinID = 6405 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6406 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6407 6408 unsigned NumArgs = TheCall->getNumArgs(); 6409 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6410 if (NumArgs < NumRequiredArgs) { 6411 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6412 << 0 /* function call */ << NumRequiredArgs << NumArgs 6413 << TheCall->getSourceRange(); 6414 } 6415 if (NumArgs >= NumRequiredArgs + 0x100) { 6416 return Diag(TheCall->getEndLoc(), 6417 diag::err_typecheck_call_too_many_args_at_most) 6418 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6419 << TheCall->getSourceRange(); 6420 } 6421 unsigned i = 0; 6422 6423 // For formatting call, check buffer arg. 6424 if (!IsSizeCall) { 6425 ExprResult Arg(TheCall->getArg(i)); 6426 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6427 Context, Context.VoidPtrTy, false); 6428 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6429 if (Arg.isInvalid()) 6430 return true; 6431 TheCall->setArg(i, Arg.get()); 6432 i++; 6433 } 6434 6435 // Check string literal arg. 6436 unsigned FormatIdx = i; 6437 { 6438 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6439 if (Arg.isInvalid()) 6440 return true; 6441 TheCall->setArg(i, Arg.get()); 6442 i++; 6443 } 6444 6445 // Make sure variadic args are scalar. 6446 unsigned FirstDataArg = i; 6447 while (i < NumArgs) { 6448 ExprResult Arg = DefaultVariadicArgumentPromotion( 6449 TheCall->getArg(i), VariadicFunction, nullptr); 6450 if (Arg.isInvalid()) 6451 return true; 6452 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6453 if (ArgSize.getQuantity() >= 0x100) { 6454 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6455 << i << (int)ArgSize.getQuantity() << 0xff 6456 << TheCall->getSourceRange(); 6457 } 6458 TheCall->setArg(i, Arg.get()); 6459 i++; 6460 } 6461 6462 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6463 // call to avoid duplicate diagnostics. 6464 if (!IsSizeCall) { 6465 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6466 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6467 bool Success = CheckFormatArguments( 6468 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6469 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6470 CheckedVarArgs); 6471 if (!Success) 6472 return true; 6473 } 6474 6475 if (IsSizeCall) { 6476 TheCall->setType(Context.getSizeType()); 6477 } else { 6478 TheCall->setType(Context.VoidPtrTy); 6479 } 6480 return false; 6481 } 6482 6483 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6484 /// TheCall is a constant expression. 6485 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6486 llvm::APSInt &Result) { 6487 Expr *Arg = TheCall->getArg(ArgNum); 6488 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6489 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6490 6491 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6492 6493 Optional<llvm::APSInt> R; 6494 if (!(R = Arg->getIntegerConstantExpr(Context))) 6495 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6496 << FDecl->getDeclName() << Arg->getSourceRange(); 6497 Result = *R; 6498 return false; 6499 } 6500 6501 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6502 /// TheCall is a constant expression in the range [Low, High]. 6503 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6504 int Low, int High, bool RangeIsError) { 6505 if (isConstantEvaluated()) 6506 return false; 6507 llvm::APSInt Result; 6508 6509 // We can't check the value of a dependent argument. 6510 Expr *Arg = TheCall->getArg(ArgNum); 6511 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6512 return false; 6513 6514 // Check constant-ness first. 6515 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6516 return true; 6517 6518 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6519 if (RangeIsError) 6520 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6521 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6522 else 6523 // Defer the warning until we know if the code will be emitted so that 6524 // dead code can ignore this. 6525 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6526 PDiag(diag::warn_argument_invalid_range) 6527 << Result.toString(10) << Low << High 6528 << Arg->getSourceRange()); 6529 } 6530 6531 return false; 6532 } 6533 6534 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6535 /// TheCall is a constant expression is a multiple of Num.. 6536 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6537 unsigned Num) { 6538 llvm::APSInt Result; 6539 6540 // We can't check the value of a dependent argument. 6541 Expr *Arg = TheCall->getArg(ArgNum); 6542 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6543 return false; 6544 6545 // Check constant-ness first. 6546 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6547 return true; 6548 6549 if (Result.getSExtValue() % Num != 0) 6550 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6551 << Num << Arg->getSourceRange(); 6552 6553 return false; 6554 } 6555 6556 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6557 /// constant expression representing a power of 2. 6558 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6559 llvm::APSInt Result; 6560 6561 // We can't check the value of a dependent argument. 6562 Expr *Arg = TheCall->getArg(ArgNum); 6563 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6564 return false; 6565 6566 // Check constant-ness first. 6567 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6568 return true; 6569 6570 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6571 // and only if x is a power of 2. 6572 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6573 return false; 6574 6575 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6576 << Arg->getSourceRange(); 6577 } 6578 6579 static bool IsShiftedByte(llvm::APSInt Value) { 6580 if (Value.isNegative()) 6581 return false; 6582 6583 // Check if it's a shifted byte, by shifting it down 6584 while (true) { 6585 // If the value fits in the bottom byte, the check passes. 6586 if (Value < 0x100) 6587 return true; 6588 6589 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6590 // fails. 6591 if ((Value & 0xFF) != 0) 6592 return false; 6593 6594 // If the bottom 8 bits are all 0, but something above that is nonzero, 6595 // then shifting the value right by 8 bits won't affect whether it's a 6596 // shifted byte or not. So do that, and go round again. 6597 Value >>= 8; 6598 } 6599 } 6600 6601 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6602 /// a constant expression representing an arbitrary byte value shifted left by 6603 /// a multiple of 8 bits. 6604 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6605 unsigned ArgBits) { 6606 llvm::APSInt Result; 6607 6608 // We can't check the value of a dependent argument. 6609 Expr *Arg = TheCall->getArg(ArgNum); 6610 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6611 return false; 6612 6613 // Check constant-ness first. 6614 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6615 return true; 6616 6617 // Truncate to the given size. 6618 Result = Result.getLoBits(ArgBits); 6619 Result.setIsUnsigned(true); 6620 6621 if (IsShiftedByte(Result)) 6622 return false; 6623 6624 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6625 << Arg->getSourceRange(); 6626 } 6627 6628 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6629 /// TheCall is a constant expression representing either a shifted byte value, 6630 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6631 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6632 /// Arm MVE intrinsics. 6633 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6634 int ArgNum, 6635 unsigned ArgBits) { 6636 llvm::APSInt Result; 6637 6638 // We can't check the value of a dependent argument. 6639 Expr *Arg = TheCall->getArg(ArgNum); 6640 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6641 return false; 6642 6643 // Check constant-ness first. 6644 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6645 return true; 6646 6647 // Truncate to the given size. 6648 Result = Result.getLoBits(ArgBits); 6649 Result.setIsUnsigned(true); 6650 6651 // Check to see if it's in either of the required forms. 6652 if (IsShiftedByte(Result) || 6653 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6654 return false; 6655 6656 return Diag(TheCall->getBeginLoc(), 6657 diag::err_argument_not_shifted_byte_or_xxff) 6658 << Arg->getSourceRange(); 6659 } 6660 6661 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6662 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6663 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6664 if (checkArgCount(*this, TheCall, 2)) 6665 return true; 6666 Expr *Arg0 = TheCall->getArg(0); 6667 Expr *Arg1 = TheCall->getArg(1); 6668 6669 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6670 if (FirstArg.isInvalid()) 6671 return true; 6672 QualType FirstArgType = FirstArg.get()->getType(); 6673 if (!FirstArgType->isAnyPointerType()) 6674 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6675 << "first" << FirstArgType << Arg0->getSourceRange(); 6676 TheCall->setArg(0, FirstArg.get()); 6677 6678 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6679 if (SecArg.isInvalid()) 6680 return true; 6681 QualType SecArgType = SecArg.get()->getType(); 6682 if (!SecArgType->isIntegerType()) 6683 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6684 << "second" << SecArgType << Arg1->getSourceRange(); 6685 6686 // Derive the return type from the pointer argument. 6687 TheCall->setType(FirstArgType); 6688 return false; 6689 } 6690 6691 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6692 if (checkArgCount(*this, TheCall, 2)) 6693 return true; 6694 6695 Expr *Arg0 = TheCall->getArg(0); 6696 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6697 if (FirstArg.isInvalid()) 6698 return true; 6699 QualType FirstArgType = FirstArg.get()->getType(); 6700 if (!FirstArgType->isAnyPointerType()) 6701 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6702 << "first" << FirstArgType << Arg0->getSourceRange(); 6703 TheCall->setArg(0, FirstArg.get()); 6704 6705 // Derive the return type from the pointer argument. 6706 TheCall->setType(FirstArgType); 6707 6708 // Second arg must be an constant in range [0,15] 6709 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6710 } 6711 6712 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6713 if (checkArgCount(*this, TheCall, 2)) 6714 return true; 6715 Expr *Arg0 = TheCall->getArg(0); 6716 Expr *Arg1 = TheCall->getArg(1); 6717 6718 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6719 if (FirstArg.isInvalid()) 6720 return true; 6721 QualType FirstArgType = FirstArg.get()->getType(); 6722 if (!FirstArgType->isAnyPointerType()) 6723 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6724 << "first" << FirstArgType << Arg0->getSourceRange(); 6725 6726 QualType SecArgType = Arg1->getType(); 6727 if (!SecArgType->isIntegerType()) 6728 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6729 << "second" << SecArgType << Arg1->getSourceRange(); 6730 TheCall->setType(Context.IntTy); 6731 return false; 6732 } 6733 6734 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6735 BuiltinID == AArch64::BI__builtin_arm_stg) { 6736 if (checkArgCount(*this, TheCall, 1)) 6737 return true; 6738 Expr *Arg0 = TheCall->getArg(0); 6739 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6740 if (FirstArg.isInvalid()) 6741 return true; 6742 6743 QualType FirstArgType = FirstArg.get()->getType(); 6744 if (!FirstArgType->isAnyPointerType()) 6745 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6746 << "first" << FirstArgType << Arg0->getSourceRange(); 6747 TheCall->setArg(0, FirstArg.get()); 6748 6749 // Derive the return type from the pointer argument. 6750 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6751 TheCall->setType(FirstArgType); 6752 return false; 6753 } 6754 6755 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6756 Expr *ArgA = TheCall->getArg(0); 6757 Expr *ArgB = TheCall->getArg(1); 6758 6759 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6760 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6761 6762 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6763 return true; 6764 6765 QualType ArgTypeA = ArgExprA.get()->getType(); 6766 QualType ArgTypeB = ArgExprB.get()->getType(); 6767 6768 auto isNull = [&] (Expr *E) -> bool { 6769 return E->isNullPointerConstant( 6770 Context, Expr::NPC_ValueDependentIsNotNull); }; 6771 6772 // argument should be either a pointer or null 6773 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6774 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6775 << "first" << ArgTypeA << ArgA->getSourceRange(); 6776 6777 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6778 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6779 << "second" << ArgTypeB << ArgB->getSourceRange(); 6780 6781 // Ensure Pointee types are compatible 6782 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6783 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6784 QualType pointeeA = ArgTypeA->getPointeeType(); 6785 QualType pointeeB = ArgTypeB->getPointeeType(); 6786 if (!Context.typesAreCompatible( 6787 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6788 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6789 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6790 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6791 << ArgB->getSourceRange(); 6792 } 6793 } 6794 6795 // at least one argument should be pointer type 6796 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6797 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6798 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6799 6800 if (isNull(ArgA)) // adopt type of the other pointer 6801 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6802 6803 if (isNull(ArgB)) 6804 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6805 6806 TheCall->setArg(0, ArgExprA.get()); 6807 TheCall->setArg(1, ArgExprB.get()); 6808 TheCall->setType(Context.LongLongTy); 6809 return false; 6810 } 6811 assert(false && "Unhandled ARM MTE intrinsic"); 6812 return true; 6813 } 6814 6815 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6816 /// TheCall is an ARM/AArch64 special register string literal. 6817 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6818 int ArgNum, unsigned ExpectedFieldNum, 6819 bool AllowName) { 6820 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6821 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6822 BuiltinID == ARM::BI__builtin_arm_rsr || 6823 BuiltinID == ARM::BI__builtin_arm_rsrp || 6824 BuiltinID == ARM::BI__builtin_arm_wsr || 6825 BuiltinID == ARM::BI__builtin_arm_wsrp; 6826 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6827 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6828 BuiltinID == AArch64::BI__builtin_arm_rsr || 6829 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6830 BuiltinID == AArch64::BI__builtin_arm_wsr || 6831 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6832 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6833 6834 // We can't check the value of a dependent argument. 6835 Expr *Arg = TheCall->getArg(ArgNum); 6836 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6837 return false; 6838 6839 // Check if the argument is a string literal. 6840 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6841 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6842 << Arg->getSourceRange(); 6843 6844 // Check the type of special register given. 6845 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6846 SmallVector<StringRef, 6> Fields; 6847 Reg.split(Fields, ":"); 6848 6849 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6850 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6851 << Arg->getSourceRange(); 6852 6853 // If the string is the name of a register then we cannot check that it is 6854 // valid here but if the string is of one the forms described in ACLE then we 6855 // can check that the supplied fields are integers and within the valid 6856 // ranges. 6857 if (Fields.size() > 1) { 6858 bool FiveFields = Fields.size() == 5; 6859 6860 bool ValidString = true; 6861 if (IsARMBuiltin) { 6862 ValidString &= Fields[0].startswith_lower("cp") || 6863 Fields[0].startswith_lower("p"); 6864 if (ValidString) 6865 Fields[0] = 6866 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6867 6868 ValidString &= Fields[2].startswith_lower("c"); 6869 if (ValidString) 6870 Fields[2] = Fields[2].drop_front(1); 6871 6872 if (FiveFields) { 6873 ValidString &= Fields[3].startswith_lower("c"); 6874 if (ValidString) 6875 Fields[3] = Fields[3].drop_front(1); 6876 } 6877 } 6878 6879 SmallVector<int, 5> Ranges; 6880 if (FiveFields) 6881 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6882 else 6883 Ranges.append({15, 7, 15}); 6884 6885 for (unsigned i=0; i<Fields.size(); ++i) { 6886 int IntField; 6887 ValidString &= !Fields[i].getAsInteger(10, IntField); 6888 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6889 } 6890 6891 if (!ValidString) 6892 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6893 << Arg->getSourceRange(); 6894 } else if (IsAArch64Builtin && Fields.size() == 1) { 6895 // If the register name is one of those that appear in the condition below 6896 // and the special register builtin being used is one of the write builtins, 6897 // then we require that the argument provided for writing to the register 6898 // is an integer constant expression. This is because it will be lowered to 6899 // an MSR (immediate) instruction, so we need to know the immediate at 6900 // compile time. 6901 if (TheCall->getNumArgs() != 2) 6902 return false; 6903 6904 std::string RegLower = Reg.lower(); 6905 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6906 RegLower != "pan" && RegLower != "uao") 6907 return false; 6908 6909 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6910 } 6911 6912 return false; 6913 } 6914 6915 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 6916 /// Emit an error and return true on failure; return false on success. 6917 /// TypeStr is a string containing the type descriptor of the value returned by 6918 /// the builtin and the descriptors of the expected type of the arguments. 6919 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 6920 6921 assert((TypeStr[0] != '\0') && 6922 "Invalid types in PPC MMA builtin declaration"); 6923 6924 unsigned Mask = 0; 6925 unsigned ArgNum = 0; 6926 6927 // The first type in TypeStr is the type of the value returned by the 6928 // builtin. So we first read that type and change the type of TheCall. 6929 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6930 TheCall->setType(type); 6931 6932 while (*TypeStr != '\0') { 6933 Mask = 0; 6934 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6935 if (ArgNum >= TheCall->getNumArgs()) { 6936 ArgNum++; 6937 break; 6938 } 6939 6940 Expr *Arg = TheCall->getArg(ArgNum); 6941 QualType ArgType = Arg->getType(); 6942 6943 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 6944 (!ExpectedType->isVoidPointerType() && 6945 ArgType.getCanonicalType() != ExpectedType)) 6946 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6947 << ArgType << ExpectedType << 1 << 0 << 0; 6948 6949 // If the value of the Mask is not 0, we have a constraint in the size of 6950 // the integer argument so here we ensure the argument is a constant that 6951 // is in the valid range. 6952 if (Mask != 0 && 6953 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 6954 return true; 6955 6956 ArgNum++; 6957 } 6958 6959 // In case we exited early from the previous loop, there are other types to 6960 // read from TypeStr. So we need to read them all to ensure we have the right 6961 // number of arguments in TheCall and if it is not the case, to display a 6962 // better error message. 6963 while (*TypeStr != '\0') { 6964 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6965 ArgNum++; 6966 } 6967 if (checkArgCount(*this, TheCall, ArgNum)) 6968 return true; 6969 6970 return false; 6971 } 6972 6973 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6974 /// This checks that the target supports __builtin_longjmp and 6975 /// that val is a constant 1. 6976 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6977 if (!Context.getTargetInfo().hasSjLjLowering()) 6978 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6979 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6980 6981 Expr *Arg = TheCall->getArg(1); 6982 llvm::APSInt Result; 6983 6984 // TODO: This is less than ideal. Overload this to take a value. 6985 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6986 return true; 6987 6988 if (Result != 1) 6989 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6990 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6991 6992 return false; 6993 } 6994 6995 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6996 /// This checks that the target supports __builtin_setjmp. 6997 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6998 if (!Context.getTargetInfo().hasSjLjLowering()) 6999 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7000 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7001 return false; 7002 } 7003 7004 namespace { 7005 7006 class UncoveredArgHandler { 7007 enum { Unknown = -1, AllCovered = -2 }; 7008 7009 signed FirstUncoveredArg = Unknown; 7010 SmallVector<const Expr *, 4> DiagnosticExprs; 7011 7012 public: 7013 UncoveredArgHandler() = default; 7014 7015 bool hasUncoveredArg() const { 7016 return (FirstUncoveredArg >= 0); 7017 } 7018 7019 unsigned getUncoveredArg() const { 7020 assert(hasUncoveredArg() && "no uncovered argument"); 7021 return FirstUncoveredArg; 7022 } 7023 7024 void setAllCovered() { 7025 // A string has been found with all arguments covered, so clear out 7026 // the diagnostics. 7027 DiagnosticExprs.clear(); 7028 FirstUncoveredArg = AllCovered; 7029 } 7030 7031 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7032 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7033 7034 // Don't update if a previous string covers all arguments. 7035 if (FirstUncoveredArg == AllCovered) 7036 return; 7037 7038 // UncoveredArgHandler tracks the highest uncovered argument index 7039 // and with it all the strings that match this index. 7040 if (NewFirstUncoveredArg == FirstUncoveredArg) 7041 DiagnosticExprs.push_back(StrExpr); 7042 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7043 DiagnosticExprs.clear(); 7044 DiagnosticExprs.push_back(StrExpr); 7045 FirstUncoveredArg = NewFirstUncoveredArg; 7046 } 7047 } 7048 7049 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7050 }; 7051 7052 enum StringLiteralCheckType { 7053 SLCT_NotALiteral, 7054 SLCT_UncheckedLiteral, 7055 SLCT_CheckedLiteral 7056 }; 7057 7058 } // namespace 7059 7060 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7061 BinaryOperatorKind BinOpKind, 7062 bool AddendIsRight) { 7063 unsigned BitWidth = Offset.getBitWidth(); 7064 unsigned AddendBitWidth = Addend.getBitWidth(); 7065 // There might be negative interim results. 7066 if (Addend.isUnsigned()) { 7067 Addend = Addend.zext(++AddendBitWidth); 7068 Addend.setIsSigned(true); 7069 } 7070 // Adjust the bit width of the APSInts. 7071 if (AddendBitWidth > BitWidth) { 7072 Offset = Offset.sext(AddendBitWidth); 7073 BitWidth = AddendBitWidth; 7074 } else if (BitWidth > AddendBitWidth) { 7075 Addend = Addend.sext(BitWidth); 7076 } 7077 7078 bool Ov = false; 7079 llvm::APSInt ResOffset = Offset; 7080 if (BinOpKind == BO_Add) 7081 ResOffset = Offset.sadd_ov(Addend, Ov); 7082 else { 7083 assert(AddendIsRight && BinOpKind == BO_Sub && 7084 "operator must be add or sub with addend on the right"); 7085 ResOffset = Offset.ssub_ov(Addend, Ov); 7086 } 7087 7088 // We add an offset to a pointer here so we should support an offset as big as 7089 // possible. 7090 if (Ov) { 7091 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7092 "index (intermediate) result too big"); 7093 Offset = Offset.sext(2 * BitWidth); 7094 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7095 return; 7096 } 7097 7098 Offset = ResOffset; 7099 } 7100 7101 namespace { 7102 7103 // This is a wrapper class around StringLiteral to support offsetted string 7104 // literals as format strings. It takes the offset into account when returning 7105 // the string and its length or the source locations to display notes correctly. 7106 class FormatStringLiteral { 7107 const StringLiteral *FExpr; 7108 int64_t Offset; 7109 7110 public: 7111 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7112 : FExpr(fexpr), Offset(Offset) {} 7113 7114 StringRef getString() const { 7115 return FExpr->getString().drop_front(Offset); 7116 } 7117 7118 unsigned getByteLength() const { 7119 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7120 } 7121 7122 unsigned getLength() const { return FExpr->getLength() - Offset; } 7123 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7124 7125 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7126 7127 QualType getType() const { return FExpr->getType(); } 7128 7129 bool isAscii() const { return FExpr->isAscii(); } 7130 bool isWide() const { return FExpr->isWide(); } 7131 bool isUTF8() const { return FExpr->isUTF8(); } 7132 bool isUTF16() const { return FExpr->isUTF16(); } 7133 bool isUTF32() const { return FExpr->isUTF32(); } 7134 bool isPascal() const { return FExpr->isPascal(); } 7135 7136 SourceLocation getLocationOfByte( 7137 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7138 const TargetInfo &Target, unsigned *StartToken = nullptr, 7139 unsigned *StartTokenByteOffset = nullptr) const { 7140 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7141 StartToken, StartTokenByteOffset); 7142 } 7143 7144 SourceLocation getBeginLoc() const LLVM_READONLY { 7145 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7146 } 7147 7148 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7149 }; 7150 7151 } // namespace 7152 7153 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7154 const Expr *OrigFormatExpr, 7155 ArrayRef<const Expr *> Args, 7156 bool HasVAListArg, unsigned format_idx, 7157 unsigned firstDataArg, 7158 Sema::FormatStringType Type, 7159 bool inFunctionCall, 7160 Sema::VariadicCallType CallType, 7161 llvm::SmallBitVector &CheckedVarArgs, 7162 UncoveredArgHandler &UncoveredArg, 7163 bool IgnoreStringsWithoutSpecifiers); 7164 7165 // Determine if an expression is a string literal or constant string. 7166 // If this function returns false on the arguments to a function expecting a 7167 // format string, we will usually need to emit a warning. 7168 // True string literals are then checked by CheckFormatString. 7169 static StringLiteralCheckType 7170 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7171 bool HasVAListArg, unsigned format_idx, 7172 unsigned firstDataArg, Sema::FormatStringType Type, 7173 Sema::VariadicCallType CallType, bool InFunctionCall, 7174 llvm::SmallBitVector &CheckedVarArgs, 7175 UncoveredArgHandler &UncoveredArg, 7176 llvm::APSInt Offset, 7177 bool IgnoreStringsWithoutSpecifiers = false) { 7178 if (S.isConstantEvaluated()) 7179 return SLCT_NotALiteral; 7180 tryAgain: 7181 assert(Offset.isSigned() && "invalid offset"); 7182 7183 if (E->isTypeDependent() || E->isValueDependent()) 7184 return SLCT_NotALiteral; 7185 7186 E = E->IgnoreParenCasts(); 7187 7188 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7189 // Technically -Wformat-nonliteral does not warn about this case. 7190 // The behavior of printf and friends in this case is implementation 7191 // dependent. Ideally if the format string cannot be null then 7192 // it should have a 'nonnull' attribute in the function prototype. 7193 return SLCT_UncheckedLiteral; 7194 7195 switch (E->getStmtClass()) { 7196 case Stmt::BinaryConditionalOperatorClass: 7197 case Stmt::ConditionalOperatorClass: { 7198 // The expression is a literal if both sub-expressions were, and it was 7199 // completely checked only if both sub-expressions were checked. 7200 const AbstractConditionalOperator *C = 7201 cast<AbstractConditionalOperator>(E); 7202 7203 // Determine whether it is necessary to check both sub-expressions, for 7204 // example, because the condition expression is a constant that can be 7205 // evaluated at compile time. 7206 bool CheckLeft = true, CheckRight = true; 7207 7208 bool Cond; 7209 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7210 S.isConstantEvaluated())) { 7211 if (Cond) 7212 CheckRight = false; 7213 else 7214 CheckLeft = false; 7215 } 7216 7217 // We need to maintain the offsets for the right and the left hand side 7218 // separately to check if every possible indexed expression is a valid 7219 // string literal. They might have different offsets for different string 7220 // literals in the end. 7221 StringLiteralCheckType Left; 7222 if (!CheckLeft) 7223 Left = SLCT_UncheckedLiteral; 7224 else { 7225 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7226 HasVAListArg, format_idx, firstDataArg, 7227 Type, CallType, InFunctionCall, 7228 CheckedVarArgs, UncoveredArg, Offset, 7229 IgnoreStringsWithoutSpecifiers); 7230 if (Left == SLCT_NotALiteral || !CheckRight) { 7231 return Left; 7232 } 7233 } 7234 7235 StringLiteralCheckType Right = checkFormatStringExpr( 7236 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7237 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7238 IgnoreStringsWithoutSpecifiers); 7239 7240 return (CheckLeft && Left < Right) ? Left : Right; 7241 } 7242 7243 case Stmt::ImplicitCastExprClass: 7244 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7245 goto tryAgain; 7246 7247 case Stmt::OpaqueValueExprClass: 7248 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7249 E = src; 7250 goto tryAgain; 7251 } 7252 return SLCT_NotALiteral; 7253 7254 case Stmt::PredefinedExprClass: 7255 // While __func__, etc., are technically not string literals, they 7256 // cannot contain format specifiers and thus are not a security 7257 // liability. 7258 return SLCT_UncheckedLiteral; 7259 7260 case Stmt::DeclRefExprClass: { 7261 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7262 7263 // As an exception, do not flag errors for variables binding to 7264 // const string literals. 7265 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7266 bool isConstant = false; 7267 QualType T = DR->getType(); 7268 7269 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7270 isConstant = AT->getElementType().isConstant(S.Context); 7271 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7272 isConstant = T.isConstant(S.Context) && 7273 PT->getPointeeType().isConstant(S.Context); 7274 } else if (T->isObjCObjectPointerType()) { 7275 // In ObjC, there is usually no "const ObjectPointer" type, 7276 // so don't check if the pointee type is constant. 7277 isConstant = T.isConstant(S.Context); 7278 } 7279 7280 if (isConstant) { 7281 if (const Expr *Init = VD->getAnyInitializer()) { 7282 // Look through initializers like const char c[] = { "foo" } 7283 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7284 if (InitList->isStringLiteralInit()) 7285 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7286 } 7287 return checkFormatStringExpr(S, Init, Args, 7288 HasVAListArg, format_idx, 7289 firstDataArg, Type, CallType, 7290 /*InFunctionCall*/ false, CheckedVarArgs, 7291 UncoveredArg, Offset); 7292 } 7293 } 7294 7295 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7296 // special check to see if the format string is a function parameter 7297 // of the function calling the printf function. If the function 7298 // has an attribute indicating it is a printf-like function, then we 7299 // should suppress warnings concerning non-literals being used in a call 7300 // to a vprintf function. For example: 7301 // 7302 // void 7303 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7304 // va_list ap; 7305 // va_start(ap, fmt); 7306 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7307 // ... 7308 // } 7309 if (HasVAListArg) { 7310 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7311 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7312 int PVIndex = PV->getFunctionScopeIndex() + 1; 7313 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7314 // adjust for implicit parameter 7315 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7316 if (MD->isInstance()) 7317 ++PVIndex; 7318 // We also check if the formats are compatible. 7319 // We can't pass a 'scanf' string to a 'printf' function. 7320 if (PVIndex == PVFormat->getFormatIdx() && 7321 Type == S.GetFormatStringType(PVFormat)) 7322 return SLCT_UncheckedLiteral; 7323 } 7324 } 7325 } 7326 } 7327 } 7328 7329 return SLCT_NotALiteral; 7330 } 7331 7332 case Stmt::CallExprClass: 7333 case Stmt::CXXMemberCallExprClass: { 7334 const CallExpr *CE = cast<CallExpr>(E); 7335 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7336 bool IsFirst = true; 7337 StringLiteralCheckType CommonResult; 7338 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7339 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7340 StringLiteralCheckType Result = checkFormatStringExpr( 7341 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7342 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7343 IgnoreStringsWithoutSpecifiers); 7344 if (IsFirst) { 7345 CommonResult = Result; 7346 IsFirst = false; 7347 } 7348 } 7349 if (!IsFirst) 7350 return CommonResult; 7351 7352 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7353 unsigned BuiltinID = FD->getBuiltinID(); 7354 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7355 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7356 const Expr *Arg = CE->getArg(0); 7357 return checkFormatStringExpr(S, Arg, Args, 7358 HasVAListArg, format_idx, 7359 firstDataArg, Type, CallType, 7360 InFunctionCall, CheckedVarArgs, 7361 UncoveredArg, Offset, 7362 IgnoreStringsWithoutSpecifiers); 7363 } 7364 } 7365 } 7366 7367 return SLCT_NotALiteral; 7368 } 7369 case Stmt::ObjCMessageExprClass: { 7370 const auto *ME = cast<ObjCMessageExpr>(E); 7371 if (const auto *MD = ME->getMethodDecl()) { 7372 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7373 // As a special case heuristic, if we're using the method -[NSBundle 7374 // localizedStringForKey:value:table:], ignore any key strings that lack 7375 // format specifiers. The idea is that if the key doesn't have any 7376 // format specifiers then its probably just a key to map to the 7377 // localized strings. If it does have format specifiers though, then its 7378 // likely that the text of the key is the format string in the 7379 // programmer's language, and should be checked. 7380 const ObjCInterfaceDecl *IFace; 7381 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7382 IFace->getIdentifier()->isStr("NSBundle") && 7383 MD->getSelector().isKeywordSelector( 7384 {"localizedStringForKey", "value", "table"})) { 7385 IgnoreStringsWithoutSpecifiers = true; 7386 } 7387 7388 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7389 return checkFormatStringExpr( 7390 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7391 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7392 IgnoreStringsWithoutSpecifiers); 7393 } 7394 } 7395 7396 return SLCT_NotALiteral; 7397 } 7398 case Stmt::ObjCStringLiteralClass: 7399 case Stmt::StringLiteralClass: { 7400 const StringLiteral *StrE = nullptr; 7401 7402 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7403 StrE = ObjCFExpr->getString(); 7404 else 7405 StrE = cast<StringLiteral>(E); 7406 7407 if (StrE) { 7408 if (Offset.isNegative() || Offset > StrE->getLength()) { 7409 // TODO: It would be better to have an explicit warning for out of 7410 // bounds literals. 7411 return SLCT_NotALiteral; 7412 } 7413 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7414 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7415 firstDataArg, Type, InFunctionCall, CallType, 7416 CheckedVarArgs, UncoveredArg, 7417 IgnoreStringsWithoutSpecifiers); 7418 return SLCT_CheckedLiteral; 7419 } 7420 7421 return SLCT_NotALiteral; 7422 } 7423 case Stmt::BinaryOperatorClass: { 7424 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7425 7426 // A string literal + an int offset is still a string literal. 7427 if (BinOp->isAdditiveOp()) { 7428 Expr::EvalResult LResult, RResult; 7429 7430 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7431 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7432 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7433 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7434 7435 if (LIsInt != RIsInt) { 7436 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7437 7438 if (LIsInt) { 7439 if (BinOpKind == BO_Add) { 7440 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7441 E = BinOp->getRHS(); 7442 goto tryAgain; 7443 } 7444 } else { 7445 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7446 E = BinOp->getLHS(); 7447 goto tryAgain; 7448 } 7449 } 7450 } 7451 7452 return SLCT_NotALiteral; 7453 } 7454 case Stmt::UnaryOperatorClass: { 7455 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7456 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7457 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7458 Expr::EvalResult IndexResult; 7459 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7460 Expr::SE_NoSideEffects, 7461 S.isConstantEvaluated())) { 7462 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7463 /*RHS is int*/ true); 7464 E = ASE->getBase(); 7465 goto tryAgain; 7466 } 7467 } 7468 7469 return SLCT_NotALiteral; 7470 } 7471 7472 default: 7473 return SLCT_NotALiteral; 7474 } 7475 } 7476 7477 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7478 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7479 .Case("scanf", FST_Scanf) 7480 .Cases("printf", "printf0", FST_Printf) 7481 .Cases("NSString", "CFString", FST_NSString) 7482 .Case("strftime", FST_Strftime) 7483 .Case("strfmon", FST_Strfmon) 7484 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7485 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7486 .Case("os_trace", FST_OSLog) 7487 .Case("os_log", FST_OSLog) 7488 .Default(FST_Unknown); 7489 } 7490 7491 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7492 /// functions) for correct use of format strings. 7493 /// Returns true if a format string has been fully checked. 7494 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7495 ArrayRef<const Expr *> Args, 7496 bool IsCXXMember, 7497 VariadicCallType CallType, 7498 SourceLocation Loc, SourceRange Range, 7499 llvm::SmallBitVector &CheckedVarArgs) { 7500 FormatStringInfo FSI; 7501 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7502 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7503 FSI.FirstDataArg, GetFormatStringType(Format), 7504 CallType, Loc, Range, CheckedVarArgs); 7505 return false; 7506 } 7507 7508 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7509 bool HasVAListArg, unsigned format_idx, 7510 unsigned firstDataArg, FormatStringType Type, 7511 VariadicCallType CallType, 7512 SourceLocation Loc, SourceRange Range, 7513 llvm::SmallBitVector &CheckedVarArgs) { 7514 // CHECK: printf/scanf-like function is called with no format string. 7515 if (format_idx >= Args.size()) { 7516 Diag(Loc, diag::warn_missing_format_string) << Range; 7517 return false; 7518 } 7519 7520 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7521 7522 // CHECK: format string is not a string literal. 7523 // 7524 // Dynamically generated format strings are difficult to 7525 // automatically vet at compile time. Requiring that format strings 7526 // are string literals: (1) permits the checking of format strings by 7527 // the compiler and thereby (2) can practically remove the source of 7528 // many format string exploits. 7529 7530 // Format string can be either ObjC string (e.g. @"%d") or 7531 // C string (e.g. "%d") 7532 // ObjC string uses the same format specifiers as C string, so we can use 7533 // the same format string checking logic for both ObjC and C strings. 7534 UncoveredArgHandler UncoveredArg; 7535 StringLiteralCheckType CT = 7536 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7537 format_idx, firstDataArg, Type, CallType, 7538 /*IsFunctionCall*/ true, CheckedVarArgs, 7539 UncoveredArg, 7540 /*no string offset*/ llvm::APSInt(64, false) = 0); 7541 7542 // Generate a diagnostic where an uncovered argument is detected. 7543 if (UncoveredArg.hasUncoveredArg()) { 7544 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7545 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7546 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7547 } 7548 7549 if (CT != SLCT_NotALiteral) 7550 // Literal format string found, check done! 7551 return CT == SLCT_CheckedLiteral; 7552 7553 // Strftime is particular as it always uses a single 'time' argument, 7554 // so it is safe to pass a non-literal string. 7555 if (Type == FST_Strftime) 7556 return false; 7557 7558 // Do not emit diag when the string param is a macro expansion and the 7559 // format is either NSString or CFString. This is a hack to prevent 7560 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7561 // which are usually used in place of NS and CF string literals. 7562 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7563 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7564 return false; 7565 7566 // If there are no arguments specified, warn with -Wformat-security, otherwise 7567 // warn only with -Wformat-nonliteral. 7568 if (Args.size() == firstDataArg) { 7569 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7570 << OrigFormatExpr->getSourceRange(); 7571 switch (Type) { 7572 default: 7573 break; 7574 case FST_Kprintf: 7575 case FST_FreeBSDKPrintf: 7576 case FST_Printf: 7577 Diag(FormatLoc, diag::note_format_security_fixit) 7578 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7579 break; 7580 case FST_NSString: 7581 Diag(FormatLoc, diag::note_format_security_fixit) 7582 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7583 break; 7584 } 7585 } else { 7586 Diag(FormatLoc, diag::warn_format_nonliteral) 7587 << OrigFormatExpr->getSourceRange(); 7588 } 7589 return false; 7590 } 7591 7592 namespace { 7593 7594 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7595 protected: 7596 Sema &S; 7597 const FormatStringLiteral *FExpr; 7598 const Expr *OrigFormatExpr; 7599 const Sema::FormatStringType FSType; 7600 const unsigned FirstDataArg; 7601 const unsigned NumDataArgs; 7602 const char *Beg; // Start of format string. 7603 const bool HasVAListArg; 7604 ArrayRef<const Expr *> Args; 7605 unsigned FormatIdx; 7606 llvm::SmallBitVector CoveredArgs; 7607 bool usesPositionalArgs = false; 7608 bool atFirstArg = true; 7609 bool inFunctionCall; 7610 Sema::VariadicCallType CallType; 7611 llvm::SmallBitVector &CheckedVarArgs; 7612 UncoveredArgHandler &UncoveredArg; 7613 7614 public: 7615 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7616 const Expr *origFormatExpr, 7617 const Sema::FormatStringType type, unsigned firstDataArg, 7618 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7619 ArrayRef<const Expr *> Args, unsigned formatIdx, 7620 bool inFunctionCall, Sema::VariadicCallType callType, 7621 llvm::SmallBitVector &CheckedVarArgs, 7622 UncoveredArgHandler &UncoveredArg) 7623 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7624 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7625 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7626 inFunctionCall(inFunctionCall), CallType(callType), 7627 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7628 CoveredArgs.resize(numDataArgs); 7629 CoveredArgs.reset(); 7630 } 7631 7632 void DoneProcessing(); 7633 7634 void HandleIncompleteSpecifier(const char *startSpecifier, 7635 unsigned specifierLen) override; 7636 7637 void HandleInvalidLengthModifier( 7638 const analyze_format_string::FormatSpecifier &FS, 7639 const analyze_format_string::ConversionSpecifier &CS, 7640 const char *startSpecifier, unsigned specifierLen, 7641 unsigned DiagID); 7642 7643 void HandleNonStandardLengthModifier( 7644 const analyze_format_string::FormatSpecifier &FS, 7645 const char *startSpecifier, unsigned specifierLen); 7646 7647 void HandleNonStandardConversionSpecifier( 7648 const analyze_format_string::ConversionSpecifier &CS, 7649 const char *startSpecifier, unsigned specifierLen); 7650 7651 void HandlePosition(const char *startPos, unsigned posLen) override; 7652 7653 void HandleInvalidPosition(const char *startSpecifier, 7654 unsigned specifierLen, 7655 analyze_format_string::PositionContext p) override; 7656 7657 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7658 7659 void HandleNullChar(const char *nullCharacter) override; 7660 7661 template <typename Range> 7662 static void 7663 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7664 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7665 bool IsStringLocation, Range StringRange, 7666 ArrayRef<FixItHint> Fixit = None); 7667 7668 protected: 7669 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7670 const char *startSpec, 7671 unsigned specifierLen, 7672 const char *csStart, unsigned csLen); 7673 7674 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7675 const char *startSpec, 7676 unsigned specifierLen); 7677 7678 SourceRange getFormatStringRange(); 7679 CharSourceRange getSpecifierRange(const char *startSpecifier, 7680 unsigned specifierLen); 7681 SourceLocation getLocationOfByte(const char *x); 7682 7683 const Expr *getDataArg(unsigned i) const; 7684 7685 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7686 const analyze_format_string::ConversionSpecifier &CS, 7687 const char *startSpecifier, unsigned specifierLen, 7688 unsigned argIndex); 7689 7690 template <typename Range> 7691 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7692 bool IsStringLocation, Range StringRange, 7693 ArrayRef<FixItHint> Fixit = None); 7694 }; 7695 7696 } // namespace 7697 7698 SourceRange CheckFormatHandler::getFormatStringRange() { 7699 return OrigFormatExpr->getSourceRange(); 7700 } 7701 7702 CharSourceRange CheckFormatHandler:: 7703 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7704 SourceLocation Start = getLocationOfByte(startSpecifier); 7705 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7706 7707 // Advance the end SourceLocation by one due to half-open ranges. 7708 End = End.getLocWithOffset(1); 7709 7710 return CharSourceRange::getCharRange(Start, End); 7711 } 7712 7713 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7714 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7715 S.getLangOpts(), S.Context.getTargetInfo()); 7716 } 7717 7718 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7719 unsigned specifierLen){ 7720 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7721 getLocationOfByte(startSpecifier), 7722 /*IsStringLocation*/true, 7723 getSpecifierRange(startSpecifier, specifierLen)); 7724 } 7725 7726 void CheckFormatHandler::HandleInvalidLengthModifier( 7727 const analyze_format_string::FormatSpecifier &FS, 7728 const analyze_format_string::ConversionSpecifier &CS, 7729 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7730 using namespace analyze_format_string; 7731 7732 const LengthModifier &LM = FS.getLengthModifier(); 7733 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7734 7735 // See if we know how to fix this length modifier. 7736 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7737 if (FixedLM) { 7738 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7739 getLocationOfByte(LM.getStart()), 7740 /*IsStringLocation*/true, 7741 getSpecifierRange(startSpecifier, specifierLen)); 7742 7743 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7744 << FixedLM->toString() 7745 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7746 7747 } else { 7748 FixItHint Hint; 7749 if (DiagID == diag::warn_format_nonsensical_length) 7750 Hint = FixItHint::CreateRemoval(LMRange); 7751 7752 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7753 getLocationOfByte(LM.getStart()), 7754 /*IsStringLocation*/true, 7755 getSpecifierRange(startSpecifier, specifierLen), 7756 Hint); 7757 } 7758 } 7759 7760 void CheckFormatHandler::HandleNonStandardLengthModifier( 7761 const analyze_format_string::FormatSpecifier &FS, 7762 const char *startSpecifier, unsigned specifierLen) { 7763 using namespace analyze_format_string; 7764 7765 const LengthModifier &LM = FS.getLengthModifier(); 7766 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7767 7768 // See if we know how to fix this length modifier. 7769 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7770 if (FixedLM) { 7771 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7772 << LM.toString() << 0, 7773 getLocationOfByte(LM.getStart()), 7774 /*IsStringLocation*/true, 7775 getSpecifierRange(startSpecifier, specifierLen)); 7776 7777 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7778 << FixedLM->toString() 7779 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7780 7781 } else { 7782 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7783 << LM.toString() << 0, 7784 getLocationOfByte(LM.getStart()), 7785 /*IsStringLocation*/true, 7786 getSpecifierRange(startSpecifier, specifierLen)); 7787 } 7788 } 7789 7790 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7791 const analyze_format_string::ConversionSpecifier &CS, 7792 const char *startSpecifier, unsigned specifierLen) { 7793 using namespace analyze_format_string; 7794 7795 // See if we know how to fix this conversion specifier. 7796 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7797 if (FixedCS) { 7798 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7799 << CS.toString() << /*conversion specifier*/1, 7800 getLocationOfByte(CS.getStart()), 7801 /*IsStringLocation*/true, 7802 getSpecifierRange(startSpecifier, specifierLen)); 7803 7804 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7805 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7806 << FixedCS->toString() 7807 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7808 } else { 7809 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7810 << CS.toString() << /*conversion specifier*/1, 7811 getLocationOfByte(CS.getStart()), 7812 /*IsStringLocation*/true, 7813 getSpecifierRange(startSpecifier, specifierLen)); 7814 } 7815 } 7816 7817 void CheckFormatHandler::HandlePosition(const char *startPos, 7818 unsigned posLen) { 7819 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7820 getLocationOfByte(startPos), 7821 /*IsStringLocation*/true, 7822 getSpecifierRange(startPos, posLen)); 7823 } 7824 7825 void 7826 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7827 analyze_format_string::PositionContext p) { 7828 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7829 << (unsigned) p, 7830 getLocationOfByte(startPos), /*IsStringLocation*/true, 7831 getSpecifierRange(startPos, posLen)); 7832 } 7833 7834 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7835 unsigned posLen) { 7836 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7837 getLocationOfByte(startPos), 7838 /*IsStringLocation*/true, 7839 getSpecifierRange(startPos, posLen)); 7840 } 7841 7842 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7843 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7844 // The presence of a null character is likely an error. 7845 EmitFormatDiagnostic( 7846 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7847 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7848 getFormatStringRange()); 7849 } 7850 } 7851 7852 // Note that this may return NULL if there was an error parsing or building 7853 // one of the argument expressions. 7854 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7855 return Args[FirstDataArg + i]; 7856 } 7857 7858 void CheckFormatHandler::DoneProcessing() { 7859 // Does the number of data arguments exceed the number of 7860 // format conversions in the format string? 7861 if (!HasVAListArg) { 7862 // Find any arguments that weren't covered. 7863 CoveredArgs.flip(); 7864 signed notCoveredArg = CoveredArgs.find_first(); 7865 if (notCoveredArg >= 0) { 7866 assert((unsigned)notCoveredArg < NumDataArgs); 7867 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7868 } else { 7869 UncoveredArg.setAllCovered(); 7870 } 7871 } 7872 } 7873 7874 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7875 const Expr *ArgExpr) { 7876 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7877 "Invalid state"); 7878 7879 if (!ArgExpr) 7880 return; 7881 7882 SourceLocation Loc = ArgExpr->getBeginLoc(); 7883 7884 if (S.getSourceManager().isInSystemMacro(Loc)) 7885 return; 7886 7887 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7888 for (auto E : DiagnosticExprs) 7889 PDiag << E->getSourceRange(); 7890 7891 CheckFormatHandler::EmitFormatDiagnostic( 7892 S, IsFunctionCall, DiagnosticExprs[0], 7893 PDiag, Loc, /*IsStringLocation*/false, 7894 DiagnosticExprs[0]->getSourceRange()); 7895 } 7896 7897 bool 7898 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7899 SourceLocation Loc, 7900 const char *startSpec, 7901 unsigned specifierLen, 7902 const char *csStart, 7903 unsigned csLen) { 7904 bool keepGoing = true; 7905 if (argIndex < NumDataArgs) { 7906 // Consider the argument coverered, even though the specifier doesn't 7907 // make sense. 7908 CoveredArgs.set(argIndex); 7909 } 7910 else { 7911 // If argIndex exceeds the number of data arguments we 7912 // don't issue a warning because that is just a cascade of warnings (and 7913 // they may have intended '%%' anyway). We don't want to continue processing 7914 // the format string after this point, however, as we will like just get 7915 // gibberish when trying to match arguments. 7916 keepGoing = false; 7917 } 7918 7919 StringRef Specifier(csStart, csLen); 7920 7921 // If the specifier in non-printable, it could be the first byte of a UTF-8 7922 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7923 // hex value. 7924 std::string CodePointStr; 7925 if (!llvm::sys::locale::isPrint(*csStart)) { 7926 llvm::UTF32 CodePoint; 7927 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7928 const llvm::UTF8 *E = 7929 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7930 llvm::ConversionResult Result = 7931 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7932 7933 if (Result != llvm::conversionOK) { 7934 unsigned char FirstChar = *csStart; 7935 CodePoint = (llvm::UTF32)FirstChar; 7936 } 7937 7938 llvm::raw_string_ostream OS(CodePointStr); 7939 if (CodePoint < 256) 7940 OS << "\\x" << llvm::format("%02x", CodePoint); 7941 else if (CodePoint <= 0xFFFF) 7942 OS << "\\u" << llvm::format("%04x", CodePoint); 7943 else 7944 OS << "\\U" << llvm::format("%08x", CodePoint); 7945 OS.flush(); 7946 Specifier = CodePointStr; 7947 } 7948 7949 EmitFormatDiagnostic( 7950 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7951 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7952 7953 return keepGoing; 7954 } 7955 7956 void 7957 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7958 const char *startSpec, 7959 unsigned specifierLen) { 7960 EmitFormatDiagnostic( 7961 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7962 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7963 } 7964 7965 bool 7966 CheckFormatHandler::CheckNumArgs( 7967 const analyze_format_string::FormatSpecifier &FS, 7968 const analyze_format_string::ConversionSpecifier &CS, 7969 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7970 7971 if (argIndex >= NumDataArgs) { 7972 PartialDiagnostic PDiag = FS.usesPositionalArg() 7973 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7974 << (argIndex+1) << NumDataArgs) 7975 : S.PDiag(diag::warn_printf_insufficient_data_args); 7976 EmitFormatDiagnostic( 7977 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7978 getSpecifierRange(startSpecifier, specifierLen)); 7979 7980 // Since more arguments than conversion tokens are given, by extension 7981 // all arguments are covered, so mark this as so. 7982 UncoveredArg.setAllCovered(); 7983 return false; 7984 } 7985 return true; 7986 } 7987 7988 template<typename Range> 7989 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7990 SourceLocation Loc, 7991 bool IsStringLocation, 7992 Range StringRange, 7993 ArrayRef<FixItHint> FixIt) { 7994 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7995 Loc, IsStringLocation, StringRange, FixIt); 7996 } 7997 7998 /// If the format string is not within the function call, emit a note 7999 /// so that the function call and string are in diagnostic messages. 8000 /// 8001 /// \param InFunctionCall if true, the format string is within the function 8002 /// call and only one diagnostic message will be produced. Otherwise, an 8003 /// extra note will be emitted pointing to location of the format string. 8004 /// 8005 /// \param ArgumentExpr the expression that is passed as the format string 8006 /// argument in the function call. Used for getting locations when two 8007 /// diagnostics are emitted. 8008 /// 8009 /// \param PDiag the callee should already have provided any strings for the 8010 /// diagnostic message. This function only adds locations and fixits 8011 /// to diagnostics. 8012 /// 8013 /// \param Loc primary location for diagnostic. If two diagnostics are 8014 /// required, one will be at Loc and a new SourceLocation will be created for 8015 /// the other one. 8016 /// 8017 /// \param IsStringLocation if true, Loc points to the format string should be 8018 /// used for the note. Otherwise, Loc points to the argument list and will 8019 /// be used with PDiag. 8020 /// 8021 /// \param StringRange some or all of the string to highlight. This is 8022 /// templated so it can accept either a CharSourceRange or a SourceRange. 8023 /// 8024 /// \param FixIt optional fix it hint for the format string. 8025 template <typename Range> 8026 void CheckFormatHandler::EmitFormatDiagnostic( 8027 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8028 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8029 Range StringRange, ArrayRef<FixItHint> FixIt) { 8030 if (InFunctionCall) { 8031 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8032 D << StringRange; 8033 D << FixIt; 8034 } else { 8035 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8036 << ArgumentExpr->getSourceRange(); 8037 8038 const Sema::SemaDiagnosticBuilder &Note = 8039 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8040 diag::note_format_string_defined); 8041 8042 Note << StringRange; 8043 Note << FixIt; 8044 } 8045 } 8046 8047 //===--- CHECK: Printf format string checking ------------------------------===// 8048 8049 namespace { 8050 8051 class CheckPrintfHandler : public CheckFormatHandler { 8052 public: 8053 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8054 const Expr *origFormatExpr, 8055 const Sema::FormatStringType type, unsigned firstDataArg, 8056 unsigned numDataArgs, bool isObjC, const char *beg, 8057 bool hasVAListArg, ArrayRef<const Expr *> Args, 8058 unsigned formatIdx, bool inFunctionCall, 8059 Sema::VariadicCallType CallType, 8060 llvm::SmallBitVector &CheckedVarArgs, 8061 UncoveredArgHandler &UncoveredArg) 8062 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8063 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8064 inFunctionCall, CallType, CheckedVarArgs, 8065 UncoveredArg) {} 8066 8067 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8068 8069 /// Returns true if '%@' specifiers are allowed in the format string. 8070 bool allowsObjCArg() const { 8071 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8072 FSType == Sema::FST_OSTrace; 8073 } 8074 8075 bool HandleInvalidPrintfConversionSpecifier( 8076 const analyze_printf::PrintfSpecifier &FS, 8077 const char *startSpecifier, 8078 unsigned specifierLen) override; 8079 8080 void handleInvalidMaskType(StringRef MaskType) override; 8081 8082 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8083 const char *startSpecifier, 8084 unsigned specifierLen) override; 8085 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8086 const char *StartSpecifier, 8087 unsigned SpecifierLen, 8088 const Expr *E); 8089 8090 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8091 const char *startSpecifier, unsigned specifierLen); 8092 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8093 const analyze_printf::OptionalAmount &Amt, 8094 unsigned type, 8095 const char *startSpecifier, unsigned specifierLen); 8096 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8097 const analyze_printf::OptionalFlag &flag, 8098 const char *startSpecifier, unsigned specifierLen); 8099 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8100 const analyze_printf::OptionalFlag &ignoredFlag, 8101 const analyze_printf::OptionalFlag &flag, 8102 const char *startSpecifier, unsigned specifierLen); 8103 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8104 const Expr *E); 8105 8106 void HandleEmptyObjCModifierFlag(const char *startFlag, 8107 unsigned flagLen) override; 8108 8109 void HandleInvalidObjCModifierFlag(const char *startFlag, 8110 unsigned flagLen) override; 8111 8112 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8113 const char *flagsEnd, 8114 const char *conversionPosition) 8115 override; 8116 }; 8117 8118 } // namespace 8119 8120 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8121 const analyze_printf::PrintfSpecifier &FS, 8122 const char *startSpecifier, 8123 unsigned specifierLen) { 8124 const analyze_printf::PrintfConversionSpecifier &CS = 8125 FS.getConversionSpecifier(); 8126 8127 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8128 getLocationOfByte(CS.getStart()), 8129 startSpecifier, specifierLen, 8130 CS.getStart(), CS.getLength()); 8131 } 8132 8133 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8134 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8135 } 8136 8137 bool CheckPrintfHandler::HandleAmount( 8138 const analyze_format_string::OptionalAmount &Amt, 8139 unsigned k, const char *startSpecifier, 8140 unsigned specifierLen) { 8141 if (Amt.hasDataArgument()) { 8142 if (!HasVAListArg) { 8143 unsigned argIndex = Amt.getArgIndex(); 8144 if (argIndex >= NumDataArgs) { 8145 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8146 << k, 8147 getLocationOfByte(Amt.getStart()), 8148 /*IsStringLocation*/true, 8149 getSpecifierRange(startSpecifier, specifierLen)); 8150 // Don't do any more checking. We will just emit 8151 // spurious errors. 8152 return false; 8153 } 8154 8155 // Type check the data argument. It should be an 'int'. 8156 // Although not in conformance with C99, we also allow the argument to be 8157 // an 'unsigned int' as that is a reasonably safe case. GCC also 8158 // doesn't emit a warning for that case. 8159 CoveredArgs.set(argIndex); 8160 const Expr *Arg = getDataArg(argIndex); 8161 if (!Arg) 8162 return false; 8163 8164 QualType T = Arg->getType(); 8165 8166 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8167 assert(AT.isValid()); 8168 8169 if (!AT.matchesType(S.Context, T)) { 8170 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8171 << k << AT.getRepresentativeTypeName(S.Context) 8172 << T << Arg->getSourceRange(), 8173 getLocationOfByte(Amt.getStart()), 8174 /*IsStringLocation*/true, 8175 getSpecifierRange(startSpecifier, specifierLen)); 8176 // Don't do any more checking. We will just emit 8177 // spurious errors. 8178 return false; 8179 } 8180 } 8181 } 8182 return true; 8183 } 8184 8185 void CheckPrintfHandler::HandleInvalidAmount( 8186 const analyze_printf::PrintfSpecifier &FS, 8187 const analyze_printf::OptionalAmount &Amt, 8188 unsigned type, 8189 const char *startSpecifier, 8190 unsigned specifierLen) { 8191 const analyze_printf::PrintfConversionSpecifier &CS = 8192 FS.getConversionSpecifier(); 8193 8194 FixItHint fixit = 8195 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8196 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8197 Amt.getConstantLength())) 8198 : FixItHint(); 8199 8200 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8201 << type << CS.toString(), 8202 getLocationOfByte(Amt.getStart()), 8203 /*IsStringLocation*/true, 8204 getSpecifierRange(startSpecifier, specifierLen), 8205 fixit); 8206 } 8207 8208 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8209 const analyze_printf::OptionalFlag &flag, 8210 const char *startSpecifier, 8211 unsigned specifierLen) { 8212 // Warn about pointless flag with a fixit removal. 8213 const analyze_printf::PrintfConversionSpecifier &CS = 8214 FS.getConversionSpecifier(); 8215 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8216 << flag.toString() << CS.toString(), 8217 getLocationOfByte(flag.getPosition()), 8218 /*IsStringLocation*/true, 8219 getSpecifierRange(startSpecifier, specifierLen), 8220 FixItHint::CreateRemoval( 8221 getSpecifierRange(flag.getPosition(), 1))); 8222 } 8223 8224 void CheckPrintfHandler::HandleIgnoredFlag( 8225 const analyze_printf::PrintfSpecifier &FS, 8226 const analyze_printf::OptionalFlag &ignoredFlag, 8227 const analyze_printf::OptionalFlag &flag, 8228 const char *startSpecifier, 8229 unsigned specifierLen) { 8230 // Warn about ignored flag with a fixit removal. 8231 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8232 << ignoredFlag.toString() << flag.toString(), 8233 getLocationOfByte(ignoredFlag.getPosition()), 8234 /*IsStringLocation*/true, 8235 getSpecifierRange(startSpecifier, specifierLen), 8236 FixItHint::CreateRemoval( 8237 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8238 } 8239 8240 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8241 unsigned flagLen) { 8242 // Warn about an empty flag. 8243 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8244 getLocationOfByte(startFlag), 8245 /*IsStringLocation*/true, 8246 getSpecifierRange(startFlag, flagLen)); 8247 } 8248 8249 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8250 unsigned flagLen) { 8251 // Warn about an invalid flag. 8252 auto Range = getSpecifierRange(startFlag, flagLen); 8253 StringRef flag(startFlag, flagLen); 8254 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8255 getLocationOfByte(startFlag), 8256 /*IsStringLocation*/true, 8257 Range, FixItHint::CreateRemoval(Range)); 8258 } 8259 8260 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8261 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8262 // Warn about using '[...]' without a '@' conversion. 8263 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8264 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8265 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8266 getLocationOfByte(conversionPosition), 8267 /*IsStringLocation*/true, 8268 Range, FixItHint::CreateRemoval(Range)); 8269 } 8270 8271 // Determines if the specified is a C++ class or struct containing 8272 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8273 // "c_str()"). 8274 template<typename MemberKind> 8275 static llvm::SmallPtrSet<MemberKind*, 1> 8276 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8277 const RecordType *RT = Ty->getAs<RecordType>(); 8278 llvm::SmallPtrSet<MemberKind*, 1> Results; 8279 8280 if (!RT) 8281 return Results; 8282 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8283 if (!RD || !RD->getDefinition()) 8284 return Results; 8285 8286 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8287 Sema::LookupMemberName); 8288 R.suppressDiagnostics(); 8289 8290 // We just need to include all members of the right kind turned up by the 8291 // filter, at this point. 8292 if (S.LookupQualifiedName(R, RT->getDecl())) 8293 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8294 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8295 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8296 Results.insert(FK); 8297 } 8298 return Results; 8299 } 8300 8301 /// Check if we could call '.c_str()' on an object. 8302 /// 8303 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8304 /// allow the call, or if it would be ambiguous). 8305 bool Sema::hasCStrMethod(const Expr *E) { 8306 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8307 8308 MethodSet Results = 8309 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8310 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8311 MI != ME; ++MI) 8312 if ((*MI)->getMinRequiredArguments() == 0) 8313 return true; 8314 return false; 8315 } 8316 8317 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8318 // better diagnostic if so. AT is assumed to be valid. 8319 // Returns true when a c_str() conversion method is found. 8320 bool CheckPrintfHandler::checkForCStrMembers( 8321 const analyze_printf::ArgType &AT, const Expr *E) { 8322 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8323 8324 MethodSet Results = 8325 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8326 8327 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8328 MI != ME; ++MI) { 8329 const CXXMethodDecl *Method = *MI; 8330 if (Method->getMinRequiredArguments() == 0 && 8331 AT.matchesType(S.Context, Method->getReturnType())) { 8332 // FIXME: Suggest parens if the expression needs them. 8333 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8334 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8335 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8336 return true; 8337 } 8338 } 8339 8340 return false; 8341 } 8342 8343 bool 8344 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8345 &FS, 8346 const char *startSpecifier, 8347 unsigned specifierLen) { 8348 using namespace analyze_format_string; 8349 using namespace analyze_printf; 8350 8351 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8352 8353 if (FS.consumesDataArgument()) { 8354 if (atFirstArg) { 8355 atFirstArg = false; 8356 usesPositionalArgs = FS.usesPositionalArg(); 8357 } 8358 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8359 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8360 startSpecifier, specifierLen); 8361 return false; 8362 } 8363 } 8364 8365 // First check if the field width, precision, and conversion specifier 8366 // have matching data arguments. 8367 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8368 startSpecifier, specifierLen)) { 8369 return false; 8370 } 8371 8372 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8373 startSpecifier, specifierLen)) { 8374 return false; 8375 } 8376 8377 if (!CS.consumesDataArgument()) { 8378 // FIXME: Technically specifying a precision or field width here 8379 // makes no sense. Worth issuing a warning at some point. 8380 return true; 8381 } 8382 8383 // Consume the argument. 8384 unsigned argIndex = FS.getArgIndex(); 8385 if (argIndex < NumDataArgs) { 8386 // The check to see if the argIndex is valid will come later. 8387 // We set the bit here because we may exit early from this 8388 // function if we encounter some other error. 8389 CoveredArgs.set(argIndex); 8390 } 8391 8392 // FreeBSD kernel extensions. 8393 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8394 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8395 // We need at least two arguments. 8396 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8397 return false; 8398 8399 // Claim the second argument. 8400 CoveredArgs.set(argIndex + 1); 8401 8402 // Type check the first argument (int for %b, pointer for %D) 8403 const Expr *Ex = getDataArg(argIndex); 8404 const analyze_printf::ArgType &AT = 8405 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8406 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8407 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8408 EmitFormatDiagnostic( 8409 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8410 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8411 << false << Ex->getSourceRange(), 8412 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8413 getSpecifierRange(startSpecifier, specifierLen)); 8414 8415 // Type check the second argument (char * for both %b and %D) 8416 Ex = getDataArg(argIndex + 1); 8417 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8418 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8419 EmitFormatDiagnostic( 8420 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8421 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8422 << false << Ex->getSourceRange(), 8423 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8424 getSpecifierRange(startSpecifier, specifierLen)); 8425 8426 return true; 8427 } 8428 8429 // Check for using an Objective-C specific conversion specifier 8430 // in a non-ObjC literal. 8431 if (!allowsObjCArg() && CS.isObjCArg()) { 8432 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8433 specifierLen); 8434 } 8435 8436 // %P can only be used with os_log. 8437 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8438 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8439 specifierLen); 8440 } 8441 8442 // %n is not allowed with os_log. 8443 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8444 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8445 getLocationOfByte(CS.getStart()), 8446 /*IsStringLocation*/ false, 8447 getSpecifierRange(startSpecifier, specifierLen)); 8448 8449 return true; 8450 } 8451 8452 // Only scalars are allowed for os_trace. 8453 if (FSType == Sema::FST_OSTrace && 8454 (CS.getKind() == ConversionSpecifier::PArg || 8455 CS.getKind() == ConversionSpecifier::sArg || 8456 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8457 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8458 specifierLen); 8459 } 8460 8461 // Check for use of public/private annotation outside of os_log(). 8462 if (FSType != Sema::FST_OSLog) { 8463 if (FS.isPublic().isSet()) { 8464 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8465 << "public", 8466 getLocationOfByte(FS.isPublic().getPosition()), 8467 /*IsStringLocation*/ false, 8468 getSpecifierRange(startSpecifier, specifierLen)); 8469 } 8470 if (FS.isPrivate().isSet()) { 8471 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8472 << "private", 8473 getLocationOfByte(FS.isPrivate().getPosition()), 8474 /*IsStringLocation*/ false, 8475 getSpecifierRange(startSpecifier, specifierLen)); 8476 } 8477 } 8478 8479 // Check for invalid use of field width 8480 if (!FS.hasValidFieldWidth()) { 8481 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8482 startSpecifier, specifierLen); 8483 } 8484 8485 // Check for invalid use of precision 8486 if (!FS.hasValidPrecision()) { 8487 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8488 startSpecifier, specifierLen); 8489 } 8490 8491 // Precision is mandatory for %P specifier. 8492 if (CS.getKind() == ConversionSpecifier::PArg && 8493 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8494 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8495 getLocationOfByte(startSpecifier), 8496 /*IsStringLocation*/ false, 8497 getSpecifierRange(startSpecifier, specifierLen)); 8498 } 8499 8500 // Check each flag does not conflict with any other component. 8501 if (!FS.hasValidThousandsGroupingPrefix()) 8502 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8503 if (!FS.hasValidLeadingZeros()) 8504 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8505 if (!FS.hasValidPlusPrefix()) 8506 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8507 if (!FS.hasValidSpacePrefix()) 8508 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8509 if (!FS.hasValidAlternativeForm()) 8510 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8511 if (!FS.hasValidLeftJustified()) 8512 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8513 8514 // Check that flags are not ignored by another flag 8515 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8516 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8517 startSpecifier, specifierLen); 8518 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8519 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8520 startSpecifier, specifierLen); 8521 8522 // Check the length modifier is valid with the given conversion specifier. 8523 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8524 S.getLangOpts())) 8525 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8526 diag::warn_format_nonsensical_length); 8527 else if (!FS.hasStandardLengthModifier()) 8528 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8529 else if (!FS.hasStandardLengthConversionCombination()) 8530 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8531 diag::warn_format_non_standard_conversion_spec); 8532 8533 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8534 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8535 8536 // The remaining checks depend on the data arguments. 8537 if (HasVAListArg) 8538 return true; 8539 8540 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8541 return false; 8542 8543 const Expr *Arg = getDataArg(argIndex); 8544 if (!Arg) 8545 return true; 8546 8547 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8548 } 8549 8550 static bool requiresParensToAddCast(const Expr *E) { 8551 // FIXME: We should have a general way to reason about operator 8552 // precedence and whether parens are actually needed here. 8553 // Take care of a few common cases where they aren't. 8554 const Expr *Inside = E->IgnoreImpCasts(); 8555 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8556 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8557 8558 switch (Inside->getStmtClass()) { 8559 case Stmt::ArraySubscriptExprClass: 8560 case Stmt::CallExprClass: 8561 case Stmt::CharacterLiteralClass: 8562 case Stmt::CXXBoolLiteralExprClass: 8563 case Stmt::DeclRefExprClass: 8564 case Stmt::FloatingLiteralClass: 8565 case Stmt::IntegerLiteralClass: 8566 case Stmt::MemberExprClass: 8567 case Stmt::ObjCArrayLiteralClass: 8568 case Stmt::ObjCBoolLiteralExprClass: 8569 case Stmt::ObjCBoxedExprClass: 8570 case Stmt::ObjCDictionaryLiteralClass: 8571 case Stmt::ObjCEncodeExprClass: 8572 case Stmt::ObjCIvarRefExprClass: 8573 case Stmt::ObjCMessageExprClass: 8574 case Stmt::ObjCPropertyRefExprClass: 8575 case Stmt::ObjCStringLiteralClass: 8576 case Stmt::ObjCSubscriptRefExprClass: 8577 case Stmt::ParenExprClass: 8578 case Stmt::StringLiteralClass: 8579 case Stmt::UnaryOperatorClass: 8580 return false; 8581 default: 8582 return true; 8583 } 8584 } 8585 8586 static std::pair<QualType, StringRef> 8587 shouldNotPrintDirectly(const ASTContext &Context, 8588 QualType IntendedTy, 8589 const Expr *E) { 8590 // Use a 'while' to peel off layers of typedefs. 8591 QualType TyTy = IntendedTy; 8592 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8593 StringRef Name = UserTy->getDecl()->getName(); 8594 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8595 .Case("CFIndex", Context.getNSIntegerType()) 8596 .Case("NSInteger", Context.getNSIntegerType()) 8597 .Case("NSUInteger", Context.getNSUIntegerType()) 8598 .Case("SInt32", Context.IntTy) 8599 .Case("UInt32", Context.UnsignedIntTy) 8600 .Default(QualType()); 8601 8602 if (!CastTy.isNull()) 8603 return std::make_pair(CastTy, Name); 8604 8605 TyTy = UserTy->desugar(); 8606 } 8607 8608 // Strip parens if necessary. 8609 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8610 return shouldNotPrintDirectly(Context, 8611 PE->getSubExpr()->getType(), 8612 PE->getSubExpr()); 8613 8614 // If this is a conditional expression, then its result type is constructed 8615 // via usual arithmetic conversions and thus there might be no necessary 8616 // typedef sugar there. Recurse to operands to check for NSInteger & 8617 // Co. usage condition. 8618 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8619 QualType TrueTy, FalseTy; 8620 StringRef TrueName, FalseName; 8621 8622 std::tie(TrueTy, TrueName) = 8623 shouldNotPrintDirectly(Context, 8624 CO->getTrueExpr()->getType(), 8625 CO->getTrueExpr()); 8626 std::tie(FalseTy, FalseName) = 8627 shouldNotPrintDirectly(Context, 8628 CO->getFalseExpr()->getType(), 8629 CO->getFalseExpr()); 8630 8631 if (TrueTy == FalseTy) 8632 return std::make_pair(TrueTy, TrueName); 8633 else if (TrueTy.isNull()) 8634 return std::make_pair(FalseTy, FalseName); 8635 else if (FalseTy.isNull()) 8636 return std::make_pair(TrueTy, TrueName); 8637 } 8638 8639 return std::make_pair(QualType(), StringRef()); 8640 } 8641 8642 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8643 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8644 /// type do not count. 8645 static bool 8646 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8647 QualType From = ICE->getSubExpr()->getType(); 8648 QualType To = ICE->getType(); 8649 // It's an integer promotion if the destination type is the promoted 8650 // source type. 8651 if (ICE->getCastKind() == CK_IntegralCast && 8652 From->isPromotableIntegerType() && 8653 S.Context.getPromotedIntegerType(From) == To) 8654 return true; 8655 // Look through vector types, since we do default argument promotion for 8656 // those in OpenCL. 8657 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8658 From = VecTy->getElementType(); 8659 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8660 To = VecTy->getElementType(); 8661 // It's a floating promotion if the source type is a lower rank. 8662 return ICE->getCastKind() == CK_FloatingCast && 8663 S.Context.getFloatingTypeOrder(From, To) < 0; 8664 } 8665 8666 bool 8667 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8668 const char *StartSpecifier, 8669 unsigned SpecifierLen, 8670 const Expr *E) { 8671 using namespace analyze_format_string; 8672 using namespace analyze_printf; 8673 8674 // Now type check the data expression that matches the 8675 // format specifier. 8676 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8677 if (!AT.isValid()) 8678 return true; 8679 8680 QualType ExprTy = E->getType(); 8681 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8682 ExprTy = TET->getUnderlyingExpr()->getType(); 8683 } 8684 8685 // Diagnose attempts to print a boolean value as a character. Unlike other 8686 // -Wformat diagnostics, this is fine from a type perspective, but it still 8687 // doesn't make sense. 8688 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8689 E->isKnownToHaveBooleanValue()) { 8690 const CharSourceRange &CSR = 8691 getSpecifierRange(StartSpecifier, SpecifierLen); 8692 SmallString<4> FSString; 8693 llvm::raw_svector_ostream os(FSString); 8694 FS.toString(os); 8695 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8696 << FSString, 8697 E->getExprLoc(), false, CSR); 8698 return true; 8699 } 8700 8701 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8702 if (Match == analyze_printf::ArgType::Match) 8703 return true; 8704 8705 // Look through argument promotions for our error message's reported type. 8706 // This includes the integral and floating promotions, but excludes array 8707 // and function pointer decay (seeing that an argument intended to be a 8708 // string has type 'char [6]' is probably more confusing than 'char *') and 8709 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8710 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8711 if (isArithmeticArgumentPromotion(S, ICE)) { 8712 E = ICE->getSubExpr(); 8713 ExprTy = E->getType(); 8714 8715 // Check if we didn't match because of an implicit cast from a 'char' 8716 // or 'short' to an 'int'. This is done because printf is a varargs 8717 // function. 8718 if (ICE->getType() == S.Context.IntTy || 8719 ICE->getType() == S.Context.UnsignedIntTy) { 8720 // All further checking is done on the subexpression 8721 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8722 AT.matchesType(S.Context, ExprTy); 8723 if (ImplicitMatch == analyze_printf::ArgType::Match) 8724 return true; 8725 if (ImplicitMatch == ArgType::NoMatchPedantic || 8726 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8727 Match = ImplicitMatch; 8728 } 8729 } 8730 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8731 // Special case for 'a', which has type 'int' in C. 8732 // Note, however, that we do /not/ want to treat multibyte constants like 8733 // 'MooV' as characters! This form is deprecated but still exists. In 8734 // addition, don't treat expressions as of type 'char' if one byte length 8735 // modifier is provided. 8736 if (ExprTy == S.Context.IntTy && 8737 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 8738 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8739 ExprTy = S.Context.CharTy; 8740 } 8741 8742 // Look through enums to their underlying type. 8743 bool IsEnum = false; 8744 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8745 ExprTy = EnumTy->getDecl()->getIntegerType(); 8746 IsEnum = true; 8747 } 8748 8749 // %C in an Objective-C context prints a unichar, not a wchar_t. 8750 // If the argument is an integer of some kind, believe the %C and suggest 8751 // a cast instead of changing the conversion specifier. 8752 QualType IntendedTy = ExprTy; 8753 if (isObjCContext() && 8754 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8755 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8756 !ExprTy->isCharType()) { 8757 // 'unichar' is defined as a typedef of unsigned short, but we should 8758 // prefer using the typedef if it is visible. 8759 IntendedTy = S.Context.UnsignedShortTy; 8760 8761 // While we are here, check if the value is an IntegerLiteral that happens 8762 // to be within the valid range. 8763 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8764 const llvm::APInt &V = IL->getValue(); 8765 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8766 return true; 8767 } 8768 8769 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8770 Sema::LookupOrdinaryName); 8771 if (S.LookupName(Result, S.getCurScope())) { 8772 NamedDecl *ND = Result.getFoundDecl(); 8773 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8774 if (TD->getUnderlyingType() == IntendedTy) 8775 IntendedTy = S.Context.getTypedefType(TD); 8776 } 8777 } 8778 } 8779 8780 // Special-case some of Darwin's platform-independence types by suggesting 8781 // casts to primitive types that are known to be large enough. 8782 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8783 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8784 QualType CastTy; 8785 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8786 if (!CastTy.isNull()) { 8787 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8788 // (long in ASTContext). Only complain to pedants. 8789 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8790 (AT.isSizeT() || AT.isPtrdiffT()) && 8791 AT.matchesType(S.Context, CastTy)) 8792 Match = ArgType::NoMatchPedantic; 8793 IntendedTy = CastTy; 8794 ShouldNotPrintDirectly = true; 8795 } 8796 } 8797 8798 // We may be able to offer a FixItHint if it is a supported type. 8799 PrintfSpecifier fixedFS = FS; 8800 bool Success = 8801 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8802 8803 if (Success) { 8804 // Get the fix string from the fixed format specifier 8805 SmallString<16> buf; 8806 llvm::raw_svector_ostream os(buf); 8807 fixedFS.toString(os); 8808 8809 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8810 8811 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8812 unsigned Diag; 8813 switch (Match) { 8814 case ArgType::Match: llvm_unreachable("expected non-matching"); 8815 case ArgType::NoMatchPedantic: 8816 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8817 break; 8818 case ArgType::NoMatchTypeConfusion: 8819 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8820 break; 8821 case ArgType::NoMatch: 8822 Diag = diag::warn_format_conversion_argument_type_mismatch; 8823 break; 8824 } 8825 8826 // In this case, the specifier is wrong and should be changed to match 8827 // the argument. 8828 EmitFormatDiagnostic(S.PDiag(Diag) 8829 << AT.getRepresentativeTypeName(S.Context) 8830 << IntendedTy << IsEnum << E->getSourceRange(), 8831 E->getBeginLoc(), 8832 /*IsStringLocation*/ false, SpecRange, 8833 FixItHint::CreateReplacement(SpecRange, os.str())); 8834 } else { 8835 // The canonical type for formatting this value is different from the 8836 // actual type of the expression. (This occurs, for example, with Darwin's 8837 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8838 // should be printed as 'long' for 64-bit compatibility.) 8839 // Rather than emitting a normal format/argument mismatch, we want to 8840 // add a cast to the recommended type (and correct the format string 8841 // if necessary). 8842 SmallString<16> CastBuf; 8843 llvm::raw_svector_ostream CastFix(CastBuf); 8844 CastFix << "("; 8845 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8846 CastFix << ")"; 8847 8848 SmallVector<FixItHint,4> Hints; 8849 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8850 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8851 8852 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8853 // If there's already a cast present, just replace it. 8854 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8855 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8856 8857 } else if (!requiresParensToAddCast(E)) { 8858 // If the expression has high enough precedence, 8859 // just write the C-style cast. 8860 Hints.push_back( 8861 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8862 } else { 8863 // Otherwise, add parens around the expression as well as the cast. 8864 CastFix << "("; 8865 Hints.push_back( 8866 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8867 8868 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8869 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8870 } 8871 8872 if (ShouldNotPrintDirectly) { 8873 // The expression has a type that should not be printed directly. 8874 // We extract the name from the typedef because we don't want to show 8875 // the underlying type in the diagnostic. 8876 StringRef Name; 8877 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8878 Name = TypedefTy->getDecl()->getName(); 8879 else 8880 Name = CastTyName; 8881 unsigned Diag = Match == ArgType::NoMatchPedantic 8882 ? diag::warn_format_argument_needs_cast_pedantic 8883 : diag::warn_format_argument_needs_cast; 8884 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8885 << E->getSourceRange(), 8886 E->getBeginLoc(), /*IsStringLocation=*/false, 8887 SpecRange, Hints); 8888 } else { 8889 // In this case, the expression could be printed using a different 8890 // specifier, but we've decided that the specifier is probably correct 8891 // and we should cast instead. Just use the normal warning message. 8892 EmitFormatDiagnostic( 8893 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8894 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8895 << E->getSourceRange(), 8896 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8897 } 8898 } 8899 } else { 8900 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8901 SpecifierLen); 8902 // Since the warning for passing non-POD types to variadic functions 8903 // was deferred until now, we emit a warning for non-POD 8904 // arguments here. 8905 switch (S.isValidVarArgType(ExprTy)) { 8906 case Sema::VAK_Valid: 8907 case Sema::VAK_ValidInCXX11: { 8908 unsigned Diag; 8909 switch (Match) { 8910 case ArgType::Match: llvm_unreachable("expected non-matching"); 8911 case ArgType::NoMatchPedantic: 8912 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8913 break; 8914 case ArgType::NoMatchTypeConfusion: 8915 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8916 break; 8917 case ArgType::NoMatch: 8918 Diag = diag::warn_format_conversion_argument_type_mismatch; 8919 break; 8920 } 8921 8922 EmitFormatDiagnostic( 8923 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8924 << IsEnum << CSR << E->getSourceRange(), 8925 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8926 break; 8927 } 8928 case Sema::VAK_Undefined: 8929 case Sema::VAK_MSVCUndefined: 8930 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8931 << S.getLangOpts().CPlusPlus11 << ExprTy 8932 << CallType 8933 << AT.getRepresentativeTypeName(S.Context) << CSR 8934 << E->getSourceRange(), 8935 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8936 checkForCStrMembers(AT, E); 8937 break; 8938 8939 case Sema::VAK_Invalid: 8940 if (ExprTy->isObjCObjectType()) 8941 EmitFormatDiagnostic( 8942 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8943 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8944 << AT.getRepresentativeTypeName(S.Context) << CSR 8945 << E->getSourceRange(), 8946 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8947 else 8948 // FIXME: If this is an initializer list, suggest removing the braces 8949 // or inserting a cast to the target type. 8950 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8951 << isa<InitListExpr>(E) << ExprTy << CallType 8952 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8953 break; 8954 } 8955 8956 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8957 "format string specifier index out of range"); 8958 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8959 } 8960 8961 return true; 8962 } 8963 8964 //===--- CHECK: Scanf format string checking ------------------------------===// 8965 8966 namespace { 8967 8968 class CheckScanfHandler : public CheckFormatHandler { 8969 public: 8970 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8971 const Expr *origFormatExpr, Sema::FormatStringType type, 8972 unsigned firstDataArg, unsigned numDataArgs, 8973 const char *beg, bool hasVAListArg, 8974 ArrayRef<const Expr *> Args, unsigned formatIdx, 8975 bool inFunctionCall, Sema::VariadicCallType CallType, 8976 llvm::SmallBitVector &CheckedVarArgs, 8977 UncoveredArgHandler &UncoveredArg) 8978 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8979 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8980 inFunctionCall, CallType, CheckedVarArgs, 8981 UncoveredArg) {} 8982 8983 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8984 const char *startSpecifier, 8985 unsigned specifierLen) override; 8986 8987 bool HandleInvalidScanfConversionSpecifier( 8988 const analyze_scanf::ScanfSpecifier &FS, 8989 const char *startSpecifier, 8990 unsigned specifierLen) override; 8991 8992 void HandleIncompleteScanList(const char *start, const char *end) override; 8993 }; 8994 8995 } // namespace 8996 8997 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8998 const char *end) { 8999 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9000 getLocationOfByte(end), /*IsStringLocation*/true, 9001 getSpecifierRange(start, end - start)); 9002 } 9003 9004 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9005 const analyze_scanf::ScanfSpecifier &FS, 9006 const char *startSpecifier, 9007 unsigned specifierLen) { 9008 const analyze_scanf::ScanfConversionSpecifier &CS = 9009 FS.getConversionSpecifier(); 9010 9011 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9012 getLocationOfByte(CS.getStart()), 9013 startSpecifier, specifierLen, 9014 CS.getStart(), CS.getLength()); 9015 } 9016 9017 bool CheckScanfHandler::HandleScanfSpecifier( 9018 const analyze_scanf::ScanfSpecifier &FS, 9019 const char *startSpecifier, 9020 unsigned specifierLen) { 9021 using namespace analyze_scanf; 9022 using namespace analyze_format_string; 9023 9024 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9025 9026 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9027 // be used to decide if we are using positional arguments consistently. 9028 if (FS.consumesDataArgument()) { 9029 if (atFirstArg) { 9030 atFirstArg = false; 9031 usesPositionalArgs = FS.usesPositionalArg(); 9032 } 9033 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9034 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9035 startSpecifier, specifierLen); 9036 return false; 9037 } 9038 } 9039 9040 // Check if the field with is non-zero. 9041 const OptionalAmount &Amt = FS.getFieldWidth(); 9042 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9043 if (Amt.getConstantAmount() == 0) { 9044 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9045 Amt.getConstantLength()); 9046 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9047 getLocationOfByte(Amt.getStart()), 9048 /*IsStringLocation*/true, R, 9049 FixItHint::CreateRemoval(R)); 9050 } 9051 } 9052 9053 if (!FS.consumesDataArgument()) { 9054 // FIXME: Technically specifying a precision or field width here 9055 // makes no sense. Worth issuing a warning at some point. 9056 return true; 9057 } 9058 9059 // Consume the argument. 9060 unsigned argIndex = FS.getArgIndex(); 9061 if (argIndex < NumDataArgs) { 9062 // The check to see if the argIndex is valid will come later. 9063 // We set the bit here because we may exit early from this 9064 // function if we encounter some other error. 9065 CoveredArgs.set(argIndex); 9066 } 9067 9068 // Check the length modifier is valid with the given conversion specifier. 9069 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9070 S.getLangOpts())) 9071 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9072 diag::warn_format_nonsensical_length); 9073 else if (!FS.hasStandardLengthModifier()) 9074 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9075 else if (!FS.hasStandardLengthConversionCombination()) 9076 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9077 diag::warn_format_non_standard_conversion_spec); 9078 9079 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9080 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9081 9082 // The remaining checks depend on the data arguments. 9083 if (HasVAListArg) 9084 return true; 9085 9086 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9087 return false; 9088 9089 // Check that the argument type matches the format specifier. 9090 const Expr *Ex = getDataArg(argIndex); 9091 if (!Ex) 9092 return true; 9093 9094 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9095 9096 if (!AT.isValid()) { 9097 return true; 9098 } 9099 9100 analyze_format_string::ArgType::MatchKind Match = 9101 AT.matchesType(S.Context, Ex->getType()); 9102 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9103 if (Match == analyze_format_string::ArgType::Match) 9104 return true; 9105 9106 ScanfSpecifier fixedFS = FS; 9107 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9108 S.getLangOpts(), S.Context); 9109 9110 unsigned Diag = 9111 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9112 : diag::warn_format_conversion_argument_type_mismatch; 9113 9114 if (Success) { 9115 // Get the fix string from the fixed format specifier. 9116 SmallString<128> buf; 9117 llvm::raw_svector_ostream os(buf); 9118 fixedFS.toString(os); 9119 9120 EmitFormatDiagnostic( 9121 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9122 << Ex->getType() << false << Ex->getSourceRange(), 9123 Ex->getBeginLoc(), 9124 /*IsStringLocation*/ false, 9125 getSpecifierRange(startSpecifier, specifierLen), 9126 FixItHint::CreateReplacement( 9127 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9128 } else { 9129 EmitFormatDiagnostic(S.PDiag(Diag) 9130 << AT.getRepresentativeTypeName(S.Context) 9131 << Ex->getType() << false << Ex->getSourceRange(), 9132 Ex->getBeginLoc(), 9133 /*IsStringLocation*/ false, 9134 getSpecifierRange(startSpecifier, specifierLen)); 9135 } 9136 9137 return true; 9138 } 9139 9140 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9141 const Expr *OrigFormatExpr, 9142 ArrayRef<const Expr *> Args, 9143 bool HasVAListArg, unsigned format_idx, 9144 unsigned firstDataArg, 9145 Sema::FormatStringType Type, 9146 bool inFunctionCall, 9147 Sema::VariadicCallType CallType, 9148 llvm::SmallBitVector &CheckedVarArgs, 9149 UncoveredArgHandler &UncoveredArg, 9150 bool IgnoreStringsWithoutSpecifiers) { 9151 // CHECK: is the format string a wide literal? 9152 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9153 CheckFormatHandler::EmitFormatDiagnostic( 9154 S, inFunctionCall, Args[format_idx], 9155 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9156 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9157 return; 9158 } 9159 9160 // Str - The format string. NOTE: this is NOT null-terminated! 9161 StringRef StrRef = FExpr->getString(); 9162 const char *Str = StrRef.data(); 9163 // Account for cases where the string literal is truncated in a declaration. 9164 const ConstantArrayType *T = 9165 S.Context.getAsConstantArrayType(FExpr->getType()); 9166 assert(T && "String literal not of constant array type!"); 9167 size_t TypeSize = T->getSize().getZExtValue(); 9168 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9169 const unsigned numDataArgs = Args.size() - firstDataArg; 9170 9171 if (IgnoreStringsWithoutSpecifiers && 9172 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9173 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9174 return; 9175 9176 // Emit a warning if the string literal is truncated and does not contain an 9177 // embedded null character. 9178 if (TypeSize <= StrRef.size() && 9179 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9180 CheckFormatHandler::EmitFormatDiagnostic( 9181 S, inFunctionCall, Args[format_idx], 9182 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9183 FExpr->getBeginLoc(), 9184 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9185 return; 9186 } 9187 9188 // CHECK: empty format string? 9189 if (StrLen == 0 && numDataArgs > 0) { 9190 CheckFormatHandler::EmitFormatDiagnostic( 9191 S, inFunctionCall, Args[format_idx], 9192 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9193 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9194 return; 9195 } 9196 9197 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9198 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9199 Type == Sema::FST_OSTrace) { 9200 CheckPrintfHandler H( 9201 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9202 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9203 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9204 CheckedVarArgs, UncoveredArg); 9205 9206 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9207 S.getLangOpts(), 9208 S.Context.getTargetInfo(), 9209 Type == Sema::FST_FreeBSDKPrintf)) 9210 H.DoneProcessing(); 9211 } else if (Type == Sema::FST_Scanf) { 9212 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9213 numDataArgs, Str, HasVAListArg, Args, format_idx, 9214 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9215 9216 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9217 S.getLangOpts(), 9218 S.Context.getTargetInfo())) 9219 H.DoneProcessing(); 9220 } // TODO: handle other formats 9221 } 9222 9223 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9224 // Str - The format string. NOTE: this is NOT null-terminated! 9225 StringRef StrRef = FExpr->getString(); 9226 const char *Str = StrRef.data(); 9227 // Account for cases where the string literal is truncated in a declaration. 9228 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9229 assert(T && "String literal not of constant array type!"); 9230 size_t TypeSize = T->getSize().getZExtValue(); 9231 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9232 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9233 getLangOpts(), 9234 Context.getTargetInfo()); 9235 } 9236 9237 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9238 9239 // Returns the related absolute value function that is larger, of 0 if one 9240 // does not exist. 9241 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9242 switch (AbsFunction) { 9243 default: 9244 return 0; 9245 9246 case Builtin::BI__builtin_abs: 9247 return Builtin::BI__builtin_labs; 9248 case Builtin::BI__builtin_labs: 9249 return Builtin::BI__builtin_llabs; 9250 case Builtin::BI__builtin_llabs: 9251 return 0; 9252 9253 case Builtin::BI__builtin_fabsf: 9254 return Builtin::BI__builtin_fabs; 9255 case Builtin::BI__builtin_fabs: 9256 return Builtin::BI__builtin_fabsl; 9257 case Builtin::BI__builtin_fabsl: 9258 return 0; 9259 9260 case Builtin::BI__builtin_cabsf: 9261 return Builtin::BI__builtin_cabs; 9262 case Builtin::BI__builtin_cabs: 9263 return Builtin::BI__builtin_cabsl; 9264 case Builtin::BI__builtin_cabsl: 9265 return 0; 9266 9267 case Builtin::BIabs: 9268 return Builtin::BIlabs; 9269 case Builtin::BIlabs: 9270 return Builtin::BIllabs; 9271 case Builtin::BIllabs: 9272 return 0; 9273 9274 case Builtin::BIfabsf: 9275 return Builtin::BIfabs; 9276 case Builtin::BIfabs: 9277 return Builtin::BIfabsl; 9278 case Builtin::BIfabsl: 9279 return 0; 9280 9281 case Builtin::BIcabsf: 9282 return Builtin::BIcabs; 9283 case Builtin::BIcabs: 9284 return Builtin::BIcabsl; 9285 case Builtin::BIcabsl: 9286 return 0; 9287 } 9288 } 9289 9290 // Returns the argument type of the absolute value function. 9291 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9292 unsigned AbsType) { 9293 if (AbsType == 0) 9294 return QualType(); 9295 9296 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9297 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9298 if (Error != ASTContext::GE_None) 9299 return QualType(); 9300 9301 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9302 if (!FT) 9303 return QualType(); 9304 9305 if (FT->getNumParams() != 1) 9306 return QualType(); 9307 9308 return FT->getParamType(0); 9309 } 9310 9311 // Returns the best absolute value function, or zero, based on type and 9312 // current absolute value function. 9313 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9314 unsigned AbsFunctionKind) { 9315 unsigned BestKind = 0; 9316 uint64_t ArgSize = Context.getTypeSize(ArgType); 9317 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9318 Kind = getLargerAbsoluteValueFunction(Kind)) { 9319 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9320 if (Context.getTypeSize(ParamType) >= ArgSize) { 9321 if (BestKind == 0) 9322 BestKind = Kind; 9323 else if (Context.hasSameType(ParamType, ArgType)) { 9324 BestKind = Kind; 9325 break; 9326 } 9327 } 9328 } 9329 return BestKind; 9330 } 9331 9332 enum AbsoluteValueKind { 9333 AVK_Integer, 9334 AVK_Floating, 9335 AVK_Complex 9336 }; 9337 9338 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9339 if (T->isIntegralOrEnumerationType()) 9340 return AVK_Integer; 9341 if (T->isRealFloatingType()) 9342 return AVK_Floating; 9343 if (T->isAnyComplexType()) 9344 return AVK_Complex; 9345 9346 llvm_unreachable("Type not integer, floating, or complex"); 9347 } 9348 9349 // Changes the absolute value function to a different type. Preserves whether 9350 // the function is a builtin. 9351 static unsigned changeAbsFunction(unsigned AbsKind, 9352 AbsoluteValueKind ValueKind) { 9353 switch (ValueKind) { 9354 case AVK_Integer: 9355 switch (AbsKind) { 9356 default: 9357 return 0; 9358 case Builtin::BI__builtin_fabsf: 9359 case Builtin::BI__builtin_fabs: 9360 case Builtin::BI__builtin_fabsl: 9361 case Builtin::BI__builtin_cabsf: 9362 case Builtin::BI__builtin_cabs: 9363 case Builtin::BI__builtin_cabsl: 9364 return Builtin::BI__builtin_abs; 9365 case Builtin::BIfabsf: 9366 case Builtin::BIfabs: 9367 case Builtin::BIfabsl: 9368 case Builtin::BIcabsf: 9369 case Builtin::BIcabs: 9370 case Builtin::BIcabsl: 9371 return Builtin::BIabs; 9372 } 9373 case AVK_Floating: 9374 switch (AbsKind) { 9375 default: 9376 return 0; 9377 case Builtin::BI__builtin_abs: 9378 case Builtin::BI__builtin_labs: 9379 case Builtin::BI__builtin_llabs: 9380 case Builtin::BI__builtin_cabsf: 9381 case Builtin::BI__builtin_cabs: 9382 case Builtin::BI__builtin_cabsl: 9383 return Builtin::BI__builtin_fabsf; 9384 case Builtin::BIabs: 9385 case Builtin::BIlabs: 9386 case Builtin::BIllabs: 9387 case Builtin::BIcabsf: 9388 case Builtin::BIcabs: 9389 case Builtin::BIcabsl: 9390 return Builtin::BIfabsf; 9391 } 9392 case AVK_Complex: 9393 switch (AbsKind) { 9394 default: 9395 return 0; 9396 case Builtin::BI__builtin_abs: 9397 case Builtin::BI__builtin_labs: 9398 case Builtin::BI__builtin_llabs: 9399 case Builtin::BI__builtin_fabsf: 9400 case Builtin::BI__builtin_fabs: 9401 case Builtin::BI__builtin_fabsl: 9402 return Builtin::BI__builtin_cabsf; 9403 case Builtin::BIabs: 9404 case Builtin::BIlabs: 9405 case Builtin::BIllabs: 9406 case Builtin::BIfabsf: 9407 case Builtin::BIfabs: 9408 case Builtin::BIfabsl: 9409 return Builtin::BIcabsf; 9410 } 9411 } 9412 llvm_unreachable("Unable to convert function"); 9413 } 9414 9415 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9416 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9417 if (!FnInfo) 9418 return 0; 9419 9420 switch (FDecl->getBuiltinID()) { 9421 default: 9422 return 0; 9423 case Builtin::BI__builtin_abs: 9424 case Builtin::BI__builtin_fabs: 9425 case Builtin::BI__builtin_fabsf: 9426 case Builtin::BI__builtin_fabsl: 9427 case Builtin::BI__builtin_labs: 9428 case Builtin::BI__builtin_llabs: 9429 case Builtin::BI__builtin_cabs: 9430 case Builtin::BI__builtin_cabsf: 9431 case Builtin::BI__builtin_cabsl: 9432 case Builtin::BIabs: 9433 case Builtin::BIlabs: 9434 case Builtin::BIllabs: 9435 case Builtin::BIfabs: 9436 case Builtin::BIfabsf: 9437 case Builtin::BIfabsl: 9438 case Builtin::BIcabs: 9439 case Builtin::BIcabsf: 9440 case Builtin::BIcabsl: 9441 return FDecl->getBuiltinID(); 9442 } 9443 llvm_unreachable("Unknown Builtin type"); 9444 } 9445 9446 // If the replacement is valid, emit a note with replacement function. 9447 // Additionally, suggest including the proper header if not already included. 9448 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9449 unsigned AbsKind, QualType ArgType) { 9450 bool EmitHeaderHint = true; 9451 const char *HeaderName = nullptr; 9452 const char *FunctionName = nullptr; 9453 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9454 FunctionName = "std::abs"; 9455 if (ArgType->isIntegralOrEnumerationType()) { 9456 HeaderName = "cstdlib"; 9457 } else if (ArgType->isRealFloatingType()) { 9458 HeaderName = "cmath"; 9459 } else { 9460 llvm_unreachable("Invalid Type"); 9461 } 9462 9463 // Lookup all std::abs 9464 if (NamespaceDecl *Std = S.getStdNamespace()) { 9465 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9466 R.suppressDiagnostics(); 9467 S.LookupQualifiedName(R, Std); 9468 9469 for (const auto *I : R) { 9470 const FunctionDecl *FDecl = nullptr; 9471 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9472 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9473 } else { 9474 FDecl = dyn_cast<FunctionDecl>(I); 9475 } 9476 if (!FDecl) 9477 continue; 9478 9479 // Found std::abs(), check that they are the right ones. 9480 if (FDecl->getNumParams() != 1) 9481 continue; 9482 9483 // Check that the parameter type can handle the argument. 9484 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9485 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9486 S.Context.getTypeSize(ArgType) <= 9487 S.Context.getTypeSize(ParamType)) { 9488 // Found a function, don't need the header hint. 9489 EmitHeaderHint = false; 9490 break; 9491 } 9492 } 9493 } 9494 } else { 9495 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9496 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9497 9498 if (HeaderName) { 9499 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9500 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9501 R.suppressDiagnostics(); 9502 S.LookupName(R, S.getCurScope()); 9503 9504 if (R.isSingleResult()) { 9505 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9506 if (FD && FD->getBuiltinID() == AbsKind) { 9507 EmitHeaderHint = false; 9508 } else { 9509 return; 9510 } 9511 } else if (!R.empty()) { 9512 return; 9513 } 9514 } 9515 } 9516 9517 S.Diag(Loc, diag::note_replace_abs_function) 9518 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9519 9520 if (!HeaderName) 9521 return; 9522 9523 if (!EmitHeaderHint) 9524 return; 9525 9526 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9527 << FunctionName; 9528 } 9529 9530 template <std::size_t StrLen> 9531 static bool IsStdFunction(const FunctionDecl *FDecl, 9532 const char (&Str)[StrLen]) { 9533 if (!FDecl) 9534 return false; 9535 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9536 return false; 9537 if (!FDecl->isInStdNamespace()) 9538 return false; 9539 9540 return true; 9541 } 9542 9543 // Warn when using the wrong abs() function. 9544 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9545 const FunctionDecl *FDecl) { 9546 if (Call->getNumArgs() != 1) 9547 return; 9548 9549 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9550 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9551 if (AbsKind == 0 && !IsStdAbs) 9552 return; 9553 9554 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9555 QualType ParamType = Call->getArg(0)->getType(); 9556 9557 // Unsigned types cannot be negative. Suggest removing the absolute value 9558 // function call. 9559 if (ArgType->isUnsignedIntegerType()) { 9560 const char *FunctionName = 9561 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9562 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9563 Diag(Call->getExprLoc(), diag::note_remove_abs) 9564 << FunctionName 9565 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9566 return; 9567 } 9568 9569 // Taking the absolute value of a pointer is very suspicious, they probably 9570 // wanted to index into an array, dereference a pointer, call a function, etc. 9571 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9572 unsigned DiagType = 0; 9573 if (ArgType->isFunctionType()) 9574 DiagType = 1; 9575 else if (ArgType->isArrayType()) 9576 DiagType = 2; 9577 9578 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9579 return; 9580 } 9581 9582 // std::abs has overloads which prevent most of the absolute value problems 9583 // from occurring. 9584 if (IsStdAbs) 9585 return; 9586 9587 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9588 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9589 9590 // The argument and parameter are the same kind. Check if they are the right 9591 // size. 9592 if (ArgValueKind == ParamValueKind) { 9593 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9594 return; 9595 9596 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9597 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9598 << FDecl << ArgType << ParamType; 9599 9600 if (NewAbsKind == 0) 9601 return; 9602 9603 emitReplacement(*this, Call->getExprLoc(), 9604 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9605 return; 9606 } 9607 9608 // ArgValueKind != ParamValueKind 9609 // The wrong type of absolute value function was used. Attempt to find the 9610 // proper one. 9611 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9612 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9613 if (NewAbsKind == 0) 9614 return; 9615 9616 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9617 << FDecl << ParamValueKind << ArgValueKind; 9618 9619 emitReplacement(*this, Call->getExprLoc(), 9620 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9621 } 9622 9623 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9624 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9625 const FunctionDecl *FDecl) { 9626 if (!Call || !FDecl) return; 9627 9628 // Ignore template specializations and macros. 9629 if (inTemplateInstantiation()) return; 9630 if (Call->getExprLoc().isMacroID()) return; 9631 9632 // Only care about the one template argument, two function parameter std::max 9633 if (Call->getNumArgs() != 2) return; 9634 if (!IsStdFunction(FDecl, "max")) return; 9635 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9636 if (!ArgList) return; 9637 if (ArgList->size() != 1) return; 9638 9639 // Check that template type argument is unsigned integer. 9640 const auto& TA = ArgList->get(0); 9641 if (TA.getKind() != TemplateArgument::Type) return; 9642 QualType ArgType = TA.getAsType(); 9643 if (!ArgType->isUnsignedIntegerType()) return; 9644 9645 // See if either argument is a literal zero. 9646 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9647 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9648 if (!MTE) return false; 9649 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9650 if (!Num) return false; 9651 if (Num->getValue() != 0) return false; 9652 return true; 9653 }; 9654 9655 const Expr *FirstArg = Call->getArg(0); 9656 const Expr *SecondArg = Call->getArg(1); 9657 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9658 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9659 9660 // Only warn when exactly one argument is zero. 9661 if (IsFirstArgZero == IsSecondArgZero) return; 9662 9663 SourceRange FirstRange = FirstArg->getSourceRange(); 9664 SourceRange SecondRange = SecondArg->getSourceRange(); 9665 9666 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9667 9668 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9669 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9670 9671 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9672 SourceRange RemovalRange; 9673 if (IsFirstArgZero) { 9674 RemovalRange = SourceRange(FirstRange.getBegin(), 9675 SecondRange.getBegin().getLocWithOffset(-1)); 9676 } else { 9677 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9678 SecondRange.getEnd()); 9679 } 9680 9681 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9682 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9683 << FixItHint::CreateRemoval(RemovalRange); 9684 } 9685 9686 //===--- CHECK: Standard memory functions ---------------------------------===// 9687 9688 /// Takes the expression passed to the size_t parameter of functions 9689 /// such as memcmp, strncat, etc and warns if it's a comparison. 9690 /// 9691 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9692 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9693 IdentifierInfo *FnName, 9694 SourceLocation FnLoc, 9695 SourceLocation RParenLoc) { 9696 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9697 if (!Size) 9698 return false; 9699 9700 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9701 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9702 return false; 9703 9704 SourceRange SizeRange = Size->getSourceRange(); 9705 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9706 << SizeRange << FnName; 9707 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9708 << FnName 9709 << FixItHint::CreateInsertion( 9710 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9711 << FixItHint::CreateRemoval(RParenLoc); 9712 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9713 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9714 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9715 ")"); 9716 9717 return true; 9718 } 9719 9720 /// Determine whether the given type is or contains a dynamic class type 9721 /// (e.g., whether it has a vtable). 9722 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9723 bool &IsContained) { 9724 // Look through array types while ignoring qualifiers. 9725 const Type *Ty = T->getBaseElementTypeUnsafe(); 9726 IsContained = false; 9727 9728 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9729 RD = RD ? RD->getDefinition() : nullptr; 9730 if (!RD || RD->isInvalidDecl()) 9731 return nullptr; 9732 9733 if (RD->isDynamicClass()) 9734 return RD; 9735 9736 // Check all the fields. If any bases were dynamic, the class is dynamic. 9737 // It's impossible for a class to transitively contain itself by value, so 9738 // infinite recursion is impossible. 9739 for (auto *FD : RD->fields()) { 9740 bool SubContained; 9741 if (const CXXRecordDecl *ContainedRD = 9742 getContainedDynamicClass(FD->getType(), SubContained)) { 9743 IsContained = true; 9744 return ContainedRD; 9745 } 9746 } 9747 9748 return nullptr; 9749 } 9750 9751 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9752 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9753 if (Unary->getKind() == UETT_SizeOf) 9754 return Unary; 9755 return nullptr; 9756 } 9757 9758 /// If E is a sizeof expression, returns its argument expression, 9759 /// otherwise returns NULL. 9760 static const Expr *getSizeOfExprArg(const Expr *E) { 9761 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9762 if (!SizeOf->isArgumentType()) 9763 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9764 return nullptr; 9765 } 9766 9767 /// If E is a sizeof expression, returns its argument type. 9768 static QualType getSizeOfArgType(const Expr *E) { 9769 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9770 return SizeOf->getTypeOfArgument(); 9771 return QualType(); 9772 } 9773 9774 namespace { 9775 9776 struct SearchNonTrivialToInitializeField 9777 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9778 using Super = 9779 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9780 9781 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9782 9783 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9784 SourceLocation SL) { 9785 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9786 asDerived().visitArray(PDIK, AT, SL); 9787 return; 9788 } 9789 9790 Super::visitWithKind(PDIK, FT, SL); 9791 } 9792 9793 void visitARCStrong(QualType FT, SourceLocation SL) { 9794 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9795 } 9796 void visitARCWeak(QualType FT, SourceLocation SL) { 9797 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9798 } 9799 void visitStruct(QualType FT, SourceLocation SL) { 9800 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9801 visit(FD->getType(), FD->getLocation()); 9802 } 9803 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9804 const ArrayType *AT, SourceLocation SL) { 9805 visit(getContext().getBaseElementType(AT), SL); 9806 } 9807 void visitTrivial(QualType FT, SourceLocation SL) {} 9808 9809 static void diag(QualType RT, const Expr *E, Sema &S) { 9810 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9811 } 9812 9813 ASTContext &getContext() { return S.getASTContext(); } 9814 9815 const Expr *E; 9816 Sema &S; 9817 }; 9818 9819 struct SearchNonTrivialToCopyField 9820 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9821 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9822 9823 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9824 9825 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9826 SourceLocation SL) { 9827 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9828 asDerived().visitArray(PCK, AT, SL); 9829 return; 9830 } 9831 9832 Super::visitWithKind(PCK, FT, SL); 9833 } 9834 9835 void visitARCStrong(QualType FT, SourceLocation SL) { 9836 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9837 } 9838 void visitARCWeak(QualType FT, SourceLocation SL) { 9839 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9840 } 9841 void visitStruct(QualType FT, SourceLocation SL) { 9842 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9843 visit(FD->getType(), FD->getLocation()); 9844 } 9845 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9846 SourceLocation SL) { 9847 visit(getContext().getBaseElementType(AT), SL); 9848 } 9849 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9850 SourceLocation SL) {} 9851 void visitTrivial(QualType FT, SourceLocation SL) {} 9852 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9853 9854 static void diag(QualType RT, const Expr *E, Sema &S) { 9855 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9856 } 9857 9858 ASTContext &getContext() { return S.getASTContext(); } 9859 9860 const Expr *E; 9861 Sema &S; 9862 }; 9863 9864 } 9865 9866 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9867 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9868 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9869 9870 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9871 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9872 return false; 9873 9874 return doesExprLikelyComputeSize(BO->getLHS()) || 9875 doesExprLikelyComputeSize(BO->getRHS()); 9876 } 9877 9878 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9879 } 9880 9881 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9882 /// 9883 /// \code 9884 /// #define MACRO 0 9885 /// foo(MACRO); 9886 /// foo(0); 9887 /// \endcode 9888 /// 9889 /// This should return true for the first call to foo, but not for the second 9890 /// (regardless of whether foo is a macro or function). 9891 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9892 SourceLocation CallLoc, 9893 SourceLocation ArgLoc) { 9894 if (!CallLoc.isMacroID()) 9895 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9896 9897 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9898 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9899 } 9900 9901 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9902 /// last two arguments transposed. 9903 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9904 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9905 return; 9906 9907 const Expr *SizeArg = 9908 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9909 9910 auto isLiteralZero = [](const Expr *E) { 9911 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9912 }; 9913 9914 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9915 SourceLocation CallLoc = Call->getRParenLoc(); 9916 SourceManager &SM = S.getSourceManager(); 9917 if (isLiteralZero(SizeArg) && 9918 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9919 9920 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9921 9922 // Some platforms #define bzero to __builtin_memset. See if this is the 9923 // case, and if so, emit a better diagnostic. 9924 if (BId == Builtin::BIbzero || 9925 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9926 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9927 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9928 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9929 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9930 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9931 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9932 } 9933 return; 9934 } 9935 9936 // If the second argument to a memset is a sizeof expression and the third 9937 // isn't, this is also likely an error. This should catch 9938 // 'memset(buf, sizeof(buf), 0xff)'. 9939 if (BId == Builtin::BImemset && 9940 doesExprLikelyComputeSize(Call->getArg(1)) && 9941 !doesExprLikelyComputeSize(Call->getArg(2))) { 9942 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9943 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9944 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9945 return; 9946 } 9947 } 9948 9949 /// Check for dangerous or invalid arguments to memset(). 9950 /// 9951 /// This issues warnings on known problematic, dangerous or unspecified 9952 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9953 /// function calls. 9954 /// 9955 /// \param Call The call expression to diagnose. 9956 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9957 unsigned BId, 9958 IdentifierInfo *FnName) { 9959 assert(BId != 0); 9960 9961 // It is possible to have a non-standard definition of memset. Validate 9962 // we have enough arguments, and if not, abort further checking. 9963 unsigned ExpectedNumArgs = 9964 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9965 if (Call->getNumArgs() < ExpectedNumArgs) 9966 return; 9967 9968 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9969 BId == Builtin::BIstrndup ? 1 : 2); 9970 unsigned LenArg = 9971 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9972 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9973 9974 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9975 Call->getBeginLoc(), Call->getRParenLoc())) 9976 return; 9977 9978 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9979 CheckMemaccessSize(*this, BId, Call); 9980 9981 // We have special checking when the length is a sizeof expression. 9982 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9983 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9984 llvm::FoldingSetNodeID SizeOfArgID; 9985 9986 // Although widely used, 'bzero' is not a standard function. Be more strict 9987 // with the argument types before allowing diagnostics and only allow the 9988 // form bzero(ptr, sizeof(...)). 9989 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9990 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9991 return; 9992 9993 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9994 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9995 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9996 9997 QualType DestTy = Dest->getType(); 9998 QualType PointeeTy; 9999 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10000 PointeeTy = DestPtrTy->getPointeeType(); 10001 10002 // Never warn about void type pointers. This can be used to suppress 10003 // false positives. 10004 if (PointeeTy->isVoidType()) 10005 continue; 10006 10007 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10008 // actually comparing the expressions for equality. Because computing the 10009 // expression IDs can be expensive, we only do this if the diagnostic is 10010 // enabled. 10011 if (SizeOfArg && 10012 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10013 SizeOfArg->getExprLoc())) { 10014 // We only compute IDs for expressions if the warning is enabled, and 10015 // cache the sizeof arg's ID. 10016 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10017 SizeOfArg->Profile(SizeOfArgID, Context, true); 10018 llvm::FoldingSetNodeID DestID; 10019 Dest->Profile(DestID, Context, true); 10020 if (DestID == SizeOfArgID) { 10021 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10022 // over sizeof(src) as well. 10023 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10024 StringRef ReadableName = FnName->getName(); 10025 10026 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10027 if (UnaryOp->getOpcode() == UO_AddrOf) 10028 ActionIdx = 1; // If its an address-of operator, just remove it. 10029 if (!PointeeTy->isIncompleteType() && 10030 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10031 ActionIdx = 2; // If the pointee's size is sizeof(char), 10032 // suggest an explicit length. 10033 10034 // If the function is defined as a builtin macro, do not show macro 10035 // expansion. 10036 SourceLocation SL = SizeOfArg->getExprLoc(); 10037 SourceRange DSR = Dest->getSourceRange(); 10038 SourceRange SSR = SizeOfArg->getSourceRange(); 10039 SourceManager &SM = getSourceManager(); 10040 10041 if (SM.isMacroArgExpansion(SL)) { 10042 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10043 SL = SM.getSpellingLoc(SL); 10044 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10045 SM.getSpellingLoc(DSR.getEnd())); 10046 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10047 SM.getSpellingLoc(SSR.getEnd())); 10048 } 10049 10050 DiagRuntimeBehavior(SL, SizeOfArg, 10051 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10052 << ReadableName 10053 << PointeeTy 10054 << DestTy 10055 << DSR 10056 << SSR); 10057 DiagRuntimeBehavior(SL, SizeOfArg, 10058 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10059 << ActionIdx 10060 << SSR); 10061 10062 break; 10063 } 10064 } 10065 10066 // Also check for cases where the sizeof argument is the exact same 10067 // type as the memory argument, and where it points to a user-defined 10068 // record type. 10069 if (SizeOfArgTy != QualType()) { 10070 if (PointeeTy->isRecordType() && 10071 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10072 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10073 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10074 << FnName << SizeOfArgTy << ArgIdx 10075 << PointeeTy << Dest->getSourceRange() 10076 << LenExpr->getSourceRange()); 10077 break; 10078 } 10079 } 10080 } else if (DestTy->isArrayType()) { 10081 PointeeTy = DestTy; 10082 } 10083 10084 if (PointeeTy == QualType()) 10085 continue; 10086 10087 // Always complain about dynamic classes. 10088 bool IsContained; 10089 if (const CXXRecordDecl *ContainedRD = 10090 getContainedDynamicClass(PointeeTy, IsContained)) { 10091 10092 unsigned OperationType = 0; 10093 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10094 // "overwritten" if we're warning about the destination for any call 10095 // but memcmp; otherwise a verb appropriate to the call. 10096 if (ArgIdx != 0 || IsCmp) { 10097 if (BId == Builtin::BImemcpy) 10098 OperationType = 1; 10099 else if(BId == Builtin::BImemmove) 10100 OperationType = 2; 10101 else if (IsCmp) 10102 OperationType = 3; 10103 } 10104 10105 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10106 PDiag(diag::warn_dyn_class_memaccess) 10107 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10108 << IsContained << ContainedRD << OperationType 10109 << Call->getCallee()->getSourceRange()); 10110 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10111 BId != Builtin::BImemset) 10112 DiagRuntimeBehavior( 10113 Dest->getExprLoc(), Dest, 10114 PDiag(diag::warn_arc_object_memaccess) 10115 << ArgIdx << FnName << PointeeTy 10116 << Call->getCallee()->getSourceRange()); 10117 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10118 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10119 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10120 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10121 PDiag(diag::warn_cstruct_memaccess) 10122 << ArgIdx << FnName << PointeeTy << 0); 10123 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10124 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10125 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10126 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10127 PDiag(diag::warn_cstruct_memaccess) 10128 << ArgIdx << FnName << PointeeTy << 1); 10129 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10130 } else { 10131 continue; 10132 } 10133 } else 10134 continue; 10135 10136 DiagRuntimeBehavior( 10137 Dest->getExprLoc(), Dest, 10138 PDiag(diag::note_bad_memaccess_silence) 10139 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10140 break; 10141 } 10142 } 10143 10144 // A little helper routine: ignore addition and subtraction of integer literals. 10145 // This intentionally does not ignore all integer constant expressions because 10146 // we don't want to remove sizeof(). 10147 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10148 Ex = Ex->IgnoreParenCasts(); 10149 10150 while (true) { 10151 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10152 if (!BO || !BO->isAdditiveOp()) 10153 break; 10154 10155 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10156 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10157 10158 if (isa<IntegerLiteral>(RHS)) 10159 Ex = LHS; 10160 else if (isa<IntegerLiteral>(LHS)) 10161 Ex = RHS; 10162 else 10163 break; 10164 } 10165 10166 return Ex; 10167 } 10168 10169 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10170 ASTContext &Context) { 10171 // Only handle constant-sized or VLAs, but not flexible members. 10172 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10173 // Only issue the FIXIT for arrays of size > 1. 10174 if (CAT->getSize().getSExtValue() <= 1) 10175 return false; 10176 } else if (!Ty->isVariableArrayType()) { 10177 return false; 10178 } 10179 return true; 10180 } 10181 10182 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10183 // be the size of the source, instead of the destination. 10184 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10185 IdentifierInfo *FnName) { 10186 10187 // Don't crash if the user has the wrong number of arguments 10188 unsigned NumArgs = Call->getNumArgs(); 10189 if ((NumArgs != 3) && (NumArgs != 4)) 10190 return; 10191 10192 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10193 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10194 const Expr *CompareWithSrc = nullptr; 10195 10196 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10197 Call->getBeginLoc(), Call->getRParenLoc())) 10198 return; 10199 10200 // Look for 'strlcpy(dst, x, sizeof(x))' 10201 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10202 CompareWithSrc = Ex; 10203 else { 10204 // Look for 'strlcpy(dst, x, strlen(x))' 10205 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10206 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10207 SizeCall->getNumArgs() == 1) 10208 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10209 } 10210 } 10211 10212 if (!CompareWithSrc) 10213 return; 10214 10215 // Determine if the argument to sizeof/strlen is equal to the source 10216 // argument. In principle there's all kinds of things you could do 10217 // here, for instance creating an == expression and evaluating it with 10218 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10219 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10220 if (!SrcArgDRE) 10221 return; 10222 10223 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10224 if (!CompareWithSrcDRE || 10225 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10226 return; 10227 10228 const Expr *OriginalSizeArg = Call->getArg(2); 10229 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10230 << OriginalSizeArg->getSourceRange() << FnName; 10231 10232 // Output a FIXIT hint if the destination is an array (rather than a 10233 // pointer to an array). This could be enhanced to handle some 10234 // pointers if we know the actual size, like if DstArg is 'array+2' 10235 // we could say 'sizeof(array)-2'. 10236 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10237 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10238 return; 10239 10240 SmallString<128> sizeString; 10241 llvm::raw_svector_ostream OS(sizeString); 10242 OS << "sizeof("; 10243 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10244 OS << ")"; 10245 10246 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10247 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10248 OS.str()); 10249 } 10250 10251 /// Check if two expressions refer to the same declaration. 10252 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10253 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10254 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10255 return D1->getDecl() == D2->getDecl(); 10256 return false; 10257 } 10258 10259 static const Expr *getStrlenExprArg(const Expr *E) { 10260 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10261 const FunctionDecl *FD = CE->getDirectCallee(); 10262 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10263 return nullptr; 10264 return CE->getArg(0)->IgnoreParenCasts(); 10265 } 10266 return nullptr; 10267 } 10268 10269 // Warn on anti-patterns as the 'size' argument to strncat. 10270 // The correct size argument should look like following: 10271 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10272 void Sema::CheckStrncatArguments(const CallExpr *CE, 10273 IdentifierInfo *FnName) { 10274 // Don't crash if the user has the wrong number of arguments. 10275 if (CE->getNumArgs() < 3) 10276 return; 10277 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10278 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10279 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10280 10281 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10282 CE->getRParenLoc())) 10283 return; 10284 10285 // Identify common expressions, which are wrongly used as the size argument 10286 // to strncat and may lead to buffer overflows. 10287 unsigned PatternType = 0; 10288 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10289 // - sizeof(dst) 10290 if (referToTheSameDecl(SizeOfArg, DstArg)) 10291 PatternType = 1; 10292 // - sizeof(src) 10293 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10294 PatternType = 2; 10295 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10296 if (BE->getOpcode() == BO_Sub) { 10297 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10298 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10299 // - sizeof(dst) - strlen(dst) 10300 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10301 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10302 PatternType = 1; 10303 // - sizeof(src) - (anything) 10304 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10305 PatternType = 2; 10306 } 10307 } 10308 10309 if (PatternType == 0) 10310 return; 10311 10312 // Generate the diagnostic. 10313 SourceLocation SL = LenArg->getBeginLoc(); 10314 SourceRange SR = LenArg->getSourceRange(); 10315 SourceManager &SM = getSourceManager(); 10316 10317 // If the function is defined as a builtin macro, do not show macro expansion. 10318 if (SM.isMacroArgExpansion(SL)) { 10319 SL = SM.getSpellingLoc(SL); 10320 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10321 SM.getSpellingLoc(SR.getEnd())); 10322 } 10323 10324 // Check if the destination is an array (rather than a pointer to an array). 10325 QualType DstTy = DstArg->getType(); 10326 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10327 Context); 10328 if (!isKnownSizeArray) { 10329 if (PatternType == 1) 10330 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10331 else 10332 Diag(SL, diag::warn_strncat_src_size) << SR; 10333 return; 10334 } 10335 10336 if (PatternType == 1) 10337 Diag(SL, diag::warn_strncat_large_size) << SR; 10338 else 10339 Diag(SL, diag::warn_strncat_src_size) << SR; 10340 10341 SmallString<128> sizeString; 10342 llvm::raw_svector_ostream OS(sizeString); 10343 OS << "sizeof("; 10344 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10345 OS << ") - "; 10346 OS << "strlen("; 10347 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10348 OS << ") - 1"; 10349 10350 Diag(SL, diag::note_strncat_wrong_size) 10351 << FixItHint::CreateReplacement(SR, OS.str()); 10352 } 10353 10354 namespace { 10355 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10356 const UnaryOperator *UnaryExpr, const Decl *D) { 10357 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10358 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10359 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10360 return; 10361 } 10362 } 10363 10364 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10365 const UnaryOperator *UnaryExpr) { 10366 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10367 const Decl *D = Lvalue->getDecl(); 10368 if (isa<VarDecl, FunctionDecl>(D)) 10369 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10370 } 10371 10372 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10373 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10374 Lvalue->getMemberDecl()); 10375 } 10376 10377 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10378 const UnaryOperator *UnaryExpr) { 10379 const auto *Lambda = dyn_cast<LambdaExpr>( 10380 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10381 if (!Lambda) 10382 return; 10383 10384 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10385 << CalleeName << 2 /*object: lambda expression*/; 10386 } 10387 10388 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10389 const DeclRefExpr *Lvalue) { 10390 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10391 if (Var == nullptr) 10392 return; 10393 10394 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10395 << CalleeName << 0 /*object: */ << Var; 10396 } 10397 10398 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10399 const CastExpr *Cast) { 10400 SmallString<128> SizeString; 10401 llvm::raw_svector_ostream OS(SizeString); 10402 10403 clang::CastKind Kind = Cast->getCastKind(); 10404 if (Kind == clang::CK_BitCast && 10405 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10406 return; 10407 if (Kind == clang::CK_IntegralToPointer && 10408 !isa<IntegerLiteral>( 10409 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10410 return; 10411 10412 switch (Cast->getCastKind()) { 10413 case clang::CK_BitCast: 10414 case clang::CK_IntegralToPointer: 10415 case clang::CK_FunctionToPointerDecay: 10416 OS << '\''; 10417 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10418 OS << '\''; 10419 break; 10420 default: 10421 return; 10422 } 10423 10424 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10425 << CalleeName << 0 /*object: */ << OS.str(); 10426 } 10427 } // namespace 10428 10429 /// Alerts the user that they are attempting to free a non-malloc'd object. 10430 void Sema::CheckFreeArguments(const CallExpr *E) { 10431 const std::string CalleeName = 10432 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10433 10434 { // Prefer something that doesn't involve a cast to make things simpler. 10435 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10436 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10437 switch (UnaryExpr->getOpcode()) { 10438 case UnaryOperator::Opcode::UO_AddrOf: 10439 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10440 case UnaryOperator::Opcode::UO_Plus: 10441 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 10442 default: 10443 break; 10444 } 10445 10446 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10447 if (Lvalue->getType()->isArrayType()) 10448 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10449 10450 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 10451 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 10452 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 10453 return; 10454 } 10455 10456 if (isa<BlockExpr>(Arg)) { 10457 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 10458 << CalleeName << 1 /*object: block*/; 10459 return; 10460 } 10461 } 10462 // Maybe the cast was important, check after the other cases. 10463 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 10464 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 10465 } 10466 10467 void 10468 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10469 SourceLocation ReturnLoc, 10470 bool isObjCMethod, 10471 const AttrVec *Attrs, 10472 const FunctionDecl *FD) { 10473 // Check if the return value is null but should not be. 10474 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10475 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10476 CheckNonNullExpr(*this, RetValExp)) 10477 Diag(ReturnLoc, diag::warn_null_ret) 10478 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10479 10480 // C++11 [basic.stc.dynamic.allocation]p4: 10481 // If an allocation function declared with a non-throwing 10482 // exception-specification fails to allocate storage, it shall return 10483 // a null pointer. Any other allocation function that fails to allocate 10484 // storage shall indicate failure only by throwing an exception [...] 10485 if (FD) { 10486 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10487 if (Op == OO_New || Op == OO_Array_New) { 10488 const FunctionProtoType *Proto 10489 = FD->getType()->castAs<FunctionProtoType>(); 10490 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10491 CheckNonNullExpr(*this, RetValExp)) 10492 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10493 << FD << getLangOpts().CPlusPlus11; 10494 } 10495 } 10496 10497 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10498 // here prevent the user from using a PPC MMA type as trailing return type. 10499 if (Context.getTargetInfo().getTriple().isPPC64()) 10500 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10501 } 10502 10503 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10504 10505 /// Check for comparisons of floating point operands using != and ==. 10506 /// Issue a warning if these are no self-comparisons, as they are not likely 10507 /// to do what the programmer intended. 10508 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10509 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10510 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10511 10512 // Special case: check for x == x (which is OK). 10513 // Do not emit warnings for such cases. 10514 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10515 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10516 if (DRL->getDecl() == DRR->getDecl()) 10517 return; 10518 10519 // Special case: check for comparisons against literals that can be exactly 10520 // represented by APFloat. In such cases, do not emit a warning. This 10521 // is a heuristic: often comparison against such literals are used to 10522 // detect if a value in a variable has not changed. This clearly can 10523 // lead to false negatives. 10524 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10525 if (FLL->isExact()) 10526 return; 10527 } else 10528 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10529 if (FLR->isExact()) 10530 return; 10531 10532 // Check for comparisons with builtin types. 10533 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10534 if (CL->getBuiltinCallee()) 10535 return; 10536 10537 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10538 if (CR->getBuiltinCallee()) 10539 return; 10540 10541 // Emit the diagnostic. 10542 Diag(Loc, diag::warn_floatingpoint_eq) 10543 << LHS->getSourceRange() << RHS->getSourceRange(); 10544 } 10545 10546 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10547 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10548 10549 namespace { 10550 10551 /// Structure recording the 'active' range of an integer-valued 10552 /// expression. 10553 struct IntRange { 10554 /// The number of bits active in the int. Note that this includes exactly one 10555 /// sign bit if !NonNegative. 10556 unsigned Width; 10557 10558 /// True if the int is known not to have negative values. If so, all leading 10559 /// bits before Width are known zero, otherwise they are known to be the 10560 /// same as the MSB within Width. 10561 bool NonNegative; 10562 10563 IntRange(unsigned Width, bool NonNegative) 10564 : Width(Width), NonNegative(NonNegative) {} 10565 10566 /// Number of bits excluding the sign bit. 10567 unsigned valueBits() const { 10568 return NonNegative ? Width : Width - 1; 10569 } 10570 10571 /// Returns the range of the bool type. 10572 static IntRange forBoolType() { 10573 return IntRange(1, true); 10574 } 10575 10576 /// Returns the range of an opaque value of the given integral type. 10577 static IntRange forValueOfType(ASTContext &C, QualType T) { 10578 return forValueOfCanonicalType(C, 10579 T->getCanonicalTypeInternal().getTypePtr()); 10580 } 10581 10582 /// Returns the range of an opaque value of a canonical integral type. 10583 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10584 assert(T->isCanonicalUnqualified()); 10585 10586 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10587 T = VT->getElementType().getTypePtr(); 10588 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10589 T = CT->getElementType().getTypePtr(); 10590 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10591 T = AT->getValueType().getTypePtr(); 10592 10593 if (!C.getLangOpts().CPlusPlus) { 10594 // For enum types in C code, use the underlying datatype. 10595 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10596 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10597 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10598 // For enum types in C++, use the known bit width of the enumerators. 10599 EnumDecl *Enum = ET->getDecl(); 10600 // In C++11, enums can have a fixed underlying type. Use this type to 10601 // compute the range. 10602 if (Enum->isFixed()) { 10603 return IntRange(C.getIntWidth(QualType(T, 0)), 10604 !ET->isSignedIntegerOrEnumerationType()); 10605 } 10606 10607 unsigned NumPositive = Enum->getNumPositiveBits(); 10608 unsigned NumNegative = Enum->getNumNegativeBits(); 10609 10610 if (NumNegative == 0) 10611 return IntRange(NumPositive, true/*NonNegative*/); 10612 else 10613 return IntRange(std::max(NumPositive + 1, NumNegative), 10614 false/*NonNegative*/); 10615 } 10616 10617 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10618 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10619 10620 const BuiltinType *BT = cast<BuiltinType>(T); 10621 assert(BT->isInteger()); 10622 10623 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10624 } 10625 10626 /// Returns the "target" range of a canonical integral type, i.e. 10627 /// the range of values expressible in the type. 10628 /// 10629 /// This matches forValueOfCanonicalType except that enums have the 10630 /// full range of their type, not the range of their enumerators. 10631 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10632 assert(T->isCanonicalUnqualified()); 10633 10634 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10635 T = VT->getElementType().getTypePtr(); 10636 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10637 T = CT->getElementType().getTypePtr(); 10638 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10639 T = AT->getValueType().getTypePtr(); 10640 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10641 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10642 10643 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10644 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10645 10646 const BuiltinType *BT = cast<BuiltinType>(T); 10647 assert(BT->isInteger()); 10648 10649 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10650 } 10651 10652 /// Returns the supremum of two ranges: i.e. their conservative merge. 10653 static IntRange join(IntRange L, IntRange R) { 10654 bool Unsigned = L.NonNegative && R.NonNegative; 10655 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 10656 L.NonNegative && R.NonNegative); 10657 } 10658 10659 /// Return the range of a bitwise-AND of the two ranges. 10660 static IntRange bit_and(IntRange L, IntRange R) { 10661 unsigned Bits = std::max(L.Width, R.Width); 10662 bool NonNegative = false; 10663 if (L.NonNegative) { 10664 Bits = std::min(Bits, L.Width); 10665 NonNegative = true; 10666 } 10667 if (R.NonNegative) { 10668 Bits = std::min(Bits, R.Width); 10669 NonNegative = true; 10670 } 10671 return IntRange(Bits, NonNegative); 10672 } 10673 10674 /// Return the range of a sum of the two ranges. 10675 static IntRange sum(IntRange L, IntRange R) { 10676 bool Unsigned = L.NonNegative && R.NonNegative; 10677 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 10678 Unsigned); 10679 } 10680 10681 /// Return the range of a difference of the two ranges. 10682 static IntRange difference(IntRange L, IntRange R) { 10683 // We need a 1-bit-wider range if: 10684 // 1) LHS can be negative: least value can be reduced. 10685 // 2) RHS can be negative: greatest value can be increased. 10686 bool CanWiden = !L.NonNegative || !R.NonNegative; 10687 bool Unsigned = L.NonNegative && R.Width == 0; 10688 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 10689 !Unsigned, 10690 Unsigned); 10691 } 10692 10693 /// Return the range of a product of the two ranges. 10694 static IntRange product(IntRange L, IntRange R) { 10695 // If both LHS and RHS can be negative, we can form 10696 // -2^L * -2^R = 2^(L + R) 10697 // which requires L + R + 1 value bits to represent. 10698 bool CanWiden = !L.NonNegative && !R.NonNegative; 10699 bool Unsigned = L.NonNegative && R.NonNegative; 10700 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 10701 Unsigned); 10702 } 10703 10704 /// Return the range of a remainder operation between the two ranges. 10705 static IntRange rem(IntRange L, IntRange R) { 10706 // The result of a remainder can't be larger than the result of 10707 // either side. The sign of the result is the sign of the LHS. 10708 bool Unsigned = L.NonNegative; 10709 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 10710 Unsigned); 10711 } 10712 }; 10713 10714 } // namespace 10715 10716 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10717 unsigned MaxWidth) { 10718 if (value.isSigned() && value.isNegative()) 10719 return IntRange(value.getMinSignedBits(), false); 10720 10721 if (value.getBitWidth() > MaxWidth) 10722 value = value.trunc(MaxWidth); 10723 10724 // isNonNegative() just checks the sign bit without considering 10725 // signedness. 10726 return IntRange(value.getActiveBits(), true); 10727 } 10728 10729 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10730 unsigned MaxWidth) { 10731 if (result.isInt()) 10732 return GetValueRange(C, result.getInt(), MaxWidth); 10733 10734 if (result.isVector()) { 10735 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10736 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10737 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10738 R = IntRange::join(R, El); 10739 } 10740 return R; 10741 } 10742 10743 if (result.isComplexInt()) { 10744 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10745 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10746 return IntRange::join(R, I); 10747 } 10748 10749 // This can happen with lossless casts to intptr_t of "based" lvalues. 10750 // Assume it might use arbitrary bits. 10751 // FIXME: The only reason we need to pass the type in here is to get 10752 // the sign right on this one case. It would be nice if APValue 10753 // preserved this. 10754 assert(result.isLValue() || result.isAddrLabelDiff()); 10755 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10756 } 10757 10758 static QualType GetExprType(const Expr *E) { 10759 QualType Ty = E->getType(); 10760 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10761 Ty = AtomicRHS->getValueType(); 10762 return Ty; 10763 } 10764 10765 /// Pseudo-evaluate the given integer expression, estimating the 10766 /// range of values it might take. 10767 /// 10768 /// \param MaxWidth The width to which the value will be truncated. 10769 /// \param Approximate If \c true, return a likely range for the result: in 10770 /// particular, assume that aritmetic on narrower types doesn't leave 10771 /// those types. If \c false, return a range including all possible 10772 /// result values. 10773 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10774 bool InConstantContext, bool Approximate) { 10775 E = E->IgnoreParens(); 10776 10777 // Try a full evaluation first. 10778 Expr::EvalResult result; 10779 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10780 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10781 10782 // I think we only want to look through implicit casts here; if the 10783 // user has an explicit widening cast, we should treat the value as 10784 // being of the new, wider type. 10785 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10786 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10787 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 10788 Approximate); 10789 10790 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10791 10792 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10793 CE->getCastKind() == CK_BooleanToSignedIntegral; 10794 10795 // Assume that non-integer casts can span the full range of the type. 10796 if (!isIntegerCast) 10797 return OutputTypeRange; 10798 10799 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10800 std::min(MaxWidth, OutputTypeRange.Width), 10801 InConstantContext, Approximate); 10802 10803 // Bail out if the subexpr's range is as wide as the cast type. 10804 if (SubRange.Width >= OutputTypeRange.Width) 10805 return OutputTypeRange; 10806 10807 // Otherwise, we take the smaller width, and we're non-negative if 10808 // either the output type or the subexpr is. 10809 return IntRange(SubRange.Width, 10810 SubRange.NonNegative || OutputTypeRange.NonNegative); 10811 } 10812 10813 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10814 // If we can fold the condition, just take that operand. 10815 bool CondResult; 10816 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10817 return GetExprRange(C, 10818 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10819 MaxWidth, InConstantContext, Approximate); 10820 10821 // Otherwise, conservatively merge. 10822 // GetExprRange requires an integer expression, but a throw expression 10823 // results in a void type. 10824 Expr *E = CO->getTrueExpr(); 10825 IntRange L = E->getType()->isVoidType() 10826 ? IntRange{0, true} 10827 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10828 E = CO->getFalseExpr(); 10829 IntRange R = E->getType()->isVoidType() 10830 ? IntRange{0, true} 10831 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10832 return IntRange::join(L, R); 10833 } 10834 10835 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10836 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 10837 10838 switch (BO->getOpcode()) { 10839 case BO_Cmp: 10840 llvm_unreachable("builtin <=> should have class type"); 10841 10842 // Boolean-valued operations are single-bit and positive. 10843 case BO_LAnd: 10844 case BO_LOr: 10845 case BO_LT: 10846 case BO_GT: 10847 case BO_LE: 10848 case BO_GE: 10849 case BO_EQ: 10850 case BO_NE: 10851 return IntRange::forBoolType(); 10852 10853 // The type of the assignments is the type of the LHS, so the RHS 10854 // is not necessarily the same type. 10855 case BO_MulAssign: 10856 case BO_DivAssign: 10857 case BO_RemAssign: 10858 case BO_AddAssign: 10859 case BO_SubAssign: 10860 case BO_XorAssign: 10861 case BO_OrAssign: 10862 // TODO: bitfields? 10863 return IntRange::forValueOfType(C, GetExprType(E)); 10864 10865 // Simple assignments just pass through the RHS, which will have 10866 // been coerced to the LHS type. 10867 case BO_Assign: 10868 // TODO: bitfields? 10869 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10870 Approximate); 10871 10872 // Operations with opaque sources are black-listed. 10873 case BO_PtrMemD: 10874 case BO_PtrMemI: 10875 return IntRange::forValueOfType(C, GetExprType(E)); 10876 10877 // Bitwise-and uses the *infinum* of the two source ranges. 10878 case BO_And: 10879 case BO_AndAssign: 10880 Combine = IntRange::bit_and; 10881 break; 10882 10883 // Left shift gets black-listed based on a judgement call. 10884 case BO_Shl: 10885 // ...except that we want to treat '1 << (blah)' as logically 10886 // positive. It's an important idiom. 10887 if (IntegerLiteral *I 10888 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10889 if (I->getValue() == 1) { 10890 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10891 return IntRange(R.Width, /*NonNegative*/ true); 10892 } 10893 } 10894 LLVM_FALLTHROUGH; 10895 10896 case BO_ShlAssign: 10897 return IntRange::forValueOfType(C, GetExprType(E)); 10898 10899 // Right shift by a constant can narrow its left argument. 10900 case BO_Shr: 10901 case BO_ShrAssign: { 10902 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 10903 Approximate); 10904 10905 // If the shift amount is a positive constant, drop the width by 10906 // that much. 10907 if (Optional<llvm::APSInt> shift = 10908 BO->getRHS()->getIntegerConstantExpr(C)) { 10909 if (shift->isNonNegative()) { 10910 unsigned zext = shift->getZExtValue(); 10911 if (zext >= L.Width) 10912 L.Width = (L.NonNegative ? 0 : 1); 10913 else 10914 L.Width -= zext; 10915 } 10916 } 10917 10918 return L; 10919 } 10920 10921 // Comma acts as its right operand. 10922 case BO_Comma: 10923 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10924 Approximate); 10925 10926 case BO_Add: 10927 if (!Approximate) 10928 Combine = IntRange::sum; 10929 break; 10930 10931 case BO_Sub: 10932 if (BO->getLHS()->getType()->isPointerType()) 10933 return IntRange::forValueOfType(C, GetExprType(E)); 10934 if (!Approximate) 10935 Combine = IntRange::difference; 10936 break; 10937 10938 case BO_Mul: 10939 if (!Approximate) 10940 Combine = IntRange::product; 10941 break; 10942 10943 // The width of a division result is mostly determined by the size 10944 // of the LHS. 10945 case BO_Div: { 10946 // Don't 'pre-truncate' the operands. 10947 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10948 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 10949 Approximate); 10950 10951 // If the divisor is constant, use that. 10952 if (Optional<llvm::APSInt> divisor = 10953 BO->getRHS()->getIntegerConstantExpr(C)) { 10954 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 10955 if (log2 >= L.Width) 10956 L.Width = (L.NonNegative ? 0 : 1); 10957 else 10958 L.Width = std::min(L.Width - log2, MaxWidth); 10959 return L; 10960 } 10961 10962 // Otherwise, just use the LHS's width. 10963 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 10964 // could be -1. 10965 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 10966 Approximate); 10967 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10968 } 10969 10970 case BO_Rem: 10971 Combine = IntRange::rem; 10972 break; 10973 10974 // The default behavior is okay for these. 10975 case BO_Xor: 10976 case BO_Or: 10977 break; 10978 } 10979 10980 // Combine the two ranges, but limit the result to the type in which we 10981 // performed the computation. 10982 QualType T = GetExprType(E); 10983 unsigned opWidth = C.getIntWidth(T); 10984 IntRange L = 10985 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 10986 IntRange R = 10987 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 10988 IntRange C = Combine(L, R); 10989 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 10990 C.Width = std::min(C.Width, MaxWidth); 10991 return C; 10992 } 10993 10994 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10995 switch (UO->getOpcode()) { 10996 // Boolean-valued operations are white-listed. 10997 case UO_LNot: 10998 return IntRange::forBoolType(); 10999 11000 // Operations with opaque sources are black-listed. 11001 case UO_Deref: 11002 case UO_AddrOf: // should be impossible 11003 return IntRange::forValueOfType(C, GetExprType(E)); 11004 11005 default: 11006 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11007 Approximate); 11008 } 11009 } 11010 11011 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11012 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11013 Approximate); 11014 11015 if (const auto *BitField = E->getSourceBitField()) 11016 return IntRange(BitField->getBitWidthValue(C), 11017 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11018 11019 return IntRange::forValueOfType(C, GetExprType(E)); 11020 } 11021 11022 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11023 bool InConstantContext, bool Approximate) { 11024 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11025 Approximate); 11026 } 11027 11028 /// Checks whether the given value, which currently has the given 11029 /// source semantics, has the same value when coerced through the 11030 /// target semantics. 11031 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11032 const llvm::fltSemantics &Src, 11033 const llvm::fltSemantics &Tgt) { 11034 llvm::APFloat truncated = value; 11035 11036 bool ignored; 11037 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11038 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11039 11040 return truncated.bitwiseIsEqual(value); 11041 } 11042 11043 /// Checks whether the given value, which currently has the given 11044 /// source semantics, has the same value when coerced through the 11045 /// target semantics. 11046 /// 11047 /// The value might be a vector of floats (or a complex number). 11048 static bool IsSameFloatAfterCast(const APValue &value, 11049 const llvm::fltSemantics &Src, 11050 const llvm::fltSemantics &Tgt) { 11051 if (value.isFloat()) 11052 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11053 11054 if (value.isVector()) { 11055 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11056 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11057 return false; 11058 return true; 11059 } 11060 11061 assert(value.isComplexFloat()); 11062 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11063 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11064 } 11065 11066 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11067 bool IsListInit = false); 11068 11069 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11070 // Suppress cases where we are comparing against an enum constant. 11071 if (const DeclRefExpr *DR = 11072 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11073 if (isa<EnumConstantDecl>(DR->getDecl())) 11074 return true; 11075 11076 // Suppress cases where the value is expanded from a macro, unless that macro 11077 // is how a language represents a boolean literal. This is the case in both C 11078 // and Objective-C. 11079 SourceLocation BeginLoc = E->getBeginLoc(); 11080 if (BeginLoc.isMacroID()) { 11081 StringRef MacroName = Lexer::getImmediateMacroName( 11082 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11083 return MacroName != "YES" && MacroName != "NO" && 11084 MacroName != "true" && MacroName != "false"; 11085 } 11086 11087 return false; 11088 } 11089 11090 static bool isKnownToHaveUnsignedValue(Expr *E) { 11091 return E->getType()->isIntegerType() && 11092 (!E->getType()->isSignedIntegerType() || 11093 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11094 } 11095 11096 namespace { 11097 /// The promoted range of values of a type. In general this has the 11098 /// following structure: 11099 /// 11100 /// |-----------| . . . |-----------| 11101 /// ^ ^ ^ ^ 11102 /// Min HoleMin HoleMax Max 11103 /// 11104 /// ... where there is only a hole if a signed type is promoted to unsigned 11105 /// (in which case Min and Max are the smallest and largest representable 11106 /// values). 11107 struct PromotedRange { 11108 // Min, or HoleMax if there is a hole. 11109 llvm::APSInt PromotedMin; 11110 // Max, or HoleMin if there is a hole. 11111 llvm::APSInt PromotedMax; 11112 11113 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11114 if (R.Width == 0) 11115 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11116 else if (R.Width >= BitWidth && !Unsigned) { 11117 // Promotion made the type *narrower*. This happens when promoting 11118 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11119 // Treat all values of 'signed int' as being in range for now. 11120 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11121 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11122 } else { 11123 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11124 .extOrTrunc(BitWidth); 11125 PromotedMin.setIsUnsigned(Unsigned); 11126 11127 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11128 .extOrTrunc(BitWidth); 11129 PromotedMax.setIsUnsigned(Unsigned); 11130 } 11131 } 11132 11133 // Determine whether this range is contiguous (has no hole). 11134 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11135 11136 // Where a constant value is within the range. 11137 enum ComparisonResult { 11138 LT = 0x1, 11139 LE = 0x2, 11140 GT = 0x4, 11141 GE = 0x8, 11142 EQ = 0x10, 11143 NE = 0x20, 11144 InRangeFlag = 0x40, 11145 11146 Less = LE | LT | NE, 11147 Min = LE | InRangeFlag, 11148 InRange = InRangeFlag, 11149 Max = GE | InRangeFlag, 11150 Greater = GE | GT | NE, 11151 11152 OnlyValue = LE | GE | EQ | InRangeFlag, 11153 InHole = NE 11154 }; 11155 11156 ComparisonResult compare(const llvm::APSInt &Value) const { 11157 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11158 Value.isUnsigned() == PromotedMin.isUnsigned()); 11159 if (!isContiguous()) { 11160 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11161 if (Value.isMinValue()) return Min; 11162 if (Value.isMaxValue()) return Max; 11163 if (Value >= PromotedMin) return InRange; 11164 if (Value <= PromotedMax) return InRange; 11165 return InHole; 11166 } 11167 11168 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11169 case -1: return Less; 11170 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11171 case 1: 11172 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11173 case -1: return InRange; 11174 case 0: return Max; 11175 case 1: return Greater; 11176 } 11177 } 11178 11179 llvm_unreachable("impossible compare result"); 11180 } 11181 11182 static llvm::Optional<StringRef> 11183 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11184 if (Op == BO_Cmp) { 11185 ComparisonResult LTFlag = LT, GTFlag = GT; 11186 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11187 11188 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11189 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11190 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11191 return llvm::None; 11192 } 11193 11194 ComparisonResult TrueFlag, FalseFlag; 11195 if (Op == BO_EQ) { 11196 TrueFlag = EQ; 11197 FalseFlag = NE; 11198 } else if (Op == BO_NE) { 11199 TrueFlag = NE; 11200 FalseFlag = EQ; 11201 } else { 11202 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11203 TrueFlag = LT; 11204 FalseFlag = GE; 11205 } else { 11206 TrueFlag = GT; 11207 FalseFlag = LE; 11208 } 11209 if (Op == BO_GE || Op == BO_LE) 11210 std::swap(TrueFlag, FalseFlag); 11211 } 11212 if (R & TrueFlag) 11213 return StringRef("true"); 11214 if (R & FalseFlag) 11215 return StringRef("false"); 11216 return llvm::None; 11217 } 11218 }; 11219 } 11220 11221 static bool HasEnumType(Expr *E) { 11222 // Strip off implicit integral promotions. 11223 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11224 if (ICE->getCastKind() != CK_IntegralCast && 11225 ICE->getCastKind() != CK_NoOp) 11226 break; 11227 E = ICE->getSubExpr(); 11228 } 11229 11230 return E->getType()->isEnumeralType(); 11231 } 11232 11233 static int classifyConstantValue(Expr *Constant) { 11234 // The values of this enumeration are used in the diagnostics 11235 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11236 enum ConstantValueKind { 11237 Miscellaneous = 0, 11238 LiteralTrue, 11239 LiteralFalse 11240 }; 11241 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11242 return BL->getValue() ? ConstantValueKind::LiteralTrue 11243 : ConstantValueKind::LiteralFalse; 11244 return ConstantValueKind::Miscellaneous; 11245 } 11246 11247 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11248 Expr *Constant, Expr *Other, 11249 const llvm::APSInt &Value, 11250 bool RhsConstant) { 11251 if (S.inTemplateInstantiation()) 11252 return false; 11253 11254 Expr *OriginalOther = Other; 11255 11256 Constant = Constant->IgnoreParenImpCasts(); 11257 Other = Other->IgnoreParenImpCasts(); 11258 11259 // Suppress warnings on tautological comparisons between values of the same 11260 // enumeration type. There are only two ways we could warn on this: 11261 // - If the constant is outside the range of representable values of 11262 // the enumeration. In such a case, we should warn about the cast 11263 // to enumeration type, not about the comparison. 11264 // - If the constant is the maximum / minimum in-range value. For an 11265 // enumeratin type, such comparisons can be meaningful and useful. 11266 if (Constant->getType()->isEnumeralType() && 11267 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11268 return false; 11269 11270 IntRange OtherValueRange = GetExprRange( 11271 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11272 11273 QualType OtherT = Other->getType(); 11274 if (const auto *AT = OtherT->getAs<AtomicType>()) 11275 OtherT = AT->getValueType(); 11276 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11277 11278 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11279 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11280 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11281 S.NSAPIObj->isObjCBOOLType(OtherT) && 11282 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11283 11284 // Whether we're treating Other as being a bool because of the form of 11285 // expression despite it having another type (typically 'int' in C). 11286 bool OtherIsBooleanDespiteType = 11287 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11288 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11289 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11290 11291 // Check if all values in the range of possible values of this expression 11292 // lead to the same comparison outcome. 11293 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11294 Value.isUnsigned()); 11295 auto Cmp = OtherPromotedValueRange.compare(Value); 11296 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11297 if (!Result) 11298 return false; 11299 11300 // Also consider the range determined by the type alone. This allows us to 11301 // classify the warning under the proper diagnostic group. 11302 bool TautologicalTypeCompare = false; 11303 { 11304 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11305 Value.isUnsigned()); 11306 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11307 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11308 RhsConstant)) { 11309 TautologicalTypeCompare = true; 11310 Cmp = TypeCmp; 11311 Result = TypeResult; 11312 } 11313 } 11314 11315 // Don't warn if the non-constant operand actually always evaluates to the 11316 // same value. 11317 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11318 return false; 11319 11320 // Suppress the diagnostic for an in-range comparison if the constant comes 11321 // from a macro or enumerator. We don't want to diagnose 11322 // 11323 // some_long_value <= INT_MAX 11324 // 11325 // when sizeof(int) == sizeof(long). 11326 bool InRange = Cmp & PromotedRange::InRangeFlag; 11327 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11328 return false; 11329 11330 // A comparison of an unsigned bit-field against 0 is really a type problem, 11331 // even though at the type level the bit-field might promote to 'signed int'. 11332 if (Other->refersToBitField() && InRange && Value == 0 && 11333 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11334 TautologicalTypeCompare = true; 11335 11336 // If this is a comparison to an enum constant, include that 11337 // constant in the diagnostic. 11338 const EnumConstantDecl *ED = nullptr; 11339 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11340 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11341 11342 // Should be enough for uint128 (39 decimal digits) 11343 SmallString<64> PrettySourceValue; 11344 llvm::raw_svector_ostream OS(PrettySourceValue); 11345 if (ED) { 11346 OS << '\'' << *ED << "' (" << Value << ")"; 11347 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11348 Constant->IgnoreParenImpCasts())) { 11349 OS << (BL->getValue() ? "YES" : "NO"); 11350 } else { 11351 OS << Value; 11352 } 11353 11354 if (!TautologicalTypeCompare) { 11355 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11356 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11357 << E->getOpcodeStr() << OS.str() << *Result 11358 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11359 return true; 11360 } 11361 11362 if (IsObjCSignedCharBool) { 11363 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11364 S.PDiag(diag::warn_tautological_compare_objc_bool) 11365 << OS.str() << *Result); 11366 return true; 11367 } 11368 11369 // FIXME: We use a somewhat different formatting for the in-range cases and 11370 // cases involving boolean values for historical reasons. We should pick a 11371 // consistent way of presenting these diagnostics. 11372 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11373 11374 S.DiagRuntimeBehavior( 11375 E->getOperatorLoc(), E, 11376 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11377 : diag::warn_tautological_bool_compare) 11378 << OS.str() << classifyConstantValue(Constant) << OtherT 11379 << OtherIsBooleanDespiteType << *Result 11380 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11381 } else { 11382 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11383 ? (HasEnumType(OriginalOther) 11384 ? diag::warn_unsigned_enum_always_true_comparison 11385 : diag::warn_unsigned_always_true_comparison) 11386 : diag::warn_tautological_constant_compare; 11387 11388 S.Diag(E->getOperatorLoc(), Diag) 11389 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11390 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11391 } 11392 11393 return true; 11394 } 11395 11396 /// Analyze the operands of the given comparison. Implements the 11397 /// fallback case from AnalyzeComparison. 11398 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11399 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11400 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11401 } 11402 11403 /// Implements -Wsign-compare. 11404 /// 11405 /// \param E the binary operator to check for warnings 11406 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11407 // The type the comparison is being performed in. 11408 QualType T = E->getLHS()->getType(); 11409 11410 // Only analyze comparison operators where both sides have been converted to 11411 // the same type. 11412 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11413 return AnalyzeImpConvsInComparison(S, E); 11414 11415 // Don't analyze value-dependent comparisons directly. 11416 if (E->isValueDependent()) 11417 return AnalyzeImpConvsInComparison(S, E); 11418 11419 Expr *LHS = E->getLHS(); 11420 Expr *RHS = E->getRHS(); 11421 11422 if (T->isIntegralType(S.Context)) { 11423 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11424 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11425 11426 // We don't care about expressions whose result is a constant. 11427 if (RHSValue && LHSValue) 11428 return AnalyzeImpConvsInComparison(S, E); 11429 11430 // We only care about expressions where just one side is literal 11431 if ((bool)RHSValue ^ (bool)LHSValue) { 11432 // Is the constant on the RHS or LHS? 11433 const bool RhsConstant = (bool)RHSValue; 11434 Expr *Const = RhsConstant ? RHS : LHS; 11435 Expr *Other = RhsConstant ? LHS : RHS; 11436 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11437 11438 // Check whether an integer constant comparison results in a value 11439 // of 'true' or 'false'. 11440 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11441 return AnalyzeImpConvsInComparison(S, E); 11442 } 11443 } 11444 11445 if (!T->hasUnsignedIntegerRepresentation()) { 11446 // We don't do anything special if this isn't an unsigned integral 11447 // comparison: we're only interested in integral comparisons, and 11448 // signed comparisons only happen in cases we don't care to warn about. 11449 return AnalyzeImpConvsInComparison(S, E); 11450 } 11451 11452 LHS = LHS->IgnoreParenImpCasts(); 11453 RHS = RHS->IgnoreParenImpCasts(); 11454 11455 if (!S.getLangOpts().CPlusPlus) { 11456 // Avoid warning about comparison of integers with different signs when 11457 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11458 // the type of `E`. 11459 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11460 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11461 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11462 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11463 } 11464 11465 // Check to see if one of the (unmodified) operands is of different 11466 // signedness. 11467 Expr *signedOperand, *unsignedOperand; 11468 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11469 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11470 "unsigned comparison between two signed integer expressions?"); 11471 signedOperand = LHS; 11472 unsignedOperand = RHS; 11473 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11474 signedOperand = RHS; 11475 unsignedOperand = LHS; 11476 } else { 11477 return AnalyzeImpConvsInComparison(S, E); 11478 } 11479 11480 // Otherwise, calculate the effective range of the signed operand. 11481 IntRange signedRange = GetExprRange( 11482 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11483 11484 // Go ahead and analyze implicit conversions in the operands. Note 11485 // that we skip the implicit conversions on both sides. 11486 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11487 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11488 11489 // If the signed range is non-negative, -Wsign-compare won't fire. 11490 if (signedRange.NonNegative) 11491 return; 11492 11493 // For (in)equality comparisons, if the unsigned operand is a 11494 // constant which cannot collide with a overflowed signed operand, 11495 // then reinterpreting the signed operand as unsigned will not 11496 // change the result of the comparison. 11497 if (E->isEqualityOp()) { 11498 unsigned comparisonWidth = S.Context.getIntWidth(T); 11499 IntRange unsignedRange = 11500 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11501 /*Approximate*/ true); 11502 11503 // We should never be unable to prove that the unsigned operand is 11504 // non-negative. 11505 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11506 11507 if (unsignedRange.Width < comparisonWidth) 11508 return; 11509 } 11510 11511 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11512 S.PDiag(diag::warn_mixed_sign_comparison) 11513 << LHS->getType() << RHS->getType() 11514 << LHS->getSourceRange() << RHS->getSourceRange()); 11515 } 11516 11517 /// Analyzes an attempt to assign the given value to a bitfield. 11518 /// 11519 /// Returns true if there was something fishy about the attempt. 11520 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11521 SourceLocation InitLoc) { 11522 assert(Bitfield->isBitField()); 11523 if (Bitfield->isInvalidDecl()) 11524 return false; 11525 11526 // White-list bool bitfields. 11527 QualType BitfieldType = Bitfield->getType(); 11528 if (BitfieldType->isBooleanType()) 11529 return false; 11530 11531 if (BitfieldType->isEnumeralType()) { 11532 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11533 // If the underlying enum type was not explicitly specified as an unsigned 11534 // type and the enum contain only positive values, MSVC++ will cause an 11535 // inconsistency by storing this as a signed type. 11536 if (S.getLangOpts().CPlusPlus11 && 11537 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11538 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11539 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11540 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11541 << BitfieldEnumDecl; 11542 } 11543 } 11544 11545 if (Bitfield->getType()->isBooleanType()) 11546 return false; 11547 11548 // Ignore value- or type-dependent expressions. 11549 if (Bitfield->getBitWidth()->isValueDependent() || 11550 Bitfield->getBitWidth()->isTypeDependent() || 11551 Init->isValueDependent() || 11552 Init->isTypeDependent()) 11553 return false; 11554 11555 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11556 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11557 11558 Expr::EvalResult Result; 11559 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11560 Expr::SE_AllowSideEffects)) { 11561 // The RHS is not constant. If the RHS has an enum type, make sure the 11562 // bitfield is wide enough to hold all the values of the enum without 11563 // truncation. 11564 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11565 EnumDecl *ED = EnumTy->getDecl(); 11566 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11567 11568 // Enum types are implicitly signed on Windows, so check if there are any 11569 // negative enumerators to see if the enum was intended to be signed or 11570 // not. 11571 bool SignedEnum = ED->getNumNegativeBits() > 0; 11572 11573 // Check for surprising sign changes when assigning enum values to a 11574 // bitfield of different signedness. If the bitfield is signed and we 11575 // have exactly the right number of bits to store this unsigned enum, 11576 // suggest changing the enum to an unsigned type. This typically happens 11577 // on Windows where unfixed enums always use an underlying type of 'int'. 11578 unsigned DiagID = 0; 11579 if (SignedEnum && !SignedBitfield) { 11580 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11581 } else if (SignedBitfield && !SignedEnum && 11582 ED->getNumPositiveBits() == FieldWidth) { 11583 DiagID = diag::warn_signed_bitfield_enum_conversion; 11584 } 11585 11586 if (DiagID) { 11587 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11588 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11589 SourceRange TypeRange = 11590 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11591 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11592 << SignedEnum << TypeRange; 11593 } 11594 11595 // Compute the required bitwidth. If the enum has negative values, we need 11596 // one more bit than the normal number of positive bits to represent the 11597 // sign bit. 11598 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11599 ED->getNumNegativeBits()) 11600 : ED->getNumPositiveBits(); 11601 11602 // Check the bitwidth. 11603 if (BitsNeeded > FieldWidth) { 11604 Expr *WidthExpr = Bitfield->getBitWidth(); 11605 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11606 << Bitfield << ED; 11607 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11608 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11609 } 11610 } 11611 11612 return false; 11613 } 11614 11615 llvm::APSInt Value = Result.Val.getInt(); 11616 11617 unsigned OriginalWidth = Value.getBitWidth(); 11618 11619 if (!Value.isSigned() || Value.isNegative()) 11620 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11621 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11622 OriginalWidth = Value.getMinSignedBits(); 11623 11624 if (OriginalWidth <= FieldWidth) 11625 return false; 11626 11627 // Compute the value which the bitfield will contain. 11628 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11629 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11630 11631 // Check whether the stored value is equal to the original value. 11632 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11633 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11634 return false; 11635 11636 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11637 // therefore don't strictly fit into a signed bitfield of width 1. 11638 if (FieldWidth == 1 && Value == 1) 11639 return false; 11640 11641 std::string PrettyValue = Value.toString(10); 11642 std::string PrettyTrunc = TruncatedValue.toString(10); 11643 11644 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11645 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11646 << Init->getSourceRange(); 11647 11648 return true; 11649 } 11650 11651 /// Analyze the given simple or compound assignment for warning-worthy 11652 /// operations. 11653 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11654 // Just recurse on the LHS. 11655 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11656 11657 // We want to recurse on the RHS as normal unless we're assigning to 11658 // a bitfield. 11659 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11660 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11661 E->getOperatorLoc())) { 11662 // Recurse, ignoring any implicit conversions on the RHS. 11663 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11664 E->getOperatorLoc()); 11665 } 11666 } 11667 11668 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11669 11670 // Diagnose implicitly sequentially-consistent atomic assignment. 11671 if (E->getLHS()->getType()->isAtomicType()) 11672 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11673 } 11674 11675 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11676 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11677 SourceLocation CContext, unsigned diag, 11678 bool pruneControlFlow = false) { 11679 if (pruneControlFlow) { 11680 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11681 S.PDiag(diag) 11682 << SourceType << T << E->getSourceRange() 11683 << SourceRange(CContext)); 11684 return; 11685 } 11686 S.Diag(E->getExprLoc(), diag) 11687 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11688 } 11689 11690 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11691 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11692 SourceLocation CContext, 11693 unsigned diag, bool pruneControlFlow = false) { 11694 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11695 } 11696 11697 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11698 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11699 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11700 } 11701 11702 static void adornObjCBoolConversionDiagWithTernaryFixit( 11703 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11704 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11705 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11706 Ignored = OVE->getSourceExpr(); 11707 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11708 isa<BinaryOperator>(Ignored) || 11709 isa<CXXOperatorCallExpr>(Ignored); 11710 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11711 if (NeedsParens) 11712 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11713 << FixItHint::CreateInsertion(EndLoc, ")"); 11714 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11715 } 11716 11717 /// Diagnose an implicit cast from a floating point value to an integer value. 11718 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11719 SourceLocation CContext) { 11720 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11721 const bool PruneWarnings = S.inTemplateInstantiation(); 11722 11723 Expr *InnerE = E->IgnoreParenImpCasts(); 11724 // We also want to warn on, e.g., "int i = -1.234" 11725 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11726 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11727 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11728 11729 const bool IsLiteral = 11730 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11731 11732 llvm::APFloat Value(0.0); 11733 bool IsConstant = 11734 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11735 if (!IsConstant) { 11736 if (isObjCSignedCharBool(S, T)) { 11737 return adornObjCBoolConversionDiagWithTernaryFixit( 11738 S, E, 11739 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11740 << E->getType()); 11741 } 11742 11743 return DiagnoseImpCast(S, E, T, CContext, 11744 diag::warn_impcast_float_integer, PruneWarnings); 11745 } 11746 11747 bool isExact = false; 11748 11749 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11750 T->hasUnsignedIntegerRepresentation()); 11751 llvm::APFloat::opStatus Result = Value.convertToInteger( 11752 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11753 11754 // FIXME: Force the precision of the source value down so we don't print 11755 // digits which are usually useless (we don't really care here if we 11756 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11757 // would automatically print the shortest representation, but it's a bit 11758 // tricky to implement. 11759 SmallString<16> PrettySourceValue; 11760 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11761 precision = (precision * 59 + 195) / 196; 11762 Value.toString(PrettySourceValue, precision); 11763 11764 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11765 return adornObjCBoolConversionDiagWithTernaryFixit( 11766 S, E, 11767 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11768 << PrettySourceValue); 11769 } 11770 11771 if (Result == llvm::APFloat::opOK && isExact) { 11772 if (IsLiteral) return; 11773 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11774 PruneWarnings); 11775 } 11776 11777 // Conversion of a floating-point value to a non-bool integer where the 11778 // integral part cannot be represented by the integer type is undefined. 11779 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11780 return DiagnoseImpCast( 11781 S, E, T, CContext, 11782 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11783 : diag::warn_impcast_float_to_integer_out_of_range, 11784 PruneWarnings); 11785 11786 unsigned DiagID = 0; 11787 if (IsLiteral) { 11788 // Warn on floating point literal to integer. 11789 DiagID = diag::warn_impcast_literal_float_to_integer; 11790 } else if (IntegerValue == 0) { 11791 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11792 return DiagnoseImpCast(S, E, T, CContext, 11793 diag::warn_impcast_float_integer, PruneWarnings); 11794 } 11795 // Warn on non-zero to zero conversion. 11796 DiagID = diag::warn_impcast_float_to_integer_zero; 11797 } else { 11798 if (IntegerValue.isUnsigned()) { 11799 if (!IntegerValue.isMaxValue()) { 11800 return DiagnoseImpCast(S, E, T, CContext, 11801 diag::warn_impcast_float_integer, PruneWarnings); 11802 } 11803 } else { // IntegerValue.isSigned() 11804 if (!IntegerValue.isMaxSignedValue() && 11805 !IntegerValue.isMinSignedValue()) { 11806 return DiagnoseImpCast(S, E, T, CContext, 11807 diag::warn_impcast_float_integer, PruneWarnings); 11808 } 11809 } 11810 // Warn on evaluatable floating point expression to integer conversion. 11811 DiagID = diag::warn_impcast_float_to_integer; 11812 } 11813 11814 SmallString<16> PrettyTargetValue; 11815 if (IsBool) 11816 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11817 else 11818 IntegerValue.toString(PrettyTargetValue); 11819 11820 if (PruneWarnings) { 11821 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11822 S.PDiag(DiagID) 11823 << E->getType() << T.getUnqualifiedType() 11824 << PrettySourceValue << PrettyTargetValue 11825 << E->getSourceRange() << SourceRange(CContext)); 11826 } else { 11827 S.Diag(E->getExprLoc(), DiagID) 11828 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11829 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11830 } 11831 } 11832 11833 /// Analyze the given compound assignment for the possible losing of 11834 /// floating-point precision. 11835 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11836 assert(isa<CompoundAssignOperator>(E) && 11837 "Must be compound assignment operation"); 11838 // Recurse on the LHS and RHS in here 11839 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11840 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11841 11842 if (E->getLHS()->getType()->isAtomicType()) 11843 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11844 11845 // Now check the outermost expression 11846 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11847 const auto *RBT = cast<CompoundAssignOperator>(E) 11848 ->getComputationResultType() 11849 ->getAs<BuiltinType>(); 11850 11851 // The below checks assume source is floating point. 11852 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11853 11854 // If source is floating point but target is an integer. 11855 if (ResultBT->isInteger()) 11856 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11857 E->getExprLoc(), diag::warn_impcast_float_integer); 11858 11859 if (!ResultBT->isFloatingPoint()) 11860 return; 11861 11862 // If both source and target are floating points, warn about losing precision. 11863 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11864 QualType(ResultBT, 0), QualType(RBT, 0)); 11865 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11866 // warn about dropping FP rank. 11867 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11868 diag::warn_impcast_float_result_precision); 11869 } 11870 11871 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11872 IntRange Range) { 11873 if (!Range.Width) return "0"; 11874 11875 llvm::APSInt ValueInRange = Value; 11876 ValueInRange.setIsSigned(!Range.NonNegative); 11877 ValueInRange = ValueInRange.trunc(Range.Width); 11878 return ValueInRange.toString(10); 11879 } 11880 11881 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11882 if (!isa<ImplicitCastExpr>(Ex)) 11883 return false; 11884 11885 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11886 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11887 const Type *Source = 11888 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11889 if (Target->isDependentType()) 11890 return false; 11891 11892 const BuiltinType *FloatCandidateBT = 11893 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11894 const Type *BoolCandidateType = ToBool ? Target : Source; 11895 11896 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11897 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11898 } 11899 11900 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11901 SourceLocation CC) { 11902 unsigned NumArgs = TheCall->getNumArgs(); 11903 for (unsigned i = 0; i < NumArgs; ++i) { 11904 Expr *CurrA = TheCall->getArg(i); 11905 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11906 continue; 11907 11908 bool IsSwapped = ((i > 0) && 11909 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11910 IsSwapped |= ((i < (NumArgs - 1)) && 11911 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11912 if (IsSwapped) { 11913 // Warn on this floating-point to bool conversion. 11914 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11915 CurrA->getType(), CC, 11916 diag::warn_impcast_floating_point_to_bool); 11917 } 11918 } 11919 } 11920 11921 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11922 SourceLocation CC) { 11923 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11924 E->getExprLoc())) 11925 return; 11926 11927 // Don't warn on functions which have return type nullptr_t. 11928 if (isa<CallExpr>(E)) 11929 return; 11930 11931 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11932 const Expr::NullPointerConstantKind NullKind = 11933 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11934 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11935 return; 11936 11937 // Return if target type is a safe conversion. 11938 if (T->isAnyPointerType() || T->isBlockPointerType() || 11939 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11940 return; 11941 11942 SourceLocation Loc = E->getSourceRange().getBegin(); 11943 11944 // Venture through the macro stacks to get to the source of macro arguments. 11945 // The new location is a better location than the complete location that was 11946 // passed in. 11947 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11948 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11949 11950 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11951 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11952 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11953 Loc, S.SourceMgr, S.getLangOpts()); 11954 if (MacroName == "NULL") 11955 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11956 } 11957 11958 // Only warn if the null and context location are in the same macro expansion. 11959 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11960 return; 11961 11962 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11963 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11964 << FixItHint::CreateReplacement(Loc, 11965 S.getFixItZeroLiteralForType(T, Loc)); 11966 } 11967 11968 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11969 ObjCArrayLiteral *ArrayLiteral); 11970 11971 static void 11972 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11973 ObjCDictionaryLiteral *DictionaryLiteral); 11974 11975 /// Check a single element within a collection literal against the 11976 /// target element type. 11977 static void checkObjCCollectionLiteralElement(Sema &S, 11978 QualType TargetElementType, 11979 Expr *Element, 11980 unsigned ElementKind) { 11981 // Skip a bitcast to 'id' or qualified 'id'. 11982 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11983 if (ICE->getCastKind() == CK_BitCast && 11984 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11985 Element = ICE->getSubExpr(); 11986 } 11987 11988 QualType ElementType = Element->getType(); 11989 ExprResult ElementResult(Element); 11990 if (ElementType->getAs<ObjCObjectPointerType>() && 11991 S.CheckSingleAssignmentConstraints(TargetElementType, 11992 ElementResult, 11993 false, false) 11994 != Sema::Compatible) { 11995 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11996 << ElementType << ElementKind << TargetElementType 11997 << Element->getSourceRange(); 11998 } 11999 12000 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12001 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12002 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12003 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12004 } 12005 12006 /// Check an Objective-C array literal being converted to the given 12007 /// target type. 12008 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12009 ObjCArrayLiteral *ArrayLiteral) { 12010 if (!S.NSArrayDecl) 12011 return; 12012 12013 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12014 if (!TargetObjCPtr) 12015 return; 12016 12017 if (TargetObjCPtr->isUnspecialized() || 12018 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12019 != S.NSArrayDecl->getCanonicalDecl()) 12020 return; 12021 12022 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12023 if (TypeArgs.size() != 1) 12024 return; 12025 12026 QualType TargetElementType = TypeArgs[0]; 12027 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12028 checkObjCCollectionLiteralElement(S, TargetElementType, 12029 ArrayLiteral->getElement(I), 12030 0); 12031 } 12032 } 12033 12034 /// Check an Objective-C dictionary literal being converted to the given 12035 /// target type. 12036 static void 12037 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12038 ObjCDictionaryLiteral *DictionaryLiteral) { 12039 if (!S.NSDictionaryDecl) 12040 return; 12041 12042 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12043 if (!TargetObjCPtr) 12044 return; 12045 12046 if (TargetObjCPtr->isUnspecialized() || 12047 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12048 != S.NSDictionaryDecl->getCanonicalDecl()) 12049 return; 12050 12051 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12052 if (TypeArgs.size() != 2) 12053 return; 12054 12055 QualType TargetKeyType = TypeArgs[0]; 12056 QualType TargetObjectType = TypeArgs[1]; 12057 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12058 auto Element = DictionaryLiteral->getKeyValueElement(I); 12059 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12060 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12061 } 12062 } 12063 12064 // Helper function to filter out cases for constant width constant conversion. 12065 // Don't warn on char array initialization or for non-decimal values. 12066 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12067 SourceLocation CC) { 12068 // If initializing from a constant, and the constant starts with '0', 12069 // then it is a binary, octal, or hexadecimal. Allow these constants 12070 // to fill all the bits, even if there is a sign change. 12071 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12072 const char FirstLiteralCharacter = 12073 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12074 if (FirstLiteralCharacter == '0') 12075 return false; 12076 } 12077 12078 // If the CC location points to a '{', and the type is char, then assume 12079 // assume it is an array initialization. 12080 if (CC.isValid() && T->isCharType()) { 12081 const char FirstContextCharacter = 12082 S.getSourceManager().getCharacterData(CC)[0]; 12083 if (FirstContextCharacter == '{') 12084 return false; 12085 } 12086 12087 return true; 12088 } 12089 12090 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12091 const auto *IL = dyn_cast<IntegerLiteral>(E); 12092 if (!IL) { 12093 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12094 if (UO->getOpcode() == UO_Minus) 12095 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12096 } 12097 } 12098 12099 return IL; 12100 } 12101 12102 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12103 E = E->IgnoreParenImpCasts(); 12104 SourceLocation ExprLoc = E->getExprLoc(); 12105 12106 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12107 BinaryOperator::Opcode Opc = BO->getOpcode(); 12108 Expr::EvalResult Result; 12109 // Do not diagnose unsigned shifts. 12110 if (Opc == BO_Shl) { 12111 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12112 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12113 if (LHS && LHS->getValue() == 0) 12114 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12115 else if (!E->isValueDependent() && LHS && RHS && 12116 RHS->getValue().isNonNegative() && 12117 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12118 S.Diag(ExprLoc, diag::warn_left_shift_always) 12119 << (Result.Val.getInt() != 0); 12120 else if (E->getType()->isSignedIntegerType()) 12121 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12122 } 12123 } 12124 12125 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12126 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12127 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12128 if (!LHS || !RHS) 12129 return; 12130 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12131 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12132 // Do not diagnose common idioms. 12133 return; 12134 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12135 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12136 } 12137 } 12138 12139 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12140 SourceLocation CC, 12141 bool *ICContext = nullptr, 12142 bool IsListInit = false) { 12143 if (E->isTypeDependent() || E->isValueDependent()) return; 12144 12145 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12146 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12147 if (Source == Target) return; 12148 if (Target->isDependentType()) return; 12149 12150 // If the conversion context location is invalid don't complain. We also 12151 // don't want to emit a warning if the issue occurs from the expansion of 12152 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12153 // delay this check as long as possible. Once we detect we are in that 12154 // scenario, we just return. 12155 if (CC.isInvalid()) 12156 return; 12157 12158 if (Source->isAtomicType()) 12159 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12160 12161 // Diagnose implicit casts to bool. 12162 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12163 if (isa<StringLiteral>(E)) 12164 // Warn on string literal to bool. Checks for string literals in logical 12165 // and expressions, for instance, assert(0 && "error here"), are 12166 // prevented by a check in AnalyzeImplicitConversions(). 12167 return DiagnoseImpCast(S, E, T, CC, 12168 diag::warn_impcast_string_literal_to_bool); 12169 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12170 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12171 // This covers the literal expressions that evaluate to Objective-C 12172 // objects. 12173 return DiagnoseImpCast(S, E, T, CC, 12174 diag::warn_impcast_objective_c_literal_to_bool); 12175 } 12176 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12177 // Warn on pointer to bool conversion that is always true. 12178 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12179 SourceRange(CC)); 12180 } 12181 } 12182 12183 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12184 // is a typedef for signed char (macOS), then that constant value has to be 1 12185 // or 0. 12186 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12187 Expr::EvalResult Result; 12188 if (E->EvaluateAsInt(Result, S.getASTContext(), 12189 Expr::SE_AllowSideEffects)) { 12190 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12191 adornObjCBoolConversionDiagWithTernaryFixit( 12192 S, E, 12193 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12194 << Result.Val.getInt().toString(10)); 12195 } 12196 return; 12197 } 12198 } 12199 12200 // Check implicit casts from Objective-C collection literals to specialized 12201 // collection types, e.g., NSArray<NSString *> *. 12202 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12203 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12204 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12205 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12206 12207 // Strip vector types. 12208 if (const auto *SourceVT = dyn_cast<VectorType>(Source)) { 12209 if (Target->isVLSTBuiltinType()) { 12210 auto SourceVectorKind = SourceVT->getVectorKind(); 12211 if (SourceVectorKind == VectorType::SveFixedLengthDataVector || 12212 SourceVectorKind == VectorType::SveFixedLengthPredicateVector || 12213 (SourceVectorKind == VectorType::GenericVector && 12214 S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits)) 12215 return; 12216 } 12217 12218 if (!isa<VectorType>(Target)) { 12219 if (S.SourceMgr.isInSystemMacro(CC)) 12220 return; 12221 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12222 } 12223 12224 // If the vector cast is cast between two vectors of the same size, it is 12225 // a bitcast, not a conversion. 12226 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12227 return; 12228 12229 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12230 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12231 } 12232 if (auto VecTy = dyn_cast<VectorType>(Target)) 12233 Target = VecTy->getElementType().getTypePtr(); 12234 12235 // Strip complex types. 12236 if (isa<ComplexType>(Source)) { 12237 if (!isa<ComplexType>(Target)) { 12238 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12239 return; 12240 12241 return DiagnoseImpCast(S, E, T, CC, 12242 S.getLangOpts().CPlusPlus 12243 ? diag::err_impcast_complex_scalar 12244 : diag::warn_impcast_complex_scalar); 12245 } 12246 12247 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12248 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12249 } 12250 12251 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12252 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12253 12254 // If the source is floating point... 12255 if (SourceBT && SourceBT->isFloatingPoint()) { 12256 // ...and the target is floating point... 12257 if (TargetBT && TargetBT->isFloatingPoint()) { 12258 // ...then warn if we're dropping FP rank. 12259 12260 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12261 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12262 if (Order > 0) { 12263 // Don't warn about float constants that are precisely 12264 // representable in the target type. 12265 Expr::EvalResult result; 12266 if (E->EvaluateAsRValue(result, S.Context)) { 12267 // Value might be a float, a float vector, or a float complex. 12268 if (IsSameFloatAfterCast(result.Val, 12269 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12270 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12271 return; 12272 } 12273 12274 if (S.SourceMgr.isInSystemMacro(CC)) 12275 return; 12276 12277 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12278 } 12279 // ... or possibly if we're increasing rank, too 12280 else if (Order < 0) { 12281 if (S.SourceMgr.isInSystemMacro(CC)) 12282 return; 12283 12284 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12285 } 12286 return; 12287 } 12288 12289 // If the target is integral, always warn. 12290 if (TargetBT && TargetBT->isInteger()) { 12291 if (S.SourceMgr.isInSystemMacro(CC)) 12292 return; 12293 12294 DiagnoseFloatingImpCast(S, E, T, CC); 12295 } 12296 12297 // Detect the case where a call result is converted from floating-point to 12298 // to bool, and the final argument to the call is converted from bool, to 12299 // discover this typo: 12300 // 12301 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12302 // 12303 // FIXME: This is an incredibly special case; is there some more general 12304 // way to detect this class of misplaced-parentheses bug? 12305 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12306 // Check last argument of function call to see if it is an 12307 // implicit cast from a type matching the type the result 12308 // is being cast to. 12309 CallExpr *CEx = cast<CallExpr>(E); 12310 if (unsigned NumArgs = CEx->getNumArgs()) { 12311 Expr *LastA = CEx->getArg(NumArgs - 1); 12312 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12313 if (isa<ImplicitCastExpr>(LastA) && 12314 InnerE->getType()->isBooleanType()) { 12315 // Warn on this floating-point to bool conversion 12316 DiagnoseImpCast(S, E, T, CC, 12317 diag::warn_impcast_floating_point_to_bool); 12318 } 12319 } 12320 } 12321 return; 12322 } 12323 12324 // Valid casts involving fixed point types should be accounted for here. 12325 if (Source->isFixedPointType()) { 12326 if (Target->isUnsaturatedFixedPointType()) { 12327 Expr::EvalResult Result; 12328 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12329 S.isConstantEvaluated())) { 12330 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12331 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12332 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12333 if (Value > MaxVal || Value < MinVal) { 12334 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12335 S.PDiag(diag::warn_impcast_fixed_point_range) 12336 << Value.toString() << T 12337 << E->getSourceRange() 12338 << clang::SourceRange(CC)); 12339 return; 12340 } 12341 } 12342 } else if (Target->isIntegerType()) { 12343 Expr::EvalResult Result; 12344 if (!S.isConstantEvaluated() && 12345 E->EvaluateAsFixedPoint(Result, S.Context, 12346 Expr::SE_AllowSideEffects)) { 12347 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12348 12349 bool Overflowed; 12350 llvm::APSInt IntResult = FXResult.convertToInt( 12351 S.Context.getIntWidth(T), 12352 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12353 12354 if (Overflowed) { 12355 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12356 S.PDiag(diag::warn_impcast_fixed_point_range) 12357 << FXResult.toString() << T 12358 << E->getSourceRange() 12359 << clang::SourceRange(CC)); 12360 return; 12361 } 12362 } 12363 } 12364 } else if (Target->isUnsaturatedFixedPointType()) { 12365 if (Source->isIntegerType()) { 12366 Expr::EvalResult Result; 12367 if (!S.isConstantEvaluated() && 12368 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12369 llvm::APSInt Value = Result.Val.getInt(); 12370 12371 bool Overflowed; 12372 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12373 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12374 12375 if (Overflowed) { 12376 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12377 S.PDiag(diag::warn_impcast_fixed_point_range) 12378 << Value.toString(/*Radix=*/10) << T 12379 << E->getSourceRange() 12380 << clang::SourceRange(CC)); 12381 return; 12382 } 12383 } 12384 } 12385 } 12386 12387 // If we are casting an integer type to a floating point type without 12388 // initialization-list syntax, we might lose accuracy if the floating 12389 // point type has a narrower significand than the integer type. 12390 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12391 TargetBT->isFloatingType() && !IsListInit) { 12392 // Determine the number of precision bits in the source integer type. 12393 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12394 /*Approximate*/ true); 12395 unsigned int SourcePrecision = SourceRange.Width; 12396 12397 // Determine the number of precision bits in the 12398 // target floating point type. 12399 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12400 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12401 12402 if (SourcePrecision > 0 && TargetPrecision > 0 && 12403 SourcePrecision > TargetPrecision) { 12404 12405 if (Optional<llvm::APSInt> SourceInt = 12406 E->getIntegerConstantExpr(S.Context)) { 12407 // If the source integer is a constant, convert it to the target 12408 // floating point type. Issue a warning if the value changes 12409 // during the whole conversion. 12410 llvm::APFloat TargetFloatValue( 12411 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12412 llvm::APFloat::opStatus ConversionStatus = 12413 TargetFloatValue.convertFromAPInt( 12414 *SourceInt, SourceBT->isSignedInteger(), 12415 llvm::APFloat::rmNearestTiesToEven); 12416 12417 if (ConversionStatus != llvm::APFloat::opOK) { 12418 std::string PrettySourceValue = SourceInt->toString(10); 12419 SmallString<32> PrettyTargetValue; 12420 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12421 12422 S.DiagRuntimeBehavior( 12423 E->getExprLoc(), E, 12424 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12425 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12426 << E->getSourceRange() << clang::SourceRange(CC)); 12427 } 12428 } else { 12429 // Otherwise, the implicit conversion may lose precision. 12430 DiagnoseImpCast(S, E, T, CC, 12431 diag::warn_impcast_integer_float_precision); 12432 } 12433 } 12434 } 12435 12436 DiagnoseNullConversion(S, E, T, CC); 12437 12438 S.DiscardMisalignedMemberAddress(Target, E); 12439 12440 if (Target->isBooleanType()) 12441 DiagnoseIntInBoolContext(S, E); 12442 12443 if (!Source->isIntegerType() || !Target->isIntegerType()) 12444 return; 12445 12446 // TODO: remove this early return once the false positives for constant->bool 12447 // in templates, macros, etc, are reduced or removed. 12448 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12449 return; 12450 12451 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12452 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12453 return adornObjCBoolConversionDiagWithTernaryFixit( 12454 S, E, 12455 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12456 << E->getType()); 12457 } 12458 12459 IntRange SourceTypeRange = 12460 IntRange::forTargetOfCanonicalType(S.Context, Source); 12461 IntRange LikelySourceRange = 12462 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12463 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12464 12465 if (LikelySourceRange.Width > TargetRange.Width) { 12466 // If the source is a constant, use a default-on diagnostic. 12467 // TODO: this should happen for bitfield stores, too. 12468 Expr::EvalResult Result; 12469 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12470 S.isConstantEvaluated())) { 12471 llvm::APSInt Value(32); 12472 Value = Result.Val.getInt(); 12473 12474 if (S.SourceMgr.isInSystemMacro(CC)) 12475 return; 12476 12477 std::string PrettySourceValue = Value.toString(10); 12478 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12479 12480 S.DiagRuntimeBehavior( 12481 E->getExprLoc(), E, 12482 S.PDiag(diag::warn_impcast_integer_precision_constant) 12483 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12484 << E->getSourceRange() << SourceRange(CC)); 12485 return; 12486 } 12487 12488 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12489 if (S.SourceMgr.isInSystemMacro(CC)) 12490 return; 12491 12492 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12493 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12494 /* pruneControlFlow */ true); 12495 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12496 } 12497 12498 if (TargetRange.Width > SourceTypeRange.Width) { 12499 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12500 if (UO->getOpcode() == UO_Minus) 12501 if (Source->isUnsignedIntegerType()) { 12502 if (Target->isUnsignedIntegerType()) 12503 return DiagnoseImpCast(S, E, T, CC, 12504 diag::warn_impcast_high_order_zero_bits); 12505 if (Target->isSignedIntegerType()) 12506 return DiagnoseImpCast(S, E, T, CC, 12507 diag::warn_impcast_nonnegative_result); 12508 } 12509 } 12510 12511 if (TargetRange.Width == LikelySourceRange.Width && 12512 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12513 Source->isSignedIntegerType()) { 12514 // Warn when doing a signed to signed conversion, warn if the positive 12515 // source value is exactly the width of the target type, which will 12516 // cause a negative value to be stored. 12517 12518 Expr::EvalResult Result; 12519 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12520 !S.SourceMgr.isInSystemMacro(CC)) { 12521 llvm::APSInt Value = Result.Val.getInt(); 12522 if (isSameWidthConstantConversion(S, E, T, CC)) { 12523 std::string PrettySourceValue = Value.toString(10); 12524 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12525 12526 S.DiagRuntimeBehavior( 12527 E->getExprLoc(), E, 12528 S.PDiag(diag::warn_impcast_integer_precision_constant) 12529 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12530 << E->getSourceRange() << SourceRange(CC)); 12531 return; 12532 } 12533 } 12534 12535 // Fall through for non-constants to give a sign conversion warning. 12536 } 12537 12538 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12539 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12540 LikelySourceRange.Width == TargetRange.Width)) { 12541 if (S.SourceMgr.isInSystemMacro(CC)) 12542 return; 12543 12544 unsigned DiagID = diag::warn_impcast_integer_sign; 12545 12546 // Traditionally, gcc has warned about this under -Wsign-compare. 12547 // We also want to warn about it in -Wconversion. 12548 // So if -Wconversion is off, use a completely identical diagnostic 12549 // in the sign-compare group. 12550 // The conditional-checking code will 12551 if (ICContext) { 12552 DiagID = diag::warn_impcast_integer_sign_conditional; 12553 *ICContext = true; 12554 } 12555 12556 return DiagnoseImpCast(S, E, T, CC, DiagID); 12557 } 12558 12559 // Diagnose conversions between different enumeration types. 12560 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12561 // type, to give us better diagnostics. 12562 QualType SourceType = E->getType(); 12563 if (!S.getLangOpts().CPlusPlus) { 12564 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12565 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12566 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12567 SourceType = S.Context.getTypeDeclType(Enum); 12568 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12569 } 12570 } 12571 12572 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12573 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12574 if (SourceEnum->getDecl()->hasNameForLinkage() && 12575 TargetEnum->getDecl()->hasNameForLinkage() && 12576 SourceEnum != TargetEnum) { 12577 if (S.SourceMgr.isInSystemMacro(CC)) 12578 return; 12579 12580 return DiagnoseImpCast(S, E, SourceType, T, CC, 12581 diag::warn_impcast_different_enum_types); 12582 } 12583 } 12584 12585 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12586 SourceLocation CC, QualType T); 12587 12588 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12589 SourceLocation CC, bool &ICContext) { 12590 E = E->IgnoreParenImpCasts(); 12591 12592 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12593 return CheckConditionalOperator(S, CO, CC, T); 12594 12595 AnalyzeImplicitConversions(S, E, CC); 12596 if (E->getType() != T) 12597 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12598 } 12599 12600 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12601 SourceLocation CC, QualType T) { 12602 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12603 12604 Expr *TrueExpr = E->getTrueExpr(); 12605 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12606 TrueExpr = BCO->getCommon(); 12607 12608 bool Suspicious = false; 12609 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12610 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12611 12612 if (T->isBooleanType()) 12613 DiagnoseIntInBoolContext(S, E); 12614 12615 // If -Wconversion would have warned about either of the candidates 12616 // for a signedness conversion to the context type... 12617 if (!Suspicious) return; 12618 12619 // ...but it's currently ignored... 12620 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12621 return; 12622 12623 // ...then check whether it would have warned about either of the 12624 // candidates for a signedness conversion to the condition type. 12625 if (E->getType() == T) return; 12626 12627 Suspicious = false; 12628 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12629 E->getType(), CC, &Suspicious); 12630 if (!Suspicious) 12631 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12632 E->getType(), CC, &Suspicious); 12633 } 12634 12635 /// Check conversion of given expression to boolean. 12636 /// Input argument E is a logical expression. 12637 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12638 if (S.getLangOpts().Bool) 12639 return; 12640 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12641 return; 12642 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12643 } 12644 12645 namespace { 12646 struct AnalyzeImplicitConversionsWorkItem { 12647 Expr *E; 12648 SourceLocation CC; 12649 bool IsListInit; 12650 }; 12651 } 12652 12653 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12654 /// that should be visited are added to WorkList. 12655 static void AnalyzeImplicitConversions( 12656 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12657 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12658 Expr *OrigE = Item.E; 12659 SourceLocation CC = Item.CC; 12660 12661 QualType T = OrigE->getType(); 12662 Expr *E = OrigE->IgnoreParenImpCasts(); 12663 12664 // Propagate whether we are in a C++ list initialization expression. 12665 // If so, we do not issue warnings for implicit int-float conversion 12666 // precision loss, because C++11 narrowing already handles it. 12667 bool IsListInit = Item.IsListInit || 12668 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12669 12670 if (E->isTypeDependent() || E->isValueDependent()) 12671 return; 12672 12673 Expr *SourceExpr = E; 12674 // Examine, but don't traverse into the source expression of an 12675 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12676 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12677 // evaluate it in the context of checking the specific conversion to T though. 12678 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12679 if (auto *Src = OVE->getSourceExpr()) 12680 SourceExpr = Src; 12681 12682 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12683 if (UO->getOpcode() == UO_Not && 12684 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12685 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12686 << OrigE->getSourceRange() << T->isBooleanType() 12687 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12688 12689 // For conditional operators, we analyze the arguments as if they 12690 // were being fed directly into the output. 12691 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12692 CheckConditionalOperator(S, CO, CC, T); 12693 return; 12694 } 12695 12696 // Check implicit argument conversions for function calls. 12697 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12698 CheckImplicitArgumentConversions(S, Call, CC); 12699 12700 // Go ahead and check any implicit conversions we might have skipped. 12701 // The non-canonical typecheck is just an optimization; 12702 // CheckImplicitConversion will filter out dead implicit conversions. 12703 if (SourceExpr->getType() != T) 12704 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12705 12706 // Now continue drilling into this expression. 12707 12708 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12709 // The bound subexpressions in a PseudoObjectExpr are not reachable 12710 // as transitive children. 12711 // FIXME: Use a more uniform representation for this. 12712 for (auto *SE : POE->semantics()) 12713 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12714 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12715 } 12716 12717 // Skip past explicit casts. 12718 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12719 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12720 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12721 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12722 WorkList.push_back({E, CC, IsListInit}); 12723 return; 12724 } 12725 12726 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12727 // Do a somewhat different check with comparison operators. 12728 if (BO->isComparisonOp()) 12729 return AnalyzeComparison(S, BO); 12730 12731 // And with simple assignments. 12732 if (BO->getOpcode() == BO_Assign) 12733 return AnalyzeAssignment(S, BO); 12734 // And with compound assignments. 12735 if (BO->isAssignmentOp()) 12736 return AnalyzeCompoundAssignment(S, BO); 12737 } 12738 12739 // These break the otherwise-useful invariant below. Fortunately, 12740 // we don't really need to recurse into them, because any internal 12741 // expressions should have been analyzed already when they were 12742 // built into statements. 12743 if (isa<StmtExpr>(E)) return; 12744 12745 // Don't descend into unevaluated contexts. 12746 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12747 12748 // Now just recurse over the expression's children. 12749 CC = E->getExprLoc(); 12750 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12751 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12752 for (Stmt *SubStmt : E->children()) { 12753 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12754 if (!ChildExpr) 12755 continue; 12756 12757 if (IsLogicalAndOperator && 12758 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12759 // Ignore checking string literals that are in logical and operators. 12760 // This is a common pattern for asserts. 12761 continue; 12762 WorkList.push_back({ChildExpr, CC, IsListInit}); 12763 } 12764 12765 if (BO && BO->isLogicalOp()) { 12766 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12767 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12768 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12769 12770 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12771 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12772 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12773 } 12774 12775 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12776 if (U->getOpcode() == UO_LNot) { 12777 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12778 } else if (U->getOpcode() != UO_AddrOf) { 12779 if (U->getSubExpr()->getType()->isAtomicType()) 12780 S.Diag(U->getSubExpr()->getBeginLoc(), 12781 diag::warn_atomic_implicit_seq_cst); 12782 } 12783 } 12784 } 12785 12786 /// AnalyzeImplicitConversions - Find and report any interesting 12787 /// implicit conversions in the given expression. There are a couple 12788 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12789 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12790 bool IsListInit/*= false*/) { 12791 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12792 WorkList.push_back({OrigE, CC, IsListInit}); 12793 while (!WorkList.empty()) 12794 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12795 } 12796 12797 /// Diagnose integer type and any valid implicit conversion to it. 12798 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12799 // Taking into account implicit conversions, 12800 // allow any integer. 12801 if (!E->getType()->isIntegerType()) { 12802 S.Diag(E->getBeginLoc(), 12803 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12804 return true; 12805 } 12806 // Potentially emit standard warnings for implicit conversions if enabled 12807 // using -Wconversion. 12808 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12809 return false; 12810 } 12811 12812 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12813 // Returns true when emitting a warning about taking the address of a reference. 12814 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12815 const PartialDiagnostic &PD) { 12816 E = E->IgnoreParenImpCasts(); 12817 12818 const FunctionDecl *FD = nullptr; 12819 12820 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12821 if (!DRE->getDecl()->getType()->isReferenceType()) 12822 return false; 12823 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12824 if (!M->getMemberDecl()->getType()->isReferenceType()) 12825 return false; 12826 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12827 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12828 return false; 12829 FD = Call->getDirectCallee(); 12830 } else { 12831 return false; 12832 } 12833 12834 SemaRef.Diag(E->getExprLoc(), PD); 12835 12836 // If possible, point to location of function. 12837 if (FD) { 12838 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12839 } 12840 12841 return true; 12842 } 12843 12844 // Returns true if the SourceLocation is expanded from any macro body. 12845 // Returns false if the SourceLocation is invalid, is from not in a macro 12846 // expansion, or is from expanded from a top-level macro argument. 12847 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12848 if (Loc.isInvalid()) 12849 return false; 12850 12851 while (Loc.isMacroID()) { 12852 if (SM.isMacroBodyExpansion(Loc)) 12853 return true; 12854 Loc = SM.getImmediateMacroCallerLoc(Loc); 12855 } 12856 12857 return false; 12858 } 12859 12860 /// Diagnose pointers that are always non-null. 12861 /// \param E the expression containing the pointer 12862 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12863 /// compared to a null pointer 12864 /// \param IsEqual True when the comparison is equal to a null pointer 12865 /// \param Range Extra SourceRange to highlight in the diagnostic 12866 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12867 Expr::NullPointerConstantKind NullKind, 12868 bool IsEqual, SourceRange Range) { 12869 if (!E) 12870 return; 12871 12872 // Don't warn inside macros. 12873 if (E->getExprLoc().isMacroID()) { 12874 const SourceManager &SM = getSourceManager(); 12875 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12876 IsInAnyMacroBody(SM, Range.getBegin())) 12877 return; 12878 } 12879 E = E->IgnoreImpCasts(); 12880 12881 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12882 12883 if (isa<CXXThisExpr>(E)) { 12884 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12885 : diag::warn_this_bool_conversion; 12886 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12887 return; 12888 } 12889 12890 bool IsAddressOf = false; 12891 12892 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12893 if (UO->getOpcode() != UO_AddrOf) 12894 return; 12895 IsAddressOf = true; 12896 E = UO->getSubExpr(); 12897 } 12898 12899 if (IsAddressOf) { 12900 unsigned DiagID = IsCompare 12901 ? diag::warn_address_of_reference_null_compare 12902 : diag::warn_address_of_reference_bool_conversion; 12903 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12904 << IsEqual; 12905 if (CheckForReference(*this, E, PD)) { 12906 return; 12907 } 12908 } 12909 12910 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12911 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12912 std::string Str; 12913 llvm::raw_string_ostream S(Str); 12914 E->printPretty(S, nullptr, getPrintingPolicy()); 12915 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12916 : diag::warn_cast_nonnull_to_bool; 12917 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12918 << E->getSourceRange() << Range << IsEqual; 12919 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12920 }; 12921 12922 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12923 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12924 if (auto *Callee = Call->getDirectCallee()) { 12925 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12926 ComplainAboutNonnullParamOrCall(A); 12927 return; 12928 } 12929 } 12930 } 12931 12932 // Expect to find a single Decl. Skip anything more complicated. 12933 ValueDecl *D = nullptr; 12934 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12935 D = R->getDecl(); 12936 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12937 D = M->getMemberDecl(); 12938 } 12939 12940 // Weak Decls can be null. 12941 if (!D || D->isWeak()) 12942 return; 12943 12944 // Check for parameter decl with nonnull attribute 12945 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12946 if (getCurFunction() && 12947 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12948 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12949 ComplainAboutNonnullParamOrCall(A); 12950 return; 12951 } 12952 12953 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12954 // Skip function template not specialized yet. 12955 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12956 return; 12957 auto ParamIter = llvm::find(FD->parameters(), PV); 12958 assert(ParamIter != FD->param_end()); 12959 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12960 12961 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12962 if (!NonNull->args_size()) { 12963 ComplainAboutNonnullParamOrCall(NonNull); 12964 return; 12965 } 12966 12967 for (const ParamIdx &ArgNo : NonNull->args()) { 12968 if (ArgNo.getASTIndex() == ParamNo) { 12969 ComplainAboutNonnullParamOrCall(NonNull); 12970 return; 12971 } 12972 } 12973 } 12974 } 12975 } 12976 } 12977 12978 QualType T = D->getType(); 12979 const bool IsArray = T->isArrayType(); 12980 const bool IsFunction = T->isFunctionType(); 12981 12982 // Address of function is used to silence the function warning. 12983 if (IsAddressOf && IsFunction) { 12984 return; 12985 } 12986 12987 // Found nothing. 12988 if (!IsAddressOf && !IsFunction && !IsArray) 12989 return; 12990 12991 // Pretty print the expression for the diagnostic. 12992 std::string Str; 12993 llvm::raw_string_ostream S(Str); 12994 E->printPretty(S, nullptr, getPrintingPolicy()); 12995 12996 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12997 : diag::warn_impcast_pointer_to_bool; 12998 enum { 12999 AddressOf, 13000 FunctionPointer, 13001 ArrayPointer 13002 } DiagType; 13003 if (IsAddressOf) 13004 DiagType = AddressOf; 13005 else if (IsFunction) 13006 DiagType = FunctionPointer; 13007 else if (IsArray) 13008 DiagType = ArrayPointer; 13009 else 13010 llvm_unreachable("Could not determine diagnostic."); 13011 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13012 << Range << IsEqual; 13013 13014 if (!IsFunction) 13015 return; 13016 13017 // Suggest '&' to silence the function warning. 13018 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13019 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13020 13021 // Check to see if '()' fixit should be emitted. 13022 QualType ReturnType; 13023 UnresolvedSet<4> NonTemplateOverloads; 13024 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13025 if (ReturnType.isNull()) 13026 return; 13027 13028 if (IsCompare) { 13029 // There are two cases here. If there is null constant, the only suggest 13030 // for a pointer return type. If the null is 0, then suggest if the return 13031 // type is a pointer or an integer type. 13032 if (!ReturnType->isPointerType()) { 13033 if (NullKind == Expr::NPCK_ZeroExpression || 13034 NullKind == Expr::NPCK_ZeroLiteral) { 13035 if (!ReturnType->isIntegerType()) 13036 return; 13037 } else { 13038 return; 13039 } 13040 } 13041 } else { // !IsCompare 13042 // For function to bool, only suggest if the function pointer has bool 13043 // return type. 13044 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13045 return; 13046 } 13047 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13048 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13049 } 13050 13051 /// Diagnoses "dangerous" implicit conversions within the given 13052 /// expression (which is a full expression). Implements -Wconversion 13053 /// and -Wsign-compare. 13054 /// 13055 /// \param CC the "context" location of the implicit conversion, i.e. 13056 /// the most location of the syntactic entity requiring the implicit 13057 /// conversion 13058 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13059 // Don't diagnose in unevaluated contexts. 13060 if (isUnevaluatedContext()) 13061 return; 13062 13063 // Don't diagnose for value- or type-dependent expressions. 13064 if (E->isTypeDependent() || E->isValueDependent()) 13065 return; 13066 13067 // Check for array bounds violations in cases where the check isn't triggered 13068 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13069 // ArraySubscriptExpr is on the RHS of a variable initialization. 13070 CheckArrayAccess(E); 13071 13072 // This is not the right CC for (e.g.) a variable initialization. 13073 AnalyzeImplicitConversions(*this, E, CC); 13074 } 13075 13076 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13077 /// Input argument E is a logical expression. 13078 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13079 ::CheckBoolLikeConversion(*this, E, CC); 13080 } 13081 13082 /// Diagnose when expression is an integer constant expression and its evaluation 13083 /// results in integer overflow 13084 void Sema::CheckForIntOverflow (Expr *E) { 13085 // Use a work list to deal with nested struct initializers. 13086 SmallVector<Expr *, 2> Exprs(1, E); 13087 13088 do { 13089 Expr *OriginalE = Exprs.pop_back_val(); 13090 Expr *E = OriginalE->IgnoreParenCasts(); 13091 13092 if (isa<BinaryOperator>(E)) { 13093 E->EvaluateForOverflow(Context); 13094 continue; 13095 } 13096 13097 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13098 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13099 else if (isa<ObjCBoxedExpr>(OriginalE)) 13100 E->EvaluateForOverflow(Context); 13101 else if (auto Call = dyn_cast<CallExpr>(E)) 13102 Exprs.append(Call->arg_begin(), Call->arg_end()); 13103 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13104 Exprs.append(Message->arg_begin(), Message->arg_end()); 13105 } while (!Exprs.empty()); 13106 } 13107 13108 namespace { 13109 13110 /// Visitor for expressions which looks for unsequenced operations on the 13111 /// same object. 13112 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13113 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13114 13115 /// A tree of sequenced regions within an expression. Two regions are 13116 /// unsequenced if one is an ancestor or a descendent of the other. When we 13117 /// finish processing an expression with sequencing, such as a comma 13118 /// expression, we fold its tree nodes into its parent, since they are 13119 /// unsequenced with respect to nodes we will visit later. 13120 class SequenceTree { 13121 struct Value { 13122 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13123 unsigned Parent : 31; 13124 unsigned Merged : 1; 13125 }; 13126 SmallVector<Value, 8> Values; 13127 13128 public: 13129 /// A region within an expression which may be sequenced with respect 13130 /// to some other region. 13131 class Seq { 13132 friend class SequenceTree; 13133 13134 unsigned Index; 13135 13136 explicit Seq(unsigned N) : Index(N) {} 13137 13138 public: 13139 Seq() : Index(0) {} 13140 }; 13141 13142 SequenceTree() { Values.push_back(Value(0)); } 13143 Seq root() const { return Seq(0); } 13144 13145 /// Create a new sequence of operations, which is an unsequenced 13146 /// subset of \p Parent. This sequence of operations is sequenced with 13147 /// respect to other children of \p Parent. 13148 Seq allocate(Seq Parent) { 13149 Values.push_back(Value(Parent.Index)); 13150 return Seq(Values.size() - 1); 13151 } 13152 13153 /// Merge a sequence of operations into its parent. 13154 void merge(Seq S) { 13155 Values[S.Index].Merged = true; 13156 } 13157 13158 /// Determine whether two operations are unsequenced. This operation 13159 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13160 /// should have been merged into its parent as appropriate. 13161 bool isUnsequenced(Seq Cur, Seq Old) { 13162 unsigned C = representative(Cur.Index); 13163 unsigned Target = representative(Old.Index); 13164 while (C >= Target) { 13165 if (C == Target) 13166 return true; 13167 C = Values[C].Parent; 13168 } 13169 return false; 13170 } 13171 13172 private: 13173 /// Pick a representative for a sequence. 13174 unsigned representative(unsigned K) { 13175 if (Values[K].Merged) 13176 // Perform path compression as we go. 13177 return Values[K].Parent = representative(Values[K].Parent); 13178 return K; 13179 } 13180 }; 13181 13182 /// An object for which we can track unsequenced uses. 13183 using Object = const NamedDecl *; 13184 13185 /// Different flavors of object usage which we track. We only track the 13186 /// least-sequenced usage of each kind. 13187 enum UsageKind { 13188 /// A read of an object. Multiple unsequenced reads are OK. 13189 UK_Use, 13190 13191 /// A modification of an object which is sequenced before the value 13192 /// computation of the expression, such as ++n in C++. 13193 UK_ModAsValue, 13194 13195 /// A modification of an object which is not sequenced before the value 13196 /// computation of the expression, such as n++. 13197 UK_ModAsSideEffect, 13198 13199 UK_Count = UK_ModAsSideEffect + 1 13200 }; 13201 13202 /// Bundle together a sequencing region and the expression corresponding 13203 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13204 struct Usage { 13205 const Expr *UsageExpr; 13206 SequenceTree::Seq Seq; 13207 13208 Usage() : UsageExpr(nullptr), Seq() {} 13209 }; 13210 13211 struct UsageInfo { 13212 Usage Uses[UK_Count]; 13213 13214 /// Have we issued a diagnostic for this object already? 13215 bool Diagnosed; 13216 13217 UsageInfo() : Uses(), Diagnosed(false) {} 13218 }; 13219 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13220 13221 Sema &SemaRef; 13222 13223 /// Sequenced regions within the expression. 13224 SequenceTree Tree; 13225 13226 /// Declaration modifications and references which we have seen. 13227 UsageInfoMap UsageMap; 13228 13229 /// The region we are currently within. 13230 SequenceTree::Seq Region; 13231 13232 /// Filled in with declarations which were modified as a side-effect 13233 /// (that is, post-increment operations). 13234 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13235 13236 /// Expressions to check later. We defer checking these to reduce 13237 /// stack usage. 13238 SmallVectorImpl<const Expr *> &WorkList; 13239 13240 /// RAII object wrapping the visitation of a sequenced subexpression of an 13241 /// expression. At the end of this process, the side-effects of the evaluation 13242 /// become sequenced with respect to the value computation of the result, so 13243 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13244 /// UK_ModAsValue. 13245 struct SequencedSubexpression { 13246 SequencedSubexpression(SequenceChecker &Self) 13247 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13248 Self.ModAsSideEffect = &ModAsSideEffect; 13249 } 13250 13251 ~SequencedSubexpression() { 13252 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13253 // Add a new usage with usage kind UK_ModAsValue, and then restore 13254 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13255 // the previous one was empty). 13256 UsageInfo &UI = Self.UsageMap[M.first]; 13257 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13258 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13259 SideEffectUsage = M.second; 13260 } 13261 Self.ModAsSideEffect = OldModAsSideEffect; 13262 } 13263 13264 SequenceChecker &Self; 13265 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13266 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13267 }; 13268 13269 /// RAII object wrapping the visitation of a subexpression which we might 13270 /// choose to evaluate as a constant. If any subexpression is evaluated and 13271 /// found to be non-constant, this allows us to suppress the evaluation of 13272 /// the outer expression. 13273 class EvaluationTracker { 13274 public: 13275 EvaluationTracker(SequenceChecker &Self) 13276 : Self(Self), Prev(Self.EvalTracker) { 13277 Self.EvalTracker = this; 13278 } 13279 13280 ~EvaluationTracker() { 13281 Self.EvalTracker = Prev; 13282 if (Prev) 13283 Prev->EvalOK &= EvalOK; 13284 } 13285 13286 bool evaluate(const Expr *E, bool &Result) { 13287 if (!EvalOK || E->isValueDependent()) 13288 return false; 13289 EvalOK = E->EvaluateAsBooleanCondition( 13290 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13291 return EvalOK; 13292 } 13293 13294 private: 13295 SequenceChecker &Self; 13296 EvaluationTracker *Prev; 13297 bool EvalOK = true; 13298 } *EvalTracker = nullptr; 13299 13300 /// Find the object which is produced by the specified expression, 13301 /// if any. 13302 Object getObject(const Expr *E, bool Mod) const { 13303 E = E->IgnoreParenCasts(); 13304 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13305 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13306 return getObject(UO->getSubExpr(), Mod); 13307 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13308 if (BO->getOpcode() == BO_Comma) 13309 return getObject(BO->getRHS(), Mod); 13310 if (Mod && BO->isAssignmentOp()) 13311 return getObject(BO->getLHS(), Mod); 13312 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13313 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13314 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13315 return ME->getMemberDecl(); 13316 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13317 // FIXME: If this is a reference, map through to its value. 13318 return DRE->getDecl(); 13319 return nullptr; 13320 } 13321 13322 /// Note that an object \p O was modified or used by an expression 13323 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13324 /// the object \p O as obtained via the \p UsageMap. 13325 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13326 // Get the old usage for the given object and usage kind. 13327 Usage &U = UI.Uses[UK]; 13328 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13329 // If we have a modification as side effect and are in a sequenced 13330 // subexpression, save the old Usage so that we can restore it later 13331 // in SequencedSubexpression::~SequencedSubexpression. 13332 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13333 ModAsSideEffect->push_back(std::make_pair(O, U)); 13334 // Then record the new usage with the current sequencing region. 13335 U.UsageExpr = UsageExpr; 13336 U.Seq = Region; 13337 } 13338 } 13339 13340 /// Check whether a modification or use of an object \p O in an expression 13341 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13342 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13343 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13344 /// usage and false we are checking for a mod-use unsequenced usage. 13345 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13346 UsageKind OtherKind, bool IsModMod) { 13347 if (UI.Diagnosed) 13348 return; 13349 13350 const Usage &U = UI.Uses[OtherKind]; 13351 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13352 return; 13353 13354 const Expr *Mod = U.UsageExpr; 13355 const Expr *ModOrUse = UsageExpr; 13356 if (OtherKind == UK_Use) 13357 std::swap(Mod, ModOrUse); 13358 13359 SemaRef.DiagRuntimeBehavior( 13360 Mod->getExprLoc(), {Mod, ModOrUse}, 13361 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13362 : diag::warn_unsequenced_mod_use) 13363 << O << SourceRange(ModOrUse->getExprLoc())); 13364 UI.Diagnosed = true; 13365 } 13366 13367 // A note on note{Pre, Post}{Use, Mod}: 13368 // 13369 // (It helps to follow the algorithm with an expression such as 13370 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13371 // operations before C++17 and both are well-defined in C++17). 13372 // 13373 // When visiting a node which uses/modify an object we first call notePreUse 13374 // or notePreMod before visiting its sub-expression(s). At this point the 13375 // children of the current node have not yet been visited and so the eventual 13376 // uses/modifications resulting from the children of the current node have not 13377 // been recorded yet. 13378 // 13379 // We then visit the children of the current node. After that notePostUse or 13380 // notePostMod is called. These will 1) detect an unsequenced modification 13381 // as side effect (as in "k++ + k") and 2) add a new usage with the 13382 // appropriate usage kind. 13383 // 13384 // We also have to be careful that some operation sequences modification as 13385 // side effect as well (for example: || or ,). To account for this we wrap 13386 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13387 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13388 // which record usages which are modifications as side effect, and then 13389 // downgrade them (or more accurately restore the previous usage which was a 13390 // modification as side effect) when exiting the scope of the sequenced 13391 // subexpression. 13392 13393 void notePreUse(Object O, const Expr *UseExpr) { 13394 UsageInfo &UI = UsageMap[O]; 13395 // Uses conflict with other modifications. 13396 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13397 } 13398 13399 void notePostUse(Object O, const Expr *UseExpr) { 13400 UsageInfo &UI = UsageMap[O]; 13401 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13402 /*IsModMod=*/false); 13403 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13404 } 13405 13406 void notePreMod(Object O, const Expr *ModExpr) { 13407 UsageInfo &UI = UsageMap[O]; 13408 // Modifications conflict with other modifications and with uses. 13409 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13410 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13411 } 13412 13413 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13414 UsageInfo &UI = UsageMap[O]; 13415 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13416 /*IsModMod=*/true); 13417 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13418 } 13419 13420 public: 13421 SequenceChecker(Sema &S, const Expr *E, 13422 SmallVectorImpl<const Expr *> &WorkList) 13423 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13424 Visit(E); 13425 // Silence a -Wunused-private-field since WorkList is now unused. 13426 // TODO: Evaluate if it can be used, and if not remove it. 13427 (void)this->WorkList; 13428 } 13429 13430 void VisitStmt(const Stmt *S) { 13431 // Skip all statements which aren't expressions for now. 13432 } 13433 13434 void VisitExpr(const Expr *E) { 13435 // By default, just recurse to evaluated subexpressions. 13436 Base::VisitStmt(E); 13437 } 13438 13439 void VisitCastExpr(const CastExpr *E) { 13440 Object O = Object(); 13441 if (E->getCastKind() == CK_LValueToRValue) 13442 O = getObject(E->getSubExpr(), false); 13443 13444 if (O) 13445 notePreUse(O, E); 13446 VisitExpr(E); 13447 if (O) 13448 notePostUse(O, E); 13449 } 13450 13451 void VisitSequencedExpressions(const Expr *SequencedBefore, 13452 const Expr *SequencedAfter) { 13453 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13454 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13455 SequenceTree::Seq OldRegion = Region; 13456 13457 { 13458 SequencedSubexpression SeqBefore(*this); 13459 Region = BeforeRegion; 13460 Visit(SequencedBefore); 13461 } 13462 13463 Region = AfterRegion; 13464 Visit(SequencedAfter); 13465 13466 Region = OldRegion; 13467 13468 Tree.merge(BeforeRegion); 13469 Tree.merge(AfterRegion); 13470 } 13471 13472 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13473 // C++17 [expr.sub]p1: 13474 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13475 // expression E1 is sequenced before the expression E2. 13476 if (SemaRef.getLangOpts().CPlusPlus17) 13477 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13478 else { 13479 Visit(ASE->getLHS()); 13480 Visit(ASE->getRHS()); 13481 } 13482 } 13483 13484 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13485 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13486 void VisitBinPtrMem(const BinaryOperator *BO) { 13487 // C++17 [expr.mptr.oper]p4: 13488 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13489 // the expression E1 is sequenced before the expression E2. 13490 if (SemaRef.getLangOpts().CPlusPlus17) 13491 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13492 else { 13493 Visit(BO->getLHS()); 13494 Visit(BO->getRHS()); 13495 } 13496 } 13497 13498 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13499 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13500 void VisitBinShlShr(const BinaryOperator *BO) { 13501 // C++17 [expr.shift]p4: 13502 // The expression E1 is sequenced before the expression E2. 13503 if (SemaRef.getLangOpts().CPlusPlus17) 13504 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13505 else { 13506 Visit(BO->getLHS()); 13507 Visit(BO->getRHS()); 13508 } 13509 } 13510 13511 void VisitBinComma(const BinaryOperator *BO) { 13512 // C++11 [expr.comma]p1: 13513 // Every value computation and side effect associated with the left 13514 // expression is sequenced before every value computation and side 13515 // effect associated with the right expression. 13516 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13517 } 13518 13519 void VisitBinAssign(const BinaryOperator *BO) { 13520 SequenceTree::Seq RHSRegion; 13521 SequenceTree::Seq LHSRegion; 13522 if (SemaRef.getLangOpts().CPlusPlus17) { 13523 RHSRegion = Tree.allocate(Region); 13524 LHSRegion = Tree.allocate(Region); 13525 } else { 13526 RHSRegion = Region; 13527 LHSRegion = Region; 13528 } 13529 SequenceTree::Seq OldRegion = Region; 13530 13531 // C++11 [expr.ass]p1: 13532 // [...] the assignment is sequenced after the value computation 13533 // of the right and left operands, [...] 13534 // 13535 // so check it before inspecting the operands and update the 13536 // map afterwards. 13537 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13538 if (O) 13539 notePreMod(O, BO); 13540 13541 if (SemaRef.getLangOpts().CPlusPlus17) { 13542 // C++17 [expr.ass]p1: 13543 // [...] The right operand is sequenced before the left operand. [...] 13544 { 13545 SequencedSubexpression SeqBefore(*this); 13546 Region = RHSRegion; 13547 Visit(BO->getRHS()); 13548 } 13549 13550 Region = LHSRegion; 13551 Visit(BO->getLHS()); 13552 13553 if (O && isa<CompoundAssignOperator>(BO)) 13554 notePostUse(O, BO); 13555 13556 } else { 13557 // C++11 does not specify any sequencing between the LHS and RHS. 13558 Region = LHSRegion; 13559 Visit(BO->getLHS()); 13560 13561 if (O && isa<CompoundAssignOperator>(BO)) 13562 notePostUse(O, BO); 13563 13564 Region = RHSRegion; 13565 Visit(BO->getRHS()); 13566 } 13567 13568 // C++11 [expr.ass]p1: 13569 // the assignment is sequenced [...] before the value computation of the 13570 // assignment expression. 13571 // C11 6.5.16/3 has no such rule. 13572 Region = OldRegion; 13573 if (O) 13574 notePostMod(O, BO, 13575 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13576 : UK_ModAsSideEffect); 13577 if (SemaRef.getLangOpts().CPlusPlus17) { 13578 Tree.merge(RHSRegion); 13579 Tree.merge(LHSRegion); 13580 } 13581 } 13582 13583 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13584 VisitBinAssign(CAO); 13585 } 13586 13587 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13588 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13589 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13590 Object O = getObject(UO->getSubExpr(), true); 13591 if (!O) 13592 return VisitExpr(UO); 13593 13594 notePreMod(O, UO); 13595 Visit(UO->getSubExpr()); 13596 // C++11 [expr.pre.incr]p1: 13597 // the expression ++x is equivalent to x+=1 13598 notePostMod(O, UO, 13599 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13600 : UK_ModAsSideEffect); 13601 } 13602 13603 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13604 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13605 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13606 Object O = getObject(UO->getSubExpr(), true); 13607 if (!O) 13608 return VisitExpr(UO); 13609 13610 notePreMod(O, UO); 13611 Visit(UO->getSubExpr()); 13612 notePostMod(O, UO, UK_ModAsSideEffect); 13613 } 13614 13615 void VisitBinLOr(const BinaryOperator *BO) { 13616 // C++11 [expr.log.or]p2: 13617 // If the second expression is evaluated, every value computation and 13618 // side effect associated with the first expression is sequenced before 13619 // every value computation and side effect associated with the 13620 // second expression. 13621 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13622 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13623 SequenceTree::Seq OldRegion = Region; 13624 13625 EvaluationTracker Eval(*this); 13626 { 13627 SequencedSubexpression Sequenced(*this); 13628 Region = LHSRegion; 13629 Visit(BO->getLHS()); 13630 } 13631 13632 // C++11 [expr.log.or]p1: 13633 // [...] the second operand is not evaluated if the first operand 13634 // evaluates to true. 13635 bool EvalResult = false; 13636 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13637 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13638 if (ShouldVisitRHS) { 13639 Region = RHSRegion; 13640 Visit(BO->getRHS()); 13641 } 13642 13643 Region = OldRegion; 13644 Tree.merge(LHSRegion); 13645 Tree.merge(RHSRegion); 13646 } 13647 13648 void VisitBinLAnd(const BinaryOperator *BO) { 13649 // C++11 [expr.log.and]p2: 13650 // If the second expression is evaluated, every value computation and 13651 // side effect associated with the first expression is sequenced before 13652 // every value computation and side effect associated with the 13653 // second expression. 13654 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13655 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13656 SequenceTree::Seq OldRegion = Region; 13657 13658 EvaluationTracker Eval(*this); 13659 { 13660 SequencedSubexpression Sequenced(*this); 13661 Region = LHSRegion; 13662 Visit(BO->getLHS()); 13663 } 13664 13665 // C++11 [expr.log.and]p1: 13666 // [...] the second operand is not evaluated if the first operand is false. 13667 bool EvalResult = false; 13668 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13669 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13670 if (ShouldVisitRHS) { 13671 Region = RHSRegion; 13672 Visit(BO->getRHS()); 13673 } 13674 13675 Region = OldRegion; 13676 Tree.merge(LHSRegion); 13677 Tree.merge(RHSRegion); 13678 } 13679 13680 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13681 // C++11 [expr.cond]p1: 13682 // [...] Every value computation and side effect associated with the first 13683 // expression is sequenced before every value computation and side effect 13684 // associated with the second or third expression. 13685 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13686 13687 // No sequencing is specified between the true and false expression. 13688 // However since exactly one of both is going to be evaluated we can 13689 // consider them to be sequenced. This is needed to avoid warning on 13690 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13691 // both the true and false expressions because we can't evaluate x. 13692 // This will still allow us to detect an expression like (pre C++17) 13693 // "(x ? y += 1 : y += 2) = y". 13694 // 13695 // We don't wrap the visitation of the true and false expression with 13696 // SequencedSubexpression because we don't want to downgrade modifications 13697 // as side effect in the true and false expressions after the visition 13698 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13699 // not warn between the two "y++", but we should warn between the "y++" 13700 // and the "y". 13701 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13702 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13703 SequenceTree::Seq OldRegion = Region; 13704 13705 EvaluationTracker Eval(*this); 13706 { 13707 SequencedSubexpression Sequenced(*this); 13708 Region = ConditionRegion; 13709 Visit(CO->getCond()); 13710 } 13711 13712 // C++11 [expr.cond]p1: 13713 // [...] The first expression is contextually converted to bool (Clause 4). 13714 // It is evaluated and if it is true, the result of the conditional 13715 // expression is the value of the second expression, otherwise that of the 13716 // third expression. Only one of the second and third expressions is 13717 // evaluated. [...] 13718 bool EvalResult = false; 13719 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13720 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13721 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13722 if (ShouldVisitTrueExpr) { 13723 Region = TrueRegion; 13724 Visit(CO->getTrueExpr()); 13725 } 13726 if (ShouldVisitFalseExpr) { 13727 Region = FalseRegion; 13728 Visit(CO->getFalseExpr()); 13729 } 13730 13731 Region = OldRegion; 13732 Tree.merge(ConditionRegion); 13733 Tree.merge(TrueRegion); 13734 Tree.merge(FalseRegion); 13735 } 13736 13737 void VisitCallExpr(const CallExpr *CE) { 13738 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13739 13740 if (CE->isUnevaluatedBuiltinCall(Context)) 13741 return; 13742 13743 // C++11 [intro.execution]p15: 13744 // When calling a function [...], every value computation and side effect 13745 // associated with any argument expression, or with the postfix expression 13746 // designating the called function, is sequenced before execution of every 13747 // expression or statement in the body of the function [and thus before 13748 // the value computation of its result]. 13749 SequencedSubexpression Sequenced(*this); 13750 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13751 // C++17 [expr.call]p5 13752 // The postfix-expression is sequenced before each expression in the 13753 // expression-list and any default argument. [...] 13754 SequenceTree::Seq CalleeRegion; 13755 SequenceTree::Seq OtherRegion; 13756 if (SemaRef.getLangOpts().CPlusPlus17) { 13757 CalleeRegion = Tree.allocate(Region); 13758 OtherRegion = Tree.allocate(Region); 13759 } else { 13760 CalleeRegion = Region; 13761 OtherRegion = Region; 13762 } 13763 SequenceTree::Seq OldRegion = Region; 13764 13765 // Visit the callee expression first. 13766 Region = CalleeRegion; 13767 if (SemaRef.getLangOpts().CPlusPlus17) { 13768 SequencedSubexpression Sequenced(*this); 13769 Visit(CE->getCallee()); 13770 } else { 13771 Visit(CE->getCallee()); 13772 } 13773 13774 // Then visit the argument expressions. 13775 Region = OtherRegion; 13776 for (const Expr *Argument : CE->arguments()) 13777 Visit(Argument); 13778 13779 Region = OldRegion; 13780 if (SemaRef.getLangOpts().CPlusPlus17) { 13781 Tree.merge(CalleeRegion); 13782 Tree.merge(OtherRegion); 13783 } 13784 }); 13785 } 13786 13787 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13788 // C++17 [over.match.oper]p2: 13789 // [...] the operator notation is first transformed to the equivalent 13790 // function-call notation as summarized in Table 12 (where @ denotes one 13791 // of the operators covered in the specified subclause). However, the 13792 // operands are sequenced in the order prescribed for the built-in 13793 // operator (Clause 8). 13794 // 13795 // From the above only overloaded binary operators and overloaded call 13796 // operators have sequencing rules in C++17 that we need to handle 13797 // separately. 13798 if (!SemaRef.getLangOpts().CPlusPlus17 || 13799 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13800 return VisitCallExpr(CXXOCE); 13801 13802 enum { 13803 NoSequencing, 13804 LHSBeforeRHS, 13805 RHSBeforeLHS, 13806 LHSBeforeRest 13807 } SequencingKind; 13808 switch (CXXOCE->getOperator()) { 13809 case OO_Equal: 13810 case OO_PlusEqual: 13811 case OO_MinusEqual: 13812 case OO_StarEqual: 13813 case OO_SlashEqual: 13814 case OO_PercentEqual: 13815 case OO_CaretEqual: 13816 case OO_AmpEqual: 13817 case OO_PipeEqual: 13818 case OO_LessLessEqual: 13819 case OO_GreaterGreaterEqual: 13820 SequencingKind = RHSBeforeLHS; 13821 break; 13822 13823 case OO_LessLess: 13824 case OO_GreaterGreater: 13825 case OO_AmpAmp: 13826 case OO_PipePipe: 13827 case OO_Comma: 13828 case OO_ArrowStar: 13829 case OO_Subscript: 13830 SequencingKind = LHSBeforeRHS; 13831 break; 13832 13833 case OO_Call: 13834 SequencingKind = LHSBeforeRest; 13835 break; 13836 13837 default: 13838 SequencingKind = NoSequencing; 13839 break; 13840 } 13841 13842 if (SequencingKind == NoSequencing) 13843 return VisitCallExpr(CXXOCE); 13844 13845 // This is a call, so all subexpressions are sequenced before the result. 13846 SequencedSubexpression Sequenced(*this); 13847 13848 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13849 assert(SemaRef.getLangOpts().CPlusPlus17 && 13850 "Should only get there with C++17 and above!"); 13851 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13852 "Should only get there with an overloaded binary operator" 13853 " or an overloaded call operator!"); 13854 13855 if (SequencingKind == LHSBeforeRest) { 13856 assert(CXXOCE->getOperator() == OO_Call && 13857 "We should only have an overloaded call operator here!"); 13858 13859 // This is very similar to VisitCallExpr, except that we only have the 13860 // C++17 case. The postfix-expression is the first argument of the 13861 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13862 // are in the following arguments. 13863 // 13864 // Note that we intentionally do not visit the callee expression since 13865 // it is just a decayed reference to a function. 13866 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13867 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13868 SequenceTree::Seq OldRegion = Region; 13869 13870 assert(CXXOCE->getNumArgs() >= 1 && 13871 "An overloaded call operator must have at least one argument" 13872 " for the postfix-expression!"); 13873 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13874 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13875 CXXOCE->getNumArgs() - 1); 13876 13877 // Visit the postfix-expression first. 13878 { 13879 Region = PostfixExprRegion; 13880 SequencedSubexpression Sequenced(*this); 13881 Visit(PostfixExpr); 13882 } 13883 13884 // Then visit the argument expressions. 13885 Region = ArgsRegion; 13886 for (const Expr *Arg : Args) 13887 Visit(Arg); 13888 13889 Region = OldRegion; 13890 Tree.merge(PostfixExprRegion); 13891 Tree.merge(ArgsRegion); 13892 } else { 13893 assert(CXXOCE->getNumArgs() == 2 && 13894 "Should only have two arguments here!"); 13895 assert((SequencingKind == LHSBeforeRHS || 13896 SequencingKind == RHSBeforeLHS) && 13897 "Unexpected sequencing kind!"); 13898 13899 // We do not visit the callee expression since it is just a decayed 13900 // reference to a function. 13901 const Expr *E1 = CXXOCE->getArg(0); 13902 const Expr *E2 = CXXOCE->getArg(1); 13903 if (SequencingKind == RHSBeforeLHS) 13904 std::swap(E1, E2); 13905 13906 return VisitSequencedExpressions(E1, E2); 13907 } 13908 }); 13909 } 13910 13911 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13912 // This is a call, so all subexpressions are sequenced before the result. 13913 SequencedSubexpression Sequenced(*this); 13914 13915 if (!CCE->isListInitialization()) 13916 return VisitExpr(CCE); 13917 13918 // In C++11, list initializations are sequenced. 13919 SmallVector<SequenceTree::Seq, 32> Elts; 13920 SequenceTree::Seq Parent = Region; 13921 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13922 E = CCE->arg_end(); 13923 I != E; ++I) { 13924 Region = Tree.allocate(Parent); 13925 Elts.push_back(Region); 13926 Visit(*I); 13927 } 13928 13929 // Forget that the initializers are sequenced. 13930 Region = Parent; 13931 for (unsigned I = 0; I < Elts.size(); ++I) 13932 Tree.merge(Elts[I]); 13933 } 13934 13935 void VisitInitListExpr(const InitListExpr *ILE) { 13936 if (!SemaRef.getLangOpts().CPlusPlus11) 13937 return VisitExpr(ILE); 13938 13939 // In C++11, list initializations are sequenced. 13940 SmallVector<SequenceTree::Seq, 32> Elts; 13941 SequenceTree::Seq Parent = Region; 13942 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13943 const Expr *E = ILE->getInit(I); 13944 if (!E) 13945 continue; 13946 Region = Tree.allocate(Parent); 13947 Elts.push_back(Region); 13948 Visit(E); 13949 } 13950 13951 // Forget that the initializers are sequenced. 13952 Region = Parent; 13953 for (unsigned I = 0; I < Elts.size(); ++I) 13954 Tree.merge(Elts[I]); 13955 } 13956 }; 13957 13958 } // namespace 13959 13960 void Sema::CheckUnsequencedOperations(const Expr *E) { 13961 SmallVector<const Expr *, 8> WorkList; 13962 WorkList.push_back(E); 13963 while (!WorkList.empty()) { 13964 const Expr *Item = WorkList.pop_back_val(); 13965 SequenceChecker(*this, Item, WorkList); 13966 } 13967 } 13968 13969 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13970 bool IsConstexpr) { 13971 llvm::SaveAndRestore<bool> ConstantContext( 13972 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13973 CheckImplicitConversions(E, CheckLoc); 13974 if (!E->isInstantiationDependent()) 13975 CheckUnsequencedOperations(E); 13976 if (!IsConstexpr && !E->isValueDependent()) 13977 CheckForIntOverflow(E); 13978 DiagnoseMisalignedMembers(); 13979 } 13980 13981 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13982 FieldDecl *BitField, 13983 Expr *Init) { 13984 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13985 } 13986 13987 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13988 SourceLocation Loc) { 13989 if (!PType->isVariablyModifiedType()) 13990 return; 13991 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13992 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13993 return; 13994 } 13995 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13996 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13997 return; 13998 } 13999 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14000 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14001 return; 14002 } 14003 14004 const ArrayType *AT = S.Context.getAsArrayType(PType); 14005 if (!AT) 14006 return; 14007 14008 if (AT->getSizeModifier() != ArrayType::Star) { 14009 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14010 return; 14011 } 14012 14013 S.Diag(Loc, diag::err_array_star_in_function_definition); 14014 } 14015 14016 /// CheckParmsForFunctionDef - Check that the parameters of the given 14017 /// function are appropriate for the definition of a function. This 14018 /// takes care of any checks that cannot be performed on the 14019 /// declaration itself, e.g., that the types of each of the function 14020 /// parameters are complete. 14021 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14022 bool CheckParameterNames) { 14023 bool HasInvalidParm = false; 14024 for (ParmVarDecl *Param : Parameters) { 14025 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14026 // function declarator that is part of a function definition of 14027 // that function shall not have incomplete type. 14028 // 14029 // This is also C++ [dcl.fct]p6. 14030 if (!Param->isInvalidDecl() && 14031 RequireCompleteType(Param->getLocation(), Param->getType(), 14032 diag::err_typecheck_decl_incomplete_type)) { 14033 Param->setInvalidDecl(); 14034 HasInvalidParm = true; 14035 } 14036 14037 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14038 // declaration of each parameter shall include an identifier. 14039 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14040 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14041 // Diagnose this as an extension in C17 and earlier. 14042 if (!getLangOpts().C2x) 14043 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14044 } 14045 14046 // C99 6.7.5.3p12: 14047 // If the function declarator is not part of a definition of that 14048 // function, parameters may have incomplete type and may use the [*] 14049 // notation in their sequences of declarator specifiers to specify 14050 // variable length array types. 14051 QualType PType = Param->getOriginalType(); 14052 // FIXME: This diagnostic should point the '[*]' if source-location 14053 // information is added for it. 14054 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14055 14056 // If the parameter is a c++ class type and it has to be destructed in the 14057 // callee function, declare the destructor so that it can be called by the 14058 // callee function. Do not perform any direct access check on the dtor here. 14059 if (!Param->isInvalidDecl()) { 14060 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14061 if (!ClassDecl->isInvalidDecl() && 14062 !ClassDecl->hasIrrelevantDestructor() && 14063 !ClassDecl->isDependentContext() && 14064 ClassDecl->isParamDestroyedInCallee()) { 14065 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14066 MarkFunctionReferenced(Param->getLocation(), Destructor); 14067 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14068 } 14069 } 14070 } 14071 14072 // Parameters with the pass_object_size attribute only need to be marked 14073 // constant at function definitions. Because we lack information about 14074 // whether we're on a declaration or definition when we're instantiating the 14075 // attribute, we need to check for constness here. 14076 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14077 if (!Param->getType().isConstQualified()) 14078 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14079 << Attr->getSpelling() << 1; 14080 14081 // Check for parameter names shadowing fields from the class. 14082 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14083 // The owning context for the parameter should be the function, but we 14084 // want to see if this function's declaration context is a record. 14085 DeclContext *DC = Param->getDeclContext(); 14086 if (DC && DC->isFunctionOrMethod()) { 14087 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14088 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14089 RD, /*DeclIsField*/ false); 14090 } 14091 } 14092 } 14093 14094 return HasInvalidParm; 14095 } 14096 14097 Optional<std::pair<CharUnits, CharUnits>> 14098 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14099 14100 /// Compute the alignment and offset of the base class object given the 14101 /// derived-to-base cast expression and the alignment and offset of the derived 14102 /// class object. 14103 static std::pair<CharUnits, CharUnits> 14104 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14105 CharUnits BaseAlignment, CharUnits Offset, 14106 ASTContext &Ctx) { 14107 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14108 ++PathI) { 14109 const CXXBaseSpecifier *Base = *PathI; 14110 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14111 if (Base->isVirtual()) { 14112 // The complete object may have a lower alignment than the non-virtual 14113 // alignment of the base, in which case the base may be misaligned. Choose 14114 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14115 // conservative lower bound of the complete object alignment. 14116 CharUnits NonVirtualAlignment = 14117 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14118 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14119 Offset = CharUnits::Zero(); 14120 } else { 14121 const ASTRecordLayout &RL = 14122 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14123 Offset += RL.getBaseClassOffset(BaseDecl); 14124 } 14125 DerivedType = Base->getType(); 14126 } 14127 14128 return std::make_pair(BaseAlignment, Offset); 14129 } 14130 14131 /// Compute the alignment and offset of a binary additive operator. 14132 static Optional<std::pair<CharUnits, CharUnits>> 14133 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14134 bool IsSub, ASTContext &Ctx) { 14135 QualType PointeeType = PtrE->getType()->getPointeeType(); 14136 14137 if (!PointeeType->isConstantSizeType()) 14138 return llvm::None; 14139 14140 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14141 14142 if (!P) 14143 return llvm::None; 14144 14145 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14146 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14147 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14148 if (IsSub) 14149 Offset = -Offset; 14150 return std::make_pair(P->first, P->second + Offset); 14151 } 14152 14153 // If the integer expression isn't a constant expression, compute the lower 14154 // bound of the alignment using the alignment and offset of the pointer 14155 // expression and the element size. 14156 return std::make_pair( 14157 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14158 CharUnits::Zero()); 14159 } 14160 14161 /// This helper function takes an lvalue expression and returns the alignment of 14162 /// a VarDecl and a constant offset from the VarDecl. 14163 Optional<std::pair<CharUnits, CharUnits>> 14164 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14165 E = E->IgnoreParens(); 14166 switch (E->getStmtClass()) { 14167 default: 14168 break; 14169 case Stmt::CStyleCastExprClass: 14170 case Stmt::CXXStaticCastExprClass: 14171 case Stmt::ImplicitCastExprClass: { 14172 auto *CE = cast<CastExpr>(E); 14173 const Expr *From = CE->getSubExpr(); 14174 switch (CE->getCastKind()) { 14175 default: 14176 break; 14177 case CK_NoOp: 14178 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14179 case CK_UncheckedDerivedToBase: 14180 case CK_DerivedToBase: { 14181 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14182 if (!P) 14183 break; 14184 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14185 P->second, Ctx); 14186 } 14187 } 14188 break; 14189 } 14190 case Stmt::ArraySubscriptExprClass: { 14191 auto *ASE = cast<ArraySubscriptExpr>(E); 14192 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14193 false, Ctx); 14194 } 14195 case Stmt::DeclRefExprClass: { 14196 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14197 // FIXME: If VD is captured by copy or is an escaping __block variable, 14198 // use the alignment of VD's type. 14199 if (!VD->getType()->isReferenceType()) 14200 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14201 if (VD->hasInit()) 14202 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14203 } 14204 break; 14205 } 14206 case Stmt::MemberExprClass: { 14207 auto *ME = cast<MemberExpr>(E); 14208 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14209 if (!FD || FD->getType()->isReferenceType()) 14210 break; 14211 Optional<std::pair<CharUnits, CharUnits>> P; 14212 if (ME->isArrow()) 14213 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14214 else 14215 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14216 if (!P) 14217 break; 14218 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14219 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14220 return std::make_pair(P->first, 14221 P->second + CharUnits::fromQuantity(Offset)); 14222 } 14223 case Stmt::UnaryOperatorClass: { 14224 auto *UO = cast<UnaryOperator>(E); 14225 switch (UO->getOpcode()) { 14226 default: 14227 break; 14228 case UO_Deref: 14229 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14230 } 14231 break; 14232 } 14233 case Stmt::BinaryOperatorClass: { 14234 auto *BO = cast<BinaryOperator>(E); 14235 auto Opcode = BO->getOpcode(); 14236 switch (Opcode) { 14237 default: 14238 break; 14239 case BO_Comma: 14240 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14241 } 14242 break; 14243 } 14244 } 14245 return llvm::None; 14246 } 14247 14248 /// This helper function takes a pointer expression and returns the alignment of 14249 /// a VarDecl and a constant offset from the VarDecl. 14250 Optional<std::pair<CharUnits, CharUnits>> 14251 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14252 E = E->IgnoreParens(); 14253 switch (E->getStmtClass()) { 14254 default: 14255 break; 14256 case Stmt::CStyleCastExprClass: 14257 case Stmt::CXXStaticCastExprClass: 14258 case Stmt::ImplicitCastExprClass: { 14259 auto *CE = cast<CastExpr>(E); 14260 const Expr *From = CE->getSubExpr(); 14261 switch (CE->getCastKind()) { 14262 default: 14263 break; 14264 case CK_NoOp: 14265 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14266 case CK_ArrayToPointerDecay: 14267 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14268 case CK_UncheckedDerivedToBase: 14269 case CK_DerivedToBase: { 14270 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14271 if (!P) 14272 break; 14273 return getDerivedToBaseAlignmentAndOffset( 14274 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14275 } 14276 } 14277 break; 14278 } 14279 case Stmt::CXXThisExprClass: { 14280 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14281 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14282 return std::make_pair(Alignment, CharUnits::Zero()); 14283 } 14284 case Stmt::UnaryOperatorClass: { 14285 auto *UO = cast<UnaryOperator>(E); 14286 if (UO->getOpcode() == UO_AddrOf) 14287 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14288 break; 14289 } 14290 case Stmt::BinaryOperatorClass: { 14291 auto *BO = cast<BinaryOperator>(E); 14292 auto Opcode = BO->getOpcode(); 14293 switch (Opcode) { 14294 default: 14295 break; 14296 case BO_Add: 14297 case BO_Sub: { 14298 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14299 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14300 std::swap(LHS, RHS); 14301 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14302 Ctx); 14303 } 14304 case BO_Comma: 14305 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14306 } 14307 break; 14308 } 14309 } 14310 return llvm::None; 14311 } 14312 14313 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14314 // See if we can compute the alignment of a VarDecl and an offset from it. 14315 Optional<std::pair<CharUnits, CharUnits>> P = 14316 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14317 14318 if (P) 14319 return P->first.alignmentAtOffset(P->second); 14320 14321 // If that failed, return the type's alignment. 14322 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14323 } 14324 14325 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14326 /// pointer cast increases the alignment requirements. 14327 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14328 // This is actually a lot of work to potentially be doing on every 14329 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14330 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14331 return; 14332 14333 // Ignore dependent types. 14334 if (T->isDependentType() || Op->getType()->isDependentType()) 14335 return; 14336 14337 // Require that the destination be a pointer type. 14338 const PointerType *DestPtr = T->getAs<PointerType>(); 14339 if (!DestPtr) return; 14340 14341 // If the destination has alignment 1, we're done. 14342 QualType DestPointee = DestPtr->getPointeeType(); 14343 if (DestPointee->isIncompleteType()) return; 14344 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14345 if (DestAlign.isOne()) return; 14346 14347 // Require that the source be a pointer type. 14348 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14349 if (!SrcPtr) return; 14350 QualType SrcPointee = SrcPtr->getPointeeType(); 14351 14352 // Explicitly allow casts from cv void*. We already implicitly 14353 // allowed casts to cv void*, since they have alignment 1. 14354 // Also allow casts involving incomplete types, which implicitly 14355 // includes 'void'. 14356 if (SrcPointee->isIncompleteType()) return; 14357 14358 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14359 14360 if (SrcAlign >= DestAlign) return; 14361 14362 Diag(TRange.getBegin(), diag::warn_cast_align) 14363 << Op->getType() << T 14364 << static_cast<unsigned>(SrcAlign.getQuantity()) 14365 << static_cast<unsigned>(DestAlign.getQuantity()) 14366 << TRange << Op->getSourceRange(); 14367 } 14368 14369 /// Check whether this array fits the idiom of a size-one tail padded 14370 /// array member of a struct. 14371 /// 14372 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14373 /// commonly used to emulate flexible arrays in C89 code. 14374 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14375 const NamedDecl *ND) { 14376 if (Size != 1 || !ND) return false; 14377 14378 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14379 if (!FD) return false; 14380 14381 // Don't consider sizes resulting from macro expansions or template argument 14382 // substitution to form C89 tail-padded arrays. 14383 14384 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14385 while (TInfo) { 14386 TypeLoc TL = TInfo->getTypeLoc(); 14387 // Look through typedefs. 14388 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14389 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14390 TInfo = TDL->getTypeSourceInfo(); 14391 continue; 14392 } 14393 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14394 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14395 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14396 return false; 14397 } 14398 break; 14399 } 14400 14401 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14402 if (!RD) return false; 14403 if (RD->isUnion()) return false; 14404 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14405 if (!CRD->isStandardLayout()) return false; 14406 } 14407 14408 // See if this is the last field decl in the record. 14409 const Decl *D = FD; 14410 while ((D = D->getNextDeclInContext())) 14411 if (isa<FieldDecl>(D)) 14412 return false; 14413 return true; 14414 } 14415 14416 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14417 const ArraySubscriptExpr *ASE, 14418 bool AllowOnePastEnd, bool IndexNegated) { 14419 // Already diagnosed by the constant evaluator. 14420 if (isConstantEvaluated()) 14421 return; 14422 14423 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14424 if (IndexExpr->isValueDependent()) 14425 return; 14426 14427 const Type *EffectiveType = 14428 BaseExpr->getType()->getPointeeOrArrayElementType(); 14429 BaseExpr = BaseExpr->IgnoreParenCasts(); 14430 const ConstantArrayType *ArrayTy = 14431 Context.getAsConstantArrayType(BaseExpr->getType()); 14432 14433 if (!ArrayTy) 14434 return; 14435 14436 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 14437 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 14438 return; 14439 14440 Expr::EvalResult Result; 14441 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14442 return; 14443 14444 llvm::APSInt index = Result.Val.getInt(); 14445 if (IndexNegated) 14446 index = -index; 14447 14448 const NamedDecl *ND = nullptr; 14449 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14450 ND = DRE->getDecl(); 14451 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14452 ND = ME->getMemberDecl(); 14453 14454 if (index.isUnsigned() || !index.isNegative()) { 14455 // It is possible that the type of the base expression after 14456 // IgnoreParenCasts is incomplete, even though the type of the base 14457 // expression before IgnoreParenCasts is complete (see PR39746 for an 14458 // example). In this case we have no information about whether the array 14459 // access exceeds the array bounds. However we can still diagnose an array 14460 // access which precedes the array bounds. 14461 if (BaseType->isIncompleteType()) 14462 return; 14463 14464 llvm::APInt size = ArrayTy->getSize(); 14465 if (!size.isStrictlyPositive()) 14466 return; 14467 14468 if (BaseType != EffectiveType) { 14469 // Make sure we're comparing apples to apples when comparing index to size 14470 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14471 uint64_t array_typesize = Context.getTypeSize(BaseType); 14472 // Handle ptrarith_typesize being zero, such as when casting to void* 14473 if (!ptrarith_typesize) ptrarith_typesize = 1; 14474 if (ptrarith_typesize != array_typesize) { 14475 // There's a cast to a different size type involved 14476 uint64_t ratio = array_typesize / ptrarith_typesize; 14477 // TODO: Be smarter about handling cases where array_typesize is not a 14478 // multiple of ptrarith_typesize 14479 if (ptrarith_typesize * ratio == array_typesize) 14480 size *= llvm::APInt(size.getBitWidth(), ratio); 14481 } 14482 } 14483 14484 if (size.getBitWidth() > index.getBitWidth()) 14485 index = index.zext(size.getBitWidth()); 14486 else if (size.getBitWidth() < index.getBitWidth()) 14487 size = size.zext(index.getBitWidth()); 14488 14489 // For array subscripting the index must be less than size, but for pointer 14490 // arithmetic also allow the index (offset) to be equal to size since 14491 // computing the next address after the end of the array is legal and 14492 // commonly done e.g. in C++ iterators and range-based for loops. 14493 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14494 return; 14495 14496 // Also don't warn for arrays of size 1 which are members of some 14497 // structure. These are often used to approximate flexible arrays in C89 14498 // code. 14499 if (IsTailPaddedMemberArray(*this, size, ND)) 14500 return; 14501 14502 // Suppress the warning if the subscript expression (as identified by the 14503 // ']' location) and the index expression are both from macro expansions 14504 // within a system header. 14505 if (ASE) { 14506 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14507 ASE->getRBracketLoc()); 14508 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14509 SourceLocation IndexLoc = 14510 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14511 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14512 return; 14513 } 14514 } 14515 14516 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 14517 if (ASE) 14518 DiagID = diag::warn_array_index_exceeds_bounds; 14519 14520 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14521 PDiag(DiagID) << index.toString(10, true) 14522 << size.toString(10, true) 14523 << (unsigned)size.getLimitedValue(~0U) 14524 << IndexExpr->getSourceRange()); 14525 } else { 14526 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14527 if (!ASE) { 14528 DiagID = diag::warn_ptr_arith_precedes_bounds; 14529 if (index.isNegative()) index = -index; 14530 } 14531 14532 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14533 PDiag(DiagID) << index.toString(10, true) 14534 << IndexExpr->getSourceRange()); 14535 } 14536 14537 if (!ND) { 14538 // Try harder to find a NamedDecl to point at in the note. 14539 while (const ArraySubscriptExpr *ASE = 14540 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14541 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14542 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14543 ND = DRE->getDecl(); 14544 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14545 ND = ME->getMemberDecl(); 14546 } 14547 14548 if (ND) 14549 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14550 PDiag(diag::note_array_declared_here) << ND); 14551 } 14552 14553 void Sema::CheckArrayAccess(const Expr *expr) { 14554 int AllowOnePastEnd = 0; 14555 while (expr) { 14556 expr = expr->IgnoreParenImpCasts(); 14557 switch (expr->getStmtClass()) { 14558 case Stmt::ArraySubscriptExprClass: { 14559 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14560 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14561 AllowOnePastEnd > 0); 14562 expr = ASE->getBase(); 14563 break; 14564 } 14565 case Stmt::MemberExprClass: { 14566 expr = cast<MemberExpr>(expr)->getBase(); 14567 break; 14568 } 14569 case Stmt::OMPArraySectionExprClass: { 14570 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 14571 if (ASE->getLowerBound()) 14572 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 14573 /*ASE=*/nullptr, AllowOnePastEnd > 0); 14574 return; 14575 } 14576 case Stmt::UnaryOperatorClass: { 14577 // Only unwrap the * and & unary operators 14578 const UnaryOperator *UO = cast<UnaryOperator>(expr); 14579 expr = UO->getSubExpr(); 14580 switch (UO->getOpcode()) { 14581 case UO_AddrOf: 14582 AllowOnePastEnd++; 14583 break; 14584 case UO_Deref: 14585 AllowOnePastEnd--; 14586 break; 14587 default: 14588 return; 14589 } 14590 break; 14591 } 14592 case Stmt::ConditionalOperatorClass: { 14593 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14594 if (const Expr *lhs = cond->getLHS()) 14595 CheckArrayAccess(lhs); 14596 if (const Expr *rhs = cond->getRHS()) 14597 CheckArrayAccess(rhs); 14598 return; 14599 } 14600 case Stmt::CXXOperatorCallExprClass: { 14601 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14602 for (const auto *Arg : OCE->arguments()) 14603 CheckArrayAccess(Arg); 14604 return; 14605 } 14606 default: 14607 return; 14608 } 14609 } 14610 } 14611 14612 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14613 14614 namespace { 14615 14616 struct RetainCycleOwner { 14617 VarDecl *Variable = nullptr; 14618 SourceRange Range; 14619 SourceLocation Loc; 14620 bool Indirect = false; 14621 14622 RetainCycleOwner() = default; 14623 14624 void setLocsFrom(Expr *e) { 14625 Loc = e->getExprLoc(); 14626 Range = e->getSourceRange(); 14627 } 14628 }; 14629 14630 } // namespace 14631 14632 /// Consider whether capturing the given variable can possibly lead to 14633 /// a retain cycle. 14634 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14635 // In ARC, it's captured strongly iff the variable has __strong 14636 // lifetime. In MRR, it's captured strongly if the variable is 14637 // __block and has an appropriate type. 14638 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14639 return false; 14640 14641 owner.Variable = var; 14642 if (ref) 14643 owner.setLocsFrom(ref); 14644 return true; 14645 } 14646 14647 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14648 while (true) { 14649 e = e->IgnoreParens(); 14650 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14651 switch (cast->getCastKind()) { 14652 case CK_BitCast: 14653 case CK_LValueBitCast: 14654 case CK_LValueToRValue: 14655 case CK_ARCReclaimReturnedObject: 14656 e = cast->getSubExpr(); 14657 continue; 14658 14659 default: 14660 return false; 14661 } 14662 } 14663 14664 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14665 ObjCIvarDecl *ivar = ref->getDecl(); 14666 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14667 return false; 14668 14669 // Try to find a retain cycle in the base. 14670 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14671 return false; 14672 14673 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14674 owner.Indirect = true; 14675 return true; 14676 } 14677 14678 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14679 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14680 if (!var) return false; 14681 return considerVariable(var, ref, owner); 14682 } 14683 14684 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14685 if (member->isArrow()) return false; 14686 14687 // Don't count this as an indirect ownership. 14688 e = member->getBase(); 14689 continue; 14690 } 14691 14692 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14693 // Only pay attention to pseudo-objects on property references. 14694 ObjCPropertyRefExpr *pre 14695 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14696 ->IgnoreParens()); 14697 if (!pre) return false; 14698 if (pre->isImplicitProperty()) return false; 14699 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14700 if (!property->isRetaining() && 14701 !(property->getPropertyIvarDecl() && 14702 property->getPropertyIvarDecl()->getType() 14703 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14704 return false; 14705 14706 owner.Indirect = true; 14707 if (pre->isSuperReceiver()) { 14708 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14709 if (!owner.Variable) 14710 return false; 14711 owner.Loc = pre->getLocation(); 14712 owner.Range = pre->getSourceRange(); 14713 return true; 14714 } 14715 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14716 ->getSourceExpr()); 14717 continue; 14718 } 14719 14720 // Array ivars? 14721 14722 return false; 14723 } 14724 } 14725 14726 namespace { 14727 14728 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14729 ASTContext &Context; 14730 VarDecl *Variable; 14731 Expr *Capturer = nullptr; 14732 bool VarWillBeReased = false; 14733 14734 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14735 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14736 Context(Context), Variable(variable) {} 14737 14738 void VisitDeclRefExpr(DeclRefExpr *ref) { 14739 if (ref->getDecl() == Variable && !Capturer) 14740 Capturer = ref; 14741 } 14742 14743 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14744 if (Capturer) return; 14745 Visit(ref->getBase()); 14746 if (Capturer && ref->isFreeIvar()) 14747 Capturer = ref; 14748 } 14749 14750 void VisitBlockExpr(BlockExpr *block) { 14751 // Look inside nested blocks 14752 if (block->getBlockDecl()->capturesVariable(Variable)) 14753 Visit(block->getBlockDecl()->getBody()); 14754 } 14755 14756 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14757 if (Capturer) return; 14758 if (OVE->getSourceExpr()) 14759 Visit(OVE->getSourceExpr()); 14760 } 14761 14762 void VisitBinaryOperator(BinaryOperator *BinOp) { 14763 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14764 return; 14765 Expr *LHS = BinOp->getLHS(); 14766 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14767 if (DRE->getDecl() != Variable) 14768 return; 14769 if (Expr *RHS = BinOp->getRHS()) { 14770 RHS = RHS->IgnoreParenCasts(); 14771 Optional<llvm::APSInt> Value; 14772 VarWillBeReased = 14773 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14774 *Value == 0); 14775 } 14776 } 14777 } 14778 }; 14779 14780 } // namespace 14781 14782 /// Check whether the given argument is a block which captures a 14783 /// variable. 14784 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14785 assert(owner.Variable && owner.Loc.isValid()); 14786 14787 e = e->IgnoreParenCasts(); 14788 14789 // Look through [^{...} copy] and Block_copy(^{...}). 14790 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14791 Selector Cmd = ME->getSelector(); 14792 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14793 e = ME->getInstanceReceiver(); 14794 if (!e) 14795 return nullptr; 14796 e = e->IgnoreParenCasts(); 14797 } 14798 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14799 if (CE->getNumArgs() == 1) { 14800 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14801 if (Fn) { 14802 const IdentifierInfo *FnI = Fn->getIdentifier(); 14803 if (FnI && FnI->isStr("_Block_copy")) { 14804 e = CE->getArg(0)->IgnoreParenCasts(); 14805 } 14806 } 14807 } 14808 } 14809 14810 BlockExpr *block = dyn_cast<BlockExpr>(e); 14811 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14812 return nullptr; 14813 14814 FindCaptureVisitor visitor(S.Context, owner.Variable); 14815 visitor.Visit(block->getBlockDecl()->getBody()); 14816 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14817 } 14818 14819 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14820 RetainCycleOwner &owner) { 14821 assert(capturer); 14822 assert(owner.Variable && owner.Loc.isValid()); 14823 14824 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14825 << owner.Variable << capturer->getSourceRange(); 14826 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14827 << owner.Indirect << owner.Range; 14828 } 14829 14830 /// Check for a keyword selector that starts with the word 'add' or 14831 /// 'set'. 14832 static bool isSetterLikeSelector(Selector sel) { 14833 if (sel.isUnarySelector()) return false; 14834 14835 StringRef str = sel.getNameForSlot(0); 14836 while (!str.empty() && str.front() == '_') str = str.substr(1); 14837 if (str.startswith("set")) 14838 str = str.substr(3); 14839 else if (str.startswith("add")) { 14840 // Specially allow 'addOperationWithBlock:'. 14841 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14842 return false; 14843 str = str.substr(3); 14844 } 14845 else 14846 return false; 14847 14848 if (str.empty()) return true; 14849 return !isLowercase(str.front()); 14850 } 14851 14852 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14853 ObjCMessageExpr *Message) { 14854 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14855 Message->getReceiverInterface(), 14856 NSAPI::ClassId_NSMutableArray); 14857 if (!IsMutableArray) { 14858 return None; 14859 } 14860 14861 Selector Sel = Message->getSelector(); 14862 14863 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14864 S.NSAPIObj->getNSArrayMethodKind(Sel); 14865 if (!MKOpt) { 14866 return None; 14867 } 14868 14869 NSAPI::NSArrayMethodKind MK = *MKOpt; 14870 14871 switch (MK) { 14872 case NSAPI::NSMutableArr_addObject: 14873 case NSAPI::NSMutableArr_insertObjectAtIndex: 14874 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14875 return 0; 14876 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14877 return 1; 14878 14879 default: 14880 return None; 14881 } 14882 14883 return None; 14884 } 14885 14886 static 14887 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14888 ObjCMessageExpr *Message) { 14889 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14890 Message->getReceiverInterface(), 14891 NSAPI::ClassId_NSMutableDictionary); 14892 if (!IsMutableDictionary) { 14893 return None; 14894 } 14895 14896 Selector Sel = Message->getSelector(); 14897 14898 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14899 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14900 if (!MKOpt) { 14901 return None; 14902 } 14903 14904 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14905 14906 switch (MK) { 14907 case NSAPI::NSMutableDict_setObjectForKey: 14908 case NSAPI::NSMutableDict_setValueForKey: 14909 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14910 return 0; 14911 14912 default: 14913 return None; 14914 } 14915 14916 return None; 14917 } 14918 14919 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14920 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14921 Message->getReceiverInterface(), 14922 NSAPI::ClassId_NSMutableSet); 14923 14924 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14925 Message->getReceiverInterface(), 14926 NSAPI::ClassId_NSMutableOrderedSet); 14927 if (!IsMutableSet && !IsMutableOrderedSet) { 14928 return None; 14929 } 14930 14931 Selector Sel = Message->getSelector(); 14932 14933 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14934 if (!MKOpt) { 14935 return None; 14936 } 14937 14938 NSAPI::NSSetMethodKind MK = *MKOpt; 14939 14940 switch (MK) { 14941 case NSAPI::NSMutableSet_addObject: 14942 case NSAPI::NSOrderedSet_setObjectAtIndex: 14943 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14944 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14945 return 0; 14946 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14947 return 1; 14948 } 14949 14950 return None; 14951 } 14952 14953 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14954 if (!Message->isInstanceMessage()) { 14955 return; 14956 } 14957 14958 Optional<int> ArgOpt; 14959 14960 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14961 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14962 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14963 return; 14964 } 14965 14966 int ArgIndex = *ArgOpt; 14967 14968 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14969 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14970 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14971 } 14972 14973 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14974 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14975 if (ArgRE->isObjCSelfExpr()) { 14976 Diag(Message->getSourceRange().getBegin(), 14977 diag::warn_objc_circular_container) 14978 << ArgRE->getDecl() << StringRef("'super'"); 14979 } 14980 } 14981 } else { 14982 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14983 14984 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14985 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14986 } 14987 14988 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14989 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14990 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14991 ValueDecl *Decl = ReceiverRE->getDecl(); 14992 Diag(Message->getSourceRange().getBegin(), 14993 diag::warn_objc_circular_container) 14994 << Decl << Decl; 14995 if (!ArgRE->isObjCSelfExpr()) { 14996 Diag(Decl->getLocation(), 14997 diag::note_objc_circular_container_declared_here) 14998 << Decl; 14999 } 15000 } 15001 } 15002 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15003 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15004 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15005 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15006 Diag(Message->getSourceRange().getBegin(), 15007 diag::warn_objc_circular_container) 15008 << Decl << Decl; 15009 Diag(Decl->getLocation(), 15010 diag::note_objc_circular_container_declared_here) 15011 << Decl; 15012 } 15013 } 15014 } 15015 } 15016 } 15017 15018 /// Check a message send to see if it's likely to cause a retain cycle. 15019 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15020 // Only check instance methods whose selector looks like a setter. 15021 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15022 return; 15023 15024 // Try to find a variable that the receiver is strongly owned by. 15025 RetainCycleOwner owner; 15026 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15027 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15028 return; 15029 } else { 15030 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15031 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15032 owner.Loc = msg->getSuperLoc(); 15033 owner.Range = msg->getSuperLoc(); 15034 } 15035 15036 // Check whether the receiver is captured by any of the arguments. 15037 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15038 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15039 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15040 // noescape blocks should not be retained by the method. 15041 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15042 continue; 15043 return diagnoseRetainCycle(*this, capturer, owner); 15044 } 15045 } 15046 } 15047 15048 /// Check a property assign to see if it's likely to cause a retain cycle. 15049 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15050 RetainCycleOwner owner; 15051 if (!findRetainCycleOwner(*this, receiver, owner)) 15052 return; 15053 15054 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15055 diagnoseRetainCycle(*this, capturer, owner); 15056 } 15057 15058 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15059 RetainCycleOwner Owner; 15060 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15061 return; 15062 15063 // Because we don't have an expression for the variable, we have to set the 15064 // location explicitly here. 15065 Owner.Loc = Var->getLocation(); 15066 Owner.Range = Var->getSourceRange(); 15067 15068 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15069 diagnoseRetainCycle(*this, Capturer, Owner); 15070 } 15071 15072 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15073 Expr *RHS, bool isProperty) { 15074 // Check if RHS is an Objective-C object literal, which also can get 15075 // immediately zapped in a weak reference. Note that we explicitly 15076 // allow ObjCStringLiterals, since those are designed to never really die. 15077 RHS = RHS->IgnoreParenImpCasts(); 15078 15079 // This enum needs to match with the 'select' in 15080 // warn_objc_arc_literal_assign (off-by-1). 15081 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15082 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15083 return false; 15084 15085 S.Diag(Loc, diag::warn_arc_literal_assign) 15086 << (unsigned) Kind 15087 << (isProperty ? 0 : 1) 15088 << RHS->getSourceRange(); 15089 15090 return true; 15091 } 15092 15093 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15094 Qualifiers::ObjCLifetime LT, 15095 Expr *RHS, bool isProperty) { 15096 // Strip off any implicit cast added to get to the one ARC-specific. 15097 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15098 if (cast->getCastKind() == CK_ARCConsumeObject) { 15099 S.Diag(Loc, diag::warn_arc_retained_assign) 15100 << (LT == Qualifiers::OCL_ExplicitNone) 15101 << (isProperty ? 0 : 1) 15102 << RHS->getSourceRange(); 15103 return true; 15104 } 15105 RHS = cast->getSubExpr(); 15106 } 15107 15108 if (LT == Qualifiers::OCL_Weak && 15109 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15110 return true; 15111 15112 return false; 15113 } 15114 15115 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15116 QualType LHS, Expr *RHS) { 15117 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15118 15119 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15120 return false; 15121 15122 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15123 return true; 15124 15125 return false; 15126 } 15127 15128 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15129 Expr *LHS, Expr *RHS) { 15130 QualType LHSType; 15131 // PropertyRef on LHS type need be directly obtained from 15132 // its declaration as it has a PseudoType. 15133 ObjCPropertyRefExpr *PRE 15134 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15135 if (PRE && !PRE->isImplicitProperty()) { 15136 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15137 if (PD) 15138 LHSType = PD->getType(); 15139 } 15140 15141 if (LHSType.isNull()) 15142 LHSType = LHS->getType(); 15143 15144 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15145 15146 if (LT == Qualifiers::OCL_Weak) { 15147 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15148 getCurFunction()->markSafeWeakUse(LHS); 15149 } 15150 15151 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15152 return; 15153 15154 // FIXME. Check for other life times. 15155 if (LT != Qualifiers::OCL_None) 15156 return; 15157 15158 if (PRE) { 15159 if (PRE->isImplicitProperty()) 15160 return; 15161 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15162 if (!PD) 15163 return; 15164 15165 unsigned Attributes = PD->getPropertyAttributes(); 15166 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15167 // when 'assign' attribute was not explicitly specified 15168 // by user, ignore it and rely on property type itself 15169 // for lifetime info. 15170 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15171 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15172 LHSType->isObjCRetainableType()) 15173 return; 15174 15175 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15176 if (cast->getCastKind() == CK_ARCConsumeObject) { 15177 Diag(Loc, diag::warn_arc_retained_property_assign) 15178 << RHS->getSourceRange(); 15179 return; 15180 } 15181 RHS = cast->getSubExpr(); 15182 } 15183 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15184 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15185 return; 15186 } 15187 } 15188 } 15189 15190 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15191 15192 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15193 SourceLocation StmtLoc, 15194 const NullStmt *Body) { 15195 // Do not warn if the body is a macro that expands to nothing, e.g: 15196 // 15197 // #define CALL(x) 15198 // if (condition) 15199 // CALL(0); 15200 if (Body->hasLeadingEmptyMacro()) 15201 return false; 15202 15203 // Get line numbers of statement and body. 15204 bool StmtLineInvalid; 15205 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15206 &StmtLineInvalid); 15207 if (StmtLineInvalid) 15208 return false; 15209 15210 bool BodyLineInvalid; 15211 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15212 &BodyLineInvalid); 15213 if (BodyLineInvalid) 15214 return false; 15215 15216 // Warn if null statement and body are on the same line. 15217 if (StmtLine != BodyLine) 15218 return false; 15219 15220 return true; 15221 } 15222 15223 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15224 const Stmt *Body, 15225 unsigned DiagID) { 15226 // Since this is a syntactic check, don't emit diagnostic for template 15227 // instantiations, this just adds noise. 15228 if (CurrentInstantiationScope) 15229 return; 15230 15231 // The body should be a null statement. 15232 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15233 if (!NBody) 15234 return; 15235 15236 // Do the usual checks. 15237 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15238 return; 15239 15240 Diag(NBody->getSemiLoc(), DiagID); 15241 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15242 } 15243 15244 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15245 const Stmt *PossibleBody) { 15246 assert(!CurrentInstantiationScope); // Ensured by caller 15247 15248 SourceLocation StmtLoc; 15249 const Stmt *Body; 15250 unsigned DiagID; 15251 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15252 StmtLoc = FS->getRParenLoc(); 15253 Body = FS->getBody(); 15254 DiagID = diag::warn_empty_for_body; 15255 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15256 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15257 Body = WS->getBody(); 15258 DiagID = diag::warn_empty_while_body; 15259 } else 15260 return; // Neither `for' nor `while'. 15261 15262 // The body should be a null statement. 15263 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15264 if (!NBody) 15265 return; 15266 15267 // Skip expensive checks if diagnostic is disabled. 15268 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15269 return; 15270 15271 // Do the usual checks. 15272 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15273 return; 15274 15275 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15276 // noise level low, emit diagnostics only if for/while is followed by a 15277 // CompoundStmt, e.g.: 15278 // for (int i = 0; i < n; i++); 15279 // { 15280 // a(i); 15281 // } 15282 // or if for/while is followed by a statement with more indentation 15283 // than for/while itself: 15284 // for (int i = 0; i < n; i++); 15285 // a(i); 15286 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15287 if (!ProbableTypo) { 15288 bool BodyColInvalid; 15289 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15290 PossibleBody->getBeginLoc(), &BodyColInvalid); 15291 if (BodyColInvalid) 15292 return; 15293 15294 bool StmtColInvalid; 15295 unsigned StmtCol = 15296 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15297 if (StmtColInvalid) 15298 return; 15299 15300 if (BodyCol > StmtCol) 15301 ProbableTypo = true; 15302 } 15303 15304 if (ProbableTypo) { 15305 Diag(NBody->getSemiLoc(), DiagID); 15306 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15307 } 15308 } 15309 15310 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15311 15312 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15313 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15314 SourceLocation OpLoc) { 15315 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15316 return; 15317 15318 if (inTemplateInstantiation()) 15319 return; 15320 15321 // Strip parens and casts away. 15322 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15323 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15324 15325 // Check for a call expression 15326 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15327 if (!CE || CE->getNumArgs() != 1) 15328 return; 15329 15330 // Check for a call to std::move 15331 if (!CE->isCallToStdMove()) 15332 return; 15333 15334 // Get argument from std::move 15335 RHSExpr = CE->getArg(0); 15336 15337 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15338 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15339 15340 // Two DeclRefExpr's, check that the decls are the same. 15341 if (LHSDeclRef && RHSDeclRef) { 15342 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15343 return; 15344 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15345 RHSDeclRef->getDecl()->getCanonicalDecl()) 15346 return; 15347 15348 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15349 << LHSExpr->getSourceRange() 15350 << RHSExpr->getSourceRange(); 15351 return; 15352 } 15353 15354 // Member variables require a different approach to check for self moves. 15355 // MemberExpr's are the same if every nested MemberExpr refers to the same 15356 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15357 // the base Expr's are CXXThisExpr's. 15358 const Expr *LHSBase = LHSExpr; 15359 const Expr *RHSBase = RHSExpr; 15360 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15361 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15362 if (!LHSME || !RHSME) 15363 return; 15364 15365 while (LHSME && RHSME) { 15366 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15367 RHSME->getMemberDecl()->getCanonicalDecl()) 15368 return; 15369 15370 LHSBase = LHSME->getBase(); 15371 RHSBase = RHSME->getBase(); 15372 LHSME = dyn_cast<MemberExpr>(LHSBase); 15373 RHSME = dyn_cast<MemberExpr>(RHSBase); 15374 } 15375 15376 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15377 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15378 if (LHSDeclRef && RHSDeclRef) { 15379 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15380 return; 15381 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15382 RHSDeclRef->getDecl()->getCanonicalDecl()) 15383 return; 15384 15385 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15386 << LHSExpr->getSourceRange() 15387 << RHSExpr->getSourceRange(); 15388 return; 15389 } 15390 15391 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15392 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15393 << LHSExpr->getSourceRange() 15394 << RHSExpr->getSourceRange(); 15395 } 15396 15397 //===--- Layout compatibility ----------------------------------------------// 15398 15399 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15400 15401 /// Check if two enumeration types are layout-compatible. 15402 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15403 // C++11 [dcl.enum] p8: 15404 // Two enumeration types are layout-compatible if they have the same 15405 // underlying type. 15406 return ED1->isComplete() && ED2->isComplete() && 15407 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15408 } 15409 15410 /// Check if two fields are layout-compatible. 15411 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15412 FieldDecl *Field2) { 15413 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15414 return false; 15415 15416 if (Field1->isBitField() != Field2->isBitField()) 15417 return false; 15418 15419 if (Field1->isBitField()) { 15420 // Make sure that the bit-fields are the same length. 15421 unsigned Bits1 = Field1->getBitWidthValue(C); 15422 unsigned Bits2 = Field2->getBitWidthValue(C); 15423 15424 if (Bits1 != Bits2) 15425 return false; 15426 } 15427 15428 return true; 15429 } 15430 15431 /// Check if two standard-layout structs are layout-compatible. 15432 /// (C++11 [class.mem] p17) 15433 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15434 RecordDecl *RD2) { 15435 // If both records are C++ classes, check that base classes match. 15436 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15437 // If one of records is a CXXRecordDecl we are in C++ mode, 15438 // thus the other one is a CXXRecordDecl, too. 15439 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15440 // Check number of base classes. 15441 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15442 return false; 15443 15444 // Check the base classes. 15445 for (CXXRecordDecl::base_class_const_iterator 15446 Base1 = D1CXX->bases_begin(), 15447 BaseEnd1 = D1CXX->bases_end(), 15448 Base2 = D2CXX->bases_begin(); 15449 Base1 != BaseEnd1; 15450 ++Base1, ++Base2) { 15451 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15452 return false; 15453 } 15454 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15455 // If only RD2 is a C++ class, it should have zero base classes. 15456 if (D2CXX->getNumBases() > 0) 15457 return false; 15458 } 15459 15460 // Check the fields. 15461 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15462 Field2End = RD2->field_end(), 15463 Field1 = RD1->field_begin(), 15464 Field1End = RD1->field_end(); 15465 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15466 if (!isLayoutCompatible(C, *Field1, *Field2)) 15467 return false; 15468 } 15469 if (Field1 != Field1End || Field2 != Field2End) 15470 return false; 15471 15472 return true; 15473 } 15474 15475 /// Check if two standard-layout unions are layout-compatible. 15476 /// (C++11 [class.mem] p18) 15477 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15478 RecordDecl *RD2) { 15479 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15480 for (auto *Field2 : RD2->fields()) 15481 UnmatchedFields.insert(Field2); 15482 15483 for (auto *Field1 : RD1->fields()) { 15484 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15485 I = UnmatchedFields.begin(), 15486 E = UnmatchedFields.end(); 15487 15488 for ( ; I != E; ++I) { 15489 if (isLayoutCompatible(C, Field1, *I)) { 15490 bool Result = UnmatchedFields.erase(*I); 15491 (void) Result; 15492 assert(Result); 15493 break; 15494 } 15495 } 15496 if (I == E) 15497 return false; 15498 } 15499 15500 return UnmatchedFields.empty(); 15501 } 15502 15503 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15504 RecordDecl *RD2) { 15505 if (RD1->isUnion() != RD2->isUnion()) 15506 return false; 15507 15508 if (RD1->isUnion()) 15509 return isLayoutCompatibleUnion(C, RD1, RD2); 15510 else 15511 return isLayoutCompatibleStruct(C, RD1, RD2); 15512 } 15513 15514 /// Check if two types are layout-compatible in C++11 sense. 15515 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15516 if (T1.isNull() || T2.isNull()) 15517 return false; 15518 15519 // C++11 [basic.types] p11: 15520 // If two types T1 and T2 are the same type, then T1 and T2 are 15521 // layout-compatible types. 15522 if (C.hasSameType(T1, T2)) 15523 return true; 15524 15525 T1 = T1.getCanonicalType().getUnqualifiedType(); 15526 T2 = T2.getCanonicalType().getUnqualifiedType(); 15527 15528 const Type::TypeClass TC1 = T1->getTypeClass(); 15529 const Type::TypeClass TC2 = T2->getTypeClass(); 15530 15531 if (TC1 != TC2) 15532 return false; 15533 15534 if (TC1 == Type::Enum) { 15535 return isLayoutCompatible(C, 15536 cast<EnumType>(T1)->getDecl(), 15537 cast<EnumType>(T2)->getDecl()); 15538 } else if (TC1 == Type::Record) { 15539 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15540 return false; 15541 15542 return isLayoutCompatible(C, 15543 cast<RecordType>(T1)->getDecl(), 15544 cast<RecordType>(T2)->getDecl()); 15545 } 15546 15547 return false; 15548 } 15549 15550 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15551 15552 /// Given a type tag expression find the type tag itself. 15553 /// 15554 /// \param TypeExpr Type tag expression, as it appears in user's code. 15555 /// 15556 /// \param VD Declaration of an identifier that appears in a type tag. 15557 /// 15558 /// \param MagicValue Type tag magic value. 15559 /// 15560 /// \param isConstantEvaluated wether the evalaution should be performed in 15561 15562 /// constant context. 15563 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15564 const ValueDecl **VD, uint64_t *MagicValue, 15565 bool isConstantEvaluated) { 15566 while(true) { 15567 if (!TypeExpr) 15568 return false; 15569 15570 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 15571 15572 switch (TypeExpr->getStmtClass()) { 15573 case Stmt::UnaryOperatorClass: { 15574 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 15575 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 15576 TypeExpr = UO->getSubExpr(); 15577 continue; 15578 } 15579 return false; 15580 } 15581 15582 case Stmt::DeclRefExprClass: { 15583 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15584 *VD = DRE->getDecl(); 15585 return true; 15586 } 15587 15588 case Stmt::IntegerLiteralClass: { 15589 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15590 llvm::APInt MagicValueAPInt = IL->getValue(); 15591 if (MagicValueAPInt.getActiveBits() <= 64) { 15592 *MagicValue = MagicValueAPInt.getZExtValue(); 15593 return true; 15594 } else 15595 return false; 15596 } 15597 15598 case Stmt::BinaryConditionalOperatorClass: 15599 case Stmt::ConditionalOperatorClass: { 15600 const AbstractConditionalOperator *ACO = 15601 cast<AbstractConditionalOperator>(TypeExpr); 15602 bool Result; 15603 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15604 isConstantEvaluated)) { 15605 if (Result) 15606 TypeExpr = ACO->getTrueExpr(); 15607 else 15608 TypeExpr = ACO->getFalseExpr(); 15609 continue; 15610 } 15611 return false; 15612 } 15613 15614 case Stmt::BinaryOperatorClass: { 15615 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15616 if (BO->getOpcode() == BO_Comma) { 15617 TypeExpr = BO->getRHS(); 15618 continue; 15619 } 15620 return false; 15621 } 15622 15623 default: 15624 return false; 15625 } 15626 } 15627 } 15628 15629 /// Retrieve the C type corresponding to type tag TypeExpr. 15630 /// 15631 /// \param TypeExpr Expression that specifies a type tag. 15632 /// 15633 /// \param MagicValues Registered magic values. 15634 /// 15635 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15636 /// kind. 15637 /// 15638 /// \param TypeInfo Information about the corresponding C type. 15639 /// 15640 /// \param isConstantEvaluated wether the evalaution should be performed in 15641 /// constant context. 15642 /// 15643 /// \returns true if the corresponding C type was found. 15644 static bool GetMatchingCType( 15645 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15646 const ASTContext &Ctx, 15647 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15648 *MagicValues, 15649 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15650 bool isConstantEvaluated) { 15651 FoundWrongKind = false; 15652 15653 // Variable declaration that has type_tag_for_datatype attribute. 15654 const ValueDecl *VD = nullptr; 15655 15656 uint64_t MagicValue; 15657 15658 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15659 return false; 15660 15661 if (VD) { 15662 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15663 if (I->getArgumentKind() != ArgumentKind) { 15664 FoundWrongKind = true; 15665 return false; 15666 } 15667 TypeInfo.Type = I->getMatchingCType(); 15668 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15669 TypeInfo.MustBeNull = I->getMustBeNull(); 15670 return true; 15671 } 15672 return false; 15673 } 15674 15675 if (!MagicValues) 15676 return false; 15677 15678 llvm::DenseMap<Sema::TypeTagMagicValue, 15679 Sema::TypeTagData>::const_iterator I = 15680 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15681 if (I == MagicValues->end()) 15682 return false; 15683 15684 TypeInfo = I->second; 15685 return true; 15686 } 15687 15688 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15689 uint64_t MagicValue, QualType Type, 15690 bool LayoutCompatible, 15691 bool MustBeNull) { 15692 if (!TypeTagForDatatypeMagicValues) 15693 TypeTagForDatatypeMagicValues.reset( 15694 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15695 15696 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15697 (*TypeTagForDatatypeMagicValues)[Magic] = 15698 TypeTagData(Type, LayoutCompatible, MustBeNull); 15699 } 15700 15701 static bool IsSameCharType(QualType T1, QualType T2) { 15702 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15703 if (!BT1) 15704 return false; 15705 15706 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15707 if (!BT2) 15708 return false; 15709 15710 BuiltinType::Kind T1Kind = BT1->getKind(); 15711 BuiltinType::Kind T2Kind = BT2->getKind(); 15712 15713 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15714 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15715 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15716 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15717 } 15718 15719 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15720 const ArrayRef<const Expr *> ExprArgs, 15721 SourceLocation CallSiteLoc) { 15722 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15723 bool IsPointerAttr = Attr->getIsPointer(); 15724 15725 // Retrieve the argument representing the 'type_tag'. 15726 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15727 if (TypeTagIdxAST >= ExprArgs.size()) { 15728 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15729 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15730 return; 15731 } 15732 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15733 bool FoundWrongKind; 15734 TypeTagData TypeInfo; 15735 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15736 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15737 TypeInfo, isConstantEvaluated())) { 15738 if (FoundWrongKind) 15739 Diag(TypeTagExpr->getExprLoc(), 15740 diag::warn_type_tag_for_datatype_wrong_kind) 15741 << TypeTagExpr->getSourceRange(); 15742 return; 15743 } 15744 15745 // Retrieve the argument representing the 'arg_idx'. 15746 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15747 if (ArgumentIdxAST >= ExprArgs.size()) { 15748 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15749 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15750 return; 15751 } 15752 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15753 if (IsPointerAttr) { 15754 // Skip implicit cast of pointer to `void *' (as a function argument). 15755 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15756 if (ICE->getType()->isVoidPointerType() && 15757 ICE->getCastKind() == CK_BitCast) 15758 ArgumentExpr = ICE->getSubExpr(); 15759 } 15760 QualType ArgumentType = ArgumentExpr->getType(); 15761 15762 // Passing a `void*' pointer shouldn't trigger a warning. 15763 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15764 return; 15765 15766 if (TypeInfo.MustBeNull) { 15767 // Type tag with matching void type requires a null pointer. 15768 if (!ArgumentExpr->isNullPointerConstant(Context, 15769 Expr::NPC_ValueDependentIsNotNull)) { 15770 Diag(ArgumentExpr->getExprLoc(), 15771 diag::warn_type_safety_null_pointer_required) 15772 << ArgumentKind->getName() 15773 << ArgumentExpr->getSourceRange() 15774 << TypeTagExpr->getSourceRange(); 15775 } 15776 return; 15777 } 15778 15779 QualType RequiredType = TypeInfo.Type; 15780 if (IsPointerAttr) 15781 RequiredType = Context.getPointerType(RequiredType); 15782 15783 bool mismatch = false; 15784 if (!TypeInfo.LayoutCompatible) { 15785 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15786 15787 // C++11 [basic.fundamental] p1: 15788 // Plain char, signed char, and unsigned char are three distinct types. 15789 // 15790 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15791 // char' depending on the current char signedness mode. 15792 if (mismatch) 15793 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15794 RequiredType->getPointeeType())) || 15795 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15796 mismatch = false; 15797 } else 15798 if (IsPointerAttr) 15799 mismatch = !isLayoutCompatible(Context, 15800 ArgumentType->getPointeeType(), 15801 RequiredType->getPointeeType()); 15802 else 15803 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15804 15805 if (mismatch) 15806 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15807 << ArgumentType << ArgumentKind 15808 << TypeInfo.LayoutCompatible << RequiredType 15809 << ArgumentExpr->getSourceRange() 15810 << TypeTagExpr->getSourceRange(); 15811 } 15812 15813 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15814 CharUnits Alignment) { 15815 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15816 } 15817 15818 void Sema::DiagnoseMisalignedMembers() { 15819 for (MisalignedMember &m : MisalignedMembers) { 15820 const NamedDecl *ND = m.RD; 15821 if (ND->getName().empty()) { 15822 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15823 ND = TD; 15824 } 15825 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15826 << m.MD << ND << m.E->getSourceRange(); 15827 } 15828 MisalignedMembers.clear(); 15829 } 15830 15831 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15832 E = E->IgnoreParens(); 15833 if (!T->isPointerType() && !T->isIntegerType()) 15834 return; 15835 if (isa<UnaryOperator>(E) && 15836 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15837 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15838 if (isa<MemberExpr>(Op)) { 15839 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15840 if (MA != MisalignedMembers.end() && 15841 (T->isIntegerType() || 15842 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15843 Context.getTypeAlignInChars( 15844 T->getPointeeType()) <= MA->Alignment)))) 15845 MisalignedMembers.erase(MA); 15846 } 15847 } 15848 } 15849 15850 void Sema::RefersToMemberWithReducedAlignment( 15851 Expr *E, 15852 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15853 Action) { 15854 const auto *ME = dyn_cast<MemberExpr>(E); 15855 if (!ME) 15856 return; 15857 15858 // No need to check expressions with an __unaligned-qualified type. 15859 if (E->getType().getQualifiers().hasUnaligned()) 15860 return; 15861 15862 // For a chain of MemberExpr like "a.b.c.d" this list 15863 // will keep FieldDecl's like [d, c, b]. 15864 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15865 const MemberExpr *TopME = nullptr; 15866 bool AnyIsPacked = false; 15867 do { 15868 QualType BaseType = ME->getBase()->getType(); 15869 if (BaseType->isDependentType()) 15870 return; 15871 if (ME->isArrow()) 15872 BaseType = BaseType->getPointeeType(); 15873 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15874 if (RD->isInvalidDecl()) 15875 return; 15876 15877 ValueDecl *MD = ME->getMemberDecl(); 15878 auto *FD = dyn_cast<FieldDecl>(MD); 15879 // We do not care about non-data members. 15880 if (!FD || FD->isInvalidDecl()) 15881 return; 15882 15883 AnyIsPacked = 15884 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15885 ReverseMemberChain.push_back(FD); 15886 15887 TopME = ME; 15888 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15889 } while (ME); 15890 assert(TopME && "We did not compute a topmost MemberExpr!"); 15891 15892 // Not the scope of this diagnostic. 15893 if (!AnyIsPacked) 15894 return; 15895 15896 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15897 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15898 // TODO: The innermost base of the member expression may be too complicated. 15899 // For now, just disregard these cases. This is left for future 15900 // improvement. 15901 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15902 return; 15903 15904 // Alignment expected by the whole expression. 15905 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15906 15907 // No need to do anything else with this case. 15908 if (ExpectedAlignment.isOne()) 15909 return; 15910 15911 // Synthesize offset of the whole access. 15912 CharUnits Offset; 15913 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15914 I++) { 15915 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15916 } 15917 15918 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15919 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15920 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15921 15922 // The base expression of the innermost MemberExpr may give 15923 // stronger guarantees than the class containing the member. 15924 if (DRE && !TopME->isArrow()) { 15925 const ValueDecl *VD = DRE->getDecl(); 15926 if (!VD->getType()->isReferenceType()) 15927 CompleteObjectAlignment = 15928 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15929 } 15930 15931 // Check if the synthesized offset fulfills the alignment. 15932 if (Offset % ExpectedAlignment != 0 || 15933 // It may fulfill the offset it but the effective alignment may still be 15934 // lower than the expected expression alignment. 15935 CompleteObjectAlignment < ExpectedAlignment) { 15936 // If this happens, we want to determine a sensible culprit of this. 15937 // Intuitively, watching the chain of member expressions from right to 15938 // left, we start with the required alignment (as required by the field 15939 // type) but some packed attribute in that chain has reduced the alignment. 15940 // It may happen that another packed structure increases it again. But if 15941 // we are here such increase has not been enough. So pointing the first 15942 // FieldDecl that either is packed or else its RecordDecl is, 15943 // seems reasonable. 15944 FieldDecl *FD = nullptr; 15945 CharUnits Alignment; 15946 for (FieldDecl *FDI : ReverseMemberChain) { 15947 if (FDI->hasAttr<PackedAttr>() || 15948 FDI->getParent()->hasAttr<PackedAttr>()) { 15949 FD = FDI; 15950 Alignment = std::min( 15951 Context.getTypeAlignInChars(FD->getType()), 15952 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15953 break; 15954 } 15955 } 15956 assert(FD && "We did not find a packed FieldDecl!"); 15957 Action(E, FD->getParent(), FD, Alignment); 15958 } 15959 } 15960 15961 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15962 using namespace std::placeholders; 15963 15964 RefersToMemberWithReducedAlignment( 15965 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15966 _2, _3, _4)); 15967 } 15968 15969 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15970 ExprResult CallResult) { 15971 if (checkArgCount(*this, TheCall, 1)) 15972 return ExprError(); 15973 15974 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15975 if (MatrixArg.isInvalid()) 15976 return MatrixArg; 15977 Expr *Matrix = MatrixArg.get(); 15978 15979 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15980 if (!MType) { 15981 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 15982 return ExprError(); 15983 } 15984 15985 // Create returned matrix type by swapping rows and columns of the argument 15986 // matrix type. 15987 QualType ResultType = Context.getConstantMatrixType( 15988 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15989 15990 // Change the return type to the type of the returned matrix. 15991 TheCall->setType(ResultType); 15992 15993 // Update call argument to use the possibly converted matrix argument. 15994 TheCall->setArg(0, Matrix); 15995 return CallResult; 15996 } 15997 15998 // Get and verify the matrix dimensions. 15999 static llvm::Optional<unsigned> 16000 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16001 SourceLocation ErrorPos; 16002 Optional<llvm::APSInt> Value = 16003 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16004 if (!Value) { 16005 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16006 << Name; 16007 return {}; 16008 } 16009 uint64_t Dim = Value->getZExtValue(); 16010 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16011 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16012 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16013 return {}; 16014 } 16015 return Dim; 16016 } 16017 16018 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16019 ExprResult CallResult) { 16020 if (!getLangOpts().MatrixTypes) { 16021 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16022 return ExprError(); 16023 } 16024 16025 if (checkArgCount(*this, TheCall, 4)) 16026 return ExprError(); 16027 16028 unsigned PtrArgIdx = 0; 16029 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16030 Expr *RowsExpr = TheCall->getArg(1); 16031 Expr *ColumnsExpr = TheCall->getArg(2); 16032 Expr *StrideExpr = TheCall->getArg(3); 16033 16034 bool ArgError = false; 16035 16036 // Check pointer argument. 16037 { 16038 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16039 if (PtrConv.isInvalid()) 16040 return PtrConv; 16041 PtrExpr = PtrConv.get(); 16042 TheCall->setArg(0, PtrExpr); 16043 if (PtrExpr->isTypeDependent()) { 16044 TheCall->setType(Context.DependentTy); 16045 return TheCall; 16046 } 16047 } 16048 16049 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16050 QualType ElementTy; 16051 if (!PtrTy) { 16052 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16053 << PtrArgIdx + 1; 16054 ArgError = true; 16055 } else { 16056 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16057 16058 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16059 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16060 << PtrArgIdx + 1; 16061 ArgError = true; 16062 } 16063 } 16064 16065 // Apply default Lvalue conversions and convert the expression to size_t. 16066 auto ApplyArgumentConversions = [this](Expr *E) { 16067 ExprResult Conv = DefaultLvalueConversion(E); 16068 if (Conv.isInvalid()) 16069 return Conv; 16070 16071 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16072 }; 16073 16074 // Apply conversion to row and column expressions. 16075 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16076 if (!RowsConv.isInvalid()) { 16077 RowsExpr = RowsConv.get(); 16078 TheCall->setArg(1, RowsExpr); 16079 } else 16080 RowsExpr = nullptr; 16081 16082 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16083 if (!ColumnsConv.isInvalid()) { 16084 ColumnsExpr = ColumnsConv.get(); 16085 TheCall->setArg(2, ColumnsExpr); 16086 } else 16087 ColumnsExpr = nullptr; 16088 16089 // If any any part of the result matrix type is still pending, just use 16090 // Context.DependentTy, until all parts are resolved. 16091 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16092 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16093 TheCall->setType(Context.DependentTy); 16094 return CallResult; 16095 } 16096 16097 // Check row and column dimenions. 16098 llvm::Optional<unsigned> MaybeRows; 16099 if (RowsExpr) 16100 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16101 16102 llvm::Optional<unsigned> MaybeColumns; 16103 if (ColumnsExpr) 16104 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16105 16106 // Check stride argument. 16107 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16108 if (StrideConv.isInvalid()) 16109 return ExprError(); 16110 StrideExpr = StrideConv.get(); 16111 TheCall->setArg(3, StrideExpr); 16112 16113 if (MaybeRows) { 16114 if (Optional<llvm::APSInt> Value = 16115 StrideExpr->getIntegerConstantExpr(Context)) { 16116 uint64_t Stride = Value->getZExtValue(); 16117 if (Stride < *MaybeRows) { 16118 Diag(StrideExpr->getBeginLoc(), 16119 diag::err_builtin_matrix_stride_too_small); 16120 ArgError = true; 16121 } 16122 } 16123 } 16124 16125 if (ArgError || !MaybeRows || !MaybeColumns) 16126 return ExprError(); 16127 16128 TheCall->setType( 16129 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16130 return CallResult; 16131 } 16132 16133 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16134 ExprResult CallResult) { 16135 if (checkArgCount(*this, TheCall, 3)) 16136 return ExprError(); 16137 16138 unsigned PtrArgIdx = 1; 16139 Expr *MatrixExpr = TheCall->getArg(0); 16140 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16141 Expr *StrideExpr = TheCall->getArg(2); 16142 16143 bool ArgError = false; 16144 16145 { 16146 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16147 if (MatrixConv.isInvalid()) 16148 return MatrixConv; 16149 MatrixExpr = MatrixConv.get(); 16150 TheCall->setArg(0, MatrixExpr); 16151 } 16152 if (MatrixExpr->isTypeDependent()) { 16153 TheCall->setType(Context.DependentTy); 16154 return TheCall; 16155 } 16156 16157 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16158 if (!MatrixTy) { 16159 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16160 ArgError = true; 16161 } 16162 16163 { 16164 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16165 if (PtrConv.isInvalid()) 16166 return PtrConv; 16167 PtrExpr = PtrConv.get(); 16168 TheCall->setArg(1, PtrExpr); 16169 if (PtrExpr->isTypeDependent()) { 16170 TheCall->setType(Context.DependentTy); 16171 return TheCall; 16172 } 16173 } 16174 16175 // Check pointer argument. 16176 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16177 if (!PtrTy) { 16178 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16179 << PtrArgIdx + 1; 16180 ArgError = true; 16181 } else { 16182 QualType ElementTy = PtrTy->getPointeeType(); 16183 if (ElementTy.isConstQualified()) { 16184 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16185 ArgError = true; 16186 } 16187 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16188 if (MatrixTy && 16189 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16190 Diag(PtrExpr->getBeginLoc(), 16191 diag::err_builtin_matrix_pointer_arg_mismatch) 16192 << ElementTy << MatrixTy->getElementType(); 16193 ArgError = true; 16194 } 16195 } 16196 16197 // Apply default Lvalue conversions and convert the stride expression to 16198 // size_t. 16199 { 16200 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16201 if (StrideConv.isInvalid()) 16202 return StrideConv; 16203 16204 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16205 if (StrideConv.isInvalid()) 16206 return StrideConv; 16207 StrideExpr = StrideConv.get(); 16208 TheCall->setArg(2, StrideExpr); 16209 } 16210 16211 // Check stride argument. 16212 if (MatrixTy) { 16213 if (Optional<llvm::APSInt> Value = 16214 StrideExpr->getIntegerConstantExpr(Context)) { 16215 uint64_t Stride = Value->getZExtValue(); 16216 if (Stride < MatrixTy->getNumRows()) { 16217 Diag(StrideExpr->getBeginLoc(), 16218 diag::err_builtin_matrix_stride_too_small); 16219 ArgError = true; 16220 } 16221 } 16222 } 16223 16224 if (ArgError) 16225 return ExprError(); 16226 16227 return CallResult; 16228 } 16229 16230 /// \brief Enforce the bounds of a TCB 16231 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16232 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16233 /// and enforce_tcb_leaf attributes. 16234 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16235 const FunctionDecl *Callee) { 16236 const FunctionDecl *Caller = getCurFunctionDecl(); 16237 16238 // Calls to builtins are not enforced. 16239 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16240 Callee->getBuiltinID() != 0) 16241 return; 16242 16243 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16244 // all TCBs the callee is a part of. 16245 llvm::StringSet<> CalleeTCBs; 16246 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16247 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16248 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16249 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16250 16251 // Go through the TCBs the caller is a part of and emit warnings if Caller 16252 // is in a TCB that the Callee is not. 16253 for_each( 16254 Caller->specific_attrs<EnforceTCBAttr>(), 16255 [&](const auto *A) { 16256 StringRef CallerTCB = A->getTCBName(); 16257 if (CalleeTCBs.count(CallerTCB) == 0) { 16258 this->Diag(TheCall->getExprLoc(), 16259 diag::warn_tcb_enforcement_violation) << Callee 16260 << CallerTCB; 16261 } 16262 }); 16263 } 16264