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. 8734 if (ExprTy == S.Context.IntTy) 8735 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8736 ExprTy = S.Context.CharTy; 8737 } 8738 8739 // Look through enums to their underlying type. 8740 bool IsEnum = false; 8741 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8742 ExprTy = EnumTy->getDecl()->getIntegerType(); 8743 IsEnum = true; 8744 } 8745 8746 // %C in an Objective-C context prints a unichar, not a wchar_t. 8747 // If the argument is an integer of some kind, believe the %C and suggest 8748 // a cast instead of changing the conversion specifier. 8749 QualType IntendedTy = ExprTy; 8750 if (isObjCContext() && 8751 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8752 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8753 !ExprTy->isCharType()) { 8754 // 'unichar' is defined as a typedef of unsigned short, but we should 8755 // prefer using the typedef if it is visible. 8756 IntendedTy = S.Context.UnsignedShortTy; 8757 8758 // While we are here, check if the value is an IntegerLiteral that happens 8759 // to be within the valid range. 8760 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8761 const llvm::APInt &V = IL->getValue(); 8762 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8763 return true; 8764 } 8765 8766 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8767 Sema::LookupOrdinaryName); 8768 if (S.LookupName(Result, S.getCurScope())) { 8769 NamedDecl *ND = Result.getFoundDecl(); 8770 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8771 if (TD->getUnderlyingType() == IntendedTy) 8772 IntendedTy = S.Context.getTypedefType(TD); 8773 } 8774 } 8775 } 8776 8777 // Special-case some of Darwin's platform-independence types by suggesting 8778 // casts to primitive types that are known to be large enough. 8779 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8780 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8781 QualType CastTy; 8782 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8783 if (!CastTy.isNull()) { 8784 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8785 // (long in ASTContext). Only complain to pedants. 8786 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8787 (AT.isSizeT() || AT.isPtrdiffT()) && 8788 AT.matchesType(S.Context, CastTy)) 8789 Match = ArgType::NoMatchPedantic; 8790 IntendedTy = CastTy; 8791 ShouldNotPrintDirectly = true; 8792 } 8793 } 8794 8795 // We may be able to offer a FixItHint if it is a supported type. 8796 PrintfSpecifier fixedFS = FS; 8797 bool Success = 8798 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8799 8800 if (Success) { 8801 // Get the fix string from the fixed format specifier 8802 SmallString<16> buf; 8803 llvm::raw_svector_ostream os(buf); 8804 fixedFS.toString(os); 8805 8806 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8807 8808 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8809 unsigned Diag; 8810 switch (Match) { 8811 case ArgType::Match: llvm_unreachable("expected non-matching"); 8812 case ArgType::NoMatchPedantic: 8813 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8814 break; 8815 case ArgType::NoMatchTypeConfusion: 8816 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8817 break; 8818 case ArgType::NoMatch: 8819 Diag = diag::warn_format_conversion_argument_type_mismatch; 8820 break; 8821 } 8822 8823 // In this case, the specifier is wrong and should be changed to match 8824 // the argument. 8825 EmitFormatDiagnostic(S.PDiag(Diag) 8826 << AT.getRepresentativeTypeName(S.Context) 8827 << IntendedTy << IsEnum << E->getSourceRange(), 8828 E->getBeginLoc(), 8829 /*IsStringLocation*/ false, SpecRange, 8830 FixItHint::CreateReplacement(SpecRange, os.str())); 8831 } else { 8832 // The canonical type for formatting this value is different from the 8833 // actual type of the expression. (This occurs, for example, with Darwin's 8834 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8835 // should be printed as 'long' for 64-bit compatibility.) 8836 // Rather than emitting a normal format/argument mismatch, we want to 8837 // add a cast to the recommended type (and correct the format string 8838 // if necessary). 8839 SmallString<16> CastBuf; 8840 llvm::raw_svector_ostream CastFix(CastBuf); 8841 CastFix << "("; 8842 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8843 CastFix << ")"; 8844 8845 SmallVector<FixItHint,4> Hints; 8846 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8847 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8848 8849 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8850 // If there's already a cast present, just replace it. 8851 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8852 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8853 8854 } else if (!requiresParensToAddCast(E)) { 8855 // If the expression has high enough precedence, 8856 // just write the C-style cast. 8857 Hints.push_back( 8858 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8859 } else { 8860 // Otherwise, add parens around the expression as well as the cast. 8861 CastFix << "("; 8862 Hints.push_back( 8863 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8864 8865 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8866 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8867 } 8868 8869 if (ShouldNotPrintDirectly) { 8870 // The expression has a type that should not be printed directly. 8871 // We extract the name from the typedef because we don't want to show 8872 // the underlying type in the diagnostic. 8873 StringRef Name; 8874 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8875 Name = TypedefTy->getDecl()->getName(); 8876 else 8877 Name = CastTyName; 8878 unsigned Diag = Match == ArgType::NoMatchPedantic 8879 ? diag::warn_format_argument_needs_cast_pedantic 8880 : diag::warn_format_argument_needs_cast; 8881 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8882 << E->getSourceRange(), 8883 E->getBeginLoc(), /*IsStringLocation=*/false, 8884 SpecRange, Hints); 8885 } else { 8886 // In this case, the expression could be printed using a different 8887 // specifier, but we've decided that the specifier is probably correct 8888 // and we should cast instead. Just use the normal warning message. 8889 EmitFormatDiagnostic( 8890 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8891 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8892 << E->getSourceRange(), 8893 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8894 } 8895 } 8896 } else { 8897 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8898 SpecifierLen); 8899 // Since the warning for passing non-POD types to variadic functions 8900 // was deferred until now, we emit a warning for non-POD 8901 // arguments here. 8902 switch (S.isValidVarArgType(ExprTy)) { 8903 case Sema::VAK_Valid: 8904 case Sema::VAK_ValidInCXX11: { 8905 unsigned Diag; 8906 switch (Match) { 8907 case ArgType::Match: llvm_unreachable("expected non-matching"); 8908 case ArgType::NoMatchPedantic: 8909 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8910 break; 8911 case ArgType::NoMatchTypeConfusion: 8912 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8913 break; 8914 case ArgType::NoMatch: 8915 Diag = diag::warn_format_conversion_argument_type_mismatch; 8916 break; 8917 } 8918 8919 EmitFormatDiagnostic( 8920 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8921 << IsEnum << CSR << E->getSourceRange(), 8922 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8923 break; 8924 } 8925 case Sema::VAK_Undefined: 8926 case Sema::VAK_MSVCUndefined: 8927 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8928 << S.getLangOpts().CPlusPlus11 << ExprTy 8929 << CallType 8930 << AT.getRepresentativeTypeName(S.Context) << CSR 8931 << E->getSourceRange(), 8932 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8933 checkForCStrMembers(AT, E); 8934 break; 8935 8936 case Sema::VAK_Invalid: 8937 if (ExprTy->isObjCObjectType()) 8938 EmitFormatDiagnostic( 8939 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8940 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8941 << AT.getRepresentativeTypeName(S.Context) << CSR 8942 << E->getSourceRange(), 8943 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8944 else 8945 // FIXME: If this is an initializer list, suggest removing the braces 8946 // or inserting a cast to the target type. 8947 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8948 << isa<InitListExpr>(E) << ExprTy << CallType 8949 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8950 break; 8951 } 8952 8953 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8954 "format string specifier index out of range"); 8955 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8956 } 8957 8958 return true; 8959 } 8960 8961 //===--- CHECK: Scanf format string checking ------------------------------===// 8962 8963 namespace { 8964 8965 class CheckScanfHandler : public CheckFormatHandler { 8966 public: 8967 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8968 const Expr *origFormatExpr, Sema::FormatStringType type, 8969 unsigned firstDataArg, unsigned numDataArgs, 8970 const char *beg, bool hasVAListArg, 8971 ArrayRef<const Expr *> Args, unsigned formatIdx, 8972 bool inFunctionCall, Sema::VariadicCallType CallType, 8973 llvm::SmallBitVector &CheckedVarArgs, 8974 UncoveredArgHandler &UncoveredArg) 8975 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8976 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8977 inFunctionCall, CallType, CheckedVarArgs, 8978 UncoveredArg) {} 8979 8980 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8981 const char *startSpecifier, 8982 unsigned specifierLen) override; 8983 8984 bool HandleInvalidScanfConversionSpecifier( 8985 const analyze_scanf::ScanfSpecifier &FS, 8986 const char *startSpecifier, 8987 unsigned specifierLen) override; 8988 8989 void HandleIncompleteScanList(const char *start, const char *end) override; 8990 }; 8991 8992 } // namespace 8993 8994 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8995 const char *end) { 8996 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8997 getLocationOfByte(end), /*IsStringLocation*/true, 8998 getSpecifierRange(start, end - start)); 8999 } 9000 9001 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9002 const analyze_scanf::ScanfSpecifier &FS, 9003 const char *startSpecifier, 9004 unsigned specifierLen) { 9005 const analyze_scanf::ScanfConversionSpecifier &CS = 9006 FS.getConversionSpecifier(); 9007 9008 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9009 getLocationOfByte(CS.getStart()), 9010 startSpecifier, specifierLen, 9011 CS.getStart(), CS.getLength()); 9012 } 9013 9014 bool CheckScanfHandler::HandleScanfSpecifier( 9015 const analyze_scanf::ScanfSpecifier &FS, 9016 const char *startSpecifier, 9017 unsigned specifierLen) { 9018 using namespace analyze_scanf; 9019 using namespace analyze_format_string; 9020 9021 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9022 9023 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9024 // be used to decide if we are using positional arguments consistently. 9025 if (FS.consumesDataArgument()) { 9026 if (atFirstArg) { 9027 atFirstArg = false; 9028 usesPositionalArgs = FS.usesPositionalArg(); 9029 } 9030 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9031 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9032 startSpecifier, specifierLen); 9033 return false; 9034 } 9035 } 9036 9037 // Check if the field with is non-zero. 9038 const OptionalAmount &Amt = FS.getFieldWidth(); 9039 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9040 if (Amt.getConstantAmount() == 0) { 9041 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9042 Amt.getConstantLength()); 9043 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9044 getLocationOfByte(Amt.getStart()), 9045 /*IsStringLocation*/true, R, 9046 FixItHint::CreateRemoval(R)); 9047 } 9048 } 9049 9050 if (!FS.consumesDataArgument()) { 9051 // FIXME: Technically specifying a precision or field width here 9052 // makes no sense. Worth issuing a warning at some point. 9053 return true; 9054 } 9055 9056 // Consume the argument. 9057 unsigned argIndex = FS.getArgIndex(); 9058 if (argIndex < NumDataArgs) { 9059 // The check to see if the argIndex is valid will come later. 9060 // We set the bit here because we may exit early from this 9061 // function if we encounter some other error. 9062 CoveredArgs.set(argIndex); 9063 } 9064 9065 // Check the length modifier is valid with the given conversion specifier. 9066 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9067 S.getLangOpts())) 9068 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9069 diag::warn_format_nonsensical_length); 9070 else if (!FS.hasStandardLengthModifier()) 9071 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9072 else if (!FS.hasStandardLengthConversionCombination()) 9073 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9074 diag::warn_format_non_standard_conversion_spec); 9075 9076 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9077 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9078 9079 // The remaining checks depend on the data arguments. 9080 if (HasVAListArg) 9081 return true; 9082 9083 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9084 return false; 9085 9086 // Check that the argument type matches the format specifier. 9087 const Expr *Ex = getDataArg(argIndex); 9088 if (!Ex) 9089 return true; 9090 9091 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9092 9093 if (!AT.isValid()) { 9094 return true; 9095 } 9096 9097 analyze_format_string::ArgType::MatchKind Match = 9098 AT.matchesType(S.Context, Ex->getType()); 9099 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9100 if (Match == analyze_format_string::ArgType::Match) 9101 return true; 9102 9103 ScanfSpecifier fixedFS = FS; 9104 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9105 S.getLangOpts(), S.Context); 9106 9107 unsigned Diag = 9108 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9109 : diag::warn_format_conversion_argument_type_mismatch; 9110 9111 if (Success) { 9112 // Get the fix string from the fixed format specifier. 9113 SmallString<128> buf; 9114 llvm::raw_svector_ostream os(buf); 9115 fixedFS.toString(os); 9116 9117 EmitFormatDiagnostic( 9118 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9119 << Ex->getType() << false << Ex->getSourceRange(), 9120 Ex->getBeginLoc(), 9121 /*IsStringLocation*/ false, 9122 getSpecifierRange(startSpecifier, specifierLen), 9123 FixItHint::CreateReplacement( 9124 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9125 } else { 9126 EmitFormatDiagnostic(S.PDiag(Diag) 9127 << AT.getRepresentativeTypeName(S.Context) 9128 << Ex->getType() << false << Ex->getSourceRange(), 9129 Ex->getBeginLoc(), 9130 /*IsStringLocation*/ false, 9131 getSpecifierRange(startSpecifier, specifierLen)); 9132 } 9133 9134 return true; 9135 } 9136 9137 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9138 const Expr *OrigFormatExpr, 9139 ArrayRef<const Expr *> Args, 9140 bool HasVAListArg, unsigned format_idx, 9141 unsigned firstDataArg, 9142 Sema::FormatStringType Type, 9143 bool inFunctionCall, 9144 Sema::VariadicCallType CallType, 9145 llvm::SmallBitVector &CheckedVarArgs, 9146 UncoveredArgHandler &UncoveredArg, 9147 bool IgnoreStringsWithoutSpecifiers) { 9148 // CHECK: is the format string a wide literal? 9149 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9150 CheckFormatHandler::EmitFormatDiagnostic( 9151 S, inFunctionCall, Args[format_idx], 9152 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9153 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9154 return; 9155 } 9156 9157 // Str - The format string. NOTE: this is NOT null-terminated! 9158 StringRef StrRef = FExpr->getString(); 9159 const char *Str = StrRef.data(); 9160 // Account for cases where the string literal is truncated in a declaration. 9161 const ConstantArrayType *T = 9162 S.Context.getAsConstantArrayType(FExpr->getType()); 9163 assert(T && "String literal not of constant array type!"); 9164 size_t TypeSize = T->getSize().getZExtValue(); 9165 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9166 const unsigned numDataArgs = Args.size() - firstDataArg; 9167 9168 if (IgnoreStringsWithoutSpecifiers && 9169 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9170 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9171 return; 9172 9173 // Emit a warning if the string literal is truncated and does not contain an 9174 // embedded null character. 9175 if (TypeSize <= StrRef.size() && 9176 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9177 CheckFormatHandler::EmitFormatDiagnostic( 9178 S, inFunctionCall, Args[format_idx], 9179 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9180 FExpr->getBeginLoc(), 9181 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9182 return; 9183 } 9184 9185 // CHECK: empty format string? 9186 if (StrLen == 0 && numDataArgs > 0) { 9187 CheckFormatHandler::EmitFormatDiagnostic( 9188 S, inFunctionCall, Args[format_idx], 9189 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9190 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9191 return; 9192 } 9193 9194 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9195 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9196 Type == Sema::FST_OSTrace) { 9197 CheckPrintfHandler H( 9198 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9199 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9200 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9201 CheckedVarArgs, UncoveredArg); 9202 9203 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9204 S.getLangOpts(), 9205 S.Context.getTargetInfo(), 9206 Type == Sema::FST_FreeBSDKPrintf)) 9207 H.DoneProcessing(); 9208 } else if (Type == Sema::FST_Scanf) { 9209 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9210 numDataArgs, Str, HasVAListArg, Args, format_idx, 9211 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9212 9213 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9214 S.getLangOpts(), 9215 S.Context.getTargetInfo())) 9216 H.DoneProcessing(); 9217 } // TODO: handle other formats 9218 } 9219 9220 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9221 // Str - The format string. NOTE: this is NOT null-terminated! 9222 StringRef StrRef = FExpr->getString(); 9223 const char *Str = StrRef.data(); 9224 // Account for cases where the string literal is truncated in a declaration. 9225 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9226 assert(T && "String literal not of constant array type!"); 9227 size_t TypeSize = T->getSize().getZExtValue(); 9228 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9229 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9230 getLangOpts(), 9231 Context.getTargetInfo()); 9232 } 9233 9234 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9235 9236 // Returns the related absolute value function that is larger, of 0 if one 9237 // does not exist. 9238 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9239 switch (AbsFunction) { 9240 default: 9241 return 0; 9242 9243 case Builtin::BI__builtin_abs: 9244 return Builtin::BI__builtin_labs; 9245 case Builtin::BI__builtin_labs: 9246 return Builtin::BI__builtin_llabs; 9247 case Builtin::BI__builtin_llabs: 9248 return 0; 9249 9250 case Builtin::BI__builtin_fabsf: 9251 return Builtin::BI__builtin_fabs; 9252 case Builtin::BI__builtin_fabs: 9253 return Builtin::BI__builtin_fabsl; 9254 case Builtin::BI__builtin_fabsl: 9255 return 0; 9256 9257 case Builtin::BI__builtin_cabsf: 9258 return Builtin::BI__builtin_cabs; 9259 case Builtin::BI__builtin_cabs: 9260 return Builtin::BI__builtin_cabsl; 9261 case Builtin::BI__builtin_cabsl: 9262 return 0; 9263 9264 case Builtin::BIabs: 9265 return Builtin::BIlabs; 9266 case Builtin::BIlabs: 9267 return Builtin::BIllabs; 9268 case Builtin::BIllabs: 9269 return 0; 9270 9271 case Builtin::BIfabsf: 9272 return Builtin::BIfabs; 9273 case Builtin::BIfabs: 9274 return Builtin::BIfabsl; 9275 case Builtin::BIfabsl: 9276 return 0; 9277 9278 case Builtin::BIcabsf: 9279 return Builtin::BIcabs; 9280 case Builtin::BIcabs: 9281 return Builtin::BIcabsl; 9282 case Builtin::BIcabsl: 9283 return 0; 9284 } 9285 } 9286 9287 // Returns the argument type of the absolute value function. 9288 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9289 unsigned AbsType) { 9290 if (AbsType == 0) 9291 return QualType(); 9292 9293 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9294 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9295 if (Error != ASTContext::GE_None) 9296 return QualType(); 9297 9298 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9299 if (!FT) 9300 return QualType(); 9301 9302 if (FT->getNumParams() != 1) 9303 return QualType(); 9304 9305 return FT->getParamType(0); 9306 } 9307 9308 // Returns the best absolute value function, or zero, based on type and 9309 // current absolute value function. 9310 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9311 unsigned AbsFunctionKind) { 9312 unsigned BestKind = 0; 9313 uint64_t ArgSize = Context.getTypeSize(ArgType); 9314 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9315 Kind = getLargerAbsoluteValueFunction(Kind)) { 9316 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9317 if (Context.getTypeSize(ParamType) >= ArgSize) { 9318 if (BestKind == 0) 9319 BestKind = Kind; 9320 else if (Context.hasSameType(ParamType, ArgType)) { 9321 BestKind = Kind; 9322 break; 9323 } 9324 } 9325 } 9326 return BestKind; 9327 } 9328 9329 enum AbsoluteValueKind { 9330 AVK_Integer, 9331 AVK_Floating, 9332 AVK_Complex 9333 }; 9334 9335 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9336 if (T->isIntegralOrEnumerationType()) 9337 return AVK_Integer; 9338 if (T->isRealFloatingType()) 9339 return AVK_Floating; 9340 if (T->isAnyComplexType()) 9341 return AVK_Complex; 9342 9343 llvm_unreachable("Type not integer, floating, or complex"); 9344 } 9345 9346 // Changes the absolute value function to a different type. Preserves whether 9347 // the function is a builtin. 9348 static unsigned changeAbsFunction(unsigned AbsKind, 9349 AbsoluteValueKind ValueKind) { 9350 switch (ValueKind) { 9351 case AVK_Integer: 9352 switch (AbsKind) { 9353 default: 9354 return 0; 9355 case Builtin::BI__builtin_fabsf: 9356 case Builtin::BI__builtin_fabs: 9357 case Builtin::BI__builtin_fabsl: 9358 case Builtin::BI__builtin_cabsf: 9359 case Builtin::BI__builtin_cabs: 9360 case Builtin::BI__builtin_cabsl: 9361 return Builtin::BI__builtin_abs; 9362 case Builtin::BIfabsf: 9363 case Builtin::BIfabs: 9364 case Builtin::BIfabsl: 9365 case Builtin::BIcabsf: 9366 case Builtin::BIcabs: 9367 case Builtin::BIcabsl: 9368 return Builtin::BIabs; 9369 } 9370 case AVK_Floating: 9371 switch (AbsKind) { 9372 default: 9373 return 0; 9374 case Builtin::BI__builtin_abs: 9375 case Builtin::BI__builtin_labs: 9376 case Builtin::BI__builtin_llabs: 9377 case Builtin::BI__builtin_cabsf: 9378 case Builtin::BI__builtin_cabs: 9379 case Builtin::BI__builtin_cabsl: 9380 return Builtin::BI__builtin_fabsf; 9381 case Builtin::BIabs: 9382 case Builtin::BIlabs: 9383 case Builtin::BIllabs: 9384 case Builtin::BIcabsf: 9385 case Builtin::BIcabs: 9386 case Builtin::BIcabsl: 9387 return Builtin::BIfabsf; 9388 } 9389 case AVK_Complex: 9390 switch (AbsKind) { 9391 default: 9392 return 0; 9393 case Builtin::BI__builtin_abs: 9394 case Builtin::BI__builtin_labs: 9395 case Builtin::BI__builtin_llabs: 9396 case Builtin::BI__builtin_fabsf: 9397 case Builtin::BI__builtin_fabs: 9398 case Builtin::BI__builtin_fabsl: 9399 return Builtin::BI__builtin_cabsf; 9400 case Builtin::BIabs: 9401 case Builtin::BIlabs: 9402 case Builtin::BIllabs: 9403 case Builtin::BIfabsf: 9404 case Builtin::BIfabs: 9405 case Builtin::BIfabsl: 9406 return Builtin::BIcabsf; 9407 } 9408 } 9409 llvm_unreachable("Unable to convert function"); 9410 } 9411 9412 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9413 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9414 if (!FnInfo) 9415 return 0; 9416 9417 switch (FDecl->getBuiltinID()) { 9418 default: 9419 return 0; 9420 case Builtin::BI__builtin_abs: 9421 case Builtin::BI__builtin_fabs: 9422 case Builtin::BI__builtin_fabsf: 9423 case Builtin::BI__builtin_fabsl: 9424 case Builtin::BI__builtin_labs: 9425 case Builtin::BI__builtin_llabs: 9426 case Builtin::BI__builtin_cabs: 9427 case Builtin::BI__builtin_cabsf: 9428 case Builtin::BI__builtin_cabsl: 9429 case Builtin::BIabs: 9430 case Builtin::BIlabs: 9431 case Builtin::BIllabs: 9432 case Builtin::BIfabs: 9433 case Builtin::BIfabsf: 9434 case Builtin::BIfabsl: 9435 case Builtin::BIcabs: 9436 case Builtin::BIcabsf: 9437 case Builtin::BIcabsl: 9438 return FDecl->getBuiltinID(); 9439 } 9440 llvm_unreachable("Unknown Builtin type"); 9441 } 9442 9443 // If the replacement is valid, emit a note with replacement function. 9444 // Additionally, suggest including the proper header if not already included. 9445 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9446 unsigned AbsKind, QualType ArgType) { 9447 bool EmitHeaderHint = true; 9448 const char *HeaderName = nullptr; 9449 const char *FunctionName = nullptr; 9450 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9451 FunctionName = "std::abs"; 9452 if (ArgType->isIntegralOrEnumerationType()) { 9453 HeaderName = "cstdlib"; 9454 } else if (ArgType->isRealFloatingType()) { 9455 HeaderName = "cmath"; 9456 } else { 9457 llvm_unreachable("Invalid Type"); 9458 } 9459 9460 // Lookup all std::abs 9461 if (NamespaceDecl *Std = S.getStdNamespace()) { 9462 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9463 R.suppressDiagnostics(); 9464 S.LookupQualifiedName(R, Std); 9465 9466 for (const auto *I : R) { 9467 const FunctionDecl *FDecl = nullptr; 9468 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9469 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9470 } else { 9471 FDecl = dyn_cast<FunctionDecl>(I); 9472 } 9473 if (!FDecl) 9474 continue; 9475 9476 // Found std::abs(), check that they are the right ones. 9477 if (FDecl->getNumParams() != 1) 9478 continue; 9479 9480 // Check that the parameter type can handle the argument. 9481 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9482 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9483 S.Context.getTypeSize(ArgType) <= 9484 S.Context.getTypeSize(ParamType)) { 9485 // Found a function, don't need the header hint. 9486 EmitHeaderHint = false; 9487 break; 9488 } 9489 } 9490 } 9491 } else { 9492 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9493 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9494 9495 if (HeaderName) { 9496 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9497 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9498 R.suppressDiagnostics(); 9499 S.LookupName(R, S.getCurScope()); 9500 9501 if (R.isSingleResult()) { 9502 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9503 if (FD && FD->getBuiltinID() == AbsKind) { 9504 EmitHeaderHint = false; 9505 } else { 9506 return; 9507 } 9508 } else if (!R.empty()) { 9509 return; 9510 } 9511 } 9512 } 9513 9514 S.Diag(Loc, diag::note_replace_abs_function) 9515 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9516 9517 if (!HeaderName) 9518 return; 9519 9520 if (!EmitHeaderHint) 9521 return; 9522 9523 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9524 << FunctionName; 9525 } 9526 9527 template <std::size_t StrLen> 9528 static bool IsStdFunction(const FunctionDecl *FDecl, 9529 const char (&Str)[StrLen]) { 9530 if (!FDecl) 9531 return false; 9532 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9533 return false; 9534 if (!FDecl->isInStdNamespace()) 9535 return false; 9536 9537 return true; 9538 } 9539 9540 // Warn when using the wrong abs() function. 9541 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9542 const FunctionDecl *FDecl) { 9543 if (Call->getNumArgs() != 1) 9544 return; 9545 9546 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9547 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9548 if (AbsKind == 0 && !IsStdAbs) 9549 return; 9550 9551 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9552 QualType ParamType = Call->getArg(0)->getType(); 9553 9554 // Unsigned types cannot be negative. Suggest removing the absolute value 9555 // function call. 9556 if (ArgType->isUnsignedIntegerType()) { 9557 const char *FunctionName = 9558 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9559 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9560 Diag(Call->getExprLoc(), diag::note_remove_abs) 9561 << FunctionName 9562 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9563 return; 9564 } 9565 9566 // Taking the absolute value of a pointer is very suspicious, they probably 9567 // wanted to index into an array, dereference a pointer, call a function, etc. 9568 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9569 unsigned DiagType = 0; 9570 if (ArgType->isFunctionType()) 9571 DiagType = 1; 9572 else if (ArgType->isArrayType()) 9573 DiagType = 2; 9574 9575 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9576 return; 9577 } 9578 9579 // std::abs has overloads which prevent most of the absolute value problems 9580 // from occurring. 9581 if (IsStdAbs) 9582 return; 9583 9584 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9585 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9586 9587 // The argument and parameter are the same kind. Check if they are the right 9588 // size. 9589 if (ArgValueKind == ParamValueKind) { 9590 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9591 return; 9592 9593 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9594 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9595 << FDecl << ArgType << ParamType; 9596 9597 if (NewAbsKind == 0) 9598 return; 9599 9600 emitReplacement(*this, Call->getExprLoc(), 9601 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9602 return; 9603 } 9604 9605 // ArgValueKind != ParamValueKind 9606 // The wrong type of absolute value function was used. Attempt to find the 9607 // proper one. 9608 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9609 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9610 if (NewAbsKind == 0) 9611 return; 9612 9613 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9614 << FDecl << ParamValueKind << ArgValueKind; 9615 9616 emitReplacement(*this, Call->getExprLoc(), 9617 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9618 } 9619 9620 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9621 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9622 const FunctionDecl *FDecl) { 9623 if (!Call || !FDecl) return; 9624 9625 // Ignore template specializations and macros. 9626 if (inTemplateInstantiation()) return; 9627 if (Call->getExprLoc().isMacroID()) return; 9628 9629 // Only care about the one template argument, two function parameter std::max 9630 if (Call->getNumArgs() != 2) return; 9631 if (!IsStdFunction(FDecl, "max")) return; 9632 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9633 if (!ArgList) return; 9634 if (ArgList->size() != 1) return; 9635 9636 // Check that template type argument is unsigned integer. 9637 const auto& TA = ArgList->get(0); 9638 if (TA.getKind() != TemplateArgument::Type) return; 9639 QualType ArgType = TA.getAsType(); 9640 if (!ArgType->isUnsignedIntegerType()) return; 9641 9642 // See if either argument is a literal zero. 9643 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9644 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9645 if (!MTE) return false; 9646 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9647 if (!Num) return false; 9648 if (Num->getValue() != 0) return false; 9649 return true; 9650 }; 9651 9652 const Expr *FirstArg = Call->getArg(0); 9653 const Expr *SecondArg = Call->getArg(1); 9654 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9655 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9656 9657 // Only warn when exactly one argument is zero. 9658 if (IsFirstArgZero == IsSecondArgZero) return; 9659 9660 SourceRange FirstRange = FirstArg->getSourceRange(); 9661 SourceRange SecondRange = SecondArg->getSourceRange(); 9662 9663 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9664 9665 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9666 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9667 9668 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9669 SourceRange RemovalRange; 9670 if (IsFirstArgZero) { 9671 RemovalRange = SourceRange(FirstRange.getBegin(), 9672 SecondRange.getBegin().getLocWithOffset(-1)); 9673 } else { 9674 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9675 SecondRange.getEnd()); 9676 } 9677 9678 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9679 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9680 << FixItHint::CreateRemoval(RemovalRange); 9681 } 9682 9683 //===--- CHECK: Standard memory functions ---------------------------------===// 9684 9685 /// Takes the expression passed to the size_t parameter of functions 9686 /// such as memcmp, strncat, etc and warns if it's a comparison. 9687 /// 9688 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9689 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9690 IdentifierInfo *FnName, 9691 SourceLocation FnLoc, 9692 SourceLocation RParenLoc) { 9693 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9694 if (!Size) 9695 return false; 9696 9697 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9698 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9699 return false; 9700 9701 SourceRange SizeRange = Size->getSourceRange(); 9702 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9703 << SizeRange << FnName; 9704 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9705 << FnName 9706 << FixItHint::CreateInsertion( 9707 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9708 << FixItHint::CreateRemoval(RParenLoc); 9709 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9710 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9711 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9712 ")"); 9713 9714 return true; 9715 } 9716 9717 /// Determine whether the given type is or contains a dynamic class type 9718 /// (e.g., whether it has a vtable). 9719 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9720 bool &IsContained) { 9721 // Look through array types while ignoring qualifiers. 9722 const Type *Ty = T->getBaseElementTypeUnsafe(); 9723 IsContained = false; 9724 9725 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9726 RD = RD ? RD->getDefinition() : nullptr; 9727 if (!RD || RD->isInvalidDecl()) 9728 return nullptr; 9729 9730 if (RD->isDynamicClass()) 9731 return RD; 9732 9733 // Check all the fields. If any bases were dynamic, the class is dynamic. 9734 // It's impossible for a class to transitively contain itself by value, so 9735 // infinite recursion is impossible. 9736 for (auto *FD : RD->fields()) { 9737 bool SubContained; 9738 if (const CXXRecordDecl *ContainedRD = 9739 getContainedDynamicClass(FD->getType(), SubContained)) { 9740 IsContained = true; 9741 return ContainedRD; 9742 } 9743 } 9744 9745 return nullptr; 9746 } 9747 9748 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9749 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9750 if (Unary->getKind() == UETT_SizeOf) 9751 return Unary; 9752 return nullptr; 9753 } 9754 9755 /// If E is a sizeof expression, returns its argument expression, 9756 /// otherwise returns NULL. 9757 static const Expr *getSizeOfExprArg(const Expr *E) { 9758 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9759 if (!SizeOf->isArgumentType()) 9760 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9761 return nullptr; 9762 } 9763 9764 /// If E is a sizeof expression, returns its argument type. 9765 static QualType getSizeOfArgType(const Expr *E) { 9766 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9767 return SizeOf->getTypeOfArgument(); 9768 return QualType(); 9769 } 9770 9771 namespace { 9772 9773 struct SearchNonTrivialToInitializeField 9774 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9775 using Super = 9776 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9777 9778 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9779 9780 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9781 SourceLocation SL) { 9782 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9783 asDerived().visitArray(PDIK, AT, SL); 9784 return; 9785 } 9786 9787 Super::visitWithKind(PDIK, FT, SL); 9788 } 9789 9790 void visitARCStrong(QualType FT, SourceLocation SL) { 9791 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9792 } 9793 void visitARCWeak(QualType FT, SourceLocation SL) { 9794 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9795 } 9796 void visitStruct(QualType FT, SourceLocation SL) { 9797 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9798 visit(FD->getType(), FD->getLocation()); 9799 } 9800 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9801 const ArrayType *AT, SourceLocation SL) { 9802 visit(getContext().getBaseElementType(AT), SL); 9803 } 9804 void visitTrivial(QualType FT, SourceLocation SL) {} 9805 9806 static void diag(QualType RT, const Expr *E, Sema &S) { 9807 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9808 } 9809 9810 ASTContext &getContext() { return S.getASTContext(); } 9811 9812 const Expr *E; 9813 Sema &S; 9814 }; 9815 9816 struct SearchNonTrivialToCopyField 9817 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9818 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9819 9820 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9821 9822 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9823 SourceLocation SL) { 9824 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9825 asDerived().visitArray(PCK, AT, SL); 9826 return; 9827 } 9828 9829 Super::visitWithKind(PCK, FT, SL); 9830 } 9831 9832 void visitARCStrong(QualType FT, SourceLocation SL) { 9833 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9834 } 9835 void visitARCWeak(QualType FT, SourceLocation SL) { 9836 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9837 } 9838 void visitStruct(QualType FT, SourceLocation SL) { 9839 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9840 visit(FD->getType(), FD->getLocation()); 9841 } 9842 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9843 SourceLocation SL) { 9844 visit(getContext().getBaseElementType(AT), SL); 9845 } 9846 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9847 SourceLocation SL) {} 9848 void visitTrivial(QualType FT, SourceLocation SL) {} 9849 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9850 9851 static void diag(QualType RT, const Expr *E, Sema &S) { 9852 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9853 } 9854 9855 ASTContext &getContext() { return S.getASTContext(); } 9856 9857 const Expr *E; 9858 Sema &S; 9859 }; 9860 9861 } 9862 9863 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9864 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9865 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9866 9867 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9868 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9869 return false; 9870 9871 return doesExprLikelyComputeSize(BO->getLHS()) || 9872 doesExprLikelyComputeSize(BO->getRHS()); 9873 } 9874 9875 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9876 } 9877 9878 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9879 /// 9880 /// \code 9881 /// #define MACRO 0 9882 /// foo(MACRO); 9883 /// foo(0); 9884 /// \endcode 9885 /// 9886 /// This should return true for the first call to foo, but not for the second 9887 /// (regardless of whether foo is a macro or function). 9888 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9889 SourceLocation CallLoc, 9890 SourceLocation ArgLoc) { 9891 if (!CallLoc.isMacroID()) 9892 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9893 9894 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9895 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9896 } 9897 9898 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9899 /// last two arguments transposed. 9900 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9901 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9902 return; 9903 9904 const Expr *SizeArg = 9905 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9906 9907 auto isLiteralZero = [](const Expr *E) { 9908 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9909 }; 9910 9911 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9912 SourceLocation CallLoc = Call->getRParenLoc(); 9913 SourceManager &SM = S.getSourceManager(); 9914 if (isLiteralZero(SizeArg) && 9915 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9916 9917 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9918 9919 // Some platforms #define bzero to __builtin_memset. See if this is the 9920 // case, and if so, emit a better diagnostic. 9921 if (BId == Builtin::BIbzero || 9922 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9923 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9924 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9925 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9926 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9927 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9928 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9929 } 9930 return; 9931 } 9932 9933 // If the second argument to a memset is a sizeof expression and the third 9934 // isn't, this is also likely an error. This should catch 9935 // 'memset(buf, sizeof(buf), 0xff)'. 9936 if (BId == Builtin::BImemset && 9937 doesExprLikelyComputeSize(Call->getArg(1)) && 9938 !doesExprLikelyComputeSize(Call->getArg(2))) { 9939 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9940 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9941 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9942 return; 9943 } 9944 } 9945 9946 /// Check for dangerous or invalid arguments to memset(). 9947 /// 9948 /// This issues warnings on known problematic, dangerous or unspecified 9949 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9950 /// function calls. 9951 /// 9952 /// \param Call The call expression to diagnose. 9953 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9954 unsigned BId, 9955 IdentifierInfo *FnName) { 9956 assert(BId != 0); 9957 9958 // It is possible to have a non-standard definition of memset. Validate 9959 // we have enough arguments, and if not, abort further checking. 9960 unsigned ExpectedNumArgs = 9961 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9962 if (Call->getNumArgs() < ExpectedNumArgs) 9963 return; 9964 9965 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9966 BId == Builtin::BIstrndup ? 1 : 2); 9967 unsigned LenArg = 9968 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9969 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9970 9971 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9972 Call->getBeginLoc(), Call->getRParenLoc())) 9973 return; 9974 9975 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9976 CheckMemaccessSize(*this, BId, Call); 9977 9978 // We have special checking when the length is a sizeof expression. 9979 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9980 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9981 llvm::FoldingSetNodeID SizeOfArgID; 9982 9983 // Although widely used, 'bzero' is not a standard function. Be more strict 9984 // with the argument types before allowing diagnostics and only allow the 9985 // form bzero(ptr, sizeof(...)). 9986 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9987 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9988 return; 9989 9990 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9991 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9992 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9993 9994 QualType DestTy = Dest->getType(); 9995 QualType PointeeTy; 9996 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9997 PointeeTy = DestPtrTy->getPointeeType(); 9998 9999 // Never warn about void type pointers. This can be used to suppress 10000 // false positives. 10001 if (PointeeTy->isVoidType()) 10002 continue; 10003 10004 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10005 // actually comparing the expressions for equality. Because computing the 10006 // expression IDs can be expensive, we only do this if the diagnostic is 10007 // enabled. 10008 if (SizeOfArg && 10009 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10010 SizeOfArg->getExprLoc())) { 10011 // We only compute IDs for expressions if the warning is enabled, and 10012 // cache the sizeof arg's ID. 10013 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10014 SizeOfArg->Profile(SizeOfArgID, Context, true); 10015 llvm::FoldingSetNodeID DestID; 10016 Dest->Profile(DestID, Context, true); 10017 if (DestID == SizeOfArgID) { 10018 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10019 // over sizeof(src) as well. 10020 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10021 StringRef ReadableName = FnName->getName(); 10022 10023 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10024 if (UnaryOp->getOpcode() == UO_AddrOf) 10025 ActionIdx = 1; // If its an address-of operator, just remove it. 10026 if (!PointeeTy->isIncompleteType() && 10027 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10028 ActionIdx = 2; // If the pointee's size is sizeof(char), 10029 // suggest an explicit length. 10030 10031 // If the function is defined as a builtin macro, do not show macro 10032 // expansion. 10033 SourceLocation SL = SizeOfArg->getExprLoc(); 10034 SourceRange DSR = Dest->getSourceRange(); 10035 SourceRange SSR = SizeOfArg->getSourceRange(); 10036 SourceManager &SM = getSourceManager(); 10037 10038 if (SM.isMacroArgExpansion(SL)) { 10039 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10040 SL = SM.getSpellingLoc(SL); 10041 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10042 SM.getSpellingLoc(DSR.getEnd())); 10043 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10044 SM.getSpellingLoc(SSR.getEnd())); 10045 } 10046 10047 DiagRuntimeBehavior(SL, SizeOfArg, 10048 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10049 << ReadableName 10050 << PointeeTy 10051 << DestTy 10052 << DSR 10053 << SSR); 10054 DiagRuntimeBehavior(SL, SizeOfArg, 10055 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10056 << ActionIdx 10057 << SSR); 10058 10059 break; 10060 } 10061 } 10062 10063 // Also check for cases where the sizeof argument is the exact same 10064 // type as the memory argument, and where it points to a user-defined 10065 // record type. 10066 if (SizeOfArgTy != QualType()) { 10067 if (PointeeTy->isRecordType() && 10068 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10069 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10070 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10071 << FnName << SizeOfArgTy << ArgIdx 10072 << PointeeTy << Dest->getSourceRange() 10073 << LenExpr->getSourceRange()); 10074 break; 10075 } 10076 } 10077 } else if (DestTy->isArrayType()) { 10078 PointeeTy = DestTy; 10079 } 10080 10081 if (PointeeTy == QualType()) 10082 continue; 10083 10084 // Always complain about dynamic classes. 10085 bool IsContained; 10086 if (const CXXRecordDecl *ContainedRD = 10087 getContainedDynamicClass(PointeeTy, IsContained)) { 10088 10089 unsigned OperationType = 0; 10090 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10091 // "overwritten" if we're warning about the destination for any call 10092 // but memcmp; otherwise a verb appropriate to the call. 10093 if (ArgIdx != 0 || IsCmp) { 10094 if (BId == Builtin::BImemcpy) 10095 OperationType = 1; 10096 else if(BId == Builtin::BImemmove) 10097 OperationType = 2; 10098 else if (IsCmp) 10099 OperationType = 3; 10100 } 10101 10102 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10103 PDiag(diag::warn_dyn_class_memaccess) 10104 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10105 << IsContained << ContainedRD << OperationType 10106 << Call->getCallee()->getSourceRange()); 10107 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10108 BId != Builtin::BImemset) 10109 DiagRuntimeBehavior( 10110 Dest->getExprLoc(), Dest, 10111 PDiag(diag::warn_arc_object_memaccess) 10112 << ArgIdx << FnName << PointeeTy 10113 << Call->getCallee()->getSourceRange()); 10114 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10115 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10116 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10117 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10118 PDiag(diag::warn_cstruct_memaccess) 10119 << ArgIdx << FnName << PointeeTy << 0); 10120 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10121 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10122 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10123 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10124 PDiag(diag::warn_cstruct_memaccess) 10125 << ArgIdx << FnName << PointeeTy << 1); 10126 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10127 } else { 10128 continue; 10129 } 10130 } else 10131 continue; 10132 10133 DiagRuntimeBehavior( 10134 Dest->getExprLoc(), Dest, 10135 PDiag(diag::note_bad_memaccess_silence) 10136 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10137 break; 10138 } 10139 } 10140 10141 // A little helper routine: ignore addition and subtraction of integer literals. 10142 // This intentionally does not ignore all integer constant expressions because 10143 // we don't want to remove sizeof(). 10144 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10145 Ex = Ex->IgnoreParenCasts(); 10146 10147 while (true) { 10148 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10149 if (!BO || !BO->isAdditiveOp()) 10150 break; 10151 10152 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10153 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10154 10155 if (isa<IntegerLiteral>(RHS)) 10156 Ex = LHS; 10157 else if (isa<IntegerLiteral>(LHS)) 10158 Ex = RHS; 10159 else 10160 break; 10161 } 10162 10163 return Ex; 10164 } 10165 10166 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10167 ASTContext &Context) { 10168 // Only handle constant-sized or VLAs, but not flexible members. 10169 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10170 // Only issue the FIXIT for arrays of size > 1. 10171 if (CAT->getSize().getSExtValue() <= 1) 10172 return false; 10173 } else if (!Ty->isVariableArrayType()) { 10174 return false; 10175 } 10176 return true; 10177 } 10178 10179 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10180 // be the size of the source, instead of the destination. 10181 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10182 IdentifierInfo *FnName) { 10183 10184 // Don't crash if the user has the wrong number of arguments 10185 unsigned NumArgs = Call->getNumArgs(); 10186 if ((NumArgs != 3) && (NumArgs != 4)) 10187 return; 10188 10189 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10190 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10191 const Expr *CompareWithSrc = nullptr; 10192 10193 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10194 Call->getBeginLoc(), Call->getRParenLoc())) 10195 return; 10196 10197 // Look for 'strlcpy(dst, x, sizeof(x))' 10198 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10199 CompareWithSrc = Ex; 10200 else { 10201 // Look for 'strlcpy(dst, x, strlen(x))' 10202 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10203 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10204 SizeCall->getNumArgs() == 1) 10205 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10206 } 10207 } 10208 10209 if (!CompareWithSrc) 10210 return; 10211 10212 // Determine if the argument to sizeof/strlen is equal to the source 10213 // argument. In principle there's all kinds of things you could do 10214 // here, for instance creating an == expression and evaluating it with 10215 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10216 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10217 if (!SrcArgDRE) 10218 return; 10219 10220 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10221 if (!CompareWithSrcDRE || 10222 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10223 return; 10224 10225 const Expr *OriginalSizeArg = Call->getArg(2); 10226 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10227 << OriginalSizeArg->getSourceRange() << FnName; 10228 10229 // Output a FIXIT hint if the destination is an array (rather than a 10230 // pointer to an array). This could be enhanced to handle some 10231 // pointers if we know the actual size, like if DstArg is 'array+2' 10232 // we could say 'sizeof(array)-2'. 10233 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10234 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10235 return; 10236 10237 SmallString<128> sizeString; 10238 llvm::raw_svector_ostream OS(sizeString); 10239 OS << "sizeof("; 10240 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10241 OS << ")"; 10242 10243 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10244 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10245 OS.str()); 10246 } 10247 10248 /// Check if two expressions refer to the same declaration. 10249 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10250 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10251 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10252 return D1->getDecl() == D2->getDecl(); 10253 return false; 10254 } 10255 10256 static const Expr *getStrlenExprArg(const Expr *E) { 10257 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10258 const FunctionDecl *FD = CE->getDirectCallee(); 10259 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10260 return nullptr; 10261 return CE->getArg(0)->IgnoreParenCasts(); 10262 } 10263 return nullptr; 10264 } 10265 10266 // Warn on anti-patterns as the 'size' argument to strncat. 10267 // The correct size argument should look like following: 10268 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10269 void Sema::CheckStrncatArguments(const CallExpr *CE, 10270 IdentifierInfo *FnName) { 10271 // Don't crash if the user has the wrong number of arguments. 10272 if (CE->getNumArgs() < 3) 10273 return; 10274 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10275 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10276 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10277 10278 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10279 CE->getRParenLoc())) 10280 return; 10281 10282 // Identify common expressions, which are wrongly used as the size argument 10283 // to strncat and may lead to buffer overflows. 10284 unsigned PatternType = 0; 10285 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10286 // - sizeof(dst) 10287 if (referToTheSameDecl(SizeOfArg, DstArg)) 10288 PatternType = 1; 10289 // - sizeof(src) 10290 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10291 PatternType = 2; 10292 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10293 if (BE->getOpcode() == BO_Sub) { 10294 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10295 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10296 // - sizeof(dst) - strlen(dst) 10297 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10298 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10299 PatternType = 1; 10300 // - sizeof(src) - (anything) 10301 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10302 PatternType = 2; 10303 } 10304 } 10305 10306 if (PatternType == 0) 10307 return; 10308 10309 // Generate the diagnostic. 10310 SourceLocation SL = LenArg->getBeginLoc(); 10311 SourceRange SR = LenArg->getSourceRange(); 10312 SourceManager &SM = getSourceManager(); 10313 10314 // If the function is defined as a builtin macro, do not show macro expansion. 10315 if (SM.isMacroArgExpansion(SL)) { 10316 SL = SM.getSpellingLoc(SL); 10317 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10318 SM.getSpellingLoc(SR.getEnd())); 10319 } 10320 10321 // Check if the destination is an array (rather than a pointer to an array). 10322 QualType DstTy = DstArg->getType(); 10323 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10324 Context); 10325 if (!isKnownSizeArray) { 10326 if (PatternType == 1) 10327 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10328 else 10329 Diag(SL, diag::warn_strncat_src_size) << SR; 10330 return; 10331 } 10332 10333 if (PatternType == 1) 10334 Diag(SL, diag::warn_strncat_large_size) << SR; 10335 else 10336 Diag(SL, diag::warn_strncat_src_size) << SR; 10337 10338 SmallString<128> sizeString; 10339 llvm::raw_svector_ostream OS(sizeString); 10340 OS << "sizeof("; 10341 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10342 OS << ") - "; 10343 OS << "strlen("; 10344 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10345 OS << ") - 1"; 10346 10347 Diag(SL, diag::note_strncat_wrong_size) 10348 << FixItHint::CreateReplacement(SR, OS.str()); 10349 } 10350 10351 namespace { 10352 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10353 const UnaryOperator *UnaryExpr, const Decl *D) { 10354 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10355 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10356 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10357 return; 10358 } 10359 } 10360 10361 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10362 const UnaryOperator *UnaryExpr) { 10363 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10364 const Decl *D = Lvalue->getDecl(); 10365 if (isa<VarDecl, FunctionDecl>(D)) 10366 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10367 } 10368 10369 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10370 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10371 Lvalue->getMemberDecl()); 10372 } 10373 10374 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10375 const UnaryOperator *UnaryExpr) { 10376 const auto *Lambda = dyn_cast<LambdaExpr>( 10377 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10378 if (!Lambda) 10379 return; 10380 10381 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10382 << CalleeName << 2 /*object: lambda expression*/; 10383 } 10384 10385 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10386 const DeclRefExpr *Lvalue) { 10387 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10388 if (Var == nullptr) 10389 return; 10390 10391 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10392 << CalleeName << 0 /*object: */ << Var; 10393 } 10394 10395 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10396 const CastExpr *Cast) { 10397 SmallString<128> SizeString; 10398 llvm::raw_svector_ostream OS(SizeString); 10399 10400 clang::CastKind Kind = Cast->getCastKind(); 10401 if (Kind == clang::CK_BitCast && 10402 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10403 return; 10404 if (Kind == clang::CK_IntegralToPointer && 10405 !isa<IntegerLiteral>( 10406 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10407 return; 10408 10409 switch (Cast->getCastKind()) { 10410 case clang::CK_BitCast: 10411 case clang::CK_IntegralToPointer: 10412 case clang::CK_FunctionToPointerDecay: 10413 OS << '\''; 10414 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10415 OS << '\''; 10416 break; 10417 default: 10418 return; 10419 } 10420 10421 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10422 << CalleeName << 0 /*object: */ << OS.str(); 10423 } 10424 } // namespace 10425 10426 /// Alerts the user that they are attempting to free a non-malloc'd object. 10427 void Sema::CheckFreeArguments(const CallExpr *E) { 10428 const std::string CalleeName = 10429 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10430 10431 { // Prefer something that doesn't involve a cast to make things simpler. 10432 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10433 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10434 switch (UnaryExpr->getOpcode()) { 10435 case UnaryOperator::Opcode::UO_AddrOf: 10436 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10437 case UnaryOperator::Opcode::UO_Plus: 10438 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 10439 default: 10440 break; 10441 } 10442 10443 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10444 if (Lvalue->getType()->isArrayType()) 10445 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10446 10447 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 10448 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 10449 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 10450 return; 10451 } 10452 10453 if (isa<BlockExpr>(Arg)) { 10454 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 10455 << CalleeName << 1 /*object: block*/; 10456 return; 10457 } 10458 } 10459 // Maybe the cast was important, check after the other cases. 10460 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 10461 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 10462 } 10463 10464 void 10465 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10466 SourceLocation ReturnLoc, 10467 bool isObjCMethod, 10468 const AttrVec *Attrs, 10469 const FunctionDecl *FD) { 10470 // Check if the return value is null but should not be. 10471 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10472 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10473 CheckNonNullExpr(*this, RetValExp)) 10474 Diag(ReturnLoc, diag::warn_null_ret) 10475 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10476 10477 // C++11 [basic.stc.dynamic.allocation]p4: 10478 // If an allocation function declared with a non-throwing 10479 // exception-specification fails to allocate storage, it shall return 10480 // a null pointer. Any other allocation function that fails to allocate 10481 // storage shall indicate failure only by throwing an exception [...] 10482 if (FD) { 10483 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10484 if (Op == OO_New || Op == OO_Array_New) { 10485 const FunctionProtoType *Proto 10486 = FD->getType()->castAs<FunctionProtoType>(); 10487 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10488 CheckNonNullExpr(*this, RetValExp)) 10489 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10490 << FD << getLangOpts().CPlusPlus11; 10491 } 10492 } 10493 10494 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10495 // here prevent the user from using a PPC MMA type as trailing return type. 10496 if (Context.getTargetInfo().getTriple().isPPC64()) 10497 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10498 } 10499 10500 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10501 10502 /// Check for comparisons of floating point operands using != and ==. 10503 /// Issue a warning if these are no self-comparisons, as they are not likely 10504 /// to do what the programmer intended. 10505 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10506 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10507 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10508 10509 // Special case: check for x == x (which is OK). 10510 // Do not emit warnings for such cases. 10511 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10512 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10513 if (DRL->getDecl() == DRR->getDecl()) 10514 return; 10515 10516 // Special case: check for comparisons against literals that can be exactly 10517 // represented by APFloat. In such cases, do not emit a warning. This 10518 // is a heuristic: often comparison against such literals are used to 10519 // detect if a value in a variable has not changed. This clearly can 10520 // lead to false negatives. 10521 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10522 if (FLL->isExact()) 10523 return; 10524 } else 10525 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10526 if (FLR->isExact()) 10527 return; 10528 10529 // Check for comparisons with builtin types. 10530 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10531 if (CL->getBuiltinCallee()) 10532 return; 10533 10534 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10535 if (CR->getBuiltinCallee()) 10536 return; 10537 10538 // Emit the diagnostic. 10539 Diag(Loc, diag::warn_floatingpoint_eq) 10540 << LHS->getSourceRange() << RHS->getSourceRange(); 10541 } 10542 10543 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10544 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10545 10546 namespace { 10547 10548 /// Structure recording the 'active' range of an integer-valued 10549 /// expression. 10550 struct IntRange { 10551 /// The number of bits active in the int. Note that this includes exactly one 10552 /// sign bit if !NonNegative. 10553 unsigned Width; 10554 10555 /// True if the int is known not to have negative values. If so, all leading 10556 /// bits before Width are known zero, otherwise they are known to be the 10557 /// same as the MSB within Width. 10558 bool NonNegative; 10559 10560 IntRange(unsigned Width, bool NonNegative) 10561 : Width(Width), NonNegative(NonNegative) {} 10562 10563 /// Number of bits excluding the sign bit. 10564 unsigned valueBits() const { 10565 return NonNegative ? Width : Width - 1; 10566 } 10567 10568 /// Returns the range of the bool type. 10569 static IntRange forBoolType() { 10570 return IntRange(1, true); 10571 } 10572 10573 /// Returns the range of an opaque value of the given integral type. 10574 static IntRange forValueOfType(ASTContext &C, QualType T) { 10575 return forValueOfCanonicalType(C, 10576 T->getCanonicalTypeInternal().getTypePtr()); 10577 } 10578 10579 /// Returns the range of an opaque value of a canonical integral type. 10580 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10581 assert(T->isCanonicalUnqualified()); 10582 10583 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10584 T = VT->getElementType().getTypePtr(); 10585 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10586 T = CT->getElementType().getTypePtr(); 10587 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10588 T = AT->getValueType().getTypePtr(); 10589 10590 if (!C.getLangOpts().CPlusPlus) { 10591 // For enum types in C code, use the underlying datatype. 10592 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10593 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10594 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10595 // For enum types in C++, use the known bit width of the enumerators. 10596 EnumDecl *Enum = ET->getDecl(); 10597 // In C++11, enums can have a fixed underlying type. Use this type to 10598 // compute the range. 10599 if (Enum->isFixed()) { 10600 return IntRange(C.getIntWidth(QualType(T, 0)), 10601 !ET->isSignedIntegerOrEnumerationType()); 10602 } 10603 10604 unsigned NumPositive = Enum->getNumPositiveBits(); 10605 unsigned NumNegative = Enum->getNumNegativeBits(); 10606 10607 if (NumNegative == 0) 10608 return IntRange(NumPositive, true/*NonNegative*/); 10609 else 10610 return IntRange(std::max(NumPositive + 1, NumNegative), 10611 false/*NonNegative*/); 10612 } 10613 10614 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10615 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10616 10617 const BuiltinType *BT = cast<BuiltinType>(T); 10618 assert(BT->isInteger()); 10619 10620 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10621 } 10622 10623 /// Returns the "target" range of a canonical integral type, i.e. 10624 /// the range of values expressible in the type. 10625 /// 10626 /// This matches forValueOfCanonicalType except that enums have the 10627 /// full range of their type, not the range of their enumerators. 10628 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10629 assert(T->isCanonicalUnqualified()); 10630 10631 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10632 T = VT->getElementType().getTypePtr(); 10633 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10634 T = CT->getElementType().getTypePtr(); 10635 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10636 T = AT->getValueType().getTypePtr(); 10637 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10638 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10639 10640 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10641 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10642 10643 const BuiltinType *BT = cast<BuiltinType>(T); 10644 assert(BT->isInteger()); 10645 10646 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10647 } 10648 10649 /// Returns the supremum of two ranges: i.e. their conservative merge. 10650 static IntRange join(IntRange L, IntRange R) { 10651 bool Unsigned = L.NonNegative && R.NonNegative; 10652 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 10653 L.NonNegative && R.NonNegative); 10654 } 10655 10656 /// Return the range of a bitwise-AND of the two ranges. 10657 static IntRange bit_and(IntRange L, IntRange R) { 10658 unsigned Bits = std::max(L.Width, R.Width); 10659 bool NonNegative = false; 10660 if (L.NonNegative) { 10661 Bits = std::min(Bits, L.Width); 10662 NonNegative = true; 10663 } 10664 if (R.NonNegative) { 10665 Bits = std::min(Bits, R.Width); 10666 NonNegative = true; 10667 } 10668 return IntRange(Bits, NonNegative); 10669 } 10670 10671 /// Return the range of a sum of the two ranges. 10672 static IntRange sum(IntRange L, IntRange R) { 10673 bool Unsigned = L.NonNegative && R.NonNegative; 10674 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 10675 Unsigned); 10676 } 10677 10678 /// Return the range of a difference of the two ranges. 10679 static IntRange difference(IntRange L, IntRange R) { 10680 // We need a 1-bit-wider range if: 10681 // 1) LHS can be negative: least value can be reduced. 10682 // 2) RHS can be negative: greatest value can be increased. 10683 bool CanWiden = !L.NonNegative || !R.NonNegative; 10684 bool Unsigned = L.NonNegative && R.Width == 0; 10685 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 10686 !Unsigned, 10687 Unsigned); 10688 } 10689 10690 /// Return the range of a product of the two ranges. 10691 static IntRange product(IntRange L, IntRange R) { 10692 // If both LHS and RHS can be negative, we can form 10693 // -2^L * -2^R = 2^(L + R) 10694 // which requires L + R + 1 value bits to represent. 10695 bool CanWiden = !L.NonNegative && !R.NonNegative; 10696 bool Unsigned = L.NonNegative && R.NonNegative; 10697 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 10698 Unsigned); 10699 } 10700 10701 /// Return the range of a remainder operation between the two ranges. 10702 static IntRange rem(IntRange L, IntRange R) { 10703 // The result of a remainder can't be larger than the result of 10704 // either side. The sign of the result is the sign of the LHS. 10705 bool Unsigned = L.NonNegative; 10706 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 10707 Unsigned); 10708 } 10709 }; 10710 10711 } // namespace 10712 10713 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10714 unsigned MaxWidth) { 10715 if (value.isSigned() && value.isNegative()) 10716 return IntRange(value.getMinSignedBits(), false); 10717 10718 if (value.getBitWidth() > MaxWidth) 10719 value = value.trunc(MaxWidth); 10720 10721 // isNonNegative() just checks the sign bit without considering 10722 // signedness. 10723 return IntRange(value.getActiveBits(), true); 10724 } 10725 10726 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10727 unsigned MaxWidth) { 10728 if (result.isInt()) 10729 return GetValueRange(C, result.getInt(), MaxWidth); 10730 10731 if (result.isVector()) { 10732 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10733 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10734 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10735 R = IntRange::join(R, El); 10736 } 10737 return R; 10738 } 10739 10740 if (result.isComplexInt()) { 10741 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10742 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10743 return IntRange::join(R, I); 10744 } 10745 10746 // This can happen with lossless casts to intptr_t of "based" lvalues. 10747 // Assume it might use arbitrary bits. 10748 // FIXME: The only reason we need to pass the type in here is to get 10749 // the sign right on this one case. It would be nice if APValue 10750 // preserved this. 10751 assert(result.isLValue() || result.isAddrLabelDiff()); 10752 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10753 } 10754 10755 static QualType GetExprType(const Expr *E) { 10756 QualType Ty = E->getType(); 10757 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10758 Ty = AtomicRHS->getValueType(); 10759 return Ty; 10760 } 10761 10762 /// Pseudo-evaluate the given integer expression, estimating the 10763 /// range of values it might take. 10764 /// 10765 /// \param MaxWidth The width to which the value will be truncated. 10766 /// \param Approximate If \c true, return a likely range for the result: in 10767 /// particular, assume that aritmetic on narrower types doesn't leave 10768 /// those types. If \c false, return a range including all possible 10769 /// result values. 10770 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10771 bool InConstantContext, bool Approximate) { 10772 E = E->IgnoreParens(); 10773 10774 // Try a full evaluation first. 10775 Expr::EvalResult result; 10776 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10777 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10778 10779 // I think we only want to look through implicit casts here; if the 10780 // user has an explicit widening cast, we should treat the value as 10781 // being of the new, wider type. 10782 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10783 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10784 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 10785 Approximate); 10786 10787 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10788 10789 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10790 CE->getCastKind() == CK_BooleanToSignedIntegral; 10791 10792 // Assume that non-integer casts can span the full range of the type. 10793 if (!isIntegerCast) 10794 return OutputTypeRange; 10795 10796 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10797 std::min(MaxWidth, OutputTypeRange.Width), 10798 InConstantContext, Approximate); 10799 10800 // Bail out if the subexpr's range is as wide as the cast type. 10801 if (SubRange.Width >= OutputTypeRange.Width) 10802 return OutputTypeRange; 10803 10804 // Otherwise, we take the smaller width, and we're non-negative if 10805 // either the output type or the subexpr is. 10806 return IntRange(SubRange.Width, 10807 SubRange.NonNegative || OutputTypeRange.NonNegative); 10808 } 10809 10810 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10811 // If we can fold the condition, just take that operand. 10812 bool CondResult; 10813 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10814 return GetExprRange(C, 10815 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10816 MaxWidth, InConstantContext, Approximate); 10817 10818 // Otherwise, conservatively merge. 10819 // GetExprRange requires an integer expression, but a throw expression 10820 // results in a void type. 10821 Expr *E = CO->getTrueExpr(); 10822 IntRange L = E->getType()->isVoidType() 10823 ? IntRange{0, true} 10824 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10825 E = CO->getFalseExpr(); 10826 IntRange R = E->getType()->isVoidType() 10827 ? IntRange{0, true} 10828 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10829 return IntRange::join(L, R); 10830 } 10831 10832 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10833 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 10834 10835 switch (BO->getOpcode()) { 10836 case BO_Cmp: 10837 llvm_unreachable("builtin <=> should have class type"); 10838 10839 // Boolean-valued operations are single-bit and positive. 10840 case BO_LAnd: 10841 case BO_LOr: 10842 case BO_LT: 10843 case BO_GT: 10844 case BO_LE: 10845 case BO_GE: 10846 case BO_EQ: 10847 case BO_NE: 10848 return IntRange::forBoolType(); 10849 10850 // The type of the assignments is the type of the LHS, so the RHS 10851 // is not necessarily the same type. 10852 case BO_MulAssign: 10853 case BO_DivAssign: 10854 case BO_RemAssign: 10855 case BO_AddAssign: 10856 case BO_SubAssign: 10857 case BO_XorAssign: 10858 case BO_OrAssign: 10859 // TODO: bitfields? 10860 return IntRange::forValueOfType(C, GetExprType(E)); 10861 10862 // Simple assignments just pass through the RHS, which will have 10863 // been coerced to the LHS type. 10864 case BO_Assign: 10865 // TODO: bitfields? 10866 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10867 Approximate); 10868 10869 // Operations with opaque sources are black-listed. 10870 case BO_PtrMemD: 10871 case BO_PtrMemI: 10872 return IntRange::forValueOfType(C, GetExprType(E)); 10873 10874 // Bitwise-and uses the *infinum* of the two source ranges. 10875 case BO_And: 10876 case BO_AndAssign: 10877 Combine = IntRange::bit_and; 10878 break; 10879 10880 // Left shift gets black-listed based on a judgement call. 10881 case BO_Shl: 10882 // ...except that we want to treat '1 << (blah)' as logically 10883 // positive. It's an important idiom. 10884 if (IntegerLiteral *I 10885 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10886 if (I->getValue() == 1) { 10887 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10888 return IntRange(R.Width, /*NonNegative*/ true); 10889 } 10890 } 10891 LLVM_FALLTHROUGH; 10892 10893 case BO_ShlAssign: 10894 return IntRange::forValueOfType(C, GetExprType(E)); 10895 10896 // Right shift by a constant can narrow its left argument. 10897 case BO_Shr: 10898 case BO_ShrAssign: { 10899 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 10900 Approximate); 10901 10902 // If the shift amount is a positive constant, drop the width by 10903 // that much. 10904 if (Optional<llvm::APSInt> shift = 10905 BO->getRHS()->getIntegerConstantExpr(C)) { 10906 if (shift->isNonNegative()) { 10907 unsigned zext = shift->getZExtValue(); 10908 if (zext >= L.Width) 10909 L.Width = (L.NonNegative ? 0 : 1); 10910 else 10911 L.Width -= zext; 10912 } 10913 } 10914 10915 return L; 10916 } 10917 10918 // Comma acts as its right operand. 10919 case BO_Comma: 10920 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10921 Approximate); 10922 10923 case BO_Add: 10924 if (!Approximate) 10925 Combine = IntRange::sum; 10926 break; 10927 10928 case BO_Sub: 10929 if (BO->getLHS()->getType()->isPointerType()) 10930 return IntRange::forValueOfType(C, GetExprType(E)); 10931 if (!Approximate) 10932 Combine = IntRange::difference; 10933 break; 10934 10935 case BO_Mul: 10936 if (!Approximate) 10937 Combine = IntRange::product; 10938 break; 10939 10940 // The width of a division result is mostly determined by the size 10941 // of the LHS. 10942 case BO_Div: { 10943 // Don't 'pre-truncate' the operands. 10944 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10945 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 10946 Approximate); 10947 10948 // If the divisor is constant, use that. 10949 if (Optional<llvm::APSInt> divisor = 10950 BO->getRHS()->getIntegerConstantExpr(C)) { 10951 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 10952 if (log2 >= L.Width) 10953 L.Width = (L.NonNegative ? 0 : 1); 10954 else 10955 L.Width = std::min(L.Width - log2, MaxWidth); 10956 return L; 10957 } 10958 10959 // Otherwise, just use the LHS's width. 10960 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 10961 // could be -1. 10962 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 10963 Approximate); 10964 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10965 } 10966 10967 case BO_Rem: 10968 Combine = IntRange::rem; 10969 break; 10970 10971 // The default behavior is okay for these. 10972 case BO_Xor: 10973 case BO_Or: 10974 break; 10975 } 10976 10977 // Combine the two ranges, but limit the result to the type in which we 10978 // performed the computation. 10979 QualType T = GetExprType(E); 10980 unsigned opWidth = C.getIntWidth(T); 10981 IntRange L = 10982 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 10983 IntRange R = 10984 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 10985 IntRange C = Combine(L, R); 10986 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 10987 C.Width = std::min(C.Width, MaxWidth); 10988 return C; 10989 } 10990 10991 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10992 switch (UO->getOpcode()) { 10993 // Boolean-valued operations are white-listed. 10994 case UO_LNot: 10995 return IntRange::forBoolType(); 10996 10997 // Operations with opaque sources are black-listed. 10998 case UO_Deref: 10999 case UO_AddrOf: // should be impossible 11000 return IntRange::forValueOfType(C, GetExprType(E)); 11001 11002 default: 11003 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11004 Approximate); 11005 } 11006 } 11007 11008 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11009 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11010 Approximate); 11011 11012 if (const auto *BitField = E->getSourceBitField()) 11013 return IntRange(BitField->getBitWidthValue(C), 11014 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11015 11016 return IntRange::forValueOfType(C, GetExprType(E)); 11017 } 11018 11019 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11020 bool InConstantContext, bool Approximate) { 11021 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11022 Approximate); 11023 } 11024 11025 /// Checks whether the given value, which currently has the given 11026 /// source semantics, has the same value when coerced through the 11027 /// target semantics. 11028 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11029 const llvm::fltSemantics &Src, 11030 const llvm::fltSemantics &Tgt) { 11031 llvm::APFloat truncated = value; 11032 11033 bool ignored; 11034 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11035 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11036 11037 return truncated.bitwiseIsEqual(value); 11038 } 11039 11040 /// Checks whether the given value, which currently has the given 11041 /// source semantics, has the same value when coerced through the 11042 /// target semantics. 11043 /// 11044 /// The value might be a vector of floats (or a complex number). 11045 static bool IsSameFloatAfterCast(const APValue &value, 11046 const llvm::fltSemantics &Src, 11047 const llvm::fltSemantics &Tgt) { 11048 if (value.isFloat()) 11049 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11050 11051 if (value.isVector()) { 11052 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11053 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11054 return false; 11055 return true; 11056 } 11057 11058 assert(value.isComplexFloat()); 11059 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11060 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11061 } 11062 11063 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11064 bool IsListInit = false); 11065 11066 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11067 // Suppress cases where we are comparing against an enum constant. 11068 if (const DeclRefExpr *DR = 11069 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11070 if (isa<EnumConstantDecl>(DR->getDecl())) 11071 return true; 11072 11073 // Suppress cases where the value is expanded from a macro, unless that macro 11074 // is how a language represents a boolean literal. This is the case in both C 11075 // and Objective-C. 11076 SourceLocation BeginLoc = E->getBeginLoc(); 11077 if (BeginLoc.isMacroID()) { 11078 StringRef MacroName = Lexer::getImmediateMacroName( 11079 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11080 return MacroName != "YES" && MacroName != "NO" && 11081 MacroName != "true" && MacroName != "false"; 11082 } 11083 11084 return false; 11085 } 11086 11087 static bool isKnownToHaveUnsignedValue(Expr *E) { 11088 return E->getType()->isIntegerType() && 11089 (!E->getType()->isSignedIntegerType() || 11090 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11091 } 11092 11093 namespace { 11094 /// The promoted range of values of a type. In general this has the 11095 /// following structure: 11096 /// 11097 /// |-----------| . . . |-----------| 11098 /// ^ ^ ^ ^ 11099 /// Min HoleMin HoleMax Max 11100 /// 11101 /// ... where there is only a hole if a signed type is promoted to unsigned 11102 /// (in which case Min and Max are the smallest and largest representable 11103 /// values). 11104 struct PromotedRange { 11105 // Min, or HoleMax if there is a hole. 11106 llvm::APSInt PromotedMin; 11107 // Max, or HoleMin if there is a hole. 11108 llvm::APSInt PromotedMax; 11109 11110 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11111 if (R.Width == 0) 11112 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11113 else if (R.Width >= BitWidth && !Unsigned) { 11114 // Promotion made the type *narrower*. This happens when promoting 11115 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11116 // Treat all values of 'signed int' as being in range for now. 11117 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11118 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11119 } else { 11120 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11121 .extOrTrunc(BitWidth); 11122 PromotedMin.setIsUnsigned(Unsigned); 11123 11124 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11125 .extOrTrunc(BitWidth); 11126 PromotedMax.setIsUnsigned(Unsigned); 11127 } 11128 } 11129 11130 // Determine whether this range is contiguous (has no hole). 11131 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11132 11133 // Where a constant value is within the range. 11134 enum ComparisonResult { 11135 LT = 0x1, 11136 LE = 0x2, 11137 GT = 0x4, 11138 GE = 0x8, 11139 EQ = 0x10, 11140 NE = 0x20, 11141 InRangeFlag = 0x40, 11142 11143 Less = LE | LT | NE, 11144 Min = LE | InRangeFlag, 11145 InRange = InRangeFlag, 11146 Max = GE | InRangeFlag, 11147 Greater = GE | GT | NE, 11148 11149 OnlyValue = LE | GE | EQ | InRangeFlag, 11150 InHole = NE 11151 }; 11152 11153 ComparisonResult compare(const llvm::APSInt &Value) const { 11154 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11155 Value.isUnsigned() == PromotedMin.isUnsigned()); 11156 if (!isContiguous()) { 11157 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11158 if (Value.isMinValue()) return Min; 11159 if (Value.isMaxValue()) return Max; 11160 if (Value >= PromotedMin) return InRange; 11161 if (Value <= PromotedMax) return InRange; 11162 return InHole; 11163 } 11164 11165 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11166 case -1: return Less; 11167 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11168 case 1: 11169 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11170 case -1: return InRange; 11171 case 0: return Max; 11172 case 1: return Greater; 11173 } 11174 } 11175 11176 llvm_unreachable("impossible compare result"); 11177 } 11178 11179 static llvm::Optional<StringRef> 11180 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11181 if (Op == BO_Cmp) { 11182 ComparisonResult LTFlag = LT, GTFlag = GT; 11183 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11184 11185 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11186 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11187 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11188 return llvm::None; 11189 } 11190 11191 ComparisonResult TrueFlag, FalseFlag; 11192 if (Op == BO_EQ) { 11193 TrueFlag = EQ; 11194 FalseFlag = NE; 11195 } else if (Op == BO_NE) { 11196 TrueFlag = NE; 11197 FalseFlag = EQ; 11198 } else { 11199 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11200 TrueFlag = LT; 11201 FalseFlag = GE; 11202 } else { 11203 TrueFlag = GT; 11204 FalseFlag = LE; 11205 } 11206 if (Op == BO_GE || Op == BO_LE) 11207 std::swap(TrueFlag, FalseFlag); 11208 } 11209 if (R & TrueFlag) 11210 return StringRef("true"); 11211 if (R & FalseFlag) 11212 return StringRef("false"); 11213 return llvm::None; 11214 } 11215 }; 11216 } 11217 11218 static bool HasEnumType(Expr *E) { 11219 // Strip off implicit integral promotions. 11220 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11221 if (ICE->getCastKind() != CK_IntegralCast && 11222 ICE->getCastKind() != CK_NoOp) 11223 break; 11224 E = ICE->getSubExpr(); 11225 } 11226 11227 return E->getType()->isEnumeralType(); 11228 } 11229 11230 static int classifyConstantValue(Expr *Constant) { 11231 // The values of this enumeration are used in the diagnostics 11232 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11233 enum ConstantValueKind { 11234 Miscellaneous = 0, 11235 LiteralTrue, 11236 LiteralFalse 11237 }; 11238 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11239 return BL->getValue() ? ConstantValueKind::LiteralTrue 11240 : ConstantValueKind::LiteralFalse; 11241 return ConstantValueKind::Miscellaneous; 11242 } 11243 11244 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11245 Expr *Constant, Expr *Other, 11246 const llvm::APSInt &Value, 11247 bool RhsConstant) { 11248 if (S.inTemplateInstantiation()) 11249 return false; 11250 11251 Expr *OriginalOther = Other; 11252 11253 Constant = Constant->IgnoreParenImpCasts(); 11254 Other = Other->IgnoreParenImpCasts(); 11255 11256 // Suppress warnings on tautological comparisons between values of the same 11257 // enumeration type. There are only two ways we could warn on this: 11258 // - If the constant is outside the range of representable values of 11259 // the enumeration. In such a case, we should warn about the cast 11260 // to enumeration type, not about the comparison. 11261 // - If the constant is the maximum / minimum in-range value. For an 11262 // enumeratin type, such comparisons can be meaningful and useful. 11263 if (Constant->getType()->isEnumeralType() && 11264 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11265 return false; 11266 11267 IntRange OtherValueRange = GetExprRange( 11268 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11269 11270 QualType OtherT = Other->getType(); 11271 if (const auto *AT = OtherT->getAs<AtomicType>()) 11272 OtherT = AT->getValueType(); 11273 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11274 11275 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11276 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11277 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11278 S.NSAPIObj->isObjCBOOLType(OtherT) && 11279 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11280 11281 // Whether we're treating Other as being a bool because of the form of 11282 // expression despite it having another type (typically 'int' in C). 11283 bool OtherIsBooleanDespiteType = 11284 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11285 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11286 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11287 11288 // Check if all values in the range of possible values of this expression 11289 // lead to the same comparison outcome. 11290 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11291 Value.isUnsigned()); 11292 auto Cmp = OtherPromotedValueRange.compare(Value); 11293 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11294 if (!Result) 11295 return false; 11296 11297 // Also consider the range determined by the type alone. This allows us to 11298 // classify the warning under the proper diagnostic group. 11299 bool TautologicalTypeCompare = false; 11300 { 11301 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11302 Value.isUnsigned()); 11303 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11304 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11305 RhsConstant)) { 11306 TautologicalTypeCompare = true; 11307 Cmp = TypeCmp; 11308 Result = TypeResult; 11309 } 11310 } 11311 11312 // Don't warn if the non-constant operand actually always evaluates to the 11313 // same value. 11314 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11315 return false; 11316 11317 // Suppress the diagnostic for an in-range comparison if the constant comes 11318 // from a macro or enumerator. We don't want to diagnose 11319 // 11320 // some_long_value <= INT_MAX 11321 // 11322 // when sizeof(int) == sizeof(long). 11323 bool InRange = Cmp & PromotedRange::InRangeFlag; 11324 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11325 return false; 11326 11327 // A comparison of an unsigned bit-field against 0 is really a type problem, 11328 // even though at the type level the bit-field might promote to 'signed int'. 11329 if (Other->refersToBitField() && InRange && Value == 0 && 11330 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11331 TautologicalTypeCompare = true; 11332 11333 // If this is a comparison to an enum constant, include that 11334 // constant in the diagnostic. 11335 const EnumConstantDecl *ED = nullptr; 11336 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11337 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11338 11339 // Should be enough for uint128 (39 decimal digits) 11340 SmallString<64> PrettySourceValue; 11341 llvm::raw_svector_ostream OS(PrettySourceValue); 11342 if (ED) { 11343 OS << '\'' << *ED << "' (" << Value << ")"; 11344 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11345 Constant->IgnoreParenImpCasts())) { 11346 OS << (BL->getValue() ? "YES" : "NO"); 11347 } else { 11348 OS << Value; 11349 } 11350 11351 if (!TautologicalTypeCompare) { 11352 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11353 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11354 << E->getOpcodeStr() << OS.str() << *Result 11355 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11356 return true; 11357 } 11358 11359 if (IsObjCSignedCharBool) { 11360 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11361 S.PDiag(diag::warn_tautological_compare_objc_bool) 11362 << OS.str() << *Result); 11363 return true; 11364 } 11365 11366 // FIXME: We use a somewhat different formatting for the in-range cases and 11367 // cases involving boolean values for historical reasons. We should pick a 11368 // consistent way of presenting these diagnostics. 11369 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11370 11371 S.DiagRuntimeBehavior( 11372 E->getOperatorLoc(), E, 11373 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11374 : diag::warn_tautological_bool_compare) 11375 << OS.str() << classifyConstantValue(Constant) << OtherT 11376 << OtherIsBooleanDespiteType << *Result 11377 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11378 } else { 11379 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11380 ? (HasEnumType(OriginalOther) 11381 ? diag::warn_unsigned_enum_always_true_comparison 11382 : diag::warn_unsigned_always_true_comparison) 11383 : diag::warn_tautological_constant_compare; 11384 11385 S.Diag(E->getOperatorLoc(), Diag) 11386 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11387 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11388 } 11389 11390 return true; 11391 } 11392 11393 /// Analyze the operands of the given comparison. Implements the 11394 /// fallback case from AnalyzeComparison. 11395 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11396 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11397 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11398 } 11399 11400 /// Implements -Wsign-compare. 11401 /// 11402 /// \param E the binary operator to check for warnings 11403 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11404 // The type the comparison is being performed in. 11405 QualType T = E->getLHS()->getType(); 11406 11407 // Only analyze comparison operators where both sides have been converted to 11408 // the same type. 11409 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11410 return AnalyzeImpConvsInComparison(S, E); 11411 11412 // Don't analyze value-dependent comparisons directly. 11413 if (E->isValueDependent()) 11414 return AnalyzeImpConvsInComparison(S, E); 11415 11416 Expr *LHS = E->getLHS(); 11417 Expr *RHS = E->getRHS(); 11418 11419 if (T->isIntegralType(S.Context)) { 11420 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11421 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11422 11423 // We don't care about expressions whose result is a constant. 11424 if (RHSValue && LHSValue) 11425 return AnalyzeImpConvsInComparison(S, E); 11426 11427 // We only care about expressions where just one side is literal 11428 if ((bool)RHSValue ^ (bool)LHSValue) { 11429 // Is the constant on the RHS or LHS? 11430 const bool RhsConstant = (bool)RHSValue; 11431 Expr *Const = RhsConstant ? RHS : LHS; 11432 Expr *Other = RhsConstant ? LHS : RHS; 11433 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11434 11435 // Check whether an integer constant comparison results in a value 11436 // of 'true' or 'false'. 11437 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11438 return AnalyzeImpConvsInComparison(S, E); 11439 } 11440 } 11441 11442 if (!T->hasUnsignedIntegerRepresentation()) { 11443 // We don't do anything special if this isn't an unsigned integral 11444 // comparison: we're only interested in integral comparisons, and 11445 // signed comparisons only happen in cases we don't care to warn about. 11446 return AnalyzeImpConvsInComparison(S, E); 11447 } 11448 11449 LHS = LHS->IgnoreParenImpCasts(); 11450 RHS = RHS->IgnoreParenImpCasts(); 11451 11452 if (!S.getLangOpts().CPlusPlus) { 11453 // Avoid warning about comparison of integers with different signs when 11454 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11455 // the type of `E`. 11456 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11457 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11458 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11459 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11460 } 11461 11462 // Check to see if one of the (unmodified) operands is of different 11463 // signedness. 11464 Expr *signedOperand, *unsignedOperand; 11465 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11466 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11467 "unsigned comparison between two signed integer expressions?"); 11468 signedOperand = LHS; 11469 unsignedOperand = RHS; 11470 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11471 signedOperand = RHS; 11472 unsignedOperand = LHS; 11473 } else { 11474 return AnalyzeImpConvsInComparison(S, E); 11475 } 11476 11477 // Otherwise, calculate the effective range of the signed operand. 11478 IntRange signedRange = GetExprRange( 11479 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11480 11481 // Go ahead and analyze implicit conversions in the operands. Note 11482 // that we skip the implicit conversions on both sides. 11483 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11484 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11485 11486 // If the signed range is non-negative, -Wsign-compare won't fire. 11487 if (signedRange.NonNegative) 11488 return; 11489 11490 // For (in)equality comparisons, if the unsigned operand is a 11491 // constant which cannot collide with a overflowed signed operand, 11492 // then reinterpreting the signed operand as unsigned will not 11493 // change the result of the comparison. 11494 if (E->isEqualityOp()) { 11495 unsigned comparisonWidth = S.Context.getIntWidth(T); 11496 IntRange unsignedRange = 11497 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11498 /*Approximate*/ true); 11499 11500 // We should never be unable to prove that the unsigned operand is 11501 // non-negative. 11502 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11503 11504 if (unsignedRange.Width < comparisonWidth) 11505 return; 11506 } 11507 11508 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11509 S.PDiag(diag::warn_mixed_sign_comparison) 11510 << LHS->getType() << RHS->getType() 11511 << LHS->getSourceRange() << RHS->getSourceRange()); 11512 } 11513 11514 /// Analyzes an attempt to assign the given value to a bitfield. 11515 /// 11516 /// Returns true if there was something fishy about the attempt. 11517 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11518 SourceLocation InitLoc) { 11519 assert(Bitfield->isBitField()); 11520 if (Bitfield->isInvalidDecl()) 11521 return false; 11522 11523 // White-list bool bitfields. 11524 QualType BitfieldType = Bitfield->getType(); 11525 if (BitfieldType->isBooleanType()) 11526 return false; 11527 11528 if (BitfieldType->isEnumeralType()) { 11529 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11530 // If the underlying enum type was not explicitly specified as an unsigned 11531 // type and the enum contain only positive values, MSVC++ will cause an 11532 // inconsistency by storing this as a signed type. 11533 if (S.getLangOpts().CPlusPlus11 && 11534 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11535 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11536 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11537 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11538 << BitfieldEnumDecl; 11539 } 11540 } 11541 11542 if (Bitfield->getType()->isBooleanType()) 11543 return false; 11544 11545 // Ignore value- or type-dependent expressions. 11546 if (Bitfield->getBitWidth()->isValueDependent() || 11547 Bitfield->getBitWidth()->isTypeDependent() || 11548 Init->isValueDependent() || 11549 Init->isTypeDependent()) 11550 return false; 11551 11552 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11553 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11554 11555 Expr::EvalResult Result; 11556 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11557 Expr::SE_AllowSideEffects)) { 11558 // The RHS is not constant. If the RHS has an enum type, make sure the 11559 // bitfield is wide enough to hold all the values of the enum without 11560 // truncation. 11561 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11562 EnumDecl *ED = EnumTy->getDecl(); 11563 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11564 11565 // Enum types are implicitly signed on Windows, so check if there are any 11566 // negative enumerators to see if the enum was intended to be signed or 11567 // not. 11568 bool SignedEnum = ED->getNumNegativeBits() > 0; 11569 11570 // Check for surprising sign changes when assigning enum values to a 11571 // bitfield of different signedness. If the bitfield is signed and we 11572 // have exactly the right number of bits to store this unsigned enum, 11573 // suggest changing the enum to an unsigned type. This typically happens 11574 // on Windows where unfixed enums always use an underlying type of 'int'. 11575 unsigned DiagID = 0; 11576 if (SignedEnum && !SignedBitfield) { 11577 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11578 } else if (SignedBitfield && !SignedEnum && 11579 ED->getNumPositiveBits() == FieldWidth) { 11580 DiagID = diag::warn_signed_bitfield_enum_conversion; 11581 } 11582 11583 if (DiagID) { 11584 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11585 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11586 SourceRange TypeRange = 11587 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11588 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11589 << SignedEnum << TypeRange; 11590 } 11591 11592 // Compute the required bitwidth. If the enum has negative values, we need 11593 // one more bit than the normal number of positive bits to represent the 11594 // sign bit. 11595 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11596 ED->getNumNegativeBits()) 11597 : ED->getNumPositiveBits(); 11598 11599 // Check the bitwidth. 11600 if (BitsNeeded > FieldWidth) { 11601 Expr *WidthExpr = Bitfield->getBitWidth(); 11602 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11603 << Bitfield << ED; 11604 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11605 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11606 } 11607 } 11608 11609 return false; 11610 } 11611 11612 llvm::APSInt Value = Result.Val.getInt(); 11613 11614 unsigned OriginalWidth = Value.getBitWidth(); 11615 11616 if (!Value.isSigned() || Value.isNegative()) 11617 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11618 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11619 OriginalWidth = Value.getMinSignedBits(); 11620 11621 if (OriginalWidth <= FieldWidth) 11622 return false; 11623 11624 // Compute the value which the bitfield will contain. 11625 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11626 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11627 11628 // Check whether the stored value is equal to the original value. 11629 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11630 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11631 return false; 11632 11633 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11634 // therefore don't strictly fit into a signed bitfield of width 1. 11635 if (FieldWidth == 1 && Value == 1) 11636 return false; 11637 11638 std::string PrettyValue = Value.toString(10); 11639 std::string PrettyTrunc = TruncatedValue.toString(10); 11640 11641 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11642 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11643 << Init->getSourceRange(); 11644 11645 return true; 11646 } 11647 11648 /// Analyze the given simple or compound assignment for warning-worthy 11649 /// operations. 11650 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11651 // Just recurse on the LHS. 11652 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11653 11654 // We want to recurse on the RHS as normal unless we're assigning to 11655 // a bitfield. 11656 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11657 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11658 E->getOperatorLoc())) { 11659 // Recurse, ignoring any implicit conversions on the RHS. 11660 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11661 E->getOperatorLoc()); 11662 } 11663 } 11664 11665 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11666 11667 // Diagnose implicitly sequentially-consistent atomic assignment. 11668 if (E->getLHS()->getType()->isAtomicType()) 11669 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11670 } 11671 11672 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11673 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11674 SourceLocation CContext, unsigned diag, 11675 bool pruneControlFlow = false) { 11676 if (pruneControlFlow) { 11677 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11678 S.PDiag(diag) 11679 << SourceType << T << E->getSourceRange() 11680 << SourceRange(CContext)); 11681 return; 11682 } 11683 S.Diag(E->getExprLoc(), diag) 11684 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11685 } 11686 11687 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11688 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11689 SourceLocation CContext, 11690 unsigned diag, bool pruneControlFlow = false) { 11691 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11692 } 11693 11694 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11695 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11696 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11697 } 11698 11699 static void adornObjCBoolConversionDiagWithTernaryFixit( 11700 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11701 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11702 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11703 Ignored = OVE->getSourceExpr(); 11704 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11705 isa<BinaryOperator>(Ignored) || 11706 isa<CXXOperatorCallExpr>(Ignored); 11707 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11708 if (NeedsParens) 11709 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11710 << FixItHint::CreateInsertion(EndLoc, ")"); 11711 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11712 } 11713 11714 /// Diagnose an implicit cast from a floating point value to an integer value. 11715 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11716 SourceLocation CContext) { 11717 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11718 const bool PruneWarnings = S.inTemplateInstantiation(); 11719 11720 Expr *InnerE = E->IgnoreParenImpCasts(); 11721 // We also want to warn on, e.g., "int i = -1.234" 11722 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11723 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11724 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11725 11726 const bool IsLiteral = 11727 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11728 11729 llvm::APFloat Value(0.0); 11730 bool IsConstant = 11731 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11732 if (!IsConstant) { 11733 if (isObjCSignedCharBool(S, T)) { 11734 return adornObjCBoolConversionDiagWithTernaryFixit( 11735 S, E, 11736 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11737 << E->getType()); 11738 } 11739 11740 return DiagnoseImpCast(S, E, T, CContext, 11741 diag::warn_impcast_float_integer, PruneWarnings); 11742 } 11743 11744 bool isExact = false; 11745 11746 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11747 T->hasUnsignedIntegerRepresentation()); 11748 llvm::APFloat::opStatus Result = Value.convertToInteger( 11749 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11750 11751 // FIXME: Force the precision of the source value down so we don't print 11752 // digits which are usually useless (we don't really care here if we 11753 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11754 // would automatically print the shortest representation, but it's a bit 11755 // tricky to implement. 11756 SmallString<16> PrettySourceValue; 11757 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11758 precision = (precision * 59 + 195) / 196; 11759 Value.toString(PrettySourceValue, precision); 11760 11761 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11762 return adornObjCBoolConversionDiagWithTernaryFixit( 11763 S, E, 11764 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11765 << PrettySourceValue); 11766 } 11767 11768 if (Result == llvm::APFloat::opOK && isExact) { 11769 if (IsLiteral) return; 11770 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11771 PruneWarnings); 11772 } 11773 11774 // Conversion of a floating-point value to a non-bool integer where the 11775 // integral part cannot be represented by the integer type is undefined. 11776 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11777 return DiagnoseImpCast( 11778 S, E, T, CContext, 11779 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11780 : diag::warn_impcast_float_to_integer_out_of_range, 11781 PruneWarnings); 11782 11783 unsigned DiagID = 0; 11784 if (IsLiteral) { 11785 // Warn on floating point literal to integer. 11786 DiagID = diag::warn_impcast_literal_float_to_integer; 11787 } else if (IntegerValue == 0) { 11788 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11789 return DiagnoseImpCast(S, E, T, CContext, 11790 diag::warn_impcast_float_integer, PruneWarnings); 11791 } 11792 // Warn on non-zero to zero conversion. 11793 DiagID = diag::warn_impcast_float_to_integer_zero; 11794 } else { 11795 if (IntegerValue.isUnsigned()) { 11796 if (!IntegerValue.isMaxValue()) { 11797 return DiagnoseImpCast(S, E, T, CContext, 11798 diag::warn_impcast_float_integer, PruneWarnings); 11799 } 11800 } else { // IntegerValue.isSigned() 11801 if (!IntegerValue.isMaxSignedValue() && 11802 !IntegerValue.isMinSignedValue()) { 11803 return DiagnoseImpCast(S, E, T, CContext, 11804 diag::warn_impcast_float_integer, PruneWarnings); 11805 } 11806 } 11807 // Warn on evaluatable floating point expression to integer conversion. 11808 DiagID = diag::warn_impcast_float_to_integer; 11809 } 11810 11811 SmallString<16> PrettyTargetValue; 11812 if (IsBool) 11813 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11814 else 11815 IntegerValue.toString(PrettyTargetValue); 11816 11817 if (PruneWarnings) { 11818 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11819 S.PDiag(DiagID) 11820 << E->getType() << T.getUnqualifiedType() 11821 << PrettySourceValue << PrettyTargetValue 11822 << E->getSourceRange() << SourceRange(CContext)); 11823 } else { 11824 S.Diag(E->getExprLoc(), DiagID) 11825 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11826 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11827 } 11828 } 11829 11830 /// Analyze the given compound assignment for the possible losing of 11831 /// floating-point precision. 11832 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11833 assert(isa<CompoundAssignOperator>(E) && 11834 "Must be compound assignment operation"); 11835 // Recurse on the LHS and RHS in here 11836 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11837 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11838 11839 if (E->getLHS()->getType()->isAtomicType()) 11840 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11841 11842 // Now check the outermost expression 11843 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11844 const auto *RBT = cast<CompoundAssignOperator>(E) 11845 ->getComputationResultType() 11846 ->getAs<BuiltinType>(); 11847 11848 // The below checks assume source is floating point. 11849 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11850 11851 // If source is floating point but target is an integer. 11852 if (ResultBT->isInteger()) 11853 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11854 E->getExprLoc(), diag::warn_impcast_float_integer); 11855 11856 if (!ResultBT->isFloatingPoint()) 11857 return; 11858 11859 // If both source and target are floating points, warn about losing precision. 11860 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11861 QualType(ResultBT, 0), QualType(RBT, 0)); 11862 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11863 // warn about dropping FP rank. 11864 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11865 diag::warn_impcast_float_result_precision); 11866 } 11867 11868 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11869 IntRange Range) { 11870 if (!Range.Width) return "0"; 11871 11872 llvm::APSInt ValueInRange = Value; 11873 ValueInRange.setIsSigned(!Range.NonNegative); 11874 ValueInRange = ValueInRange.trunc(Range.Width); 11875 return ValueInRange.toString(10); 11876 } 11877 11878 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11879 if (!isa<ImplicitCastExpr>(Ex)) 11880 return false; 11881 11882 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11883 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11884 const Type *Source = 11885 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11886 if (Target->isDependentType()) 11887 return false; 11888 11889 const BuiltinType *FloatCandidateBT = 11890 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11891 const Type *BoolCandidateType = ToBool ? Target : Source; 11892 11893 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11894 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11895 } 11896 11897 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11898 SourceLocation CC) { 11899 unsigned NumArgs = TheCall->getNumArgs(); 11900 for (unsigned i = 0; i < NumArgs; ++i) { 11901 Expr *CurrA = TheCall->getArg(i); 11902 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11903 continue; 11904 11905 bool IsSwapped = ((i > 0) && 11906 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11907 IsSwapped |= ((i < (NumArgs - 1)) && 11908 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11909 if (IsSwapped) { 11910 // Warn on this floating-point to bool conversion. 11911 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11912 CurrA->getType(), CC, 11913 diag::warn_impcast_floating_point_to_bool); 11914 } 11915 } 11916 } 11917 11918 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11919 SourceLocation CC) { 11920 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11921 E->getExprLoc())) 11922 return; 11923 11924 // Don't warn on functions which have return type nullptr_t. 11925 if (isa<CallExpr>(E)) 11926 return; 11927 11928 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11929 const Expr::NullPointerConstantKind NullKind = 11930 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11931 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11932 return; 11933 11934 // Return if target type is a safe conversion. 11935 if (T->isAnyPointerType() || T->isBlockPointerType() || 11936 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11937 return; 11938 11939 SourceLocation Loc = E->getSourceRange().getBegin(); 11940 11941 // Venture through the macro stacks to get to the source of macro arguments. 11942 // The new location is a better location than the complete location that was 11943 // passed in. 11944 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11945 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11946 11947 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11948 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11949 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11950 Loc, S.SourceMgr, S.getLangOpts()); 11951 if (MacroName == "NULL") 11952 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11953 } 11954 11955 // Only warn if the null and context location are in the same macro expansion. 11956 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11957 return; 11958 11959 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11960 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11961 << FixItHint::CreateReplacement(Loc, 11962 S.getFixItZeroLiteralForType(T, Loc)); 11963 } 11964 11965 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11966 ObjCArrayLiteral *ArrayLiteral); 11967 11968 static void 11969 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11970 ObjCDictionaryLiteral *DictionaryLiteral); 11971 11972 /// Check a single element within a collection literal against the 11973 /// target element type. 11974 static void checkObjCCollectionLiteralElement(Sema &S, 11975 QualType TargetElementType, 11976 Expr *Element, 11977 unsigned ElementKind) { 11978 // Skip a bitcast to 'id' or qualified 'id'. 11979 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11980 if (ICE->getCastKind() == CK_BitCast && 11981 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11982 Element = ICE->getSubExpr(); 11983 } 11984 11985 QualType ElementType = Element->getType(); 11986 ExprResult ElementResult(Element); 11987 if (ElementType->getAs<ObjCObjectPointerType>() && 11988 S.CheckSingleAssignmentConstraints(TargetElementType, 11989 ElementResult, 11990 false, false) 11991 != Sema::Compatible) { 11992 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11993 << ElementType << ElementKind << TargetElementType 11994 << Element->getSourceRange(); 11995 } 11996 11997 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11998 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11999 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12000 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12001 } 12002 12003 /// Check an Objective-C array literal being converted to the given 12004 /// target type. 12005 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12006 ObjCArrayLiteral *ArrayLiteral) { 12007 if (!S.NSArrayDecl) 12008 return; 12009 12010 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12011 if (!TargetObjCPtr) 12012 return; 12013 12014 if (TargetObjCPtr->isUnspecialized() || 12015 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12016 != S.NSArrayDecl->getCanonicalDecl()) 12017 return; 12018 12019 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12020 if (TypeArgs.size() != 1) 12021 return; 12022 12023 QualType TargetElementType = TypeArgs[0]; 12024 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12025 checkObjCCollectionLiteralElement(S, TargetElementType, 12026 ArrayLiteral->getElement(I), 12027 0); 12028 } 12029 } 12030 12031 /// Check an Objective-C dictionary literal being converted to the given 12032 /// target type. 12033 static void 12034 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12035 ObjCDictionaryLiteral *DictionaryLiteral) { 12036 if (!S.NSDictionaryDecl) 12037 return; 12038 12039 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12040 if (!TargetObjCPtr) 12041 return; 12042 12043 if (TargetObjCPtr->isUnspecialized() || 12044 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12045 != S.NSDictionaryDecl->getCanonicalDecl()) 12046 return; 12047 12048 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12049 if (TypeArgs.size() != 2) 12050 return; 12051 12052 QualType TargetKeyType = TypeArgs[0]; 12053 QualType TargetObjectType = TypeArgs[1]; 12054 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12055 auto Element = DictionaryLiteral->getKeyValueElement(I); 12056 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12057 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12058 } 12059 } 12060 12061 // Helper function to filter out cases for constant width constant conversion. 12062 // Don't warn on char array initialization or for non-decimal values. 12063 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12064 SourceLocation CC) { 12065 // If initializing from a constant, and the constant starts with '0', 12066 // then it is a binary, octal, or hexadecimal. Allow these constants 12067 // to fill all the bits, even if there is a sign change. 12068 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12069 const char FirstLiteralCharacter = 12070 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12071 if (FirstLiteralCharacter == '0') 12072 return false; 12073 } 12074 12075 // If the CC location points to a '{', and the type is char, then assume 12076 // assume it is an array initialization. 12077 if (CC.isValid() && T->isCharType()) { 12078 const char FirstContextCharacter = 12079 S.getSourceManager().getCharacterData(CC)[0]; 12080 if (FirstContextCharacter == '{') 12081 return false; 12082 } 12083 12084 return true; 12085 } 12086 12087 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12088 const auto *IL = dyn_cast<IntegerLiteral>(E); 12089 if (!IL) { 12090 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12091 if (UO->getOpcode() == UO_Minus) 12092 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12093 } 12094 } 12095 12096 return IL; 12097 } 12098 12099 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12100 E = E->IgnoreParenImpCasts(); 12101 SourceLocation ExprLoc = E->getExprLoc(); 12102 12103 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12104 BinaryOperator::Opcode Opc = BO->getOpcode(); 12105 Expr::EvalResult Result; 12106 // Do not diagnose unsigned shifts. 12107 if (Opc == BO_Shl) { 12108 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12109 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12110 if (LHS && LHS->getValue() == 0) 12111 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12112 else if (!E->isValueDependent() && LHS && RHS && 12113 RHS->getValue().isNonNegative() && 12114 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12115 S.Diag(ExprLoc, diag::warn_left_shift_always) 12116 << (Result.Val.getInt() != 0); 12117 else if (E->getType()->isSignedIntegerType()) 12118 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12119 } 12120 } 12121 12122 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12123 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12124 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12125 if (!LHS || !RHS) 12126 return; 12127 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12128 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12129 // Do not diagnose common idioms. 12130 return; 12131 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12132 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12133 } 12134 } 12135 12136 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12137 SourceLocation CC, 12138 bool *ICContext = nullptr, 12139 bool IsListInit = false) { 12140 if (E->isTypeDependent() || E->isValueDependent()) return; 12141 12142 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12143 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12144 if (Source == Target) return; 12145 if (Target->isDependentType()) return; 12146 12147 // If the conversion context location is invalid don't complain. We also 12148 // don't want to emit a warning if the issue occurs from the expansion of 12149 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12150 // delay this check as long as possible. Once we detect we are in that 12151 // scenario, we just return. 12152 if (CC.isInvalid()) 12153 return; 12154 12155 if (Source->isAtomicType()) 12156 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12157 12158 // Diagnose implicit casts to bool. 12159 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12160 if (isa<StringLiteral>(E)) 12161 // Warn on string literal to bool. Checks for string literals in logical 12162 // and expressions, for instance, assert(0 && "error here"), are 12163 // prevented by a check in AnalyzeImplicitConversions(). 12164 return DiagnoseImpCast(S, E, T, CC, 12165 diag::warn_impcast_string_literal_to_bool); 12166 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12167 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12168 // This covers the literal expressions that evaluate to Objective-C 12169 // objects. 12170 return DiagnoseImpCast(S, E, T, CC, 12171 diag::warn_impcast_objective_c_literal_to_bool); 12172 } 12173 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12174 // Warn on pointer to bool conversion that is always true. 12175 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12176 SourceRange(CC)); 12177 } 12178 } 12179 12180 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12181 // is a typedef for signed char (macOS), then that constant value has to be 1 12182 // or 0. 12183 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12184 Expr::EvalResult Result; 12185 if (E->EvaluateAsInt(Result, S.getASTContext(), 12186 Expr::SE_AllowSideEffects)) { 12187 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12188 adornObjCBoolConversionDiagWithTernaryFixit( 12189 S, E, 12190 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12191 << Result.Val.getInt().toString(10)); 12192 } 12193 return; 12194 } 12195 } 12196 12197 // Check implicit casts from Objective-C collection literals to specialized 12198 // collection types, e.g., NSArray<NSString *> *. 12199 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12200 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12201 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12202 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12203 12204 // Strip vector types. 12205 if (const auto *SourceVT = dyn_cast<VectorType>(Source)) { 12206 if (Target->isVLSTBuiltinType()) { 12207 auto SourceVectorKind = SourceVT->getVectorKind(); 12208 if (SourceVectorKind == VectorType::SveFixedLengthDataVector || 12209 SourceVectorKind == VectorType::SveFixedLengthPredicateVector || 12210 (SourceVectorKind == VectorType::GenericVector && 12211 S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits)) 12212 return; 12213 } 12214 12215 if (!isa<VectorType>(Target)) { 12216 if (S.SourceMgr.isInSystemMacro(CC)) 12217 return; 12218 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12219 } 12220 12221 // If the vector cast is cast between two vectors of the same size, it is 12222 // a bitcast, not a conversion. 12223 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12224 return; 12225 12226 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12227 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12228 } 12229 if (auto VecTy = dyn_cast<VectorType>(Target)) 12230 Target = VecTy->getElementType().getTypePtr(); 12231 12232 // Strip complex types. 12233 if (isa<ComplexType>(Source)) { 12234 if (!isa<ComplexType>(Target)) { 12235 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12236 return; 12237 12238 return DiagnoseImpCast(S, E, T, CC, 12239 S.getLangOpts().CPlusPlus 12240 ? diag::err_impcast_complex_scalar 12241 : diag::warn_impcast_complex_scalar); 12242 } 12243 12244 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12245 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12246 } 12247 12248 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12249 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12250 12251 // If the source is floating point... 12252 if (SourceBT && SourceBT->isFloatingPoint()) { 12253 // ...and the target is floating point... 12254 if (TargetBT && TargetBT->isFloatingPoint()) { 12255 // ...then warn if we're dropping FP rank. 12256 12257 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12258 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12259 if (Order > 0) { 12260 // Don't warn about float constants that are precisely 12261 // representable in the target type. 12262 Expr::EvalResult result; 12263 if (E->EvaluateAsRValue(result, S.Context)) { 12264 // Value might be a float, a float vector, or a float complex. 12265 if (IsSameFloatAfterCast(result.Val, 12266 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12267 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12268 return; 12269 } 12270 12271 if (S.SourceMgr.isInSystemMacro(CC)) 12272 return; 12273 12274 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12275 } 12276 // ... or possibly if we're increasing rank, too 12277 else if (Order < 0) { 12278 if (S.SourceMgr.isInSystemMacro(CC)) 12279 return; 12280 12281 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12282 } 12283 return; 12284 } 12285 12286 // If the target is integral, always warn. 12287 if (TargetBT && TargetBT->isInteger()) { 12288 if (S.SourceMgr.isInSystemMacro(CC)) 12289 return; 12290 12291 DiagnoseFloatingImpCast(S, E, T, CC); 12292 } 12293 12294 // Detect the case where a call result is converted from floating-point to 12295 // to bool, and the final argument to the call is converted from bool, to 12296 // discover this typo: 12297 // 12298 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12299 // 12300 // FIXME: This is an incredibly special case; is there some more general 12301 // way to detect this class of misplaced-parentheses bug? 12302 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12303 // Check last argument of function call to see if it is an 12304 // implicit cast from a type matching the type the result 12305 // is being cast to. 12306 CallExpr *CEx = cast<CallExpr>(E); 12307 if (unsigned NumArgs = CEx->getNumArgs()) { 12308 Expr *LastA = CEx->getArg(NumArgs - 1); 12309 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12310 if (isa<ImplicitCastExpr>(LastA) && 12311 InnerE->getType()->isBooleanType()) { 12312 // Warn on this floating-point to bool conversion 12313 DiagnoseImpCast(S, E, T, CC, 12314 diag::warn_impcast_floating_point_to_bool); 12315 } 12316 } 12317 } 12318 return; 12319 } 12320 12321 // Valid casts involving fixed point types should be accounted for here. 12322 if (Source->isFixedPointType()) { 12323 if (Target->isUnsaturatedFixedPointType()) { 12324 Expr::EvalResult Result; 12325 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12326 S.isConstantEvaluated())) { 12327 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12328 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12329 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12330 if (Value > MaxVal || Value < MinVal) { 12331 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12332 S.PDiag(diag::warn_impcast_fixed_point_range) 12333 << Value.toString() << T 12334 << E->getSourceRange() 12335 << clang::SourceRange(CC)); 12336 return; 12337 } 12338 } 12339 } else if (Target->isIntegerType()) { 12340 Expr::EvalResult Result; 12341 if (!S.isConstantEvaluated() && 12342 E->EvaluateAsFixedPoint(Result, S.Context, 12343 Expr::SE_AllowSideEffects)) { 12344 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12345 12346 bool Overflowed; 12347 llvm::APSInt IntResult = FXResult.convertToInt( 12348 S.Context.getIntWidth(T), 12349 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12350 12351 if (Overflowed) { 12352 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12353 S.PDiag(diag::warn_impcast_fixed_point_range) 12354 << FXResult.toString() << T 12355 << E->getSourceRange() 12356 << clang::SourceRange(CC)); 12357 return; 12358 } 12359 } 12360 } 12361 } else if (Target->isUnsaturatedFixedPointType()) { 12362 if (Source->isIntegerType()) { 12363 Expr::EvalResult Result; 12364 if (!S.isConstantEvaluated() && 12365 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12366 llvm::APSInt Value = Result.Val.getInt(); 12367 12368 bool Overflowed; 12369 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12370 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12371 12372 if (Overflowed) { 12373 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12374 S.PDiag(diag::warn_impcast_fixed_point_range) 12375 << Value.toString(/*Radix=*/10) << T 12376 << E->getSourceRange() 12377 << clang::SourceRange(CC)); 12378 return; 12379 } 12380 } 12381 } 12382 } 12383 12384 // If we are casting an integer type to a floating point type without 12385 // initialization-list syntax, we might lose accuracy if the floating 12386 // point type has a narrower significand than the integer type. 12387 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12388 TargetBT->isFloatingType() && !IsListInit) { 12389 // Determine the number of precision bits in the source integer type. 12390 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12391 /*Approximate*/ true); 12392 unsigned int SourcePrecision = SourceRange.Width; 12393 12394 // Determine the number of precision bits in the 12395 // target floating point type. 12396 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12397 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12398 12399 if (SourcePrecision > 0 && TargetPrecision > 0 && 12400 SourcePrecision > TargetPrecision) { 12401 12402 if (Optional<llvm::APSInt> SourceInt = 12403 E->getIntegerConstantExpr(S.Context)) { 12404 // If the source integer is a constant, convert it to the target 12405 // floating point type. Issue a warning if the value changes 12406 // during the whole conversion. 12407 llvm::APFloat TargetFloatValue( 12408 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12409 llvm::APFloat::opStatus ConversionStatus = 12410 TargetFloatValue.convertFromAPInt( 12411 *SourceInt, SourceBT->isSignedInteger(), 12412 llvm::APFloat::rmNearestTiesToEven); 12413 12414 if (ConversionStatus != llvm::APFloat::opOK) { 12415 std::string PrettySourceValue = SourceInt->toString(10); 12416 SmallString<32> PrettyTargetValue; 12417 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12418 12419 S.DiagRuntimeBehavior( 12420 E->getExprLoc(), E, 12421 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12422 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12423 << E->getSourceRange() << clang::SourceRange(CC)); 12424 } 12425 } else { 12426 // Otherwise, the implicit conversion may lose precision. 12427 DiagnoseImpCast(S, E, T, CC, 12428 diag::warn_impcast_integer_float_precision); 12429 } 12430 } 12431 } 12432 12433 DiagnoseNullConversion(S, E, T, CC); 12434 12435 S.DiscardMisalignedMemberAddress(Target, E); 12436 12437 if (Target->isBooleanType()) 12438 DiagnoseIntInBoolContext(S, E); 12439 12440 if (!Source->isIntegerType() || !Target->isIntegerType()) 12441 return; 12442 12443 // TODO: remove this early return once the false positives for constant->bool 12444 // in templates, macros, etc, are reduced or removed. 12445 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12446 return; 12447 12448 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12449 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12450 return adornObjCBoolConversionDiagWithTernaryFixit( 12451 S, E, 12452 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12453 << E->getType()); 12454 } 12455 12456 IntRange SourceTypeRange = 12457 IntRange::forTargetOfCanonicalType(S.Context, Source); 12458 IntRange LikelySourceRange = 12459 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12460 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12461 12462 if (LikelySourceRange.Width > TargetRange.Width) { 12463 // If the source is a constant, use a default-on diagnostic. 12464 // TODO: this should happen for bitfield stores, too. 12465 Expr::EvalResult Result; 12466 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12467 S.isConstantEvaluated())) { 12468 llvm::APSInt Value(32); 12469 Value = Result.Val.getInt(); 12470 12471 if (S.SourceMgr.isInSystemMacro(CC)) 12472 return; 12473 12474 std::string PrettySourceValue = Value.toString(10); 12475 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12476 12477 S.DiagRuntimeBehavior( 12478 E->getExprLoc(), E, 12479 S.PDiag(diag::warn_impcast_integer_precision_constant) 12480 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12481 << E->getSourceRange() << SourceRange(CC)); 12482 return; 12483 } 12484 12485 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12486 if (S.SourceMgr.isInSystemMacro(CC)) 12487 return; 12488 12489 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12490 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12491 /* pruneControlFlow */ true); 12492 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12493 } 12494 12495 if (TargetRange.Width > SourceTypeRange.Width) { 12496 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12497 if (UO->getOpcode() == UO_Minus) 12498 if (Source->isUnsignedIntegerType()) { 12499 if (Target->isUnsignedIntegerType()) 12500 return DiagnoseImpCast(S, E, T, CC, 12501 diag::warn_impcast_high_order_zero_bits); 12502 if (Target->isSignedIntegerType()) 12503 return DiagnoseImpCast(S, E, T, CC, 12504 diag::warn_impcast_nonnegative_result); 12505 } 12506 } 12507 12508 if (TargetRange.Width == LikelySourceRange.Width && 12509 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12510 Source->isSignedIntegerType()) { 12511 // Warn when doing a signed to signed conversion, warn if the positive 12512 // source value is exactly the width of the target type, which will 12513 // cause a negative value to be stored. 12514 12515 Expr::EvalResult Result; 12516 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12517 !S.SourceMgr.isInSystemMacro(CC)) { 12518 llvm::APSInt Value = Result.Val.getInt(); 12519 if (isSameWidthConstantConversion(S, E, T, CC)) { 12520 std::string PrettySourceValue = Value.toString(10); 12521 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12522 12523 S.DiagRuntimeBehavior( 12524 E->getExprLoc(), E, 12525 S.PDiag(diag::warn_impcast_integer_precision_constant) 12526 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12527 << E->getSourceRange() << SourceRange(CC)); 12528 return; 12529 } 12530 } 12531 12532 // Fall through for non-constants to give a sign conversion warning. 12533 } 12534 12535 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12536 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12537 LikelySourceRange.Width == TargetRange.Width)) { 12538 if (S.SourceMgr.isInSystemMacro(CC)) 12539 return; 12540 12541 unsigned DiagID = diag::warn_impcast_integer_sign; 12542 12543 // Traditionally, gcc has warned about this under -Wsign-compare. 12544 // We also want to warn about it in -Wconversion. 12545 // So if -Wconversion is off, use a completely identical diagnostic 12546 // in the sign-compare group. 12547 // The conditional-checking code will 12548 if (ICContext) { 12549 DiagID = diag::warn_impcast_integer_sign_conditional; 12550 *ICContext = true; 12551 } 12552 12553 return DiagnoseImpCast(S, E, T, CC, DiagID); 12554 } 12555 12556 // Diagnose conversions between different enumeration types. 12557 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12558 // type, to give us better diagnostics. 12559 QualType SourceType = E->getType(); 12560 if (!S.getLangOpts().CPlusPlus) { 12561 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12562 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12563 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12564 SourceType = S.Context.getTypeDeclType(Enum); 12565 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12566 } 12567 } 12568 12569 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12570 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12571 if (SourceEnum->getDecl()->hasNameForLinkage() && 12572 TargetEnum->getDecl()->hasNameForLinkage() && 12573 SourceEnum != TargetEnum) { 12574 if (S.SourceMgr.isInSystemMacro(CC)) 12575 return; 12576 12577 return DiagnoseImpCast(S, E, SourceType, T, CC, 12578 diag::warn_impcast_different_enum_types); 12579 } 12580 } 12581 12582 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12583 SourceLocation CC, QualType T); 12584 12585 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12586 SourceLocation CC, bool &ICContext) { 12587 E = E->IgnoreParenImpCasts(); 12588 12589 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12590 return CheckConditionalOperator(S, CO, CC, T); 12591 12592 AnalyzeImplicitConversions(S, E, CC); 12593 if (E->getType() != T) 12594 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12595 } 12596 12597 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12598 SourceLocation CC, QualType T) { 12599 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12600 12601 Expr *TrueExpr = E->getTrueExpr(); 12602 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12603 TrueExpr = BCO->getCommon(); 12604 12605 bool Suspicious = false; 12606 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12607 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12608 12609 if (T->isBooleanType()) 12610 DiagnoseIntInBoolContext(S, E); 12611 12612 // If -Wconversion would have warned about either of the candidates 12613 // for a signedness conversion to the context type... 12614 if (!Suspicious) return; 12615 12616 // ...but it's currently ignored... 12617 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12618 return; 12619 12620 // ...then check whether it would have warned about either of the 12621 // candidates for a signedness conversion to the condition type. 12622 if (E->getType() == T) return; 12623 12624 Suspicious = false; 12625 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12626 E->getType(), CC, &Suspicious); 12627 if (!Suspicious) 12628 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12629 E->getType(), CC, &Suspicious); 12630 } 12631 12632 /// Check conversion of given expression to boolean. 12633 /// Input argument E is a logical expression. 12634 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12635 if (S.getLangOpts().Bool) 12636 return; 12637 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12638 return; 12639 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12640 } 12641 12642 namespace { 12643 struct AnalyzeImplicitConversionsWorkItem { 12644 Expr *E; 12645 SourceLocation CC; 12646 bool IsListInit; 12647 }; 12648 } 12649 12650 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12651 /// that should be visited are added to WorkList. 12652 static void AnalyzeImplicitConversions( 12653 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12654 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12655 Expr *OrigE = Item.E; 12656 SourceLocation CC = Item.CC; 12657 12658 QualType T = OrigE->getType(); 12659 Expr *E = OrigE->IgnoreParenImpCasts(); 12660 12661 // Propagate whether we are in a C++ list initialization expression. 12662 // If so, we do not issue warnings for implicit int-float conversion 12663 // precision loss, because C++11 narrowing already handles it. 12664 bool IsListInit = Item.IsListInit || 12665 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12666 12667 if (E->isTypeDependent() || E->isValueDependent()) 12668 return; 12669 12670 Expr *SourceExpr = E; 12671 // Examine, but don't traverse into the source expression of an 12672 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12673 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12674 // evaluate it in the context of checking the specific conversion to T though. 12675 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12676 if (auto *Src = OVE->getSourceExpr()) 12677 SourceExpr = Src; 12678 12679 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12680 if (UO->getOpcode() == UO_Not && 12681 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12682 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12683 << OrigE->getSourceRange() << T->isBooleanType() 12684 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12685 12686 // For conditional operators, we analyze the arguments as if they 12687 // were being fed directly into the output. 12688 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12689 CheckConditionalOperator(S, CO, CC, T); 12690 return; 12691 } 12692 12693 // Check implicit argument conversions for function calls. 12694 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12695 CheckImplicitArgumentConversions(S, Call, CC); 12696 12697 // Go ahead and check any implicit conversions we might have skipped. 12698 // The non-canonical typecheck is just an optimization; 12699 // CheckImplicitConversion will filter out dead implicit conversions. 12700 if (SourceExpr->getType() != T) 12701 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12702 12703 // Now continue drilling into this expression. 12704 12705 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12706 // The bound subexpressions in a PseudoObjectExpr are not reachable 12707 // as transitive children. 12708 // FIXME: Use a more uniform representation for this. 12709 for (auto *SE : POE->semantics()) 12710 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12711 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12712 } 12713 12714 // Skip past explicit casts. 12715 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12716 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12717 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12718 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12719 WorkList.push_back({E, CC, IsListInit}); 12720 return; 12721 } 12722 12723 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12724 // Do a somewhat different check with comparison operators. 12725 if (BO->isComparisonOp()) 12726 return AnalyzeComparison(S, BO); 12727 12728 // And with simple assignments. 12729 if (BO->getOpcode() == BO_Assign) 12730 return AnalyzeAssignment(S, BO); 12731 // And with compound assignments. 12732 if (BO->isAssignmentOp()) 12733 return AnalyzeCompoundAssignment(S, BO); 12734 } 12735 12736 // These break the otherwise-useful invariant below. Fortunately, 12737 // we don't really need to recurse into them, because any internal 12738 // expressions should have been analyzed already when they were 12739 // built into statements. 12740 if (isa<StmtExpr>(E)) return; 12741 12742 // Don't descend into unevaluated contexts. 12743 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12744 12745 // Now just recurse over the expression's children. 12746 CC = E->getExprLoc(); 12747 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12748 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12749 for (Stmt *SubStmt : E->children()) { 12750 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12751 if (!ChildExpr) 12752 continue; 12753 12754 if (IsLogicalAndOperator && 12755 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12756 // Ignore checking string literals that are in logical and operators. 12757 // This is a common pattern for asserts. 12758 continue; 12759 WorkList.push_back({ChildExpr, CC, IsListInit}); 12760 } 12761 12762 if (BO && BO->isLogicalOp()) { 12763 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12764 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12765 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12766 12767 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12768 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12769 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12770 } 12771 12772 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12773 if (U->getOpcode() == UO_LNot) { 12774 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12775 } else if (U->getOpcode() != UO_AddrOf) { 12776 if (U->getSubExpr()->getType()->isAtomicType()) 12777 S.Diag(U->getSubExpr()->getBeginLoc(), 12778 diag::warn_atomic_implicit_seq_cst); 12779 } 12780 } 12781 } 12782 12783 /// AnalyzeImplicitConversions - Find and report any interesting 12784 /// implicit conversions in the given expression. There are a couple 12785 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12786 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12787 bool IsListInit/*= false*/) { 12788 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12789 WorkList.push_back({OrigE, CC, IsListInit}); 12790 while (!WorkList.empty()) 12791 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12792 } 12793 12794 /// Diagnose integer type and any valid implicit conversion to it. 12795 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12796 // Taking into account implicit conversions, 12797 // allow any integer. 12798 if (!E->getType()->isIntegerType()) { 12799 S.Diag(E->getBeginLoc(), 12800 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12801 return true; 12802 } 12803 // Potentially emit standard warnings for implicit conversions if enabled 12804 // using -Wconversion. 12805 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12806 return false; 12807 } 12808 12809 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12810 // Returns true when emitting a warning about taking the address of a reference. 12811 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12812 const PartialDiagnostic &PD) { 12813 E = E->IgnoreParenImpCasts(); 12814 12815 const FunctionDecl *FD = nullptr; 12816 12817 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12818 if (!DRE->getDecl()->getType()->isReferenceType()) 12819 return false; 12820 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12821 if (!M->getMemberDecl()->getType()->isReferenceType()) 12822 return false; 12823 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12824 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12825 return false; 12826 FD = Call->getDirectCallee(); 12827 } else { 12828 return false; 12829 } 12830 12831 SemaRef.Diag(E->getExprLoc(), PD); 12832 12833 // If possible, point to location of function. 12834 if (FD) { 12835 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12836 } 12837 12838 return true; 12839 } 12840 12841 // Returns true if the SourceLocation is expanded from any macro body. 12842 // Returns false if the SourceLocation is invalid, is from not in a macro 12843 // expansion, or is from expanded from a top-level macro argument. 12844 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12845 if (Loc.isInvalid()) 12846 return false; 12847 12848 while (Loc.isMacroID()) { 12849 if (SM.isMacroBodyExpansion(Loc)) 12850 return true; 12851 Loc = SM.getImmediateMacroCallerLoc(Loc); 12852 } 12853 12854 return false; 12855 } 12856 12857 /// Diagnose pointers that are always non-null. 12858 /// \param E the expression containing the pointer 12859 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12860 /// compared to a null pointer 12861 /// \param IsEqual True when the comparison is equal to a null pointer 12862 /// \param Range Extra SourceRange to highlight in the diagnostic 12863 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12864 Expr::NullPointerConstantKind NullKind, 12865 bool IsEqual, SourceRange Range) { 12866 if (!E) 12867 return; 12868 12869 // Don't warn inside macros. 12870 if (E->getExprLoc().isMacroID()) { 12871 const SourceManager &SM = getSourceManager(); 12872 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12873 IsInAnyMacroBody(SM, Range.getBegin())) 12874 return; 12875 } 12876 E = E->IgnoreImpCasts(); 12877 12878 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12879 12880 if (isa<CXXThisExpr>(E)) { 12881 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12882 : diag::warn_this_bool_conversion; 12883 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12884 return; 12885 } 12886 12887 bool IsAddressOf = false; 12888 12889 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12890 if (UO->getOpcode() != UO_AddrOf) 12891 return; 12892 IsAddressOf = true; 12893 E = UO->getSubExpr(); 12894 } 12895 12896 if (IsAddressOf) { 12897 unsigned DiagID = IsCompare 12898 ? diag::warn_address_of_reference_null_compare 12899 : diag::warn_address_of_reference_bool_conversion; 12900 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12901 << IsEqual; 12902 if (CheckForReference(*this, E, PD)) { 12903 return; 12904 } 12905 } 12906 12907 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12908 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12909 std::string Str; 12910 llvm::raw_string_ostream S(Str); 12911 E->printPretty(S, nullptr, getPrintingPolicy()); 12912 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12913 : diag::warn_cast_nonnull_to_bool; 12914 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12915 << E->getSourceRange() << Range << IsEqual; 12916 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12917 }; 12918 12919 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12920 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12921 if (auto *Callee = Call->getDirectCallee()) { 12922 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12923 ComplainAboutNonnullParamOrCall(A); 12924 return; 12925 } 12926 } 12927 } 12928 12929 // Expect to find a single Decl. Skip anything more complicated. 12930 ValueDecl *D = nullptr; 12931 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12932 D = R->getDecl(); 12933 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12934 D = M->getMemberDecl(); 12935 } 12936 12937 // Weak Decls can be null. 12938 if (!D || D->isWeak()) 12939 return; 12940 12941 // Check for parameter decl with nonnull attribute 12942 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12943 if (getCurFunction() && 12944 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12945 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12946 ComplainAboutNonnullParamOrCall(A); 12947 return; 12948 } 12949 12950 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12951 // Skip function template not specialized yet. 12952 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12953 return; 12954 auto ParamIter = llvm::find(FD->parameters(), PV); 12955 assert(ParamIter != FD->param_end()); 12956 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12957 12958 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12959 if (!NonNull->args_size()) { 12960 ComplainAboutNonnullParamOrCall(NonNull); 12961 return; 12962 } 12963 12964 for (const ParamIdx &ArgNo : NonNull->args()) { 12965 if (ArgNo.getASTIndex() == ParamNo) { 12966 ComplainAboutNonnullParamOrCall(NonNull); 12967 return; 12968 } 12969 } 12970 } 12971 } 12972 } 12973 } 12974 12975 QualType T = D->getType(); 12976 const bool IsArray = T->isArrayType(); 12977 const bool IsFunction = T->isFunctionType(); 12978 12979 // Address of function is used to silence the function warning. 12980 if (IsAddressOf && IsFunction) { 12981 return; 12982 } 12983 12984 // Found nothing. 12985 if (!IsAddressOf && !IsFunction && !IsArray) 12986 return; 12987 12988 // Pretty print the expression for the diagnostic. 12989 std::string Str; 12990 llvm::raw_string_ostream S(Str); 12991 E->printPretty(S, nullptr, getPrintingPolicy()); 12992 12993 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12994 : diag::warn_impcast_pointer_to_bool; 12995 enum { 12996 AddressOf, 12997 FunctionPointer, 12998 ArrayPointer 12999 } DiagType; 13000 if (IsAddressOf) 13001 DiagType = AddressOf; 13002 else if (IsFunction) 13003 DiagType = FunctionPointer; 13004 else if (IsArray) 13005 DiagType = ArrayPointer; 13006 else 13007 llvm_unreachable("Could not determine diagnostic."); 13008 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13009 << Range << IsEqual; 13010 13011 if (!IsFunction) 13012 return; 13013 13014 // Suggest '&' to silence the function warning. 13015 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13016 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13017 13018 // Check to see if '()' fixit should be emitted. 13019 QualType ReturnType; 13020 UnresolvedSet<4> NonTemplateOverloads; 13021 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13022 if (ReturnType.isNull()) 13023 return; 13024 13025 if (IsCompare) { 13026 // There are two cases here. If there is null constant, the only suggest 13027 // for a pointer return type. If the null is 0, then suggest if the return 13028 // type is a pointer or an integer type. 13029 if (!ReturnType->isPointerType()) { 13030 if (NullKind == Expr::NPCK_ZeroExpression || 13031 NullKind == Expr::NPCK_ZeroLiteral) { 13032 if (!ReturnType->isIntegerType()) 13033 return; 13034 } else { 13035 return; 13036 } 13037 } 13038 } else { // !IsCompare 13039 // For function to bool, only suggest if the function pointer has bool 13040 // return type. 13041 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13042 return; 13043 } 13044 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13045 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13046 } 13047 13048 /// Diagnoses "dangerous" implicit conversions within the given 13049 /// expression (which is a full expression). Implements -Wconversion 13050 /// and -Wsign-compare. 13051 /// 13052 /// \param CC the "context" location of the implicit conversion, i.e. 13053 /// the most location of the syntactic entity requiring the implicit 13054 /// conversion 13055 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13056 // Don't diagnose in unevaluated contexts. 13057 if (isUnevaluatedContext()) 13058 return; 13059 13060 // Don't diagnose for value- or type-dependent expressions. 13061 if (E->isTypeDependent() || E->isValueDependent()) 13062 return; 13063 13064 // Check for array bounds violations in cases where the check isn't triggered 13065 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13066 // ArraySubscriptExpr is on the RHS of a variable initialization. 13067 CheckArrayAccess(E); 13068 13069 // This is not the right CC for (e.g.) a variable initialization. 13070 AnalyzeImplicitConversions(*this, E, CC); 13071 } 13072 13073 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13074 /// Input argument E is a logical expression. 13075 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13076 ::CheckBoolLikeConversion(*this, E, CC); 13077 } 13078 13079 /// Diagnose when expression is an integer constant expression and its evaluation 13080 /// results in integer overflow 13081 void Sema::CheckForIntOverflow (Expr *E) { 13082 // Use a work list to deal with nested struct initializers. 13083 SmallVector<Expr *, 2> Exprs(1, E); 13084 13085 do { 13086 Expr *OriginalE = Exprs.pop_back_val(); 13087 Expr *E = OriginalE->IgnoreParenCasts(); 13088 13089 if (isa<BinaryOperator>(E)) { 13090 E->EvaluateForOverflow(Context); 13091 continue; 13092 } 13093 13094 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13095 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13096 else if (isa<ObjCBoxedExpr>(OriginalE)) 13097 E->EvaluateForOverflow(Context); 13098 else if (auto Call = dyn_cast<CallExpr>(E)) 13099 Exprs.append(Call->arg_begin(), Call->arg_end()); 13100 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13101 Exprs.append(Message->arg_begin(), Message->arg_end()); 13102 } while (!Exprs.empty()); 13103 } 13104 13105 namespace { 13106 13107 /// Visitor for expressions which looks for unsequenced operations on the 13108 /// same object. 13109 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13110 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13111 13112 /// A tree of sequenced regions within an expression. Two regions are 13113 /// unsequenced if one is an ancestor or a descendent of the other. When we 13114 /// finish processing an expression with sequencing, such as a comma 13115 /// expression, we fold its tree nodes into its parent, since they are 13116 /// unsequenced with respect to nodes we will visit later. 13117 class SequenceTree { 13118 struct Value { 13119 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13120 unsigned Parent : 31; 13121 unsigned Merged : 1; 13122 }; 13123 SmallVector<Value, 8> Values; 13124 13125 public: 13126 /// A region within an expression which may be sequenced with respect 13127 /// to some other region. 13128 class Seq { 13129 friend class SequenceTree; 13130 13131 unsigned Index; 13132 13133 explicit Seq(unsigned N) : Index(N) {} 13134 13135 public: 13136 Seq() : Index(0) {} 13137 }; 13138 13139 SequenceTree() { Values.push_back(Value(0)); } 13140 Seq root() const { return Seq(0); } 13141 13142 /// Create a new sequence of operations, which is an unsequenced 13143 /// subset of \p Parent. This sequence of operations is sequenced with 13144 /// respect to other children of \p Parent. 13145 Seq allocate(Seq Parent) { 13146 Values.push_back(Value(Parent.Index)); 13147 return Seq(Values.size() - 1); 13148 } 13149 13150 /// Merge a sequence of operations into its parent. 13151 void merge(Seq S) { 13152 Values[S.Index].Merged = true; 13153 } 13154 13155 /// Determine whether two operations are unsequenced. This operation 13156 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13157 /// should have been merged into its parent as appropriate. 13158 bool isUnsequenced(Seq Cur, Seq Old) { 13159 unsigned C = representative(Cur.Index); 13160 unsigned Target = representative(Old.Index); 13161 while (C >= Target) { 13162 if (C == Target) 13163 return true; 13164 C = Values[C].Parent; 13165 } 13166 return false; 13167 } 13168 13169 private: 13170 /// Pick a representative for a sequence. 13171 unsigned representative(unsigned K) { 13172 if (Values[K].Merged) 13173 // Perform path compression as we go. 13174 return Values[K].Parent = representative(Values[K].Parent); 13175 return K; 13176 } 13177 }; 13178 13179 /// An object for which we can track unsequenced uses. 13180 using Object = const NamedDecl *; 13181 13182 /// Different flavors of object usage which we track. We only track the 13183 /// least-sequenced usage of each kind. 13184 enum UsageKind { 13185 /// A read of an object. Multiple unsequenced reads are OK. 13186 UK_Use, 13187 13188 /// A modification of an object which is sequenced before the value 13189 /// computation of the expression, such as ++n in C++. 13190 UK_ModAsValue, 13191 13192 /// A modification of an object which is not sequenced before the value 13193 /// computation of the expression, such as n++. 13194 UK_ModAsSideEffect, 13195 13196 UK_Count = UK_ModAsSideEffect + 1 13197 }; 13198 13199 /// Bundle together a sequencing region and the expression corresponding 13200 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13201 struct Usage { 13202 const Expr *UsageExpr; 13203 SequenceTree::Seq Seq; 13204 13205 Usage() : UsageExpr(nullptr), Seq() {} 13206 }; 13207 13208 struct UsageInfo { 13209 Usage Uses[UK_Count]; 13210 13211 /// Have we issued a diagnostic for this object already? 13212 bool Diagnosed; 13213 13214 UsageInfo() : Uses(), Diagnosed(false) {} 13215 }; 13216 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13217 13218 Sema &SemaRef; 13219 13220 /// Sequenced regions within the expression. 13221 SequenceTree Tree; 13222 13223 /// Declaration modifications and references which we have seen. 13224 UsageInfoMap UsageMap; 13225 13226 /// The region we are currently within. 13227 SequenceTree::Seq Region; 13228 13229 /// Filled in with declarations which were modified as a side-effect 13230 /// (that is, post-increment operations). 13231 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13232 13233 /// Expressions to check later. We defer checking these to reduce 13234 /// stack usage. 13235 SmallVectorImpl<const Expr *> &WorkList; 13236 13237 /// RAII object wrapping the visitation of a sequenced subexpression of an 13238 /// expression. At the end of this process, the side-effects of the evaluation 13239 /// become sequenced with respect to the value computation of the result, so 13240 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13241 /// UK_ModAsValue. 13242 struct SequencedSubexpression { 13243 SequencedSubexpression(SequenceChecker &Self) 13244 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13245 Self.ModAsSideEffect = &ModAsSideEffect; 13246 } 13247 13248 ~SequencedSubexpression() { 13249 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13250 // Add a new usage with usage kind UK_ModAsValue, and then restore 13251 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13252 // the previous one was empty). 13253 UsageInfo &UI = Self.UsageMap[M.first]; 13254 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13255 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13256 SideEffectUsage = M.second; 13257 } 13258 Self.ModAsSideEffect = OldModAsSideEffect; 13259 } 13260 13261 SequenceChecker &Self; 13262 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13263 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13264 }; 13265 13266 /// RAII object wrapping the visitation of a subexpression which we might 13267 /// choose to evaluate as a constant. If any subexpression is evaluated and 13268 /// found to be non-constant, this allows us to suppress the evaluation of 13269 /// the outer expression. 13270 class EvaluationTracker { 13271 public: 13272 EvaluationTracker(SequenceChecker &Self) 13273 : Self(Self), Prev(Self.EvalTracker) { 13274 Self.EvalTracker = this; 13275 } 13276 13277 ~EvaluationTracker() { 13278 Self.EvalTracker = Prev; 13279 if (Prev) 13280 Prev->EvalOK &= EvalOK; 13281 } 13282 13283 bool evaluate(const Expr *E, bool &Result) { 13284 if (!EvalOK || E->isValueDependent()) 13285 return false; 13286 EvalOK = E->EvaluateAsBooleanCondition( 13287 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13288 return EvalOK; 13289 } 13290 13291 private: 13292 SequenceChecker &Self; 13293 EvaluationTracker *Prev; 13294 bool EvalOK = true; 13295 } *EvalTracker = nullptr; 13296 13297 /// Find the object which is produced by the specified expression, 13298 /// if any. 13299 Object getObject(const Expr *E, bool Mod) const { 13300 E = E->IgnoreParenCasts(); 13301 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13302 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13303 return getObject(UO->getSubExpr(), Mod); 13304 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13305 if (BO->getOpcode() == BO_Comma) 13306 return getObject(BO->getRHS(), Mod); 13307 if (Mod && BO->isAssignmentOp()) 13308 return getObject(BO->getLHS(), Mod); 13309 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13310 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13311 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13312 return ME->getMemberDecl(); 13313 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13314 // FIXME: If this is a reference, map through to its value. 13315 return DRE->getDecl(); 13316 return nullptr; 13317 } 13318 13319 /// Note that an object \p O was modified or used by an expression 13320 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13321 /// the object \p O as obtained via the \p UsageMap. 13322 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13323 // Get the old usage for the given object and usage kind. 13324 Usage &U = UI.Uses[UK]; 13325 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13326 // If we have a modification as side effect and are in a sequenced 13327 // subexpression, save the old Usage so that we can restore it later 13328 // in SequencedSubexpression::~SequencedSubexpression. 13329 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13330 ModAsSideEffect->push_back(std::make_pair(O, U)); 13331 // Then record the new usage with the current sequencing region. 13332 U.UsageExpr = UsageExpr; 13333 U.Seq = Region; 13334 } 13335 } 13336 13337 /// Check whether a modification or use of an object \p O in an expression 13338 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13339 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13340 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13341 /// usage and false we are checking for a mod-use unsequenced usage. 13342 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13343 UsageKind OtherKind, bool IsModMod) { 13344 if (UI.Diagnosed) 13345 return; 13346 13347 const Usage &U = UI.Uses[OtherKind]; 13348 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13349 return; 13350 13351 const Expr *Mod = U.UsageExpr; 13352 const Expr *ModOrUse = UsageExpr; 13353 if (OtherKind == UK_Use) 13354 std::swap(Mod, ModOrUse); 13355 13356 SemaRef.DiagRuntimeBehavior( 13357 Mod->getExprLoc(), {Mod, ModOrUse}, 13358 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13359 : diag::warn_unsequenced_mod_use) 13360 << O << SourceRange(ModOrUse->getExprLoc())); 13361 UI.Diagnosed = true; 13362 } 13363 13364 // A note on note{Pre, Post}{Use, Mod}: 13365 // 13366 // (It helps to follow the algorithm with an expression such as 13367 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13368 // operations before C++17 and both are well-defined in C++17). 13369 // 13370 // When visiting a node which uses/modify an object we first call notePreUse 13371 // or notePreMod before visiting its sub-expression(s). At this point the 13372 // children of the current node have not yet been visited and so the eventual 13373 // uses/modifications resulting from the children of the current node have not 13374 // been recorded yet. 13375 // 13376 // We then visit the children of the current node. After that notePostUse or 13377 // notePostMod is called. These will 1) detect an unsequenced modification 13378 // as side effect (as in "k++ + k") and 2) add a new usage with the 13379 // appropriate usage kind. 13380 // 13381 // We also have to be careful that some operation sequences modification as 13382 // side effect as well (for example: || or ,). To account for this we wrap 13383 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13384 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13385 // which record usages which are modifications as side effect, and then 13386 // downgrade them (or more accurately restore the previous usage which was a 13387 // modification as side effect) when exiting the scope of the sequenced 13388 // subexpression. 13389 13390 void notePreUse(Object O, const Expr *UseExpr) { 13391 UsageInfo &UI = UsageMap[O]; 13392 // Uses conflict with other modifications. 13393 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13394 } 13395 13396 void notePostUse(Object O, const Expr *UseExpr) { 13397 UsageInfo &UI = UsageMap[O]; 13398 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13399 /*IsModMod=*/false); 13400 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13401 } 13402 13403 void notePreMod(Object O, const Expr *ModExpr) { 13404 UsageInfo &UI = UsageMap[O]; 13405 // Modifications conflict with other modifications and with uses. 13406 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13407 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13408 } 13409 13410 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13411 UsageInfo &UI = UsageMap[O]; 13412 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13413 /*IsModMod=*/true); 13414 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13415 } 13416 13417 public: 13418 SequenceChecker(Sema &S, const Expr *E, 13419 SmallVectorImpl<const Expr *> &WorkList) 13420 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13421 Visit(E); 13422 // Silence a -Wunused-private-field since WorkList is now unused. 13423 // TODO: Evaluate if it can be used, and if not remove it. 13424 (void)this->WorkList; 13425 } 13426 13427 void VisitStmt(const Stmt *S) { 13428 // Skip all statements which aren't expressions for now. 13429 } 13430 13431 void VisitExpr(const Expr *E) { 13432 // By default, just recurse to evaluated subexpressions. 13433 Base::VisitStmt(E); 13434 } 13435 13436 void VisitCastExpr(const CastExpr *E) { 13437 Object O = Object(); 13438 if (E->getCastKind() == CK_LValueToRValue) 13439 O = getObject(E->getSubExpr(), false); 13440 13441 if (O) 13442 notePreUse(O, E); 13443 VisitExpr(E); 13444 if (O) 13445 notePostUse(O, E); 13446 } 13447 13448 void VisitSequencedExpressions(const Expr *SequencedBefore, 13449 const Expr *SequencedAfter) { 13450 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13451 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13452 SequenceTree::Seq OldRegion = Region; 13453 13454 { 13455 SequencedSubexpression SeqBefore(*this); 13456 Region = BeforeRegion; 13457 Visit(SequencedBefore); 13458 } 13459 13460 Region = AfterRegion; 13461 Visit(SequencedAfter); 13462 13463 Region = OldRegion; 13464 13465 Tree.merge(BeforeRegion); 13466 Tree.merge(AfterRegion); 13467 } 13468 13469 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13470 // C++17 [expr.sub]p1: 13471 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13472 // expression E1 is sequenced before the expression E2. 13473 if (SemaRef.getLangOpts().CPlusPlus17) 13474 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13475 else { 13476 Visit(ASE->getLHS()); 13477 Visit(ASE->getRHS()); 13478 } 13479 } 13480 13481 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13482 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13483 void VisitBinPtrMem(const BinaryOperator *BO) { 13484 // C++17 [expr.mptr.oper]p4: 13485 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13486 // the expression E1 is sequenced before the expression E2. 13487 if (SemaRef.getLangOpts().CPlusPlus17) 13488 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13489 else { 13490 Visit(BO->getLHS()); 13491 Visit(BO->getRHS()); 13492 } 13493 } 13494 13495 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13496 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13497 void VisitBinShlShr(const BinaryOperator *BO) { 13498 // C++17 [expr.shift]p4: 13499 // The expression E1 is sequenced before the expression E2. 13500 if (SemaRef.getLangOpts().CPlusPlus17) 13501 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13502 else { 13503 Visit(BO->getLHS()); 13504 Visit(BO->getRHS()); 13505 } 13506 } 13507 13508 void VisitBinComma(const BinaryOperator *BO) { 13509 // C++11 [expr.comma]p1: 13510 // Every value computation and side effect associated with the left 13511 // expression is sequenced before every value computation and side 13512 // effect associated with the right expression. 13513 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13514 } 13515 13516 void VisitBinAssign(const BinaryOperator *BO) { 13517 SequenceTree::Seq RHSRegion; 13518 SequenceTree::Seq LHSRegion; 13519 if (SemaRef.getLangOpts().CPlusPlus17) { 13520 RHSRegion = Tree.allocate(Region); 13521 LHSRegion = Tree.allocate(Region); 13522 } else { 13523 RHSRegion = Region; 13524 LHSRegion = Region; 13525 } 13526 SequenceTree::Seq OldRegion = Region; 13527 13528 // C++11 [expr.ass]p1: 13529 // [...] the assignment is sequenced after the value computation 13530 // of the right and left operands, [...] 13531 // 13532 // so check it before inspecting the operands and update the 13533 // map afterwards. 13534 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13535 if (O) 13536 notePreMod(O, BO); 13537 13538 if (SemaRef.getLangOpts().CPlusPlus17) { 13539 // C++17 [expr.ass]p1: 13540 // [...] The right operand is sequenced before the left operand. [...] 13541 { 13542 SequencedSubexpression SeqBefore(*this); 13543 Region = RHSRegion; 13544 Visit(BO->getRHS()); 13545 } 13546 13547 Region = LHSRegion; 13548 Visit(BO->getLHS()); 13549 13550 if (O && isa<CompoundAssignOperator>(BO)) 13551 notePostUse(O, BO); 13552 13553 } else { 13554 // C++11 does not specify any sequencing between the LHS and RHS. 13555 Region = LHSRegion; 13556 Visit(BO->getLHS()); 13557 13558 if (O && isa<CompoundAssignOperator>(BO)) 13559 notePostUse(O, BO); 13560 13561 Region = RHSRegion; 13562 Visit(BO->getRHS()); 13563 } 13564 13565 // C++11 [expr.ass]p1: 13566 // the assignment is sequenced [...] before the value computation of the 13567 // assignment expression. 13568 // C11 6.5.16/3 has no such rule. 13569 Region = OldRegion; 13570 if (O) 13571 notePostMod(O, BO, 13572 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13573 : UK_ModAsSideEffect); 13574 if (SemaRef.getLangOpts().CPlusPlus17) { 13575 Tree.merge(RHSRegion); 13576 Tree.merge(LHSRegion); 13577 } 13578 } 13579 13580 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13581 VisitBinAssign(CAO); 13582 } 13583 13584 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13585 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13586 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13587 Object O = getObject(UO->getSubExpr(), true); 13588 if (!O) 13589 return VisitExpr(UO); 13590 13591 notePreMod(O, UO); 13592 Visit(UO->getSubExpr()); 13593 // C++11 [expr.pre.incr]p1: 13594 // the expression ++x is equivalent to x+=1 13595 notePostMod(O, UO, 13596 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13597 : UK_ModAsSideEffect); 13598 } 13599 13600 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13601 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13602 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13603 Object O = getObject(UO->getSubExpr(), true); 13604 if (!O) 13605 return VisitExpr(UO); 13606 13607 notePreMod(O, UO); 13608 Visit(UO->getSubExpr()); 13609 notePostMod(O, UO, UK_ModAsSideEffect); 13610 } 13611 13612 void VisitBinLOr(const BinaryOperator *BO) { 13613 // C++11 [expr.log.or]p2: 13614 // If the second expression is evaluated, every value computation and 13615 // side effect associated with the first expression is sequenced before 13616 // every value computation and side effect associated with the 13617 // second expression. 13618 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13619 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13620 SequenceTree::Seq OldRegion = Region; 13621 13622 EvaluationTracker Eval(*this); 13623 { 13624 SequencedSubexpression Sequenced(*this); 13625 Region = LHSRegion; 13626 Visit(BO->getLHS()); 13627 } 13628 13629 // C++11 [expr.log.or]p1: 13630 // [...] the second operand is not evaluated if the first operand 13631 // evaluates to true. 13632 bool EvalResult = false; 13633 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13634 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13635 if (ShouldVisitRHS) { 13636 Region = RHSRegion; 13637 Visit(BO->getRHS()); 13638 } 13639 13640 Region = OldRegion; 13641 Tree.merge(LHSRegion); 13642 Tree.merge(RHSRegion); 13643 } 13644 13645 void VisitBinLAnd(const BinaryOperator *BO) { 13646 // C++11 [expr.log.and]p2: 13647 // If the second expression is evaluated, every value computation and 13648 // side effect associated with the first expression is sequenced before 13649 // every value computation and side effect associated with the 13650 // second expression. 13651 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13652 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13653 SequenceTree::Seq OldRegion = Region; 13654 13655 EvaluationTracker Eval(*this); 13656 { 13657 SequencedSubexpression Sequenced(*this); 13658 Region = LHSRegion; 13659 Visit(BO->getLHS()); 13660 } 13661 13662 // C++11 [expr.log.and]p1: 13663 // [...] the second operand is not evaluated if the first operand is false. 13664 bool EvalResult = false; 13665 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13666 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13667 if (ShouldVisitRHS) { 13668 Region = RHSRegion; 13669 Visit(BO->getRHS()); 13670 } 13671 13672 Region = OldRegion; 13673 Tree.merge(LHSRegion); 13674 Tree.merge(RHSRegion); 13675 } 13676 13677 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13678 // C++11 [expr.cond]p1: 13679 // [...] Every value computation and side effect associated with the first 13680 // expression is sequenced before every value computation and side effect 13681 // associated with the second or third expression. 13682 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13683 13684 // No sequencing is specified between the true and false expression. 13685 // However since exactly one of both is going to be evaluated we can 13686 // consider them to be sequenced. This is needed to avoid warning on 13687 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13688 // both the true and false expressions because we can't evaluate x. 13689 // This will still allow us to detect an expression like (pre C++17) 13690 // "(x ? y += 1 : y += 2) = y". 13691 // 13692 // We don't wrap the visitation of the true and false expression with 13693 // SequencedSubexpression because we don't want to downgrade modifications 13694 // as side effect in the true and false expressions after the visition 13695 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13696 // not warn between the two "y++", but we should warn between the "y++" 13697 // and the "y". 13698 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13699 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13700 SequenceTree::Seq OldRegion = Region; 13701 13702 EvaluationTracker Eval(*this); 13703 { 13704 SequencedSubexpression Sequenced(*this); 13705 Region = ConditionRegion; 13706 Visit(CO->getCond()); 13707 } 13708 13709 // C++11 [expr.cond]p1: 13710 // [...] The first expression is contextually converted to bool (Clause 4). 13711 // It is evaluated and if it is true, the result of the conditional 13712 // expression is the value of the second expression, otherwise that of the 13713 // third expression. Only one of the second and third expressions is 13714 // evaluated. [...] 13715 bool EvalResult = false; 13716 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13717 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13718 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13719 if (ShouldVisitTrueExpr) { 13720 Region = TrueRegion; 13721 Visit(CO->getTrueExpr()); 13722 } 13723 if (ShouldVisitFalseExpr) { 13724 Region = FalseRegion; 13725 Visit(CO->getFalseExpr()); 13726 } 13727 13728 Region = OldRegion; 13729 Tree.merge(ConditionRegion); 13730 Tree.merge(TrueRegion); 13731 Tree.merge(FalseRegion); 13732 } 13733 13734 void VisitCallExpr(const CallExpr *CE) { 13735 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13736 13737 if (CE->isUnevaluatedBuiltinCall(Context)) 13738 return; 13739 13740 // C++11 [intro.execution]p15: 13741 // When calling a function [...], every value computation and side effect 13742 // associated with any argument expression, or with the postfix expression 13743 // designating the called function, is sequenced before execution of every 13744 // expression or statement in the body of the function [and thus before 13745 // the value computation of its result]. 13746 SequencedSubexpression Sequenced(*this); 13747 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13748 // C++17 [expr.call]p5 13749 // The postfix-expression is sequenced before each expression in the 13750 // expression-list and any default argument. [...] 13751 SequenceTree::Seq CalleeRegion; 13752 SequenceTree::Seq OtherRegion; 13753 if (SemaRef.getLangOpts().CPlusPlus17) { 13754 CalleeRegion = Tree.allocate(Region); 13755 OtherRegion = Tree.allocate(Region); 13756 } else { 13757 CalleeRegion = Region; 13758 OtherRegion = Region; 13759 } 13760 SequenceTree::Seq OldRegion = Region; 13761 13762 // Visit the callee expression first. 13763 Region = CalleeRegion; 13764 if (SemaRef.getLangOpts().CPlusPlus17) { 13765 SequencedSubexpression Sequenced(*this); 13766 Visit(CE->getCallee()); 13767 } else { 13768 Visit(CE->getCallee()); 13769 } 13770 13771 // Then visit the argument expressions. 13772 Region = OtherRegion; 13773 for (const Expr *Argument : CE->arguments()) 13774 Visit(Argument); 13775 13776 Region = OldRegion; 13777 if (SemaRef.getLangOpts().CPlusPlus17) { 13778 Tree.merge(CalleeRegion); 13779 Tree.merge(OtherRegion); 13780 } 13781 }); 13782 } 13783 13784 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13785 // C++17 [over.match.oper]p2: 13786 // [...] the operator notation is first transformed to the equivalent 13787 // function-call notation as summarized in Table 12 (where @ denotes one 13788 // of the operators covered in the specified subclause). However, the 13789 // operands are sequenced in the order prescribed for the built-in 13790 // operator (Clause 8). 13791 // 13792 // From the above only overloaded binary operators and overloaded call 13793 // operators have sequencing rules in C++17 that we need to handle 13794 // separately. 13795 if (!SemaRef.getLangOpts().CPlusPlus17 || 13796 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13797 return VisitCallExpr(CXXOCE); 13798 13799 enum { 13800 NoSequencing, 13801 LHSBeforeRHS, 13802 RHSBeforeLHS, 13803 LHSBeforeRest 13804 } SequencingKind; 13805 switch (CXXOCE->getOperator()) { 13806 case OO_Equal: 13807 case OO_PlusEqual: 13808 case OO_MinusEqual: 13809 case OO_StarEqual: 13810 case OO_SlashEqual: 13811 case OO_PercentEqual: 13812 case OO_CaretEqual: 13813 case OO_AmpEqual: 13814 case OO_PipeEqual: 13815 case OO_LessLessEqual: 13816 case OO_GreaterGreaterEqual: 13817 SequencingKind = RHSBeforeLHS; 13818 break; 13819 13820 case OO_LessLess: 13821 case OO_GreaterGreater: 13822 case OO_AmpAmp: 13823 case OO_PipePipe: 13824 case OO_Comma: 13825 case OO_ArrowStar: 13826 case OO_Subscript: 13827 SequencingKind = LHSBeforeRHS; 13828 break; 13829 13830 case OO_Call: 13831 SequencingKind = LHSBeforeRest; 13832 break; 13833 13834 default: 13835 SequencingKind = NoSequencing; 13836 break; 13837 } 13838 13839 if (SequencingKind == NoSequencing) 13840 return VisitCallExpr(CXXOCE); 13841 13842 // This is a call, so all subexpressions are sequenced before the result. 13843 SequencedSubexpression Sequenced(*this); 13844 13845 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13846 assert(SemaRef.getLangOpts().CPlusPlus17 && 13847 "Should only get there with C++17 and above!"); 13848 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13849 "Should only get there with an overloaded binary operator" 13850 " or an overloaded call operator!"); 13851 13852 if (SequencingKind == LHSBeforeRest) { 13853 assert(CXXOCE->getOperator() == OO_Call && 13854 "We should only have an overloaded call operator here!"); 13855 13856 // This is very similar to VisitCallExpr, except that we only have the 13857 // C++17 case. The postfix-expression is the first argument of the 13858 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13859 // are in the following arguments. 13860 // 13861 // Note that we intentionally do not visit the callee expression since 13862 // it is just a decayed reference to a function. 13863 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13864 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13865 SequenceTree::Seq OldRegion = Region; 13866 13867 assert(CXXOCE->getNumArgs() >= 1 && 13868 "An overloaded call operator must have at least one argument" 13869 " for the postfix-expression!"); 13870 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13871 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13872 CXXOCE->getNumArgs() - 1); 13873 13874 // Visit the postfix-expression first. 13875 { 13876 Region = PostfixExprRegion; 13877 SequencedSubexpression Sequenced(*this); 13878 Visit(PostfixExpr); 13879 } 13880 13881 // Then visit the argument expressions. 13882 Region = ArgsRegion; 13883 for (const Expr *Arg : Args) 13884 Visit(Arg); 13885 13886 Region = OldRegion; 13887 Tree.merge(PostfixExprRegion); 13888 Tree.merge(ArgsRegion); 13889 } else { 13890 assert(CXXOCE->getNumArgs() == 2 && 13891 "Should only have two arguments here!"); 13892 assert((SequencingKind == LHSBeforeRHS || 13893 SequencingKind == RHSBeforeLHS) && 13894 "Unexpected sequencing kind!"); 13895 13896 // We do not visit the callee expression since it is just a decayed 13897 // reference to a function. 13898 const Expr *E1 = CXXOCE->getArg(0); 13899 const Expr *E2 = CXXOCE->getArg(1); 13900 if (SequencingKind == RHSBeforeLHS) 13901 std::swap(E1, E2); 13902 13903 return VisitSequencedExpressions(E1, E2); 13904 } 13905 }); 13906 } 13907 13908 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13909 // This is a call, so all subexpressions are sequenced before the result. 13910 SequencedSubexpression Sequenced(*this); 13911 13912 if (!CCE->isListInitialization()) 13913 return VisitExpr(CCE); 13914 13915 // In C++11, list initializations are sequenced. 13916 SmallVector<SequenceTree::Seq, 32> Elts; 13917 SequenceTree::Seq Parent = Region; 13918 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13919 E = CCE->arg_end(); 13920 I != E; ++I) { 13921 Region = Tree.allocate(Parent); 13922 Elts.push_back(Region); 13923 Visit(*I); 13924 } 13925 13926 // Forget that the initializers are sequenced. 13927 Region = Parent; 13928 for (unsigned I = 0; I < Elts.size(); ++I) 13929 Tree.merge(Elts[I]); 13930 } 13931 13932 void VisitInitListExpr(const InitListExpr *ILE) { 13933 if (!SemaRef.getLangOpts().CPlusPlus11) 13934 return VisitExpr(ILE); 13935 13936 // In C++11, list initializations are sequenced. 13937 SmallVector<SequenceTree::Seq, 32> Elts; 13938 SequenceTree::Seq Parent = Region; 13939 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13940 const Expr *E = ILE->getInit(I); 13941 if (!E) 13942 continue; 13943 Region = Tree.allocate(Parent); 13944 Elts.push_back(Region); 13945 Visit(E); 13946 } 13947 13948 // Forget that the initializers are sequenced. 13949 Region = Parent; 13950 for (unsigned I = 0; I < Elts.size(); ++I) 13951 Tree.merge(Elts[I]); 13952 } 13953 }; 13954 13955 } // namespace 13956 13957 void Sema::CheckUnsequencedOperations(const Expr *E) { 13958 SmallVector<const Expr *, 8> WorkList; 13959 WorkList.push_back(E); 13960 while (!WorkList.empty()) { 13961 const Expr *Item = WorkList.pop_back_val(); 13962 SequenceChecker(*this, Item, WorkList); 13963 } 13964 } 13965 13966 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13967 bool IsConstexpr) { 13968 llvm::SaveAndRestore<bool> ConstantContext( 13969 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13970 CheckImplicitConversions(E, CheckLoc); 13971 if (!E->isInstantiationDependent()) 13972 CheckUnsequencedOperations(E); 13973 if (!IsConstexpr && !E->isValueDependent()) 13974 CheckForIntOverflow(E); 13975 DiagnoseMisalignedMembers(); 13976 } 13977 13978 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13979 FieldDecl *BitField, 13980 Expr *Init) { 13981 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13982 } 13983 13984 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13985 SourceLocation Loc) { 13986 if (!PType->isVariablyModifiedType()) 13987 return; 13988 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13989 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13990 return; 13991 } 13992 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13993 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13994 return; 13995 } 13996 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13997 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13998 return; 13999 } 14000 14001 const ArrayType *AT = S.Context.getAsArrayType(PType); 14002 if (!AT) 14003 return; 14004 14005 if (AT->getSizeModifier() != ArrayType::Star) { 14006 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14007 return; 14008 } 14009 14010 S.Diag(Loc, diag::err_array_star_in_function_definition); 14011 } 14012 14013 /// CheckParmsForFunctionDef - Check that the parameters of the given 14014 /// function are appropriate for the definition of a function. This 14015 /// takes care of any checks that cannot be performed on the 14016 /// declaration itself, e.g., that the types of each of the function 14017 /// parameters are complete. 14018 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14019 bool CheckParameterNames) { 14020 bool HasInvalidParm = false; 14021 for (ParmVarDecl *Param : Parameters) { 14022 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14023 // function declarator that is part of a function definition of 14024 // that function shall not have incomplete type. 14025 // 14026 // This is also C++ [dcl.fct]p6. 14027 if (!Param->isInvalidDecl() && 14028 RequireCompleteType(Param->getLocation(), Param->getType(), 14029 diag::err_typecheck_decl_incomplete_type)) { 14030 Param->setInvalidDecl(); 14031 HasInvalidParm = true; 14032 } 14033 14034 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14035 // declaration of each parameter shall include an identifier. 14036 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14037 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14038 // Diagnose this as an extension in C17 and earlier. 14039 if (!getLangOpts().C2x) 14040 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14041 } 14042 14043 // C99 6.7.5.3p12: 14044 // If the function declarator is not part of a definition of that 14045 // function, parameters may have incomplete type and may use the [*] 14046 // notation in their sequences of declarator specifiers to specify 14047 // variable length array types. 14048 QualType PType = Param->getOriginalType(); 14049 // FIXME: This diagnostic should point the '[*]' if source-location 14050 // information is added for it. 14051 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14052 14053 // If the parameter is a c++ class type and it has to be destructed in the 14054 // callee function, declare the destructor so that it can be called by the 14055 // callee function. Do not perform any direct access check on the dtor here. 14056 if (!Param->isInvalidDecl()) { 14057 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14058 if (!ClassDecl->isInvalidDecl() && 14059 !ClassDecl->hasIrrelevantDestructor() && 14060 !ClassDecl->isDependentContext() && 14061 ClassDecl->isParamDestroyedInCallee()) { 14062 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14063 MarkFunctionReferenced(Param->getLocation(), Destructor); 14064 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14065 } 14066 } 14067 } 14068 14069 // Parameters with the pass_object_size attribute only need to be marked 14070 // constant at function definitions. Because we lack information about 14071 // whether we're on a declaration or definition when we're instantiating the 14072 // attribute, we need to check for constness here. 14073 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14074 if (!Param->getType().isConstQualified()) 14075 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14076 << Attr->getSpelling() << 1; 14077 14078 // Check for parameter names shadowing fields from the class. 14079 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14080 // The owning context for the parameter should be the function, but we 14081 // want to see if this function's declaration context is a record. 14082 DeclContext *DC = Param->getDeclContext(); 14083 if (DC && DC->isFunctionOrMethod()) { 14084 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14085 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14086 RD, /*DeclIsField*/ false); 14087 } 14088 } 14089 } 14090 14091 return HasInvalidParm; 14092 } 14093 14094 Optional<std::pair<CharUnits, CharUnits>> 14095 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14096 14097 /// Compute the alignment and offset of the base class object given the 14098 /// derived-to-base cast expression and the alignment and offset of the derived 14099 /// class object. 14100 static std::pair<CharUnits, CharUnits> 14101 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14102 CharUnits BaseAlignment, CharUnits Offset, 14103 ASTContext &Ctx) { 14104 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14105 ++PathI) { 14106 const CXXBaseSpecifier *Base = *PathI; 14107 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14108 if (Base->isVirtual()) { 14109 // The complete object may have a lower alignment than the non-virtual 14110 // alignment of the base, in which case the base may be misaligned. Choose 14111 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14112 // conservative lower bound of the complete object alignment. 14113 CharUnits NonVirtualAlignment = 14114 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14115 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14116 Offset = CharUnits::Zero(); 14117 } else { 14118 const ASTRecordLayout &RL = 14119 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14120 Offset += RL.getBaseClassOffset(BaseDecl); 14121 } 14122 DerivedType = Base->getType(); 14123 } 14124 14125 return std::make_pair(BaseAlignment, Offset); 14126 } 14127 14128 /// Compute the alignment and offset of a binary additive operator. 14129 static Optional<std::pair<CharUnits, CharUnits>> 14130 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14131 bool IsSub, ASTContext &Ctx) { 14132 QualType PointeeType = PtrE->getType()->getPointeeType(); 14133 14134 if (!PointeeType->isConstantSizeType()) 14135 return llvm::None; 14136 14137 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14138 14139 if (!P) 14140 return llvm::None; 14141 14142 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14143 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14144 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14145 if (IsSub) 14146 Offset = -Offset; 14147 return std::make_pair(P->first, P->second + Offset); 14148 } 14149 14150 // If the integer expression isn't a constant expression, compute the lower 14151 // bound of the alignment using the alignment and offset of the pointer 14152 // expression and the element size. 14153 return std::make_pair( 14154 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14155 CharUnits::Zero()); 14156 } 14157 14158 /// This helper function takes an lvalue expression and returns the alignment of 14159 /// a VarDecl and a constant offset from the VarDecl. 14160 Optional<std::pair<CharUnits, CharUnits>> 14161 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14162 E = E->IgnoreParens(); 14163 switch (E->getStmtClass()) { 14164 default: 14165 break; 14166 case Stmt::CStyleCastExprClass: 14167 case Stmt::CXXStaticCastExprClass: 14168 case Stmt::ImplicitCastExprClass: { 14169 auto *CE = cast<CastExpr>(E); 14170 const Expr *From = CE->getSubExpr(); 14171 switch (CE->getCastKind()) { 14172 default: 14173 break; 14174 case CK_NoOp: 14175 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14176 case CK_UncheckedDerivedToBase: 14177 case CK_DerivedToBase: { 14178 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14179 if (!P) 14180 break; 14181 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14182 P->second, Ctx); 14183 } 14184 } 14185 break; 14186 } 14187 case Stmt::ArraySubscriptExprClass: { 14188 auto *ASE = cast<ArraySubscriptExpr>(E); 14189 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14190 false, Ctx); 14191 } 14192 case Stmt::DeclRefExprClass: { 14193 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14194 // FIXME: If VD is captured by copy or is an escaping __block variable, 14195 // use the alignment of VD's type. 14196 if (!VD->getType()->isReferenceType()) 14197 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14198 if (VD->hasInit()) 14199 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14200 } 14201 break; 14202 } 14203 case Stmt::MemberExprClass: { 14204 auto *ME = cast<MemberExpr>(E); 14205 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14206 if (!FD || FD->getType()->isReferenceType()) 14207 break; 14208 Optional<std::pair<CharUnits, CharUnits>> P; 14209 if (ME->isArrow()) 14210 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14211 else 14212 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14213 if (!P) 14214 break; 14215 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14216 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14217 return std::make_pair(P->first, 14218 P->second + CharUnits::fromQuantity(Offset)); 14219 } 14220 case Stmt::UnaryOperatorClass: { 14221 auto *UO = cast<UnaryOperator>(E); 14222 switch (UO->getOpcode()) { 14223 default: 14224 break; 14225 case UO_Deref: 14226 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14227 } 14228 break; 14229 } 14230 case Stmt::BinaryOperatorClass: { 14231 auto *BO = cast<BinaryOperator>(E); 14232 auto Opcode = BO->getOpcode(); 14233 switch (Opcode) { 14234 default: 14235 break; 14236 case BO_Comma: 14237 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14238 } 14239 break; 14240 } 14241 } 14242 return llvm::None; 14243 } 14244 14245 /// This helper function takes a pointer expression and returns the alignment of 14246 /// a VarDecl and a constant offset from the VarDecl. 14247 Optional<std::pair<CharUnits, CharUnits>> 14248 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14249 E = E->IgnoreParens(); 14250 switch (E->getStmtClass()) { 14251 default: 14252 break; 14253 case Stmt::CStyleCastExprClass: 14254 case Stmt::CXXStaticCastExprClass: 14255 case Stmt::ImplicitCastExprClass: { 14256 auto *CE = cast<CastExpr>(E); 14257 const Expr *From = CE->getSubExpr(); 14258 switch (CE->getCastKind()) { 14259 default: 14260 break; 14261 case CK_NoOp: 14262 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14263 case CK_ArrayToPointerDecay: 14264 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14265 case CK_UncheckedDerivedToBase: 14266 case CK_DerivedToBase: { 14267 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14268 if (!P) 14269 break; 14270 return getDerivedToBaseAlignmentAndOffset( 14271 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14272 } 14273 } 14274 break; 14275 } 14276 case Stmt::CXXThisExprClass: { 14277 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14278 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14279 return std::make_pair(Alignment, CharUnits::Zero()); 14280 } 14281 case Stmt::UnaryOperatorClass: { 14282 auto *UO = cast<UnaryOperator>(E); 14283 if (UO->getOpcode() == UO_AddrOf) 14284 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14285 break; 14286 } 14287 case Stmt::BinaryOperatorClass: { 14288 auto *BO = cast<BinaryOperator>(E); 14289 auto Opcode = BO->getOpcode(); 14290 switch (Opcode) { 14291 default: 14292 break; 14293 case BO_Add: 14294 case BO_Sub: { 14295 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14296 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14297 std::swap(LHS, RHS); 14298 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14299 Ctx); 14300 } 14301 case BO_Comma: 14302 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14303 } 14304 break; 14305 } 14306 } 14307 return llvm::None; 14308 } 14309 14310 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14311 // See if we can compute the alignment of a VarDecl and an offset from it. 14312 Optional<std::pair<CharUnits, CharUnits>> P = 14313 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14314 14315 if (P) 14316 return P->first.alignmentAtOffset(P->second); 14317 14318 // If that failed, return the type's alignment. 14319 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14320 } 14321 14322 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14323 /// pointer cast increases the alignment requirements. 14324 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14325 // This is actually a lot of work to potentially be doing on every 14326 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14327 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14328 return; 14329 14330 // Ignore dependent types. 14331 if (T->isDependentType() || Op->getType()->isDependentType()) 14332 return; 14333 14334 // Require that the destination be a pointer type. 14335 const PointerType *DestPtr = T->getAs<PointerType>(); 14336 if (!DestPtr) return; 14337 14338 // If the destination has alignment 1, we're done. 14339 QualType DestPointee = DestPtr->getPointeeType(); 14340 if (DestPointee->isIncompleteType()) return; 14341 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14342 if (DestAlign.isOne()) return; 14343 14344 // Require that the source be a pointer type. 14345 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14346 if (!SrcPtr) return; 14347 QualType SrcPointee = SrcPtr->getPointeeType(); 14348 14349 // Explicitly allow casts from cv void*. We already implicitly 14350 // allowed casts to cv void*, since they have alignment 1. 14351 // Also allow casts involving incomplete types, which implicitly 14352 // includes 'void'. 14353 if (SrcPointee->isIncompleteType()) return; 14354 14355 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14356 14357 if (SrcAlign >= DestAlign) return; 14358 14359 Diag(TRange.getBegin(), diag::warn_cast_align) 14360 << Op->getType() << T 14361 << static_cast<unsigned>(SrcAlign.getQuantity()) 14362 << static_cast<unsigned>(DestAlign.getQuantity()) 14363 << TRange << Op->getSourceRange(); 14364 } 14365 14366 /// Check whether this array fits the idiom of a size-one tail padded 14367 /// array member of a struct. 14368 /// 14369 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14370 /// commonly used to emulate flexible arrays in C89 code. 14371 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14372 const NamedDecl *ND) { 14373 if (Size != 1 || !ND) return false; 14374 14375 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14376 if (!FD) return false; 14377 14378 // Don't consider sizes resulting from macro expansions or template argument 14379 // substitution to form C89 tail-padded arrays. 14380 14381 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14382 while (TInfo) { 14383 TypeLoc TL = TInfo->getTypeLoc(); 14384 // Look through typedefs. 14385 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14386 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14387 TInfo = TDL->getTypeSourceInfo(); 14388 continue; 14389 } 14390 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14391 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14392 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14393 return false; 14394 } 14395 break; 14396 } 14397 14398 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14399 if (!RD) return false; 14400 if (RD->isUnion()) return false; 14401 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14402 if (!CRD->isStandardLayout()) return false; 14403 } 14404 14405 // See if this is the last field decl in the record. 14406 const Decl *D = FD; 14407 while ((D = D->getNextDeclInContext())) 14408 if (isa<FieldDecl>(D)) 14409 return false; 14410 return true; 14411 } 14412 14413 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14414 const ArraySubscriptExpr *ASE, 14415 bool AllowOnePastEnd, bool IndexNegated) { 14416 // Already diagnosed by the constant evaluator. 14417 if (isConstantEvaluated()) 14418 return; 14419 14420 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14421 if (IndexExpr->isValueDependent()) 14422 return; 14423 14424 const Type *EffectiveType = 14425 BaseExpr->getType()->getPointeeOrArrayElementType(); 14426 BaseExpr = BaseExpr->IgnoreParenCasts(); 14427 const ConstantArrayType *ArrayTy = 14428 Context.getAsConstantArrayType(BaseExpr->getType()); 14429 14430 if (!ArrayTy) 14431 return; 14432 14433 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 14434 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 14435 return; 14436 14437 Expr::EvalResult Result; 14438 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14439 return; 14440 14441 llvm::APSInt index = Result.Val.getInt(); 14442 if (IndexNegated) 14443 index = -index; 14444 14445 const NamedDecl *ND = nullptr; 14446 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14447 ND = DRE->getDecl(); 14448 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14449 ND = ME->getMemberDecl(); 14450 14451 if (index.isUnsigned() || !index.isNegative()) { 14452 // It is possible that the type of the base expression after 14453 // IgnoreParenCasts is incomplete, even though the type of the base 14454 // expression before IgnoreParenCasts is complete (see PR39746 for an 14455 // example). In this case we have no information about whether the array 14456 // access exceeds the array bounds. However we can still diagnose an array 14457 // access which precedes the array bounds. 14458 if (BaseType->isIncompleteType()) 14459 return; 14460 14461 llvm::APInt size = ArrayTy->getSize(); 14462 if (!size.isStrictlyPositive()) 14463 return; 14464 14465 if (BaseType != EffectiveType) { 14466 // Make sure we're comparing apples to apples when comparing index to size 14467 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14468 uint64_t array_typesize = Context.getTypeSize(BaseType); 14469 // Handle ptrarith_typesize being zero, such as when casting to void* 14470 if (!ptrarith_typesize) ptrarith_typesize = 1; 14471 if (ptrarith_typesize != array_typesize) { 14472 // There's a cast to a different size type involved 14473 uint64_t ratio = array_typesize / ptrarith_typesize; 14474 // TODO: Be smarter about handling cases where array_typesize is not a 14475 // multiple of ptrarith_typesize 14476 if (ptrarith_typesize * ratio == array_typesize) 14477 size *= llvm::APInt(size.getBitWidth(), ratio); 14478 } 14479 } 14480 14481 if (size.getBitWidth() > index.getBitWidth()) 14482 index = index.zext(size.getBitWidth()); 14483 else if (size.getBitWidth() < index.getBitWidth()) 14484 size = size.zext(index.getBitWidth()); 14485 14486 // For array subscripting the index must be less than size, but for pointer 14487 // arithmetic also allow the index (offset) to be equal to size since 14488 // computing the next address after the end of the array is legal and 14489 // commonly done e.g. in C++ iterators and range-based for loops. 14490 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14491 return; 14492 14493 // Also don't warn for arrays of size 1 which are members of some 14494 // structure. These are often used to approximate flexible arrays in C89 14495 // code. 14496 if (IsTailPaddedMemberArray(*this, size, ND)) 14497 return; 14498 14499 // Suppress the warning if the subscript expression (as identified by the 14500 // ']' location) and the index expression are both from macro expansions 14501 // within a system header. 14502 if (ASE) { 14503 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14504 ASE->getRBracketLoc()); 14505 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14506 SourceLocation IndexLoc = 14507 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14508 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14509 return; 14510 } 14511 } 14512 14513 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 14514 if (ASE) 14515 DiagID = diag::warn_array_index_exceeds_bounds; 14516 14517 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14518 PDiag(DiagID) << index.toString(10, true) 14519 << size.toString(10, true) 14520 << (unsigned)size.getLimitedValue(~0U) 14521 << IndexExpr->getSourceRange()); 14522 } else { 14523 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14524 if (!ASE) { 14525 DiagID = diag::warn_ptr_arith_precedes_bounds; 14526 if (index.isNegative()) index = -index; 14527 } 14528 14529 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14530 PDiag(DiagID) << index.toString(10, true) 14531 << IndexExpr->getSourceRange()); 14532 } 14533 14534 if (!ND) { 14535 // Try harder to find a NamedDecl to point at in the note. 14536 while (const ArraySubscriptExpr *ASE = 14537 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14538 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14539 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14540 ND = DRE->getDecl(); 14541 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14542 ND = ME->getMemberDecl(); 14543 } 14544 14545 if (ND) 14546 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14547 PDiag(diag::note_array_declared_here) << ND); 14548 } 14549 14550 void Sema::CheckArrayAccess(const Expr *expr) { 14551 int AllowOnePastEnd = 0; 14552 while (expr) { 14553 expr = expr->IgnoreParenImpCasts(); 14554 switch (expr->getStmtClass()) { 14555 case Stmt::ArraySubscriptExprClass: { 14556 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14557 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14558 AllowOnePastEnd > 0); 14559 expr = ASE->getBase(); 14560 break; 14561 } 14562 case Stmt::MemberExprClass: { 14563 expr = cast<MemberExpr>(expr)->getBase(); 14564 break; 14565 } 14566 case Stmt::OMPArraySectionExprClass: { 14567 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 14568 if (ASE->getLowerBound()) 14569 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 14570 /*ASE=*/nullptr, AllowOnePastEnd > 0); 14571 return; 14572 } 14573 case Stmt::UnaryOperatorClass: { 14574 // Only unwrap the * and & unary operators 14575 const UnaryOperator *UO = cast<UnaryOperator>(expr); 14576 expr = UO->getSubExpr(); 14577 switch (UO->getOpcode()) { 14578 case UO_AddrOf: 14579 AllowOnePastEnd++; 14580 break; 14581 case UO_Deref: 14582 AllowOnePastEnd--; 14583 break; 14584 default: 14585 return; 14586 } 14587 break; 14588 } 14589 case Stmt::ConditionalOperatorClass: { 14590 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14591 if (const Expr *lhs = cond->getLHS()) 14592 CheckArrayAccess(lhs); 14593 if (const Expr *rhs = cond->getRHS()) 14594 CheckArrayAccess(rhs); 14595 return; 14596 } 14597 case Stmt::CXXOperatorCallExprClass: { 14598 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14599 for (const auto *Arg : OCE->arguments()) 14600 CheckArrayAccess(Arg); 14601 return; 14602 } 14603 default: 14604 return; 14605 } 14606 } 14607 } 14608 14609 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14610 14611 namespace { 14612 14613 struct RetainCycleOwner { 14614 VarDecl *Variable = nullptr; 14615 SourceRange Range; 14616 SourceLocation Loc; 14617 bool Indirect = false; 14618 14619 RetainCycleOwner() = default; 14620 14621 void setLocsFrom(Expr *e) { 14622 Loc = e->getExprLoc(); 14623 Range = e->getSourceRange(); 14624 } 14625 }; 14626 14627 } // namespace 14628 14629 /// Consider whether capturing the given variable can possibly lead to 14630 /// a retain cycle. 14631 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14632 // In ARC, it's captured strongly iff the variable has __strong 14633 // lifetime. In MRR, it's captured strongly if the variable is 14634 // __block and has an appropriate type. 14635 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14636 return false; 14637 14638 owner.Variable = var; 14639 if (ref) 14640 owner.setLocsFrom(ref); 14641 return true; 14642 } 14643 14644 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14645 while (true) { 14646 e = e->IgnoreParens(); 14647 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14648 switch (cast->getCastKind()) { 14649 case CK_BitCast: 14650 case CK_LValueBitCast: 14651 case CK_LValueToRValue: 14652 case CK_ARCReclaimReturnedObject: 14653 e = cast->getSubExpr(); 14654 continue; 14655 14656 default: 14657 return false; 14658 } 14659 } 14660 14661 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14662 ObjCIvarDecl *ivar = ref->getDecl(); 14663 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14664 return false; 14665 14666 // Try to find a retain cycle in the base. 14667 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14668 return false; 14669 14670 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14671 owner.Indirect = true; 14672 return true; 14673 } 14674 14675 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14676 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14677 if (!var) return false; 14678 return considerVariable(var, ref, owner); 14679 } 14680 14681 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14682 if (member->isArrow()) return false; 14683 14684 // Don't count this as an indirect ownership. 14685 e = member->getBase(); 14686 continue; 14687 } 14688 14689 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14690 // Only pay attention to pseudo-objects on property references. 14691 ObjCPropertyRefExpr *pre 14692 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14693 ->IgnoreParens()); 14694 if (!pre) return false; 14695 if (pre->isImplicitProperty()) return false; 14696 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14697 if (!property->isRetaining() && 14698 !(property->getPropertyIvarDecl() && 14699 property->getPropertyIvarDecl()->getType() 14700 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14701 return false; 14702 14703 owner.Indirect = true; 14704 if (pre->isSuperReceiver()) { 14705 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14706 if (!owner.Variable) 14707 return false; 14708 owner.Loc = pre->getLocation(); 14709 owner.Range = pre->getSourceRange(); 14710 return true; 14711 } 14712 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14713 ->getSourceExpr()); 14714 continue; 14715 } 14716 14717 // Array ivars? 14718 14719 return false; 14720 } 14721 } 14722 14723 namespace { 14724 14725 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14726 ASTContext &Context; 14727 VarDecl *Variable; 14728 Expr *Capturer = nullptr; 14729 bool VarWillBeReased = false; 14730 14731 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14732 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14733 Context(Context), Variable(variable) {} 14734 14735 void VisitDeclRefExpr(DeclRefExpr *ref) { 14736 if (ref->getDecl() == Variable && !Capturer) 14737 Capturer = ref; 14738 } 14739 14740 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14741 if (Capturer) return; 14742 Visit(ref->getBase()); 14743 if (Capturer && ref->isFreeIvar()) 14744 Capturer = ref; 14745 } 14746 14747 void VisitBlockExpr(BlockExpr *block) { 14748 // Look inside nested blocks 14749 if (block->getBlockDecl()->capturesVariable(Variable)) 14750 Visit(block->getBlockDecl()->getBody()); 14751 } 14752 14753 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14754 if (Capturer) return; 14755 if (OVE->getSourceExpr()) 14756 Visit(OVE->getSourceExpr()); 14757 } 14758 14759 void VisitBinaryOperator(BinaryOperator *BinOp) { 14760 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14761 return; 14762 Expr *LHS = BinOp->getLHS(); 14763 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14764 if (DRE->getDecl() != Variable) 14765 return; 14766 if (Expr *RHS = BinOp->getRHS()) { 14767 RHS = RHS->IgnoreParenCasts(); 14768 Optional<llvm::APSInt> Value; 14769 VarWillBeReased = 14770 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14771 *Value == 0); 14772 } 14773 } 14774 } 14775 }; 14776 14777 } // namespace 14778 14779 /// Check whether the given argument is a block which captures a 14780 /// variable. 14781 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14782 assert(owner.Variable && owner.Loc.isValid()); 14783 14784 e = e->IgnoreParenCasts(); 14785 14786 // Look through [^{...} copy] and Block_copy(^{...}). 14787 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14788 Selector Cmd = ME->getSelector(); 14789 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14790 e = ME->getInstanceReceiver(); 14791 if (!e) 14792 return nullptr; 14793 e = e->IgnoreParenCasts(); 14794 } 14795 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14796 if (CE->getNumArgs() == 1) { 14797 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14798 if (Fn) { 14799 const IdentifierInfo *FnI = Fn->getIdentifier(); 14800 if (FnI && FnI->isStr("_Block_copy")) { 14801 e = CE->getArg(0)->IgnoreParenCasts(); 14802 } 14803 } 14804 } 14805 } 14806 14807 BlockExpr *block = dyn_cast<BlockExpr>(e); 14808 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14809 return nullptr; 14810 14811 FindCaptureVisitor visitor(S.Context, owner.Variable); 14812 visitor.Visit(block->getBlockDecl()->getBody()); 14813 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14814 } 14815 14816 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14817 RetainCycleOwner &owner) { 14818 assert(capturer); 14819 assert(owner.Variable && owner.Loc.isValid()); 14820 14821 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14822 << owner.Variable << capturer->getSourceRange(); 14823 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14824 << owner.Indirect << owner.Range; 14825 } 14826 14827 /// Check for a keyword selector that starts with the word 'add' or 14828 /// 'set'. 14829 static bool isSetterLikeSelector(Selector sel) { 14830 if (sel.isUnarySelector()) return false; 14831 14832 StringRef str = sel.getNameForSlot(0); 14833 while (!str.empty() && str.front() == '_') str = str.substr(1); 14834 if (str.startswith("set")) 14835 str = str.substr(3); 14836 else if (str.startswith("add")) { 14837 // Specially allow 'addOperationWithBlock:'. 14838 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14839 return false; 14840 str = str.substr(3); 14841 } 14842 else 14843 return false; 14844 14845 if (str.empty()) return true; 14846 return !isLowercase(str.front()); 14847 } 14848 14849 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14850 ObjCMessageExpr *Message) { 14851 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14852 Message->getReceiverInterface(), 14853 NSAPI::ClassId_NSMutableArray); 14854 if (!IsMutableArray) { 14855 return None; 14856 } 14857 14858 Selector Sel = Message->getSelector(); 14859 14860 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14861 S.NSAPIObj->getNSArrayMethodKind(Sel); 14862 if (!MKOpt) { 14863 return None; 14864 } 14865 14866 NSAPI::NSArrayMethodKind MK = *MKOpt; 14867 14868 switch (MK) { 14869 case NSAPI::NSMutableArr_addObject: 14870 case NSAPI::NSMutableArr_insertObjectAtIndex: 14871 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14872 return 0; 14873 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14874 return 1; 14875 14876 default: 14877 return None; 14878 } 14879 14880 return None; 14881 } 14882 14883 static 14884 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14885 ObjCMessageExpr *Message) { 14886 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14887 Message->getReceiverInterface(), 14888 NSAPI::ClassId_NSMutableDictionary); 14889 if (!IsMutableDictionary) { 14890 return None; 14891 } 14892 14893 Selector Sel = Message->getSelector(); 14894 14895 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14896 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14897 if (!MKOpt) { 14898 return None; 14899 } 14900 14901 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14902 14903 switch (MK) { 14904 case NSAPI::NSMutableDict_setObjectForKey: 14905 case NSAPI::NSMutableDict_setValueForKey: 14906 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14907 return 0; 14908 14909 default: 14910 return None; 14911 } 14912 14913 return None; 14914 } 14915 14916 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14917 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14918 Message->getReceiverInterface(), 14919 NSAPI::ClassId_NSMutableSet); 14920 14921 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14922 Message->getReceiverInterface(), 14923 NSAPI::ClassId_NSMutableOrderedSet); 14924 if (!IsMutableSet && !IsMutableOrderedSet) { 14925 return None; 14926 } 14927 14928 Selector Sel = Message->getSelector(); 14929 14930 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14931 if (!MKOpt) { 14932 return None; 14933 } 14934 14935 NSAPI::NSSetMethodKind MK = *MKOpt; 14936 14937 switch (MK) { 14938 case NSAPI::NSMutableSet_addObject: 14939 case NSAPI::NSOrderedSet_setObjectAtIndex: 14940 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14941 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14942 return 0; 14943 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14944 return 1; 14945 } 14946 14947 return None; 14948 } 14949 14950 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14951 if (!Message->isInstanceMessage()) { 14952 return; 14953 } 14954 14955 Optional<int> ArgOpt; 14956 14957 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14958 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14959 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14960 return; 14961 } 14962 14963 int ArgIndex = *ArgOpt; 14964 14965 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14966 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14967 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14968 } 14969 14970 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14971 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14972 if (ArgRE->isObjCSelfExpr()) { 14973 Diag(Message->getSourceRange().getBegin(), 14974 diag::warn_objc_circular_container) 14975 << ArgRE->getDecl() << StringRef("'super'"); 14976 } 14977 } 14978 } else { 14979 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14980 14981 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14982 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14983 } 14984 14985 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14986 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14987 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14988 ValueDecl *Decl = ReceiverRE->getDecl(); 14989 Diag(Message->getSourceRange().getBegin(), 14990 diag::warn_objc_circular_container) 14991 << Decl << Decl; 14992 if (!ArgRE->isObjCSelfExpr()) { 14993 Diag(Decl->getLocation(), 14994 diag::note_objc_circular_container_declared_here) 14995 << Decl; 14996 } 14997 } 14998 } 14999 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15000 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15001 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15002 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15003 Diag(Message->getSourceRange().getBegin(), 15004 diag::warn_objc_circular_container) 15005 << Decl << Decl; 15006 Diag(Decl->getLocation(), 15007 diag::note_objc_circular_container_declared_here) 15008 << Decl; 15009 } 15010 } 15011 } 15012 } 15013 } 15014 15015 /// Check a message send to see if it's likely to cause a retain cycle. 15016 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15017 // Only check instance methods whose selector looks like a setter. 15018 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15019 return; 15020 15021 // Try to find a variable that the receiver is strongly owned by. 15022 RetainCycleOwner owner; 15023 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15024 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15025 return; 15026 } else { 15027 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15028 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15029 owner.Loc = msg->getSuperLoc(); 15030 owner.Range = msg->getSuperLoc(); 15031 } 15032 15033 // Check whether the receiver is captured by any of the arguments. 15034 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15035 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15036 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15037 // noescape blocks should not be retained by the method. 15038 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15039 continue; 15040 return diagnoseRetainCycle(*this, capturer, owner); 15041 } 15042 } 15043 } 15044 15045 /// Check a property assign to see if it's likely to cause a retain cycle. 15046 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15047 RetainCycleOwner owner; 15048 if (!findRetainCycleOwner(*this, receiver, owner)) 15049 return; 15050 15051 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15052 diagnoseRetainCycle(*this, capturer, owner); 15053 } 15054 15055 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15056 RetainCycleOwner Owner; 15057 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15058 return; 15059 15060 // Because we don't have an expression for the variable, we have to set the 15061 // location explicitly here. 15062 Owner.Loc = Var->getLocation(); 15063 Owner.Range = Var->getSourceRange(); 15064 15065 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15066 diagnoseRetainCycle(*this, Capturer, Owner); 15067 } 15068 15069 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15070 Expr *RHS, bool isProperty) { 15071 // Check if RHS is an Objective-C object literal, which also can get 15072 // immediately zapped in a weak reference. Note that we explicitly 15073 // allow ObjCStringLiterals, since those are designed to never really die. 15074 RHS = RHS->IgnoreParenImpCasts(); 15075 15076 // This enum needs to match with the 'select' in 15077 // warn_objc_arc_literal_assign (off-by-1). 15078 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15079 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15080 return false; 15081 15082 S.Diag(Loc, diag::warn_arc_literal_assign) 15083 << (unsigned) Kind 15084 << (isProperty ? 0 : 1) 15085 << RHS->getSourceRange(); 15086 15087 return true; 15088 } 15089 15090 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15091 Qualifiers::ObjCLifetime LT, 15092 Expr *RHS, bool isProperty) { 15093 // Strip off any implicit cast added to get to the one ARC-specific. 15094 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15095 if (cast->getCastKind() == CK_ARCConsumeObject) { 15096 S.Diag(Loc, diag::warn_arc_retained_assign) 15097 << (LT == Qualifiers::OCL_ExplicitNone) 15098 << (isProperty ? 0 : 1) 15099 << RHS->getSourceRange(); 15100 return true; 15101 } 15102 RHS = cast->getSubExpr(); 15103 } 15104 15105 if (LT == Qualifiers::OCL_Weak && 15106 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15107 return true; 15108 15109 return false; 15110 } 15111 15112 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15113 QualType LHS, Expr *RHS) { 15114 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15115 15116 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15117 return false; 15118 15119 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15120 return true; 15121 15122 return false; 15123 } 15124 15125 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15126 Expr *LHS, Expr *RHS) { 15127 QualType LHSType; 15128 // PropertyRef on LHS type need be directly obtained from 15129 // its declaration as it has a PseudoType. 15130 ObjCPropertyRefExpr *PRE 15131 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15132 if (PRE && !PRE->isImplicitProperty()) { 15133 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15134 if (PD) 15135 LHSType = PD->getType(); 15136 } 15137 15138 if (LHSType.isNull()) 15139 LHSType = LHS->getType(); 15140 15141 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15142 15143 if (LT == Qualifiers::OCL_Weak) { 15144 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15145 getCurFunction()->markSafeWeakUse(LHS); 15146 } 15147 15148 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15149 return; 15150 15151 // FIXME. Check for other life times. 15152 if (LT != Qualifiers::OCL_None) 15153 return; 15154 15155 if (PRE) { 15156 if (PRE->isImplicitProperty()) 15157 return; 15158 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15159 if (!PD) 15160 return; 15161 15162 unsigned Attributes = PD->getPropertyAttributes(); 15163 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15164 // when 'assign' attribute was not explicitly specified 15165 // by user, ignore it and rely on property type itself 15166 // for lifetime info. 15167 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15168 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15169 LHSType->isObjCRetainableType()) 15170 return; 15171 15172 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15173 if (cast->getCastKind() == CK_ARCConsumeObject) { 15174 Diag(Loc, diag::warn_arc_retained_property_assign) 15175 << RHS->getSourceRange(); 15176 return; 15177 } 15178 RHS = cast->getSubExpr(); 15179 } 15180 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15181 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15182 return; 15183 } 15184 } 15185 } 15186 15187 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15188 15189 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15190 SourceLocation StmtLoc, 15191 const NullStmt *Body) { 15192 // Do not warn if the body is a macro that expands to nothing, e.g: 15193 // 15194 // #define CALL(x) 15195 // if (condition) 15196 // CALL(0); 15197 if (Body->hasLeadingEmptyMacro()) 15198 return false; 15199 15200 // Get line numbers of statement and body. 15201 bool StmtLineInvalid; 15202 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15203 &StmtLineInvalid); 15204 if (StmtLineInvalid) 15205 return false; 15206 15207 bool BodyLineInvalid; 15208 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15209 &BodyLineInvalid); 15210 if (BodyLineInvalid) 15211 return false; 15212 15213 // Warn if null statement and body are on the same line. 15214 if (StmtLine != BodyLine) 15215 return false; 15216 15217 return true; 15218 } 15219 15220 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15221 const Stmt *Body, 15222 unsigned DiagID) { 15223 // Since this is a syntactic check, don't emit diagnostic for template 15224 // instantiations, this just adds noise. 15225 if (CurrentInstantiationScope) 15226 return; 15227 15228 // The body should be a null statement. 15229 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15230 if (!NBody) 15231 return; 15232 15233 // Do the usual checks. 15234 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15235 return; 15236 15237 Diag(NBody->getSemiLoc(), DiagID); 15238 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15239 } 15240 15241 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15242 const Stmt *PossibleBody) { 15243 assert(!CurrentInstantiationScope); // Ensured by caller 15244 15245 SourceLocation StmtLoc; 15246 const Stmt *Body; 15247 unsigned DiagID; 15248 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15249 StmtLoc = FS->getRParenLoc(); 15250 Body = FS->getBody(); 15251 DiagID = diag::warn_empty_for_body; 15252 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15253 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15254 Body = WS->getBody(); 15255 DiagID = diag::warn_empty_while_body; 15256 } else 15257 return; // Neither `for' nor `while'. 15258 15259 // The body should be a null statement. 15260 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15261 if (!NBody) 15262 return; 15263 15264 // Skip expensive checks if diagnostic is disabled. 15265 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15266 return; 15267 15268 // Do the usual checks. 15269 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15270 return; 15271 15272 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15273 // noise level low, emit diagnostics only if for/while is followed by a 15274 // CompoundStmt, e.g.: 15275 // for (int i = 0; i < n; i++); 15276 // { 15277 // a(i); 15278 // } 15279 // or if for/while is followed by a statement with more indentation 15280 // than for/while itself: 15281 // for (int i = 0; i < n; i++); 15282 // a(i); 15283 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15284 if (!ProbableTypo) { 15285 bool BodyColInvalid; 15286 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15287 PossibleBody->getBeginLoc(), &BodyColInvalid); 15288 if (BodyColInvalid) 15289 return; 15290 15291 bool StmtColInvalid; 15292 unsigned StmtCol = 15293 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15294 if (StmtColInvalid) 15295 return; 15296 15297 if (BodyCol > StmtCol) 15298 ProbableTypo = true; 15299 } 15300 15301 if (ProbableTypo) { 15302 Diag(NBody->getSemiLoc(), DiagID); 15303 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15304 } 15305 } 15306 15307 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15308 15309 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15310 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15311 SourceLocation OpLoc) { 15312 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15313 return; 15314 15315 if (inTemplateInstantiation()) 15316 return; 15317 15318 // Strip parens and casts away. 15319 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15320 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15321 15322 // Check for a call expression 15323 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15324 if (!CE || CE->getNumArgs() != 1) 15325 return; 15326 15327 // Check for a call to std::move 15328 if (!CE->isCallToStdMove()) 15329 return; 15330 15331 // Get argument from std::move 15332 RHSExpr = CE->getArg(0); 15333 15334 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15335 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15336 15337 // Two DeclRefExpr's, check that the decls are the same. 15338 if (LHSDeclRef && RHSDeclRef) { 15339 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15340 return; 15341 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15342 RHSDeclRef->getDecl()->getCanonicalDecl()) 15343 return; 15344 15345 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15346 << LHSExpr->getSourceRange() 15347 << RHSExpr->getSourceRange(); 15348 return; 15349 } 15350 15351 // Member variables require a different approach to check for self moves. 15352 // MemberExpr's are the same if every nested MemberExpr refers to the same 15353 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15354 // the base Expr's are CXXThisExpr's. 15355 const Expr *LHSBase = LHSExpr; 15356 const Expr *RHSBase = RHSExpr; 15357 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15358 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15359 if (!LHSME || !RHSME) 15360 return; 15361 15362 while (LHSME && RHSME) { 15363 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15364 RHSME->getMemberDecl()->getCanonicalDecl()) 15365 return; 15366 15367 LHSBase = LHSME->getBase(); 15368 RHSBase = RHSME->getBase(); 15369 LHSME = dyn_cast<MemberExpr>(LHSBase); 15370 RHSME = dyn_cast<MemberExpr>(RHSBase); 15371 } 15372 15373 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15374 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15375 if (LHSDeclRef && RHSDeclRef) { 15376 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15377 return; 15378 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15379 RHSDeclRef->getDecl()->getCanonicalDecl()) 15380 return; 15381 15382 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15383 << LHSExpr->getSourceRange() 15384 << RHSExpr->getSourceRange(); 15385 return; 15386 } 15387 15388 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15389 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15390 << LHSExpr->getSourceRange() 15391 << RHSExpr->getSourceRange(); 15392 } 15393 15394 //===--- Layout compatibility ----------------------------------------------// 15395 15396 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15397 15398 /// Check if two enumeration types are layout-compatible. 15399 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15400 // C++11 [dcl.enum] p8: 15401 // Two enumeration types are layout-compatible if they have the same 15402 // underlying type. 15403 return ED1->isComplete() && ED2->isComplete() && 15404 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15405 } 15406 15407 /// Check if two fields are layout-compatible. 15408 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15409 FieldDecl *Field2) { 15410 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15411 return false; 15412 15413 if (Field1->isBitField() != Field2->isBitField()) 15414 return false; 15415 15416 if (Field1->isBitField()) { 15417 // Make sure that the bit-fields are the same length. 15418 unsigned Bits1 = Field1->getBitWidthValue(C); 15419 unsigned Bits2 = Field2->getBitWidthValue(C); 15420 15421 if (Bits1 != Bits2) 15422 return false; 15423 } 15424 15425 return true; 15426 } 15427 15428 /// Check if two standard-layout structs are layout-compatible. 15429 /// (C++11 [class.mem] p17) 15430 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15431 RecordDecl *RD2) { 15432 // If both records are C++ classes, check that base classes match. 15433 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15434 // If one of records is a CXXRecordDecl we are in C++ mode, 15435 // thus the other one is a CXXRecordDecl, too. 15436 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15437 // Check number of base classes. 15438 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15439 return false; 15440 15441 // Check the base classes. 15442 for (CXXRecordDecl::base_class_const_iterator 15443 Base1 = D1CXX->bases_begin(), 15444 BaseEnd1 = D1CXX->bases_end(), 15445 Base2 = D2CXX->bases_begin(); 15446 Base1 != BaseEnd1; 15447 ++Base1, ++Base2) { 15448 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15449 return false; 15450 } 15451 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15452 // If only RD2 is a C++ class, it should have zero base classes. 15453 if (D2CXX->getNumBases() > 0) 15454 return false; 15455 } 15456 15457 // Check the fields. 15458 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15459 Field2End = RD2->field_end(), 15460 Field1 = RD1->field_begin(), 15461 Field1End = RD1->field_end(); 15462 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15463 if (!isLayoutCompatible(C, *Field1, *Field2)) 15464 return false; 15465 } 15466 if (Field1 != Field1End || Field2 != Field2End) 15467 return false; 15468 15469 return true; 15470 } 15471 15472 /// Check if two standard-layout unions are layout-compatible. 15473 /// (C++11 [class.mem] p18) 15474 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15475 RecordDecl *RD2) { 15476 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15477 for (auto *Field2 : RD2->fields()) 15478 UnmatchedFields.insert(Field2); 15479 15480 for (auto *Field1 : RD1->fields()) { 15481 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15482 I = UnmatchedFields.begin(), 15483 E = UnmatchedFields.end(); 15484 15485 for ( ; I != E; ++I) { 15486 if (isLayoutCompatible(C, Field1, *I)) { 15487 bool Result = UnmatchedFields.erase(*I); 15488 (void) Result; 15489 assert(Result); 15490 break; 15491 } 15492 } 15493 if (I == E) 15494 return false; 15495 } 15496 15497 return UnmatchedFields.empty(); 15498 } 15499 15500 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15501 RecordDecl *RD2) { 15502 if (RD1->isUnion() != RD2->isUnion()) 15503 return false; 15504 15505 if (RD1->isUnion()) 15506 return isLayoutCompatibleUnion(C, RD1, RD2); 15507 else 15508 return isLayoutCompatibleStruct(C, RD1, RD2); 15509 } 15510 15511 /// Check if two types are layout-compatible in C++11 sense. 15512 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15513 if (T1.isNull() || T2.isNull()) 15514 return false; 15515 15516 // C++11 [basic.types] p11: 15517 // If two types T1 and T2 are the same type, then T1 and T2 are 15518 // layout-compatible types. 15519 if (C.hasSameType(T1, T2)) 15520 return true; 15521 15522 T1 = T1.getCanonicalType().getUnqualifiedType(); 15523 T2 = T2.getCanonicalType().getUnqualifiedType(); 15524 15525 const Type::TypeClass TC1 = T1->getTypeClass(); 15526 const Type::TypeClass TC2 = T2->getTypeClass(); 15527 15528 if (TC1 != TC2) 15529 return false; 15530 15531 if (TC1 == Type::Enum) { 15532 return isLayoutCompatible(C, 15533 cast<EnumType>(T1)->getDecl(), 15534 cast<EnumType>(T2)->getDecl()); 15535 } else if (TC1 == Type::Record) { 15536 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15537 return false; 15538 15539 return isLayoutCompatible(C, 15540 cast<RecordType>(T1)->getDecl(), 15541 cast<RecordType>(T2)->getDecl()); 15542 } 15543 15544 return false; 15545 } 15546 15547 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15548 15549 /// Given a type tag expression find the type tag itself. 15550 /// 15551 /// \param TypeExpr Type tag expression, as it appears in user's code. 15552 /// 15553 /// \param VD Declaration of an identifier that appears in a type tag. 15554 /// 15555 /// \param MagicValue Type tag magic value. 15556 /// 15557 /// \param isConstantEvaluated wether the evalaution should be performed in 15558 15559 /// constant context. 15560 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15561 const ValueDecl **VD, uint64_t *MagicValue, 15562 bool isConstantEvaluated) { 15563 while(true) { 15564 if (!TypeExpr) 15565 return false; 15566 15567 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 15568 15569 switch (TypeExpr->getStmtClass()) { 15570 case Stmt::UnaryOperatorClass: { 15571 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 15572 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 15573 TypeExpr = UO->getSubExpr(); 15574 continue; 15575 } 15576 return false; 15577 } 15578 15579 case Stmt::DeclRefExprClass: { 15580 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15581 *VD = DRE->getDecl(); 15582 return true; 15583 } 15584 15585 case Stmt::IntegerLiteralClass: { 15586 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15587 llvm::APInt MagicValueAPInt = IL->getValue(); 15588 if (MagicValueAPInt.getActiveBits() <= 64) { 15589 *MagicValue = MagicValueAPInt.getZExtValue(); 15590 return true; 15591 } else 15592 return false; 15593 } 15594 15595 case Stmt::BinaryConditionalOperatorClass: 15596 case Stmt::ConditionalOperatorClass: { 15597 const AbstractConditionalOperator *ACO = 15598 cast<AbstractConditionalOperator>(TypeExpr); 15599 bool Result; 15600 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15601 isConstantEvaluated)) { 15602 if (Result) 15603 TypeExpr = ACO->getTrueExpr(); 15604 else 15605 TypeExpr = ACO->getFalseExpr(); 15606 continue; 15607 } 15608 return false; 15609 } 15610 15611 case Stmt::BinaryOperatorClass: { 15612 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15613 if (BO->getOpcode() == BO_Comma) { 15614 TypeExpr = BO->getRHS(); 15615 continue; 15616 } 15617 return false; 15618 } 15619 15620 default: 15621 return false; 15622 } 15623 } 15624 } 15625 15626 /// Retrieve the C type corresponding to type tag TypeExpr. 15627 /// 15628 /// \param TypeExpr Expression that specifies a type tag. 15629 /// 15630 /// \param MagicValues Registered magic values. 15631 /// 15632 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15633 /// kind. 15634 /// 15635 /// \param TypeInfo Information about the corresponding C type. 15636 /// 15637 /// \param isConstantEvaluated wether the evalaution should be performed in 15638 /// constant context. 15639 /// 15640 /// \returns true if the corresponding C type was found. 15641 static bool GetMatchingCType( 15642 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15643 const ASTContext &Ctx, 15644 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15645 *MagicValues, 15646 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15647 bool isConstantEvaluated) { 15648 FoundWrongKind = false; 15649 15650 // Variable declaration that has type_tag_for_datatype attribute. 15651 const ValueDecl *VD = nullptr; 15652 15653 uint64_t MagicValue; 15654 15655 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15656 return false; 15657 15658 if (VD) { 15659 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15660 if (I->getArgumentKind() != ArgumentKind) { 15661 FoundWrongKind = true; 15662 return false; 15663 } 15664 TypeInfo.Type = I->getMatchingCType(); 15665 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15666 TypeInfo.MustBeNull = I->getMustBeNull(); 15667 return true; 15668 } 15669 return false; 15670 } 15671 15672 if (!MagicValues) 15673 return false; 15674 15675 llvm::DenseMap<Sema::TypeTagMagicValue, 15676 Sema::TypeTagData>::const_iterator I = 15677 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15678 if (I == MagicValues->end()) 15679 return false; 15680 15681 TypeInfo = I->second; 15682 return true; 15683 } 15684 15685 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15686 uint64_t MagicValue, QualType Type, 15687 bool LayoutCompatible, 15688 bool MustBeNull) { 15689 if (!TypeTagForDatatypeMagicValues) 15690 TypeTagForDatatypeMagicValues.reset( 15691 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15692 15693 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15694 (*TypeTagForDatatypeMagicValues)[Magic] = 15695 TypeTagData(Type, LayoutCompatible, MustBeNull); 15696 } 15697 15698 static bool IsSameCharType(QualType T1, QualType T2) { 15699 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15700 if (!BT1) 15701 return false; 15702 15703 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15704 if (!BT2) 15705 return false; 15706 15707 BuiltinType::Kind T1Kind = BT1->getKind(); 15708 BuiltinType::Kind T2Kind = BT2->getKind(); 15709 15710 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15711 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15712 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15713 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15714 } 15715 15716 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15717 const ArrayRef<const Expr *> ExprArgs, 15718 SourceLocation CallSiteLoc) { 15719 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15720 bool IsPointerAttr = Attr->getIsPointer(); 15721 15722 // Retrieve the argument representing the 'type_tag'. 15723 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15724 if (TypeTagIdxAST >= ExprArgs.size()) { 15725 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15726 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15727 return; 15728 } 15729 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15730 bool FoundWrongKind; 15731 TypeTagData TypeInfo; 15732 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15733 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15734 TypeInfo, isConstantEvaluated())) { 15735 if (FoundWrongKind) 15736 Diag(TypeTagExpr->getExprLoc(), 15737 diag::warn_type_tag_for_datatype_wrong_kind) 15738 << TypeTagExpr->getSourceRange(); 15739 return; 15740 } 15741 15742 // Retrieve the argument representing the 'arg_idx'. 15743 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15744 if (ArgumentIdxAST >= ExprArgs.size()) { 15745 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15746 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15747 return; 15748 } 15749 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15750 if (IsPointerAttr) { 15751 // Skip implicit cast of pointer to `void *' (as a function argument). 15752 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15753 if (ICE->getType()->isVoidPointerType() && 15754 ICE->getCastKind() == CK_BitCast) 15755 ArgumentExpr = ICE->getSubExpr(); 15756 } 15757 QualType ArgumentType = ArgumentExpr->getType(); 15758 15759 // Passing a `void*' pointer shouldn't trigger a warning. 15760 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15761 return; 15762 15763 if (TypeInfo.MustBeNull) { 15764 // Type tag with matching void type requires a null pointer. 15765 if (!ArgumentExpr->isNullPointerConstant(Context, 15766 Expr::NPC_ValueDependentIsNotNull)) { 15767 Diag(ArgumentExpr->getExprLoc(), 15768 diag::warn_type_safety_null_pointer_required) 15769 << ArgumentKind->getName() 15770 << ArgumentExpr->getSourceRange() 15771 << TypeTagExpr->getSourceRange(); 15772 } 15773 return; 15774 } 15775 15776 QualType RequiredType = TypeInfo.Type; 15777 if (IsPointerAttr) 15778 RequiredType = Context.getPointerType(RequiredType); 15779 15780 bool mismatch = false; 15781 if (!TypeInfo.LayoutCompatible) { 15782 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15783 15784 // C++11 [basic.fundamental] p1: 15785 // Plain char, signed char, and unsigned char are three distinct types. 15786 // 15787 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15788 // char' depending on the current char signedness mode. 15789 if (mismatch) 15790 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15791 RequiredType->getPointeeType())) || 15792 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15793 mismatch = false; 15794 } else 15795 if (IsPointerAttr) 15796 mismatch = !isLayoutCompatible(Context, 15797 ArgumentType->getPointeeType(), 15798 RequiredType->getPointeeType()); 15799 else 15800 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15801 15802 if (mismatch) 15803 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15804 << ArgumentType << ArgumentKind 15805 << TypeInfo.LayoutCompatible << RequiredType 15806 << ArgumentExpr->getSourceRange() 15807 << TypeTagExpr->getSourceRange(); 15808 } 15809 15810 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15811 CharUnits Alignment) { 15812 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15813 } 15814 15815 void Sema::DiagnoseMisalignedMembers() { 15816 for (MisalignedMember &m : MisalignedMembers) { 15817 const NamedDecl *ND = m.RD; 15818 if (ND->getName().empty()) { 15819 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15820 ND = TD; 15821 } 15822 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15823 << m.MD << ND << m.E->getSourceRange(); 15824 } 15825 MisalignedMembers.clear(); 15826 } 15827 15828 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15829 E = E->IgnoreParens(); 15830 if (!T->isPointerType() && !T->isIntegerType()) 15831 return; 15832 if (isa<UnaryOperator>(E) && 15833 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15834 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15835 if (isa<MemberExpr>(Op)) { 15836 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15837 if (MA != MisalignedMembers.end() && 15838 (T->isIntegerType() || 15839 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15840 Context.getTypeAlignInChars( 15841 T->getPointeeType()) <= MA->Alignment)))) 15842 MisalignedMembers.erase(MA); 15843 } 15844 } 15845 } 15846 15847 void Sema::RefersToMemberWithReducedAlignment( 15848 Expr *E, 15849 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15850 Action) { 15851 const auto *ME = dyn_cast<MemberExpr>(E); 15852 if (!ME) 15853 return; 15854 15855 // No need to check expressions with an __unaligned-qualified type. 15856 if (E->getType().getQualifiers().hasUnaligned()) 15857 return; 15858 15859 // For a chain of MemberExpr like "a.b.c.d" this list 15860 // will keep FieldDecl's like [d, c, b]. 15861 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15862 const MemberExpr *TopME = nullptr; 15863 bool AnyIsPacked = false; 15864 do { 15865 QualType BaseType = ME->getBase()->getType(); 15866 if (BaseType->isDependentType()) 15867 return; 15868 if (ME->isArrow()) 15869 BaseType = BaseType->getPointeeType(); 15870 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15871 if (RD->isInvalidDecl()) 15872 return; 15873 15874 ValueDecl *MD = ME->getMemberDecl(); 15875 auto *FD = dyn_cast<FieldDecl>(MD); 15876 // We do not care about non-data members. 15877 if (!FD || FD->isInvalidDecl()) 15878 return; 15879 15880 AnyIsPacked = 15881 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15882 ReverseMemberChain.push_back(FD); 15883 15884 TopME = ME; 15885 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15886 } while (ME); 15887 assert(TopME && "We did not compute a topmost MemberExpr!"); 15888 15889 // Not the scope of this diagnostic. 15890 if (!AnyIsPacked) 15891 return; 15892 15893 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15894 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15895 // TODO: The innermost base of the member expression may be too complicated. 15896 // For now, just disregard these cases. This is left for future 15897 // improvement. 15898 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15899 return; 15900 15901 // Alignment expected by the whole expression. 15902 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15903 15904 // No need to do anything else with this case. 15905 if (ExpectedAlignment.isOne()) 15906 return; 15907 15908 // Synthesize offset of the whole access. 15909 CharUnits Offset; 15910 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15911 I++) { 15912 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15913 } 15914 15915 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15916 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15917 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15918 15919 // The base expression of the innermost MemberExpr may give 15920 // stronger guarantees than the class containing the member. 15921 if (DRE && !TopME->isArrow()) { 15922 const ValueDecl *VD = DRE->getDecl(); 15923 if (!VD->getType()->isReferenceType()) 15924 CompleteObjectAlignment = 15925 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15926 } 15927 15928 // Check if the synthesized offset fulfills the alignment. 15929 if (Offset % ExpectedAlignment != 0 || 15930 // It may fulfill the offset it but the effective alignment may still be 15931 // lower than the expected expression alignment. 15932 CompleteObjectAlignment < ExpectedAlignment) { 15933 // If this happens, we want to determine a sensible culprit of this. 15934 // Intuitively, watching the chain of member expressions from right to 15935 // left, we start with the required alignment (as required by the field 15936 // type) but some packed attribute in that chain has reduced the alignment. 15937 // It may happen that another packed structure increases it again. But if 15938 // we are here such increase has not been enough. So pointing the first 15939 // FieldDecl that either is packed or else its RecordDecl is, 15940 // seems reasonable. 15941 FieldDecl *FD = nullptr; 15942 CharUnits Alignment; 15943 for (FieldDecl *FDI : ReverseMemberChain) { 15944 if (FDI->hasAttr<PackedAttr>() || 15945 FDI->getParent()->hasAttr<PackedAttr>()) { 15946 FD = FDI; 15947 Alignment = std::min( 15948 Context.getTypeAlignInChars(FD->getType()), 15949 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15950 break; 15951 } 15952 } 15953 assert(FD && "We did not find a packed FieldDecl!"); 15954 Action(E, FD->getParent(), FD, Alignment); 15955 } 15956 } 15957 15958 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15959 using namespace std::placeholders; 15960 15961 RefersToMemberWithReducedAlignment( 15962 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15963 _2, _3, _4)); 15964 } 15965 15966 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15967 ExprResult CallResult) { 15968 if (checkArgCount(*this, TheCall, 1)) 15969 return ExprError(); 15970 15971 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15972 if (MatrixArg.isInvalid()) 15973 return MatrixArg; 15974 Expr *Matrix = MatrixArg.get(); 15975 15976 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15977 if (!MType) { 15978 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 15979 return ExprError(); 15980 } 15981 15982 // Create returned matrix type by swapping rows and columns of the argument 15983 // matrix type. 15984 QualType ResultType = Context.getConstantMatrixType( 15985 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15986 15987 // Change the return type to the type of the returned matrix. 15988 TheCall->setType(ResultType); 15989 15990 // Update call argument to use the possibly converted matrix argument. 15991 TheCall->setArg(0, Matrix); 15992 return CallResult; 15993 } 15994 15995 // Get and verify the matrix dimensions. 15996 static llvm::Optional<unsigned> 15997 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 15998 SourceLocation ErrorPos; 15999 Optional<llvm::APSInt> Value = 16000 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16001 if (!Value) { 16002 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16003 << Name; 16004 return {}; 16005 } 16006 uint64_t Dim = Value->getZExtValue(); 16007 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16008 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16009 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16010 return {}; 16011 } 16012 return Dim; 16013 } 16014 16015 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16016 ExprResult CallResult) { 16017 if (!getLangOpts().MatrixTypes) { 16018 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16019 return ExprError(); 16020 } 16021 16022 if (checkArgCount(*this, TheCall, 4)) 16023 return ExprError(); 16024 16025 unsigned PtrArgIdx = 0; 16026 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16027 Expr *RowsExpr = TheCall->getArg(1); 16028 Expr *ColumnsExpr = TheCall->getArg(2); 16029 Expr *StrideExpr = TheCall->getArg(3); 16030 16031 bool ArgError = false; 16032 16033 // Check pointer argument. 16034 { 16035 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16036 if (PtrConv.isInvalid()) 16037 return PtrConv; 16038 PtrExpr = PtrConv.get(); 16039 TheCall->setArg(0, PtrExpr); 16040 if (PtrExpr->isTypeDependent()) { 16041 TheCall->setType(Context.DependentTy); 16042 return TheCall; 16043 } 16044 } 16045 16046 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16047 QualType ElementTy; 16048 if (!PtrTy) { 16049 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16050 << PtrArgIdx + 1; 16051 ArgError = true; 16052 } else { 16053 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16054 16055 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16056 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16057 << PtrArgIdx + 1; 16058 ArgError = true; 16059 } 16060 } 16061 16062 // Apply default Lvalue conversions and convert the expression to size_t. 16063 auto ApplyArgumentConversions = [this](Expr *E) { 16064 ExprResult Conv = DefaultLvalueConversion(E); 16065 if (Conv.isInvalid()) 16066 return Conv; 16067 16068 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16069 }; 16070 16071 // Apply conversion to row and column expressions. 16072 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16073 if (!RowsConv.isInvalid()) { 16074 RowsExpr = RowsConv.get(); 16075 TheCall->setArg(1, RowsExpr); 16076 } else 16077 RowsExpr = nullptr; 16078 16079 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16080 if (!ColumnsConv.isInvalid()) { 16081 ColumnsExpr = ColumnsConv.get(); 16082 TheCall->setArg(2, ColumnsExpr); 16083 } else 16084 ColumnsExpr = nullptr; 16085 16086 // If any any part of the result matrix type is still pending, just use 16087 // Context.DependentTy, until all parts are resolved. 16088 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16089 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16090 TheCall->setType(Context.DependentTy); 16091 return CallResult; 16092 } 16093 16094 // Check row and column dimenions. 16095 llvm::Optional<unsigned> MaybeRows; 16096 if (RowsExpr) 16097 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16098 16099 llvm::Optional<unsigned> MaybeColumns; 16100 if (ColumnsExpr) 16101 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16102 16103 // Check stride argument. 16104 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16105 if (StrideConv.isInvalid()) 16106 return ExprError(); 16107 StrideExpr = StrideConv.get(); 16108 TheCall->setArg(3, StrideExpr); 16109 16110 if (MaybeRows) { 16111 if (Optional<llvm::APSInt> Value = 16112 StrideExpr->getIntegerConstantExpr(Context)) { 16113 uint64_t Stride = Value->getZExtValue(); 16114 if (Stride < *MaybeRows) { 16115 Diag(StrideExpr->getBeginLoc(), 16116 diag::err_builtin_matrix_stride_too_small); 16117 ArgError = true; 16118 } 16119 } 16120 } 16121 16122 if (ArgError || !MaybeRows || !MaybeColumns) 16123 return ExprError(); 16124 16125 TheCall->setType( 16126 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16127 return CallResult; 16128 } 16129 16130 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16131 ExprResult CallResult) { 16132 if (checkArgCount(*this, TheCall, 3)) 16133 return ExprError(); 16134 16135 unsigned PtrArgIdx = 1; 16136 Expr *MatrixExpr = TheCall->getArg(0); 16137 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16138 Expr *StrideExpr = TheCall->getArg(2); 16139 16140 bool ArgError = false; 16141 16142 { 16143 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16144 if (MatrixConv.isInvalid()) 16145 return MatrixConv; 16146 MatrixExpr = MatrixConv.get(); 16147 TheCall->setArg(0, MatrixExpr); 16148 } 16149 if (MatrixExpr->isTypeDependent()) { 16150 TheCall->setType(Context.DependentTy); 16151 return TheCall; 16152 } 16153 16154 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16155 if (!MatrixTy) { 16156 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16157 ArgError = true; 16158 } 16159 16160 { 16161 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16162 if (PtrConv.isInvalid()) 16163 return PtrConv; 16164 PtrExpr = PtrConv.get(); 16165 TheCall->setArg(1, PtrExpr); 16166 if (PtrExpr->isTypeDependent()) { 16167 TheCall->setType(Context.DependentTy); 16168 return TheCall; 16169 } 16170 } 16171 16172 // Check pointer argument. 16173 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16174 if (!PtrTy) { 16175 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16176 << PtrArgIdx + 1; 16177 ArgError = true; 16178 } else { 16179 QualType ElementTy = PtrTy->getPointeeType(); 16180 if (ElementTy.isConstQualified()) { 16181 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16182 ArgError = true; 16183 } 16184 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16185 if (MatrixTy && 16186 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16187 Diag(PtrExpr->getBeginLoc(), 16188 diag::err_builtin_matrix_pointer_arg_mismatch) 16189 << ElementTy << MatrixTy->getElementType(); 16190 ArgError = true; 16191 } 16192 } 16193 16194 // Apply default Lvalue conversions and convert the stride expression to 16195 // size_t. 16196 { 16197 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16198 if (StrideConv.isInvalid()) 16199 return StrideConv; 16200 16201 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16202 if (StrideConv.isInvalid()) 16203 return StrideConv; 16204 StrideExpr = StrideConv.get(); 16205 TheCall->setArg(2, StrideExpr); 16206 } 16207 16208 // Check stride argument. 16209 if (MatrixTy) { 16210 if (Optional<llvm::APSInt> Value = 16211 StrideExpr->getIntegerConstantExpr(Context)) { 16212 uint64_t Stride = Value->getZExtValue(); 16213 if (Stride < MatrixTy->getNumRows()) { 16214 Diag(StrideExpr->getBeginLoc(), 16215 diag::err_builtin_matrix_stride_too_small); 16216 ArgError = true; 16217 } 16218 } 16219 } 16220 16221 if (ArgError) 16222 return ExprError(); 16223 16224 return CallResult; 16225 } 16226 16227 /// \brief Enforce the bounds of a TCB 16228 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16229 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16230 /// and enforce_tcb_leaf attributes. 16231 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16232 const FunctionDecl *Callee) { 16233 const FunctionDecl *Caller = getCurFunctionDecl(); 16234 16235 // Calls to builtins are not enforced. 16236 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16237 Callee->getBuiltinID() != 0) 16238 return; 16239 16240 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16241 // all TCBs the callee is a part of. 16242 llvm::StringSet<> CalleeTCBs; 16243 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16244 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16245 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16246 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16247 16248 // Go through the TCBs the caller is a part of and emit warnings if Caller 16249 // is in a TCB that the Callee is not. 16250 for_each( 16251 Caller->specific_attrs<EnforceTCBAttr>(), 16252 [&](const auto *A) { 16253 StringRef CallerTCB = A->getTCBName(); 16254 if (CalleeTCBs.count(CallerTCB) == 0) { 16255 this->Diag(TheCall->getExprLoc(), 16256 diag::warn_tcb_enforcement_violation) << Callee 16257 << CallerTCB; 16258 } 16259 }); 16260 } 16261