1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check the number of arguments and set the result type to 199 /// the argument type. 200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 201 if (checkArgCount(S, TheCall, 1)) 202 return true; 203 204 TheCall->setType(TheCall->getArg(0)->getType()); 205 return false; 206 } 207 208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 210 /// type (but not a function pointer) and that the alignment is a power-of-two. 211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 212 if (checkArgCount(S, TheCall, 2)) 213 return true; 214 215 clang::Expr *Source = TheCall->getArg(0); 216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 217 218 auto IsValidIntegerType = [](QualType Ty) { 219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 220 }; 221 QualType SrcTy = Source->getType(); 222 // We should also be able to use it with arrays (but not functions!). 223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 224 SrcTy = S.Context.getDecayedType(SrcTy); 225 } 226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 227 SrcTy->isFunctionPointerType()) { 228 // FIXME: this is not quite the right error message since we don't allow 229 // floating point types, or member pointers. 230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 231 << SrcTy; 232 return true; 233 } 234 235 clang::Expr *AlignOp = TheCall->getArg(1); 236 if (!IsValidIntegerType(AlignOp->getType())) { 237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 238 << AlignOp->getType(); 239 return true; 240 } 241 Expr::EvalResult AlignResult; 242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 243 // We can't check validity of alignment if it is value dependent. 244 if (!AlignOp->isValueDependent() && 245 AlignOp->EvaluateAsInt(AlignResult, S.Context, 246 Expr::SE_AllowSideEffects)) { 247 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 248 llvm::APSInt MaxValue( 249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 250 if (AlignValue < 1) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 252 return true; 253 } 254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 256 << MaxValue.toString(10); 257 return true; 258 } 259 if (!AlignValue.isPowerOf2()) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 261 return true; 262 } 263 if (AlignValue == 1) { 264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 265 << IsBooleanAlignBuiltin; 266 } 267 } 268 269 ExprResult SrcArg = S.PerformCopyInitialization( 270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 271 SourceLocation(), Source); 272 if (SrcArg.isInvalid()) 273 return true; 274 TheCall->setArg(0, SrcArg.get()); 275 ExprResult AlignArg = 276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 277 S.Context, AlignOp->getType(), false), 278 SourceLocation(), AlignOp); 279 if (AlignArg.isInvalid()) 280 return true; 281 TheCall->setArg(1, AlignArg.get()); 282 // For align_up/align_down, the return type is the same as the (potentially 283 // decayed) argument type including qualifiers. For is_aligned(), the result 284 // is always bool. 285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 286 return false; 287 } 288 289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 290 unsigned BuiltinID) { 291 if (checkArgCount(S, TheCall, 3)) 292 return true; 293 294 // First two arguments should be integers. 295 for (unsigned I = 0; I < 2; ++I) { 296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 297 if (Arg.isInvalid()) return true; 298 TheCall->setArg(I, Arg.get()); 299 300 QualType Ty = Arg.get()->getType(); 301 if (!Ty->isIntegerType()) { 302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 303 << Ty << Arg.get()->getSourceRange(); 304 return true; 305 } 306 } 307 308 // Third argument should be a pointer to a non-const integer. 309 // IRGen correctly handles volatile, restrict, and address spaces, and 310 // the other qualifiers aren't possible. 311 { 312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 313 if (Arg.isInvalid()) return true; 314 TheCall->setArg(2, Arg.get()); 315 316 QualType Ty = Arg.get()->getType(); 317 const auto *PtrTy = Ty->getAs<PointerType>(); 318 if (!PtrTy || 319 !PtrTy->getPointeeType()->isIntegerType() || 320 PtrTy->getPointeeType().isConstQualified()) { 321 S.Diag(Arg.get()->getBeginLoc(), 322 diag::err_overflow_builtin_must_be_ptr_int) 323 << Ty << Arg.get()->getSourceRange(); 324 return true; 325 } 326 } 327 328 // Disallow signed ExtIntType args larger than 128 bits to mul function until 329 // we improve backend support. 330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 331 for (unsigned I = 0; I < 3; ++I) { 332 const auto Arg = TheCall->getArg(I); 333 // Third argument will be a pointer. 334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 335 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 336 S.getASTContext().getIntWidth(Ty) > 128) 337 return S.Diag(Arg->getBeginLoc(), 338 diag::err_overflow_builtin_ext_int_max_size) 339 << 128; 340 } 341 } 342 343 return false; 344 } 345 346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 347 if (checkArgCount(S, BuiltinCall, 2)) 348 return true; 349 350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 352 Expr *Call = BuiltinCall->getArg(0); 353 Expr *Chain = BuiltinCall->getArg(1); 354 355 if (Call->getStmtClass() != Stmt::CallExprClass) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 auto CE = cast<CallExpr>(Call); 362 if (CE->getCallee()->getType()->isBlockPointerType()) { 363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 364 << Call->getSourceRange(); 365 return true; 366 } 367 368 const Decl *TargetDecl = CE->getCalleeDecl(); 369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 370 if (FD->getBuiltinID()) { 371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 372 << Call->getSourceRange(); 373 return true; 374 } 375 376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 378 << Call->getSourceRange(); 379 return true; 380 } 381 382 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 383 if (ChainResult.isInvalid()) 384 return true; 385 if (!ChainResult.get()->getType()->isPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 387 << Chain->getSourceRange(); 388 return true; 389 } 390 391 QualType ReturnTy = CE->getCallReturnType(S.Context); 392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 393 QualType BuiltinTy = S.Context.getFunctionType( 394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 396 397 Builtin = 398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 399 400 BuiltinCall->setType(CE->getType()); 401 BuiltinCall->setValueKind(CE->getValueKind()); 402 BuiltinCall->setObjectKind(CE->getObjectKind()); 403 BuiltinCall->setCallee(Builtin); 404 BuiltinCall->setArg(1, ChainResult.get()); 405 406 return false; 407 } 408 409 namespace { 410 411 class EstimateSizeFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 size_t Size; 414 415 public: 416 EstimateSizeFormatHandler(StringRef Format) 417 : Size(std::min(Format.find(0), Format.size()) + 418 1 /* null byte always written by sprintf */) {} 419 420 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 421 const char *, unsigned SpecifierLen) override { 422 423 const size_t FieldWidth = computeFieldWidth(FS); 424 const size_t Precision = computePrecision(FS); 425 426 // The actual format. 427 switch (FS.getConversionSpecifier().getKind()) { 428 // Just a char. 429 case analyze_format_string::ConversionSpecifier::cArg: 430 case analyze_format_string::ConversionSpecifier::CArg: 431 Size += std::max(FieldWidth, (size_t)1); 432 break; 433 // Just an integer. 434 case analyze_format_string::ConversionSpecifier::dArg: 435 case analyze_format_string::ConversionSpecifier::DArg: 436 case analyze_format_string::ConversionSpecifier::iArg: 437 case analyze_format_string::ConversionSpecifier::oArg: 438 case analyze_format_string::ConversionSpecifier::OArg: 439 case analyze_format_string::ConversionSpecifier::uArg: 440 case analyze_format_string::ConversionSpecifier::UArg: 441 case analyze_format_string::ConversionSpecifier::xArg: 442 case analyze_format_string::ConversionSpecifier::XArg: 443 Size += std::max(FieldWidth, Precision); 444 break; 445 446 // %g style conversion switches between %f or %e style dynamically. 447 // %f always takes less space, so default to it. 448 case analyze_format_string::ConversionSpecifier::gArg: 449 case analyze_format_string::ConversionSpecifier::GArg: 450 451 // Floating point number in the form '[+]ddd.ddd'. 452 case analyze_format_string::ConversionSpecifier::fArg: 453 case analyze_format_string::ConversionSpecifier::FArg: 454 Size += std::max(FieldWidth, 1 /* integer part */ + 455 (Precision ? 1 + Precision 456 : 0) /* period + decimal */); 457 break; 458 459 // Floating point number in the form '[-]d.ddde[+-]dd'. 460 case analyze_format_string::ConversionSpecifier::eArg: 461 case analyze_format_string::ConversionSpecifier::EArg: 462 Size += 463 std::max(FieldWidth, 464 1 /* integer part */ + 465 (Precision ? 1 + Precision : 0) /* period + decimal */ + 466 1 /* e or E letter */ + 2 /* exponent */); 467 break; 468 469 // Floating point number in the form '[-]0xh.hhhhp±dd'. 470 case analyze_format_string::ConversionSpecifier::aArg: 471 case analyze_format_string::ConversionSpecifier::AArg: 472 Size += 473 std::max(FieldWidth, 474 2 /* 0x */ + 1 /* integer part */ + 475 (Precision ? 1 + Precision : 0) /* period + decimal */ + 476 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 477 break; 478 479 // Just a string. 480 case analyze_format_string::ConversionSpecifier::sArg: 481 case analyze_format_string::ConversionSpecifier::SArg: 482 Size += FieldWidth; 483 break; 484 485 // Just a pointer in the form '0xddd'. 486 case analyze_format_string::ConversionSpecifier::pArg: 487 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 488 break; 489 490 // A plain percent. 491 case analyze_format_string::ConversionSpecifier::PercentArg: 492 Size += 1; 493 break; 494 495 default: 496 break; 497 } 498 499 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 500 501 if (FS.hasAlternativeForm()) { 502 switch (FS.getConversionSpecifier().getKind()) { 503 default: 504 break; 505 // Force a leading '0'. 506 case analyze_format_string::ConversionSpecifier::oArg: 507 Size += 1; 508 break; 509 // Force a leading '0x'. 510 case analyze_format_string::ConversionSpecifier::xArg: 511 case analyze_format_string::ConversionSpecifier::XArg: 512 Size += 2; 513 break; 514 // Force a period '.' before decimal, even if precision is 0. 515 case analyze_format_string::ConversionSpecifier::aArg: 516 case analyze_format_string::ConversionSpecifier::AArg: 517 case analyze_format_string::ConversionSpecifier::eArg: 518 case analyze_format_string::ConversionSpecifier::EArg: 519 case analyze_format_string::ConversionSpecifier::fArg: 520 case analyze_format_string::ConversionSpecifier::FArg: 521 case analyze_format_string::ConversionSpecifier::gArg: 522 case analyze_format_string::ConversionSpecifier::GArg: 523 Size += (Precision ? 0 : 1); 524 break; 525 } 526 } 527 assert(SpecifierLen <= Size && "no underflow"); 528 Size -= SpecifierLen; 529 return true; 530 } 531 532 size_t getSizeLowerBound() const { return Size; } 533 534 private: 535 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 536 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 537 size_t FieldWidth = 0; 538 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 539 FieldWidth = FW.getConstantAmount(); 540 return FieldWidth; 541 } 542 543 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 544 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 545 size_t Precision = 0; 546 547 // See man 3 printf for default precision value based on the specifier. 548 switch (FW.getHowSpecified()) { 549 case analyze_format_string::OptionalAmount::NotSpecified: 550 switch (FS.getConversionSpecifier().getKind()) { 551 default: 552 break; 553 case analyze_format_string::ConversionSpecifier::dArg: // %d 554 case analyze_format_string::ConversionSpecifier::DArg: // %D 555 case analyze_format_string::ConversionSpecifier::iArg: // %i 556 Precision = 1; 557 break; 558 case analyze_format_string::ConversionSpecifier::oArg: // %d 559 case analyze_format_string::ConversionSpecifier::OArg: // %D 560 case analyze_format_string::ConversionSpecifier::uArg: // %d 561 case analyze_format_string::ConversionSpecifier::UArg: // %D 562 case analyze_format_string::ConversionSpecifier::xArg: // %d 563 case analyze_format_string::ConversionSpecifier::XArg: // %D 564 Precision = 1; 565 break; 566 case analyze_format_string::ConversionSpecifier::fArg: // %f 567 case analyze_format_string::ConversionSpecifier::FArg: // %F 568 case analyze_format_string::ConversionSpecifier::eArg: // %e 569 case analyze_format_string::ConversionSpecifier::EArg: // %E 570 case analyze_format_string::ConversionSpecifier::gArg: // %g 571 case analyze_format_string::ConversionSpecifier::GArg: // %G 572 Precision = 6; 573 break; 574 case analyze_format_string::ConversionSpecifier::pArg: // %d 575 Precision = 1; 576 break; 577 } 578 break; 579 case analyze_format_string::OptionalAmount::Constant: 580 Precision = FW.getConstantAmount(); 581 break; 582 default: 583 break; 584 } 585 return Precision; 586 } 587 }; 588 589 } // namespace 590 591 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 592 /// __builtin_*_chk function, then use the object size argument specified in the 593 /// source. Otherwise, infer the object size using __builtin_object_size. 594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 595 CallExpr *TheCall) { 596 // FIXME: There are some more useful checks we could be doing here: 597 // - Evaluate strlen of strcpy arguments, use as object size. 598 599 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 600 isConstantEvaluated()) 601 return; 602 603 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 604 if (!BuiltinID) 605 return; 606 607 const TargetInfo &TI = getASTContext().getTargetInfo(); 608 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 609 610 unsigned DiagID = 0; 611 bool IsChkVariant = false; 612 Optional<llvm::APSInt> UsedSize; 613 unsigned SizeIndex, ObjectIndex; 614 switch (BuiltinID) { 615 default: 616 return; 617 case Builtin::BIsprintf: 618 case Builtin::BI__builtin___sprintf_chk: { 619 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 620 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 621 622 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 623 624 if (!Format->isAscii() && !Format->isUTF8()) 625 return; 626 627 StringRef FormatStrRef = Format->getString(); 628 EstimateSizeFormatHandler H(FormatStrRef); 629 const char *FormatBytes = FormatStrRef.data(); 630 const ConstantArrayType *T = 631 Context.getAsConstantArrayType(Format->getType()); 632 assert(T && "String literal not of constant array type!"); 633 size_t TypeSize = T->getSize().getZExtValue(); 634 635 // In case there's a null byte somewhere. 636 size_t StrLen = 637 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 638 if (!analyze_format_string::ParsePrintfString( 639 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 640 Context.getTargetInfo(), false)) { 641 DiagID = diag::warn_fortify_source_format_overflow; 642 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 643 .extOrTrunc(SizeTypeWidth); 644 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 645 IsChkVariant = true; 646 ObjectIndex = 2; 647 } else { 648 IsChkVariant = false; 649 ObjectIndex = 0; 650 } 651 break; 652 } 653 } 654 return; 655 } 656 case Builtin::BI__builtin___memcpy_chk: 657 case Builtin::BI__builtin___memmove_chk: 658 case Builtin::BI__builtin___memset_chk: 659 case Builtin::BI__builtin___strlcat_chk: 660 case Builtin::BI__builtin___strlcpy_chk: 661 case Builtin::BI__builtin___strncat_chk: 662 case Builtin::BI__builtin___strncpy_chk: 663 case Builtin::BI__builtin___stpncpy_chk: 664 case Builtin::BI__builtin___memccpy_chk: 665 case Builtin::BI__builtin___mempcpy_chk: { 666 DiagID = diag::warn_builtin_chk_overflow; 667 IsChkVariant = true; 668 SizeIndex = TheCall->getNumArgs() - 2; 669 ObjectIndex = TheCall->getNumArgs() - 1; 670 break; 671 } 672 673 case Builtin::BI__builtin___snprintf_chk: 674 case Builtin::BI__builtin___vsnprintf_chk: { 675 DiagID = diag::warn_builtin_chk_overflow; 676 IsChkVariant = true; 677 SizeIndex = 1; 678 ObjectIndex = 3; 679 break; 680 } 681 682 case Builtin::BIstrncat: 683 case Builtin::BI__builtin_strncat: 684 case Builtin::BIstrncpy: 685 case Builtin::BI__builtin_strncpy: 686 case Builtin::BIstpncpy: 687 case Builtin::BI__builtin_stpncpy: { 688 // Whether these functions overflow depends on the runtime strlen of the 689 // string, not just the buffer size, so emitting the "always overflow" 690 // diagnostic isn't quite right. We should still diagnose passing a buffer 691 // size larger than the destination buffer though; this is a runtime abort 692 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 693 DiagID = diag::warn_fortify_source_size_mismatch; 694 SizeIndex = TheCall->getNumArgs() - 1; 695 ObjectIndex = 0; 696 break; 697 } 698 699 case Builtin::BImemcpy: 700 case Builtin::BI__builtin_memcpy: 701 case Builtin::BImemmove: 702 case Builtin::BI__builtin_memmove: 703 case Builtin::BImemset: 704 case Builtin::BI__builtin_memset: 705 case Builtin::BImempcpy: 706 case Builtin::BI__builtin_mempcpy: { 707 DiagID = diag::warn_fortify_source_overflow; 708 SizeIndex = TheCall->getNumArgs() - 1; 709 ObjectIndex = 0; 710 break; 711 } 712 case Builtin::BIsnprintf: 713 case Builtin::BI__builtin_snprintf: 714 case Builtin::BIvsnprintf: 715 case Builtin::BI__builtin_vsnprintf: { 716 DiagID = diag::warn_fortify_source_size_mismatch; 717 SizeIndex = 1; 718 ObjectIndex = 0; 719 break; 720 } 721 } 722 723 llvm::APSInt ObjectSize; 724 // For __builtin___*_chk, the object size is explicitly provided by the caller 725 // (usually using __builtin_object_size). Use that value to check this call. 726 if (IsChkVariant) { 727 Expr::EvalResult Result; 728 Expr *SizeArg = TheCall->getArg(ObjectIndex); 729 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 730 return; 731 ObjectSize = Result.Val.getInt(); 732 733 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 734 } else { 735 // If the parameter has a pass_object_size attribute, then we should use its 736 // (potentially) more strict checking mode. Otherwise, conservatively assume 737 // type 0. 738 int BOSType = 0; 739 if (const auto *POS = 740 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 741 BOSType = POS->getType(); 742 743 Expr *ObjArg = TheCall->getArg(ObjectIndex); 744 uint64_t Result; 745 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 746 return; 747 // Get the object size in the target's size_t width. 748 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 749 } 750 751 // Evaluate the number of bytes of the object that this call will use. 752 if (!UsedSize) { 753 Expr::EvalResult Result; 754 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 755 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 756 return; 757 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 758 } 759 760 if (UsedSize.getValue().ule(ObjectSize)) 761 return; 762 763 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 764 // Skim off the details of whichever builtin was called to produce a better 765 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 766 if (IsChkVariant) { 767 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 768 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 769 } else if (FunctionName.startswith("__builtin_")) { 770 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 771 } 772 773 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 774 PDiag(DiagID) 775 << FunctionName << ObjectSize.toString(/*Radix=*/10) 776 << UsedSize.getValue().toString(/*Radix=*/10)); 777 } 778 779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 780 Scope::ScopeFlags NeededScopeFlags, 781 unsigned DiagID) { 782 // Scopes aren't available during instantiation. Fortunately, builtin 783 // functions cannot be template args so they cannot be formed through template 784 // instantiation. Therefore checking once during the parse is sufficient. 785 if (SemaRef.inTemplateInstantiation()) 786 return false; 787 788 Scope *S = SemaRef.getCurScope(); 789 while (S && !S->isSEHExceptScope()) 790 S = S->getParent(); 791 if (!S || !(S->getFlags() & NeededScopeFlags)) { 792 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 793 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 794 << DRE->getDecl()->getIdentifier(); 795 return true; 796 } 797 798 return false; 799 } 800 801 static inline bool isBlockPointer(Expr *Arg) { 802 return Arg->getType()->isBlockPointerType(); 803 } 804 805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 806 /// void*, which is a requirement of device side enqueue. 807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 808 const BlockPointerType *BPT = 809 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 810 ArrayRef<QualType> Params = 811 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 812 unsigned ArgCounter = 0; 813 bool IllegalParams = false; 814 // Iterate through the block parameters until either one is found that is not 815 // a local void*, or the block is valid. 816 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 817 I != E; ++I, ++ArgCounter) { 818 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 819 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 820 LangAS::opencl_local) { 821 // Get the location of the error. If a block literal has been passed 822 // (BlockExpr) then we can point straight to the offending argument, 823 // else we just point to the variable reference. 824 SourceLocation ErrorLoc; 825 if (isa<BlockExpr>(BlockArg)) { 826 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 827 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 828 } else if (isa<DeclRefExpr>(BlockArg)) { 829 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 830 } 831 S.Diag(ErrorLoc, 832 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 833 IllegalParams = true; 834 } 835 } 836 837 return IllegalParams; 838 } 839 840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 841 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_subgroups", 842 S.getLangOpts())) { 843 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 844 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 845 return true; 846 } 847 return false; 848 } 849 850 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 851 if (checkArgCount(S, TheCall, 2)) 852 return true; 853 854 if (checkOpenCLSubgroupExt(S, TheCall)) 855 return true; 856 857 // First argument is an ndrange_t type. 858 Expr *NDRangeArg = TheCall->getArg(0); 859 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 860 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 861 << TheCall->getDirectCallee() << "'ndrange_t'"; 862 return true; 863 } 864 865 Expr *BlockArg = TheCall->getArg(1); 866 if (!isBlockPointer(BlockArg)) { 867 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 868 << TheCall->getDirectCallee() << "block"; 869 return true; 870 } 871 return checkOpenCLBlockArgs(S, BlockArg); 872 } 873 874 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 875 /// get_kernel_work_group_size 876 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 877 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 878 if (checkArgCount(S, TheCall, 1)) 879 return true; 880 881 Expr *BlockArg = TheCall->getArg(0); 882 if (!isBlockPointer(BlockArg)) { 883 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 884 << TheCall->getDirectCallee() << "block"; 885 return true; 886 } 887 return checkOpenCLBlockArgs(S, BlockArg); 888 } 889 890 /// Diagnose integer type and any valid implicit conversion to it. 891 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 892 const QualType &IntType); 893 894 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 895 unsigned Start, unsigned End) { 896 bool IllegalParams = false; 897 for (unsigned I = Start; I <= End; ++I) 898 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 899 S.Context.getSizeType()); 900 return IllegalParams; 901 } 902 903 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 904 /// 'local void*' parameter of passed block. 905 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 906 Expr *BlockArg, 907 unsigned NumNonVarArgs) { 908 const BlockPointerType *BPT = 909 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 910 unsigned NumBlockParams = 911 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 912 unsigned TotalNumArgs = TheCall->getNumArgs(); 913 914 // For each argument passed to the block, a corresponding uint needs to 915 // be passed to describe the size of the local memory. 916 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 917 S.Diag(TheCall->getBeginLoc(), 918 diag::err_opencl_enqueue_kernel_local_size_args); 919 return true; 920 } 921 922 // Check that the sizes of the local memory are specified by integers. 923 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 924 TotalNumArgs - 1); 925 } 926 927 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 928 /// overload formats specified in Table 6.13.17.1. 929 /// int enqueue_kernel(queue_t queue, 930 /// kernel_enqueue_flags_t flags, 931 /// const ndrange_t ndrange, 932 /// void (^block)(void)) 933 /// int enqueue_kernel(queue_t queue, 934 /// kernel_enqueue_flags_t flags, 935 /// const ndrange_t ndrange, 936 /// uint num_events_in_wait_list, 937 /// clk_event_t *event_wait_list, 938 /// clk_event_t *event_ret, 939 /// void (^block)(void)) 940 /// int enqueue_kernel(queue_t queue, 941 /// kernel_enqueue_flags_t flags, 942 /// const ndrange_t ndrange, 943 /// void (^block)(local void*, ...), 944 /// uint size0, ...) 945 /// int enqueue_kernel(queue_t queue, 946 /// kernel_enqueue_flags_t flags, 947 /// const ndrange_t ndrange, 948 /// uint num_events_in_wait_list, 949 /// clk_event_t *event_wait_list, 950 /// clk_event_t *event_ret, 951 /// void (^block)(local void*, ...), 952 /// uint size0, ...) 953 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 954 unsigned NumArgs = TheCall->getNumArgs(); 955 956 if (NumArgs < 4) { 957 S.Diag(TheCall->getBeginLoc(), 958 diag::err_typecheck_call_too_few_args_at_least) 959 << 0 << 4 << NumArgs; 960 return true; 961 } 962 963 Expr *Arg0 = TheCall->getArg(0); 964 Expr *Arg1 = TheCall->getArg(1); 965 Expr *Arg2 = TheCall->getArg(2); 966 Expr *Arg3 = TheCall->getArg(3); 967 968 // First argument always needs to be a queue_t type. 969 if (!Arg0->getType()->isQueueT()) { 970 S.Diag(TheCall->getArg(0)->getBeginLoc(), 971 diag::err_opencl_builtin_expected_type) 972 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 973 return true; 974 } 975 976 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 977 if (!Arg1->getType()->isIntegerType()) { 978 S.Diag(TheCall->getArg(1)->getBeginLoc(), 979 diag::err_opencl_builtin_expected_type) 980 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 981 return true; 982 } 983 984 // Third argument is always an ndrange_t type. 985 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 986 S.Diag(TheCall->getArg(2)->getBeginLoc(), 987 diag::err_opencl_builtin_expected_type) 988 << TheCall->getDirectCallee() << "'ndrange_t'"; 989 return true; 990 } 991 992 // With four arguments, there is only one form that the function could be 993 // called in: no events and no variable arguments. 994 if (NumArgs == 4) { 995 // check that the last argument is the right block type. 996 if (!isBlockPointer(Arg3)) { 997 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 998 << TheCall->getDirectCallee() << "block"; 999 return true; 1000 } 1001 // we have a block type, check the prototype 1002 const BlockPointerType *BPT = 1003 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1004 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1005 S.Diag(Arg3->getBeginLoc(), 1006 diag::err_opencl_enqueue_kernel_blocks_no_args); 1007 return true; 1008 } 1009 return false; 1010 } 1011 // we can have block + varargs. 1012 if (isBlockPointer(Arg3)) 1013 return (checkOpenCLBlockArgs(S, Arg3) || 1014 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1015 // last two cases with either exactly 7 args or 7 args and varargs. 1016 if (NumArgs >= 7) { 1017 // check common block argument. 1018 Expr *Arg6 = TheCall->getArg(6); 1019 if (!isBlockPointer(Arg6)) { 1020 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1021 << TheCall->getDirectCallee() << "block"; 1022 return true; 1023 } 1024 if (checkOpenCLBlockArgs(S, Arg6)) 1025 return true; 1026 1027 // Forth argument has to be any integer type. 1028 if (!Arg3->getType()->isIntegerType()) { 1029 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1030 diag::err_opencl_builtin_expected_type) 1031 << TheCall->getDirectCallee() << "integer"; 1032 return true; 1033 } 1034 // check remaining common arguments. 1035 Expr *Arg4 = TheCall->getArg(4); 1036 Expr *Arg5 = TheCall->getArg(5); 1037 1038 // Fifth argument is always passed as a pointer to clk_event_t. 1039 if (!Arg4->isNullPointerConstant(S.Context, 1040 Expr::NPC_ValueDependentIsNotNull) && 1041 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1042 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1043 diag::err_opencl_builtin_expected_type) 1044 << TheCall->getDirectCallee() 1045 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1046 return true; 1047 } 1048 1049 // Sixth argument is always passed as a pointer to clk_event_t. 1050 if (!Arg5->isNullPointerConstant(S.Context, 1051 Expr::NPC_ValueDependentIsNotNull) && 1052 !(Arg5->getType()->isPointerType() && 1053 Arg5->getType()->getPointeeType()->isClkEventT())) { 1054 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1055 diag::err_opencl_builtin_expected_type) 1056 << TheCall->getDirectCallee() 1057 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1058 return true; 1059 } 1060 1061 if (NumArgs == 7) 1062 return false; 1063 1064 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1065 } 1066 1067 // None of the specific case has been detected, give generic error 1068 S.Diag(TheCall->getBeginLoc(), 1069 diag::err_opencl_enqueue_kernel_incorrect_args); 1070 return true; 1071 } 1072 1073 /// Returns OpenCL access qual. 1074 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1075 return D->getAttr<OpenCLAccessAttr>(); 1076 } 1077 1078 /// Returns true if pipe element type is different from the pointer. 1079 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1080 const Expr *Arg0 = Call->getArg(0); 1081 // First argument type should always be pipe. 1082 if (!Arg0->getType()->isPipeType()) { 1083 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1084 << Call->getDirectCallee() << Arg0->getSourceRange(); 1085 return true; 1086 } 1087 OpenCLAccessAttr *AccessQual = 1088 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1089 // Validates the access qualifier is compatible with the call. 1090 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1091 // read_only and write_only, and assumed to be read_only if no qualifier is 1092 // specified. 1093 switch (Call->getDirectCallee()->getBuiltinID()) { 1094 case Builtin::BIread_pipe: 1095 case Builtin::BIreserve_read_pipe: 1096 case Builtin::BIcommit_read_pipe: 1097 case Builtin::BIwork_group_reserve_read_pipe: 1098 case Builtin::BIsub_group_reserve_read_pipe: 1099 case Builtin::BIwork_group_commit_read_pipe: 1100 case Builtin::BIsub_group_commit_read_pipe: 1101 if (!(!AccessQual || AccessQual->isReadOnly())) { 1102 S.Diag(Arg0->getBeginLoc(), 1103 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1104 << "read_only" << Arg0->getSourceRange(); 1105 return true; 1106 } 1107 break; 1108 case Builtin::BIwrite_pipe: 1109 case Builtin::BIreserve_write_pipe: 1110 case Builtin::BIcommit_write_pipe: 1111 case Builtin::BIwork_group_reserve_write_pipe: 1112 case Builtin::BIsub_group_reserve_write_pipe: 1113 case Builtin::BIwork_group_commit_write_pipe: 1114 case Builtin::BIsub_group_commit_write_pipe: 1115 if (!(AccessQual && AccessQual->isWriteOnly())) { 1116 S.Diag(Arg0->getBeginLoc(), 1117 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1118 << "write_only" << Arg0->getSourceRange(); 1119 return true; 1120 } 1121 break; 1122 default: 1123 break; 1124 } 1125 return false; 1126 } 1127 1128 /// Returns true if pipe element type is different from the pointer. 1129 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1130 const Expr *Arg0 = Call->getArg(0); 1131 const Expr *ArgIdx = Call->getArg(Idx); 1132 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1133 const QualType EltTy = PipeTy->getElementType(); 1134 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1135 // The Idx argument should be a pointer and the type of the pointer and 1136 // the type of pipe element should also be the same. 1137 if (!ArgTy || 1138 !S.Context.hasSameType( 1139 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1140 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1141 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1142 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1143 return true; 1144 } 1145 return false; 1146 } 1147 1148 // Performs semantic analysis for the read/write_pipe call. 1149 // \param S Reference to the semantic analyzer. 1150 // \param Call A pointer to the builtin call. 1151 // \return True if a semantic error has been found, false otherwise. 1152 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1153 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1154 // functions have two forms. 1155 switch (Call->getNumArgs()) { 1156 case 2: 1157 if (checkOpenCLPipeArg(S, Call)) 1158 return true; 1159 // The call with 2 arguments should be 1160 // read/write_pipe(pipe T, T*). 1161 // Check packet type T. 1162 if (checkOpenCLPipePacketType(S, Call, 1)) 1163 return true; 1164 break; 1165 1166 case 4: { 1167 if (checkOpenCLPipeArg(S, Call)) 1168 return true; 1169 // The call with 4 arguments should be 1170 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1171 // Check reserve_id_t. 1172 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1173 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1174 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1175 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1176 return true; 1177 } 1178 1179 // Check the index. 1180 const Expr *Arg2 = Call->getArg(2); 1181 if (!Arg2->getType()->isIntegerType() && 1182 !Arg2->getType()->isUnsignedIntegerType()) { 1183 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1184 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1185 << Arg2->getType() << Arg2->getSourceRange(); 1186 return true; 1187 } 1188 1189 // Check packet type T. 1190 if (checkOpenCLPipePacketType(S, Call, 3)) 1191 return true; 1192 } break; 1193 default: 1194 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1195 << Call->getDirectCallee() << Call->getSourceRange(); 1196 return true; 1197 } 1198 1199 return false; 1200 } 1201 1202 // Performs a semantic analysis on the {work_group_/sub_group_ 1203 // /_}reserve_{read/write}_pipe 1204 // \param S Reference to the semantic analyzer. 1205 // \param Call The call to the builtin function to be analyzed. 1206 // \return True if a semantic error was found, false otherwise. 1207 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1208 if (checkArgCount(S, Call, 2)) 1209 return true; 1210 1211 if (checkOpenCLPipeArg(S, Call)) 1212 return true; 1213 1214 // Check the reserve size. 1215 if (!Call->getArg(1)->getType()->isIntegerType() && 1216 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1217 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1218 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1219 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1220 return true; 1221 } 1222 1223 // Since return type of reserve_read/write_pipe built-in function is 1224 // reserve_id_t, which is not defined in the builtin def file , we used int 1225 // as return type and need to override the return type of these functions. 1226 Call->setType(S.Context.OCLReserveIDTy); 1227 1228 return false; 1229 } 1230 1231 // Performs a semantic analysis on {work_group_/sub_group_ 1232 // /_}commit_{read/write}_pipe 1233 // \param S Reference to the semantic analyzer. 1234 // \param Call The call to the builtin function to be analyzed. 1235 // \return True if a semantic error was found, false otherwise. 1236 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1237 if (checkArgCount(S, Call, 2)) 1238 return true; 1239 1240 if (checkOpenCLPipeArg(S, Call)) 1241 return true; 1242 1243 // Check reserve_id_t. 1244 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1245 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1246 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1247 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1248 return true; 1249 } 1250 1251 return false; 1252 } 1253 1254 // Performs a semantic analysis on the call to built-in Pipe 1255 // Query Functions. 1256 // \param S Reference to the semantic analyzer. 1257 // \param Call The call to the builtin function to be analyzed. 1258 // \return True if a semantic error was found, false otherwise. 1259 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1260 if (checkArgCount(S, Call, 1)) 1261 return true; 1262 1263 if (!Call->getArg(0)->getType()->isPipeType()) { 1264 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1265 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1266 return true; 1267 } 1268 1269 return false; 1270 } 1271 1272 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1273 // Performs semantic analysis for the to_global/local/private call. 1274 // \param S Reference to the semantic analyzer. 1275 // \param BuiltinID ID of the builtin function. 1276 // \param Call A pointer to the builtin call. 1277 // \return True if a semantic error has been found, false otherwise. 1278 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1279 CallExpr *Call) { 1280 if (checkArgCount(S, Call, 1)) 1281 return true; 1282 1283 auto RT = Call->getArg(0)->getType(); 1284 if (!RT->isPointerType() || RT->getPointeeType() 1285 .getAddressSpace() == LangAS::opencl_constant) { 1286 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1287 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1288 return true; 1289 } 1290 1291 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1292 S.Diag(Call->getArg(0)->getBeginLoc(), 1293 diag::warn_opencl_generic_address_space_arg) 1294 << Call->getDirectCallee()->getNameInfo().getAsString() 1295 << Call->getArg(0)->getSourceRange(); 1296 } 1297 1298 RT = RT->getPointeeType(); 1299 auto Qual = RT.getQualifiers(); 1300 switch (BuiltinID) { 1301 case Builtin::BIto_global: 1302 Qual.setAddressSpace(LangAS::opencl_global); 1303 break; 1304 case Builtin::BIto_local: 1305 Qual.setAddressSpace(LangAS::opencl_local); 1306 break; 1307 case Builtin::BIto_private: 1308 Qual.setAddressSpace(LangAS::opencl_private); 1309 break; 1310 default: 1311 llvm_unreachable("Invalid builtin function"); 1312 } 1313 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1314 RT.getUnqualifiedType(), Qual))); 1315 1316 return false; 1317 } 1318 1319 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1320 if (checkArgCount(S, TheCall, 1)) 1321 return ExprError(); 1322 1323 // Compute __builtin_launder's parameter type from the argument. 1324 // The parameter type is: 1325 // * The type of the argument if it's not an array or function type, 1326 // Otherwise, 1327 // * The decayed argument type. 1328 QualType ParamTy = [&]() { 1329 QualType ArgTy = TheCall->getArg(0)->getType(); 1330 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1331 return S.Context.getPointerType(Ty->getElementType()); 1332 if (ArgTy->isFunctionType()) { 1333 return S.Context.getPointerType(ArgTy); 1334 } 1335 return ArgTy; 1336 }(); 1337 1338 TheCall->setType(ParamTy); 1339 1340 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1341 if (!ParamTy->isPointerType()) 1342 return 0; 1343 if (ParamTy->isFunctionPointerType()) 1344 return 1; 1345 if (ParamTy->isVoidPointerType()) 1346 return 2; 1347 return llvm::Optional<unsigned>{}; 1348 }(); 1349 if (DiagSelect.hasValue()) { 1350 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1351 << DiagSelect.getValue() << TheCall->getSourceRange(); 1352 return ExprError(); 1353 } 1354 1355 // We either have an incomplete class type, or we have a class template 1356 // whose instantiation has not been forced. Example: 1357 // 1358 // template <class T> struct Foo { T value; }; 1359 // Foo<int> *p = nullptr; 1360 // auto *d = __builtin_launder(p); 1361 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1362 diag::err_incomplete_type)) 1363 return ExprError(); 1364 1365 assert(ParamTy->getPointeeType()->isObjectType() && 1366 "Unhandled non-object pointer case"); 1367 1368 InitializedEntity Entity = 1369 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1370 ExprResult Arg = 1371 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1372 if (Arg.isInvalid()) 1373 return ExprError(); 1374 TheCall->setArg(0, Arg.get()); 1375 1376 return TheCall; 1377 } 1378 1379 // Emit an error and return true if the current architecture is not in the list 1380 // of supported architectures. 1381 static bool 1382 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1383 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1384 llvm::Triple::ArchType CurArch = 1385 S.getASTContext().getTargetInfo().getTriple().getArch(); 1386 if (llvm::is_contained(SupportedArchs, CurArch)) 1387 return false; 1388 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1389 << TheCall->getSourceRange(); 1390 return true; 1391 } 1392 1393 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1394 SourceLocation CallSiteLoc); 1395 1396 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1397 CallExpr *TheCall) { 1398 switch (TI.getTriple().getArch()) { 1399 default: 1400 // Some builtins don't require additional checking, so just consider these 1401 // acceptable. 1402 return false; 1403 case llvm::Triple::arm: 1404 case llvm::Triple::armeb: 1405 case llvm::Triple::thumb: 1406 case llvm::Triple::thumbeb: 1407 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1408 case llvm::Triple::aarch64: 1409 case llvm::Triple::aarch64_32: 1410 case llvm::Triple::aarch64_be: 1411 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1412 case llvm::Triple::bpfeb: 1413 case llvm::Triple::bpfel: 1414 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1415 case llvm::Triple::hexagon: 1416 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1417 case llvm::Triple::mips: 1418 case llvm::Triple::mipsel: 1419 case llvm::Triple::mips64: 1420 case llvm::Triple::mips64el: 1421 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1422 case llvm::Triple::systemz: 1423 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1424 case llvm::Triple::x86: 1425 case llvm::Triple::x86_64: 1426 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1427 case llvm::Triple::ppc: 1428 case llvm::Triple::ppcle: 1429 case llvm::Triple::ppc64: 1430 case llvm::Triple::ppc64le: 1431 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1432 case llvm::Triple::amdgcn: 1433 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1434 case llvm::Triple::riscv32: 1435 case llvm::Triple::riscv64: 1436 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1437 } 1438 } 1439 1440 ExprResult 1441 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1442 CallExpr *TheCall) { 1443 ExprResult TheCallResult(TheCall); 1444 1445 // Find out if any arguments are required to be integer constant expressions. 1446 unsigned ICEArguments = 0; 1447 ASTContext::GetBuiltinTypeError Error; 1448 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1449 if (Error != ASTContext::GE_None) 1450 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1451 1452 // If any arguments are required to be ICE's, check and diagnose. 1453 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1454 // Skip arguments not required to be ICE's. 1455 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1456 1457 llvm::APSInt Result; 1458 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1459 return true; 1460 ICEArguments &= ~(1 << ArgNo); 1461 } 1462 1463 switch (BuiltinID) { 1464 case Builtin::BI__builtin___CFStringMakeConstantString: 1465 assert(TheCall->getNumArgs() == 1 && 1466 "Wrong # arguments to builtin CFStringMakeConstantString"); 1467 if (CheckObjCString(TheCall->getArg(0))) 1468 return ExprError(); 1469 break; 1470 case Builtin::BI__builtin_ms_va_start: 1471 case Builtin::BI__builtin_stdarg_start: 1472 case Builtin::BI__builtin_va_start: 1473 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1474 return ExprError(); 1475 break; 1476 case Builtin::BI__va_start: { 1477 switch (Context.getTargetInfo().getTriple().getArch()) { 1478 case llvm::Triple::aarch64: 1479 case llvm::Triple::arm: 1480 case llvm::Triple::thumb: 1481 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1482 return ExprError(); 1483 break; 1484 default: 1485 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1486 return ExprError(); 1487 break; 1488 } 1489 break; 1490 } 1491 1492 // The acquire, release, and no fence variants are ARM and AArch64 only. 1493 case Builtin::BI_interlockedbittestandset_acq: 1494 case Builtin::BI_interlockedbittestandset_rel: 1495 case Builtin::BI_interlockedbittestandset_nf: 1496 case Builtin::BI_interlockedbittestandreset_acq: 1497 case Builtin::BI_interlockedbittestandreset_rel: 1498 case Builtin::BI_interlockedbittestandreset_nf: 1499 if (CheckBuiltinTargetSupport( 1500 *this, BuiltinID, TheCall, 1501 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1502 return ExprError(); 1503 break; 1504 1505 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1506 case Builtin::BI_bittest64: 1507 case Builtin::BI_bittestandcomplement64: 1508 case Builtin::BI_bittestandreset64: 1509 case Builtin::BI_bittestandset64: 1510 case Builtin::BI_interlockedbittestandreset64: 1511 case Builtin::BI_interlockedbittestandset64: 1512 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1513 {llvm::Triple::x86_64, llvm::Triple::arm, 1514 llvm::Triple::thumb, llvm::Triple::aarch64})) 1515 return ExprError(); 1516 break; 1517 1518 case Builtin::BI__builtin_isgreater: 1519 case Builtin::BI__builtin_isgreaterequal: 1520 case Builtin::BI__builtin_isless: 1521 case Builtin::BI__builtin_islessequal: 1522 case Builtin::BI__builtin_islessgreater: 1523 case Builtin::BI__builtin_isunordered: 1524 if (SemaBuiltinUnorderedCompare(TheCall)) 1525 return ExprError(); 1526 break; 1527 case Builtin::BI__builtin_fpclassify: 1528 if (SemaBuiltinFPClassification(TheCall, 6)) 1529 return ExprError(); 1530 break; 1531 case Builtin::BI__builtin_isfinite: 1532 case Builtin::BI__builtin_isinf: 1533 case Builtin::BI__builtin_isinf_sign: 1534 case Builtin::BI__builtin_isnan: 1535 case Builtin::BI__builtin_isnormal: 1536 case Builtin::BI__builtin_signbit: 1537 case Builtin::BI__builtin_signbitf: 1538 case Builtin::BI__builtin_signbitl: 1539 if (SemaBuiltinFPClassification(TheCall, 1)) 1540 return ExprError(); 1541 break; 1542 case Builtin::BI__builtin_shufflevector: 1543 return SemaBuiltinShuffleVector(TheCall); 1544 // TheCall will be freed by the smart pointer here, but that's fine, since 1545 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1546 case Builtin::BI__builtin_prefetch: 1547 if (SemaBuiltinPrefetch(TheCall)) 1548 return ExprError(); 1549 break; 1550 case Builtin::BI__builtin_alloca_with_align: 1551 if (SemaBuiltinAllocaWithAlign(TheCall)) 1552 return ExprError(); 1553 LLVM_FALLTHROUGH; 1554 case Builtin::BI__builtin_alloca: 1555 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1556 << TheCall->getDirectCallee(); 1557 break; 1558 case Builtin::BI__assume: 1559 case Builtin::BI__builtin_assume: 1560 if (SemaBuiltinAssume(TheCall)) 1561 return ExprError(); 1562 break; 1563 case Builtin::BI__builtin_assume_aligned: 1564 if (SemaBuiltinAssumeAligned(TheCall)) 1565 return ExprError(); 1566 break; 1567 case Builtin::BI__builtin_dynamic_object_size: 1568 case Builtin::BI__builtin_object_size: 1569 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1570 return ExprError(); 1571 break; 1572 case Builtin::BI__builtin_longjmp: 1573 if (SemaBuiltinLongjmp(TheCall)) 1574 return ExprError(); 1575 break; 1576 case Builtin::BI__builtin_setjmp: 1577 if (SemaBuiltinSetjmp(TheCall)) 1578 return ExprError(); 1579 break; 1580 case Builtin::BI__builtin_classify_type: 1581 if (checkArgCount(*this, TheCall, 1)) return true; 1582 TheCall->setType(Context.IntTy); 1583 break; 1584 case Builtin::BI__builtin_complex: 1585 if (SemaBuiltinComplex(TheCall)) 1586 return ExprError(); 1587 break; 1588 case Builtin::BI__builtin_constant_p: { 1589 if (checkArgCount(*this, TheCall, 1)) return true; 1590 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1591 if (Arg.isInvalid()) return true; 1592 TheCall->setArg(0, Arg.get()); 1593 TheCall->setType(Context.IntTy); 1594 break; 1595 } 1596 case Builtin::BI__builtin_launder: 1597 return SemaBuiltinLaunder(*this, TheCall); 1598 case Builtin::BI__sync_fetch_and_add: 1599 case Builtin::BI__sync_fetch_and_add_1: 1600 case Builtin::BI__sync_fetch_and_add_2: 1601 case Builtin::BI__sync_fetch_and_add_4: 1602 case Builtin::BI__sync_fetch_and_add_8: 1603 case Builtin::BI__sync_fetch_and_add_16: 1604 case Builtin::BI__sync_fetch_and_sub: 1605 case Builtin::BI__sync_fetch_and_sub_1: 1606 case Builtin::BI__sync_fetch_and_sub_2: 1607 case Builtin::BI__sync_fetch_and_sub_4: 1608 case Builtin::BI__sync_fetch_and_sub_8: 1609 case Builtin::BI__sync_fetch_and_sub_16: 1610 case Builtin::BI__sync_fetch_and_or: 1611 case Builtin::BI__sync_fetch_and_or_1: 1612 case Builtin::BI__sync_fetch_and_or_2: 1613 case Builtin::BI__sync_fetch_and_or_4: 1614 case Builtin::BI__sync_fetch_and_or_8: 1615 case Builtin::BI__sync_fetch_and_or_16: 1616 case Builtin::BI__sync_fetch_and_and: 1617 case Builtin::BI__sync_fetch_and_and_1: 1618 case Builtin::BI__sync_fetch_and_and_2: 1619 case Builtin::BI__sync_fetch_and_and_4: 1620 case Builtin::BI__sync_fetch_and_and_8: 1621 case Builtin::BI__sync_fetch_and_and_16: 1622 case Builtin::BI__sync_fetch_and_xor: 1623 case Builtin::BI__sync_fetch_and_xor_1: 1624 case Builtin::BI__sync_fetch_and_xor_2: 1625 case Builtin::BI__sync_fetch_and_xor_4: 1626 case Builtin::BI__sync_fetch_and_xor_8: 1627 case Builtin::BI__sync_fetch_and_xor_16: 1628 case Builtin::BI__sync_fetch_and_nand: 1629 case Builtin::BI__sync_fetch_and_nand_1: 1630 case Builtin::BI__sync_fetch_and_nand_2: 1631 case Builtin::BI__sync_fetch_and_nand_4: 1632 case Builtin::BI__sync_fetch_and_nand_8: 1633 case Builtin::BI__sync_fetch_and_nand_16: 1634 case Builtin::BI__sync_add_and_fetch: 1635 case Builtin::BI__sync_add_and_fetch_1: 1636 case Builtin::BI__sync_add_and_fetch_2: 1637 case Builtin::BI__sync_add_and_fetch_4: 1638 case Builtin::BI__sync_add_and_fetch_8: 1639 case Builtin::BI__sync_add_and_fetch_16: 1640 case Builtin::BI__sync_sub_and_fetch: 1641 case Builtin::BI__sync_sub_and_fetch_1: 1642 case Builtin::BI__sync_sub_and_fetch_2: 1643 case Builtin::BI__sync_sub_and_fetch_4: 1644 case Builtin::BI__sync_sub_and_fetch_8: 1645 case Builtin::BI__sync_sub_and_fetch_16: 1646 case Builtin::BI__sync_and_and_fetch: 1647 case Builtin::BI__sync_and_and_fetch_1: 1648 case Builtin::BI__sync_and_and_fetch_2: 1649 case Builtin::BI__sync_and_and_fetch_4: 1650 case Builtin::BI__sync_and_and_fetch_8: 1651 case Builtin::BI__sync_and_and_fetch_16: 1652 case Builtin::BI__sync_or_and_fetch: 1653 case Builtin::BI__sync_or_and_fetch_1: 1654 case Builtin::BI__sync_or_and_fetch_2: 1655 case Builtin::BI__sync_or_and_fetch_4: 1656 case Builtin::BI__sync_or_and_fetch_8: 1657 case Builtin::BI__sync_or_and_fetch_16: 1658 case Builtin::BI__sync_xor_and_fetch: 1659 case Builtin::BI__sync_xor_and_fetch_1: 1660 case Builtin::BI__sync_xor_and_fetch_2: 1661 case Builtin::BI__sync_xor_and_fetch_4: 1662 case Builtin::BI__sync_xor_and_fetch_8: 1663 case Builtin::BI__sync_xor_and_fetch_16: 1664 case Builtin::BI__sync_nand_and_fetch: 1665 case Builtin::BI__sync_nand_and_fetch_1: 1666 case Builtin::BI__sync_nand_and_fetch_2: 1667 case Builtin::BI__sync_nand_and_fetch_4: 1668 case Builtin::BI__sync_nand_and_fetch_8: 1669 case Builtin::BI__sync_nand_and_fetch_16: 1670 case Builtin::BI__sync_val_compare_and_swap: 1671 case Builtin::BI__sync_val_compare_and_swap_1: 1672 case Builtin::BI__sync_val_compare_and_swap_2: 1673 case Builtin::BI__sync_val_compare_and_swap_4: 1674 case Builtin::BI__sync_val_compare_and_swap_8: 1675 case Builtin::BI__sync_val_compare_and_swap_16: 1676 case Builtin::BI__sync_bool_compare_and_swap: 1677 case Builtin::BI__sync_bool_compare_and_swap_1: 1678 case Builtin::BI__sync_bool_compare_and_swap_2: 1679 case Builtin::BI__sync_bool_compare_and_swap_4: 1680 case Builtin::BI__sync_bool_compare_and_swap_8: 1681 case Builtin::BI__sync_bool_compare_and_swap_16: 1682 case Builtin::BI__sync_lock_test_and_set: 1683 case Builtin::BI__sync_lock_test_and_set_1: 1684 case Builtin::BI__sync_lock_test_and_set_2: 1685 case Builtin::BI__sync_lock_test_and_set_4: 1686 case Builtin::BI__sync_lock_test_and_set_8: 1687 case Builtin::BI__sync_lock_test_and_set_16: 1688 case Builtin::BI__sync_lock_release: 1689 case Builtin::BI__sync_lock_release_1: 1690 case Builtin::BI__sync_lock_release_2: 1691 case Builtin::BI__sync_lock_release_4: 1692 case Builtin::BI__sync_lock_release_8: 1693 case Builtin::BI__sync_lock_release_16: 1694 case Builtin::BI__sync_swap: 1695 case Builtin::BI__sync_swap_1: 1696 case Builtin::BI__sync_swap_2: 1697 case Builtin::BI__sync_swap_4: 1698 case Builtin::BI__sync_swap_8: 1699 case Builtin::BI__sync_swap_16: 1700 return SemaBuiltinAtomicOverloaded(TheCallResult); 1701 case Builtin::BI__sync_synchronize: 1702 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1703 << TheCall->getCallee()->getSourceRange(); 1704 break; 1705 case Builtin::BI__builtin_nontemporal_load: 1706 case Builtin::BI__builtin_nontemporal_store: 1707 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1708 case Builtin::BI__builtin_memcpy_inline: { 1709 clang::Expr *SizeOp = TheCall->getArg(2); 1710 // We warn about copying to or from `nullptr` pointers when `size` is 1711 // greater than 0. When `size` is value dependent we cannot evaluate its 1712 // value so we bail out. 1713 if (SizeOp->isValueDependent()) 1714 break; 1715 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1716 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1717 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1718 } 1719 break; 1720 } 1721 #define BUILTIN(ID, TYPE, ATTRS) 1722 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1723 case Builtin::BI##ID: \ 1724 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1725 #include "clang/Basic/Builtins.def" 1726 case Builtin::BI__annotation: 1727 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1728 return ExprError(); 1729 break; 1730 case Builtin::BI__builtin_annotation: 1731 if (SemaBuiltinAnnotation(*this, TheCall)) 1732 return ExprError(); 1733 break; 1734 case Builtin::BI__builtin_addressof: 1735 if (SemaBuiltinAddressof(*this, TheCall)) 1736 return ExprError(); 1737 break; 1738 case Builtin::BI__builtin_is_aligned: 1739 case Builtin::BI__builtin_align_up: 1740 case Builtin::BI__builtin_align_down: 1741 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1742 return ExprError(); 1743 break; 1744 case Builtin::BI__builtin_add_overflow: 1745 case Builtin::BI__builtin_sub_overflow: 1746 case Builtin::BI__builtin_mul_overflow: 1747 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1748 return ExprError(); 1749 break; 1750 case Builtin::BI__builtin_operator_new: 1751 case Builtin::BI__builtin_operator_delete: { 1752 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1753 ExprResult Res = 1754 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1755 if (Res.isInvalid()) 1756 CorrectDelayedTyposInExpr(TheCallResult.get()); 1757 return Res; 1758 } 1759 case Builtin::BI__builtin_dump_struct: { 1760 // We first want to ensure we are called with 2 arguments 1761 if (checkArgCount(*this, TheCall, 2)) 1762 return ExprError(); 1763 // Ensure that the first argument is of type 'struct XX *' 1764 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1765 const QualType PtrArgType = PtrArg->getType(); 1766 if (!PtrArgType->isPointerType() || 1767 !PtrArgType->getPointeeType()->isRecordType()) { 1768 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1769 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1770 << "structure pointer"; 1771 return ExprError(); 1772 } 1773 1774 // Ensure that the second argument is of type 'FunctionType' 1775 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1776 const QualType FnPtrArgType = FnPtrArg->getType(); 1777 if (!FnPtrArgType->isPointerType()) { 1778 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1779 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1780 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1781 return ExprError(); 1782 } 1783 1784 const auto *FuncType = 1785 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1786 1787 if (!FuncType) { 1788 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1789 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1790 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1791 return ExprError(); 1792 } 1793 1794 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1795 if (!FT->getNumParams()) { 1796 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1797 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1798 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1799 return ExprError(); 1800 } 1801 QualType PT = FT->getParamType(0); 1802 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1803 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1804 !PT->getPointeeType().isConstQualified()) { 1805 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1806 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1807 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1808 return ExprError(); 1809 } 1810 } 1811 1812 TheCall->setType(Context.IntTy); 1813 break; 1814 } 1815 case Builtin::BI__builtin_expect_with_probability: { 1816 // We first want to ensure we are called with 3 arguments 1817 if (checkArgCount(*this, TheCall, 3)) 1818 return ExprError(); 1819 // then check probability is constant float in range [0.0, 1.0] 1820 const Expr *ProbArg = TheCall->getArg(2); 1821 SmallVector<PartialDiagnosticAt, 8> Notes; 1822 Expr::EvalResult Eval; 1823 Eval.Diag = &Notes; 1824 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1825 !Eval.Val.isFloat()) { 1826 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1827 << ProbArg->getSourceRange(); 1828 for (const PartialDiagnosticAt &PDiag : Notes) 1829 Diag(PDiag.first, PDiag.second); 1830 return ExprError(); 1831 } 1832 llvm::APFloat Probability = Eval.Val.getFloat(); 1833 bool LoseInfo = false; 1834 Probability.convert(llvm::APFloat::IEEEdouble(), 1835 llvm::RoundingMode::Dynamic, &LoseInfo); 1836 if (!(Probability >= llvm::APFloat(0.0) && 1837 Probability <= llvm::APFloat(1.0))) { 1838 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1839 << ProbArg->getSourceRange(); 1840 return ExprError(); 1841 } 1842 break; 1843 } 1844 case Builtin::BI__builtin_preserve_access_index: 1845 if (SemaBuiltinPreserveAI(*this, TheCall)) 1846 return ExprError(); 1847 break; 1848 case Builtin::BI__builtin_call_with_static_chain: 1849 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1850 return ExprError(); 1851 break; 1852 case Builtin::BI__exception_code: 1853 case Builtin::BI_exception_code: 1854 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1855 diag::err_seh___except_block)) 1856 return ExprError(); 1857 break; 1858 case Builtin::BI__exception_info: 1859 case Builtin::BI_exception_info: 1860 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1861 diag::err_seh___except_filter)) 1862 return ExprError(); 1863 break; 1864 case Builtin::BI__GetExceptionInfo: 1865 if (checkArgCount(*this, TheCall, 1)) 1866 return ExprError(); 1867 1868 if (CheckCXXThrowOperand( 1869 TheCall->getBeginLoc(), 1870 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1871 TheCall)) 1872 return ExprError(); 1873 1874 TheCall->setType(Context.VoidPtrTy); 1875 break; 1876 // OpenCL v2.0, s6.13.16 - Pipe functions 1877 case Builtin::BIread_pipe: 1878 case Builtin::BIwrite_pipe: 1879 // Since those two functions are declared with var args, we need a semantic 1880 // check for the argument. 1881 if (SemaBuiltinRWPipe(*this, TheCall)) 1882 return ExprError(); 1883 break; 1884 case Builtin::BIreserve_read_pipe: 1885 case Builtin::BIreserve_write_pipe: 1886 case Builtin::BIwork_group_reserve_read_pipe: 1887 case Builtin::BIwork_group_reserve_write_pipe: 1888 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1889 return ExprError(); 1890 break; 1891 case Builtin::BIsub_group_reserve_read_pipe: 1892 case Builtin::BIsub_group_reserve_write_pipe: 1893 if (checkOpenCLSubgroupExt(*this, TheCall) || 1894 SemaBuiltinReserveRWPipe(*this, TheCall)) 1895 return ExprError(); 1896 break; 1897 case Builtin::BIcommit_read_pipe: 1898 case Builtin::BIcommit_write_pipe: 1899 case Builtin::BIwork_group_commit_read_pipe: 1900 case Builtin::BIwork_group_commit_write_pipe: 1901 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1902 return ExprError(); 1903 break; 1904 case Builtin::BIsub_group_commit_read_pipe: 1905 case Builtin::BIsub_group_commit_write_pipe: 1906 if (checkOpenCLSubgroupExt(*this, TheCall) || 1907 SemaBuiltinCommitRWPipe(*this, TheCall)) 1908 return ExprError(); 1909 break; 1910 case Builtin::BIget_pipe_num_packets: 1911 case Builtin::BIget_pipe_max_packets: 1912 if (SemaBuiltinPipePackets(*this, TheCall)) 1913 return ExprError(); 1914 break; 1915 case Builtin::BIto_global: 1916 case Builtin::BIto_local: 1917 case Builtin::BIto_private: 1918 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1919 return ExprError(); 1920 break; 1921 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1922 case Builtin::BIenqueue_kernel: 1923 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1924 return ExprError(); 1925 break; 1926 case Builtin::BIget_kernel_work_group_size: 1927 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1928 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1929 return ExprError(); 1930 break; 1931 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1932 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1933 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1934 return ExprError(); 1935 break; 1936 case Builtin::BI__builtin_os_log_format: 1937 Cleanup.setExprNeedsCleanups(true); 1938 LLVM_FALLTHROUGH; 1939 case Builtin::BI__builtin_os_log_format_buffer_size: 1940 if (SemaBuiltinOSLogFormat(TheCall)) 1941 return ExprError(); 1942 break; 1943 case Builtin::BI__builtin_frame_address: 1944 case Builtin::BI__builtin_return_address: { 1945 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1946 return ExprError(); 1947 1948 // -Wframe-address warning if non-zero passed to builtin 1949 // return/frame address. 1950 Expr::EvalResult Result; 1951 if (!TheCall->getArg(0)->isValueDependent() && 1952 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1953 Result.Val.getInt() != 0) 1954 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1955 << ((BuiltinID == Builtin::BI__builtin_return_address) 1956 ? "__builtin_return_address" 1957 : "__builtin_frame_address") 1958 << TheCall->getSourceRange(); 1959 break; 1960 } 1961 1962 case Builtin::BI__builtin_matrix_transpose: 1963 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1964 1965 case Builtin::BI__builtin_matrix_column_major_load: 1966 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1967 1968 case Builtin::BI__builtin_matrix_column_major_store: 1969 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1970 1971 case Builtin::BI__builtin_get_device_side_mangled_name: { 1972 auto Check = [](CallExpr *TheCall) { 1973 if (TheCall->getNumArgs() != 1) 1974 return false; 1975 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 1976 if (!DRE) 1977 return false; 1978 auto *D = DRE->getDecl(); 1979 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 1980 return false; 1981 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 1982 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 1983 }; 1984 if (!Check(TheCall)) { 1985 Diag(TheCall->getBeginLoc(), 1986 diag::err_hip_invalid_args_builtin_mangled_name); 1987 return ExprError(); 1988 } 1989 } 1990 } 1991 1992 // Since the target specific builtins for each arch overlap, only check those 1993 // of the arch we are compiling for. 1994 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1995 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1996 assert(Context.getAuxTargetInfo() && 1997 "Aux Target Builtin, but not an aux target?"); 1998 1999 if (CheckTSBuiltinFunctionCall( 2000 *Context.getAuxTargetInfo(), 2001 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2002 return ExprError(); 2003 } else { 2004 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2005 TheCall)) 2006 return ExprError(); 2007 } 2008 } 2009 2010 return TheCallResult; 2011 } 2012 2013 // Get the valid immediate range for the specified NEON type code. 2014 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2015 NeonTypeFlags Type(t); 2016 int IsQuad = ForceQuad ? true : Type.isQuad(); 2017 switch (Type.getEltType()) { 2018 case NeonTypeFlags::Int8: 2019 case NeonTypeFlags::Poly8: 2020 return shift ? 7 : (8 << IsQuad) - 1; 2021 case NeonTypeFlags::Int16: 2022 case NeonTypeFlags::Poly16: 2023 return shift ? 15 : (4 << IsQuad) - 1; 2024 case NeonTypeFlags::Int32: 2025 return shift ? 31 : (2 << IsQuad) - 1; 2026 case NeonTypeFlags::Int64: 2027 case NeonTypeFlags::Poly64: 2028 return shift ? 63 : (1 << IsQuad) - 1; 2029 case NeonTypeFlags::Poly128: 2030 return shift ? 127 : (1 << IsQuad) - 1; 2031 case NeonTypeFlags::Float16: 2032 assert(!shift && "cannot shift float types!"); 2033 return (4 << IsQuad) - 1; 2034 case NeonTypeFlags::Float32: 2035 assert(!shift && "cannot shift float types!"); 2036 return (2 << IsQuad) - 1; 2037 case NeonTypeFlags::Float64: 2038 assert(!shift && "cannot shift float types!"); 2039 return (1 << IsQuad) - 1; 2040 case NeonTypeFlags::BFloat16: 2041 assert(!shift && "cannot shift float types!"); 2042 return (4 << IsQuad) - 1; 2043 } 2044 llvm_unreachable("Invalid NeonTypeFlag!"); 2045 } 2046 2047 /// getNeonEltType - Return the QualType corresponding to the elements of 2048 /// the vector type specified by the NeonTypeFlags. This is used to check 2049 /// the pointer arguments for Neon load/store intrinsics. 2050 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2051 bool IsPolyUnsigned, bool IsInt64Long) { 2052 switch (Flags.getEltType()) { 2053 case NeonTypeFlags::Int8: 2054 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2055 case NeonTypeFlags::Int16: 2056 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2057 case NeonTypeFlags::Int32: 2058 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2059 case NeonTypeFlags::Int64: 2060 if (IsInt64Long) 2061 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2062 else 2063 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2064 : Context.LongLongTy; 2065 case NeonTypeFlags::Poly8: 2066 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2067 case NeonTypeFlags::Poly16: 2068 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2069 case NeonTypeFlags::Poly64: 2070 if (IsInt64Long) 2071 return Context.UnsignedLongTy; 2072 else 2073 return Context.UnsignedLongLongTy; 2074 case NeonTypeFlags::Poly128: 2075 break; 2076 case NeonTypeFlags::Float16: 2077 return Context.HalfTy; 2078 case NeonTypeFlags::Float32: 2079 return Context.FloatTy; 2080 case NeonTypeFlags::Float64: 2081 return Context.DoubleTy; 2082 case NeonTypeFlags::BFloat16: 2083 return Context.BFloat16Ty; 2084 } 2085 llvm_unreachable("Invalid NeonTypeFlag!"); 2086 } 2087 2088 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2089 // Range check SVE intrinsics that take immediate values. 2090 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2091 2092 switch (BuiltinID) { 2093 default: 2094 return false; 2095 #define GET_SVE_IMMEDIATE_CHECK 2096 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2097 #undef GET_SVE_IMMEDIATE_CHECK 2098 } 2099 2100 // Perform all the immediate checks for this builtin call. 2101 bool HasError = false; 2102 for (auto &I : ImmChecks) { 2103 int ArgNum, CheckTy, ElementSizeInBits; 2104 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2105 2106 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2107 2108 // Function that checks whether the operand (ArgNum) is an immediate 2109 // that is one of the predefined values. 2110 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2111 int ErrDiag) -> bool { 2112 // We can't check the value of a dependent argument. 2113 Expr *Arg = TheCall->getArg(ArgNum); 2114 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2115 return false; 2116 2117 // Check constant-ness first. 2118 llvm::APSInt Imm; 2119 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2120 return true; 2121 2122 if (!CheckImm(Imm.getSExtValue())) 2123 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2124 return false; 2125 }; 2126 2127 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2128 case SVETypeFlags::ImmCheck0_31: 2129 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2130 HasError = true; 2131 break; 2132 case SVETypeFlags::ImmCheck0_13: 2133 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2134 HasError = true; 2135 break; 2136 case SVETypeFlags::ImmCheck1_16: 2137 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2138 HasError = true; 2139 break; 2140 case SVETypeFlags::ImmCheck0_7: 2141 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2142 HasError = true; 2143 break; 2144 case SVETypeFlags::ImmCheckExtract: 2145 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2146 (2048 / ElementSizeInBits) - 1)) 2147 HasError = true; 2148 break; 2149 case SVETypeFlags::ImmCheckShiftRight: 2150 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2151 HasError = true; 2152 break; 2153 case SVETypeFlags::ImmCheckShiftRightNarrow: 2154 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2155 ElementSizeInBits / 2)) 2156 HasError = true; 2157 break; 2158 case SVETypeFlags::ImmCheckShiftLeft: 2159 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2160 ElementSizeInBits - 1)) 2161 HasError = true; 2162 break; 2163 case SVETypeFlags::ImmCheckLaneIndex: 2164 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2165 (128 / (1 * ElementSizeInBits)) - 1)) 2166 HasError = true; 2167 break; 2168 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2169 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2170 (128 / (2 * ElementSizeInBits)) - 1)) 2171 HasError = true; 2172 break; 2173 case SVETypeFlags::ImmCheckLaneIndexDot: 2174 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2175 (128 / (4 * ElementSizeInBits)) - 1)) 2176 HasError = true; 2177 break; 2178 case SVETypeFlags::ImmCheckComplexRot90_270: 2179 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2180 diag::err_rotation_argument_to_cadd)) 2181 HasError = true; 2182 break; 2183 case SVETypeFlags::ImmCheckComplexRotAll90: 2184 if (CheckImmediateInSet( 2185 [](int64_t V) { 2186 return V == 0 || V == 90 || V == 180 || V == 270; 2187 }, 2188 diag::err_rotation_argument_to_cmla)) 2189 HasError = true; 2190 break; 2191 case SVETypeFlags::ImmCheck0_1: 2192 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2193 HasError = true; 2194 break; 2195 case SVETypeFlags::ImmCheck0_2: 2196 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2197 HasError = true; 2198 break; 2199 case SVETypeFlags::ImmCheck0_3: 2200 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2201 HasError = true; 2202 break; 2203 } 2204 } 2205 2206 return HasError; 2207 } 2208 2209 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2210 unsigned BuiltinID, CallExpr *TheCall) { 2211 llvm::APSInt Result; 2212 uint64_t mask = 0; 2213 unsigned TV = 0; 2214 int PtrArgNum = -1; 2215 bool HasConstPtr = false; 2216 switch (BuiltinID) { 2217 #define GET_NEON_OVERLOAD_CHECK 2218 #include "clang/Basic/arm_neon.inc" 2219 #include "clang/Basic/arm_fp16.inc" 2220 #undef GET_NEON_OVERLOAD_CHECK 2221 } 2222 2223 // For NEON intrinsics which are overloaded on vector element type, validate 2224 // the immediate which specifies which variant to emit. 2225 unsigned ImmArg = TheCall->getNumArgs()-1; 2226 if (mask) { 2227 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2228 return true; 2229 2230 TV = Result.getLimitedValue(64); 2231 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2232 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2233 << TheCall->getArg(ImmArg)->getSourceRange(); 2234 } 2235 2236 if (PtrArgNum >= 0) { 2237 // Check that pointer arguments have the specified type. 2238 Expr *Arg = TheCall->getArg(PtrArgNum); 2239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2240 Arg = ICE->getSubExpr(); 2241 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2242 QualType RHSTy = RHS.get()->getType(); 2243 2244 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2245 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2246 Arch == llvm::Triple::aarch64_32 || 2247 Arch == llvm::Triple::aarch64_be; 2248 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2249 QualType EltTy = 2250 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2251 if (HasConstPtr) 2252 EltTy = EltTy.withConst(); 2253 QualType LHSTy = Context.getPointerType(EltTy); 2254 AssignConvertType ConvTy; 2255 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2256 if (RHS.isInvalid()) 2257 return true; 2258 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2259 RHS.get(), AA_Assigning)) 2260 return true; 2261 } 2262 2263 // For NEON intrinsics which take an immediate value as part of the 2264 // instruction, range check them here. 2265 unsigned i = 0, l = 0, u = 0; 2266 switch (BuiltinID) { 2267 default: 2268 return false; 2269 #define GET_NEON_IMMEDIATE_CHECK 2270 #include "clang/Basic/arm_neon.inc" 2271 #include "clang/Basic/arm_fp16.inc" 2272 #undef GET_NEON_IMMEDIATE_CHECK 2273 } 2274 2275 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2276 } 2277 2278 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2279 switch (BuiltinID) { 2280 default: 2281 return false; 2282 #include "clang/Basic/arm_mve_builtin_sema.inc" 2283 } 2284 } 2285 2286 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2287 CallExpr *TheCall) { 2288 bool Err = false; 2289 switch (BuiltinID) { 2290 default: 2291 return false; 2292 #include "clang/Basic/arm_cde_builtin_sema.inc" 2293 } 2294 2295 if (Err) 2296 return true; 2297 2298 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2299 } 2300 2301 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2302 const Expr *CoprocArg, bool WantCDE) { 2303 if (isConstantEvaluated()) 2304 return false; 2305 2306 // We can't check the value of a dependent argument. 2307 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2308 return false; 2309 2310 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2311 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2312 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2313 2314 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2315 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2316 2317 if (IsCDECoproc != WantCDE) 2318 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2319 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2320 2321 return false; 2322 } 2323 2324 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2325 unsigned MaxWidth) { 2326 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2327 BuiltinID == ARM::BI__builtin_arm_ldaex || 2328 BuiltinID == ARM::BI__builtin_arm_strex || 2329 BuiltinID == ARM::BI__builtin_arm_stlex || 2330 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2331 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2332 BuiltinID == AArch64::BI__builtin_arm_strex || 2333 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2334 "unexpected ARM builtin"); 2335 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2336 BuiltinID == ARM::BI__builtin_arm_ldaex || 2337 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2338 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2339 2340 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2341 2342 // Ensure that we have the proper number of arguments. 2343 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2344 return true; 2345 2346 // Inspect the pointer argument of the atomic builtin. This should always be 2347 // a pointer type, whose element is an integral scalar or pointer type. 2348 // Because it is a pointer type, we don't have to worry about any implicit 2349 // casts here. 2350 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2351 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2352 if (PointerArgRes.isInvalid()) 2353 return true; 2354 PointerArg = PointerArgRes.get(); 2355 2356 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2357 if (!pointerType) { 2358 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2359 << PointerArg->getType() << PointerArg->getSourceRange(); 2360 return true; 2361 } 2362 2363 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2364 // task is to insert the appropriate casts into the AST. First work out just 2365 // what the appropriate type is. 2366 QualType ValType = pointerType->getPointeeType(); 2367 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2368 if (IsLdrex) 2369 AddrType.addConst(); 2370 2371 // Issue a warning if the cast is dodgy. 2372 CastKind CastNeeded = CK_NoOp; 2373 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2374 CastNeeded = CK_BitCast; 2375 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2376 << PointerArg->getType() << Context.getPointerType(AddrType) 2377 << AA_Passing << PointerArg->getSourceRange(); 2378 } 2379 2380 // Finally, do the cast and replace the argument with the corrected version. 2381 AddrType = Context.getPointerType(AddrType); 2382 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2383 if (PointerArgRes.isInvalid()) 2384 return true; 2385 PointerArg = PointerArgRes.get(); 2386 2387 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2388 2389 // In general, we allow ints, floats and pointers to be loaded and stored. 2390 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2391 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2392 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2393 << PointerArg->getType() << PointerArg->getSourceRange(); 2394 return true; 2395 } 2396 2397 // But ARM doesn't have instructions to deal with 128-bit versions. 2398 if (Context.getTypeSize(ValType) > MaxWidth) { 2399 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2400 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2401 << PointerArg->getType() << PointerArg->getSourceRange(); 2402 return true; 2403 } 2404 2405 switch (ValType.getObjCLifetime()) { 2406 case Qualifiers::OCL_None: 2407 case Qualifiers::OCL_ExplicitNone: 2408 // okay 2409 break; 2410 2411 case Qualifiers::OCL_Weak: 2412 case Qualifiers::OCL_Strong: 2413 case Qualifiers::OCL_Autoreleasing: 2414 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2415 << ValType << PointerArg->getSourceRange(); 2416 return true; 2417 } 2418 2419 if (IsLdrex) { 2420 TheCall->setType(ValType); 2421 return false; 2422 } 2423 2424 // Initialize the argument to be stored. 2425 ExprResult ValArg = TheCall->getArg(0); 2426 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2427 Context, ValType, /*consume*/ false); 2428 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2429 if (ValArg.isInvalid()) 2430 return true; 2431 TheCall->setArg(0, ValArg.get()); 2432 2433 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2434 // but the custom checker bypasses all default analysis. 2435 TheCall->setType(Context.IntTy); 2436 return false; 2437 } 2438 2439 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2440 CallExpr *TheCall) { 2441 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2442 BuiltinID == ARM::BI__builtin_arm_ldaex || 2443 BuiltinID == ARM::BI__builtin_arm_strex || 2444 BuiltinID == ARM::BI__builtin_arm_stlex) { 2445 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2446 } 2447 2448 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2449 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2450 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2451 } 2452 2453 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2454 BuiltinID == ARM::BI__builtin_arm_wsr64) 2455 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2456 2457 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2458 BuiltinID == ARM::BI__builtin_arm_rsrp || 2459 BuiltinID == ARM::BI__builtin_arm_wsr || 2460 BuiltinID == ARM::BI__builtin_arm_wsrp) 2461 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2462 2463 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2464 return true; 2465 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2466 return true; 2467 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2468 return true; 2469 2470 // For intrinsics which take an immediate value as part of the instruction, 2471 // range check them here. 2472 // FIXME: VFP Intrinsics should error if VFP not present. 2473 switch (BuiltinID) { 2474 default: return false; 2475 case ARM::BI__builtin_arm_ssat: 2476 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2477 case ARM::BI__builtin_arm_usat: 2478 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2479 case ARM::BI__builtin_arm_ssat16: 2480 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2481 case ARM::BI__builtin_arm_usat16: 2482 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2483 case ARM::BI__builtin_arm_vcvtr_f: 2484 case ARM::BI__builtin_arm_vcvtr_d: 2485 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2486 case ARM::BI__builtin_arm_dmb: 2487 case ARM::BI__builtin_arm_dsb: 2488 case ARM::BI__builtin_arm_isb: 2489 case ARM::BI__builtin_arm_dbg: 2490 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2491 case ARM::BI__builtin_arm_cdp: 2492 case ARM::BI__builtin_arm_cdp2: 2493 case ARM::BI__builtin_arm_mcr: 2494 case ARM::BI__builtin_arm_mcr2: 2495 case ARM::BI__builtin_arm_mrc: 2496 case ARM::BI__builtin_arm_mrc2: 2497 case ARM::BI__builtin_arm_mcrr: 2498 case ARM::BI__builtin_arm_mcrr2: 2499 case ARM::BI__builtin_arm_mrrc: 2500 case ARM::BI__builtin_arm_mrrc2: 2501 case ARM::BI__builtin_arm_ldc: 2502 case ARM::BI__builtin_arm_ldcl: 2503 case ARM::BI__builtin_arm_ldc2: 2504 case ARM::BI__builtin_arm_ldc2l: 2505 case ARM::BI__builtin_arm_stc: 2506 case ARM::BI__builtin_arm_stcl: 2507 case ARM::BI__builtin_arm_stc2: 2508 case ARM::BI__builtin_arm_stc2l: 2509 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2510 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2511 /*WantCDE*/ false); 2512 } 2513 } 2514 2515 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2516 unsigned BuiltinID, 2517 CallExpr *TheCall) { 2518 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2519 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2520 BuiltinID == AArch64::BI__builtin_arm_strex || 2521 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2522 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2523 } 2524 2525 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2526 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2527 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2528 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2529 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2530 } 2531 2532 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2533 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2534 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2535 2536 // Memory Tagging Extensions (MTE) Intrinsics 2537 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2538 BuiltinID == AArch64::BI__builtin_arm_addg || 2539 BuiltinID == AArch64::BI__builtin_arm_gmi || 2540 BuiltinID == AArch64::BI__builtin_arm_ldg || 2541 BuiltinID == AArch64::BI__builtin_arm_stg || 2542 BuiltinID == AArch64::BI__builtin_arm_subp) { 2543 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2544 } 2545 2546 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2547 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2548 BuiltinID == AArch64::BI__builtin_arm_wsr || 2549 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2550 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2551 2552 // Only check the valid encoding range. Any constant in this range would be 2553 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2554 // an exception for incorrect registers. This matches MSVC behavior. 2555 if (BuiltinID == AArch64::BI_ReadStatusReg || 2556 BuiltinID == AArch64::BI_WriteStatusReg) 2557 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2558 2559 if (BuiltinID == AArch64::BI__getReg) 2560 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2561 2562 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2563 return true; 2564 2565 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2566 return true; 2567 2568 // For intrinsics which take an immediate value as part of the instruction, 2569 // range check them here. 2570 unsigned i = 0, l = 0, u = 0; 2571 switch (BuiltinID) { 2572 default: return false; 2573 case AArch64::BI__builtin_arm_dmb: 2574 case AArch64::BI__builtin_arm_dsb: 2575 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2576 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2577 } 2578 2579 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2580 } 2581 2582 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2583 if (Arg->getType()->getAsPlaceholderType()) 2584 return false; 2585 2586 // The first argument needs to be a record field access. 2587 // If it is an array element access, we delay decision 2588 // to BPF backend to check whether the access is a 2589 // field access or not. 2590 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2591 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2592 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2593 } 2594 2595 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2596 QualType VectorTy, QualType EltTy) { 2597 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2598 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2599 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2600 << Call->getSourceRange() << VectorEltTy << EltTy; 2601 return false; 2602 } 2603 return true; 2604 } 2605 2606 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2607 QualType ArgType = Arg->getType(); 2608 if (ArgType->getAsPlaceholderType()) 2609 return false; 2610 2611 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2612 // format: 2613 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2614 // 2. <type> var; 2615 // __builtin_preserve_type_info(var, flag); 2616 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2617 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2618 return false; 2619 2620 // Typedef type. 2621 if (ArgType->getAs<TypedefType>()) 2622 return true; 2623 2624 // Record type or Enum type. 2625 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2626 if (const auto *RT = Ty->getAs<RecordType>()) { 2627 if (!RT->getDecl()->getDeclName().isEmpty()) 2628 return true; 2629 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2630 if (!ET->getDecl()->getDeclName().isEmpty()) 2631 return true; 2632 } 2633 2634 return false; 2635 } 2636 2637 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2638 QualType ArgType = Arg->getType(); 2639 if (ArgType->getAsPlaceholderType()) 2640 return false; 2641 2642 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2643 // format: 2644 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2645 // flag); 2646 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2647 if (!UO) 2648 return false; 2649 2650 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2651 if (!CE) 2652 return false; 2653 if (CE->getCastKind() != CK_IntegralToPointer && 2654 CE->getCastKind() != CK_NullToPointer) 2655 return false; 2656 2657 // The integer must be from an EnumConstantDecl. 2658 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2659 if (!DR) 2660 return false; 2661 2662 const EnumConstantDecl *Enumerator = 2663 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2664 if (!Enumerator) 2665 return false; 2666 2667 // The type must be EnumType. 2668 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2669 const auto *ET = Ty->getAs<EnumType>(); 2670 if (!ET) 2671 return false; 2672 2673 // The enum value must be supported. 2674 for (auto *EDI : ET->getDecl()->enumerators()) { 2675 if (EDI == Enumerator) 2676 return true; 2677 } 2678 2679 return false; 2680 } 2681 2682 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2683 CallExpr *TheCall) { 2684 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2685 BuiltinID == BPF::BI__builtin_btf_type_id || 2686 BuiltinID == BPF::BI__builtin_preserve_type_info || 2687 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2688 "unexpected BPF builtin"); 2689 2690 if (checkArgCount(*this, TheCall, 2)) 2691 return true; 2692 2693 // The second argument needs to be a constant int 2694 Expr *Arg = TheCall->getArg(1); 2695 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2696 diag::kind kind; 2697 if (!Value) { 2698 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2699 kind = diag::err_preserve_field_info_not_const; 2700 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2701 kind = diag::err_btf_type_id_not_const; 2702 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2703 kind = diag::err_preserve_type_info_not_const; 2704 else 2705 kind = diag::err_preserve_enum_value_not_const; 2706 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2707 return true; 2708 } 2709 2710 // The first argument 2711 Arg = TheCall->getArg(0); 2712 bool InvalidArg = false; 2713 bool ReturnUnsignedInt = true; 2714 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2715 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2716 InvalidArg = true; 2717 kind = diag::err_preserve_field_info_not_field; 2718 } 2719 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2720 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2721 InvalidArg = true; 2722 kind = diag::err_preserve_type_info_invalid; 2723 } 2724 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2725 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2726 InvalidArg = true; 2727 kind = diag::err_preserve_enum_value_invalid; 2728 } 2729 ReturnUnsignedInt = false; 2730 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2731 ReturnUnsignedInt = false; 2732 } 2733 2734 if (InvalidArg) { 2735 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2736 return true; 2737 } 2738 2739 if (ReturnUnsignedInt) 2740 TheCall->setType(Context.UnsignedIntTy); 2741 else 2742 TheCall->setType(Context.UnsignedLongTy); 2743 return false; 2744 } 2745 2746 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2747 struct ArgInfo { 2748 uint8_t OpNum; 2749 bool IsSigned; 2750 uint8_t BitWidth; 2751 uint8_t Align; 2752 }; 2753 struct BuiltinInfo { 2754 unsigned BuiltinID; 2755 ArgInfo Infos[2]; 2756 }; 2757 2758 static BuiltinInfo Infos[] = { 2759 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2760 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2761 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2762 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2763 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2764 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2765 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2766 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2767 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2768 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2769 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2770 2771 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2782 2783 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2835 {{ 1, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2843 {{ 1, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2850 { 2, false, 5, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2852 { 2, false, 6, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2854 { 3, false, 5, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2856 { 3, false, 6, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2873 {{ 2, false, 4, 0 }, 2874 { 3, false, 5, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2876 {{ 2, false, 4, 0 }, 2877 { 3, false, 5, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2879 {{ 2, false, 4, 0 }, 2880 { 3, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2882 {{ 2, false, 4, 0 }, 2883 { 3, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2895 { 2, false, 5, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2897 { 2, false, 6, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2907 {{ 1, false, 4, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2910 {{ 1, false, 4, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2931 {{ 3, false, 1, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2936 {{ 3, false, 1, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2940 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2941 {{ 3, false, 1, 0 }} }, 2942 }; 2943 2944 // Use a dynamically initialized static to sort the table exactly once on 2945 // first run. 2946 static const bool SortOnce = 2947 (llvm::sort(Infos, 2948 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2949 return LHS.BuiltinID < RHS.BuiltinID; 2950 }), 2951 true); 2952 (void)SortOnce; 2953 2954 const BuiltinInfo *F = llvm::partition_point( 2955 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2956 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2957 return false; 2958 2959 bool Error = false; 2960 2961 for (const ArgInfo &A : F->Infos) { 2962 // Ignore empty ArgInfo elements. 2963 if (A.BitWidth == 0) 2964 continue; 2965 2966 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2967 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2968 if (!A.Align) { 2969 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2970 } else { 2971 unsigned M = 1 << A.Align; 2972 Min *= M; 2973 Max *= M; 2974 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2975 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2976 } 2977 } 2978 return Error; 2979 } 2980 2981 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2982 CallExpr *TheCall) { 2983 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2984 } 2985 2986 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2987 unsigned BuiltinID, CallExpr *TheCall) { 2988 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2989 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2990 } 2991 2992 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2993 CallExpr *TheCall) { 2994 2995 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2996 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2997 if (!TI.hasFeature("dsp")) 2998 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2999 } 3000 3001 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3002 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3003 if (!TI.hasFeature("dspr2")) 3004 return Diag(TheCall->getBeginLoc(), 3005 diag::err_mips_builtin_requires_dspr2); 3006 } 3007 3008 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3009 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3010 if (!TI.hasFeature("msa")) 3011 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3012 } 3013 3014 return false; 3015 } 3016 3017 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3018 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3019 // ordering for DSP is unspecified. MSA is ordered by the data format used 3020 // by the underlying instruction i.e., df/m, df/n and then by size. 3021 // 3022 // FIXME: The size tests here should instead be tablegen'd along with the 3023 // definitions from include/clang/Basic/BuiltinsMips.def. 3024 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3025 // be too. 3026 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3027 unsigned i = 0, l = 0, u = 0, m = 0; 3028 switch (BuiltinID) { 3029 default: return false; 3030 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3031 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3032 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3033 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3034 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3035 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3036 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3037 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3038 // df/m field. 3039 // These intrinsics take an unsigned 3 bit immediate. 3040 case Mips::BI__builtin_msa_bclri_b: 3041 case Mips::BI__builtin_msa_bnegi_b: 3042 case Mips::BI__builtin_msa_bseti_b: 3043 case Mips::BI__builtin_msa_sat_s_b: 3044 case Mips::BI__builtin_msa_sat_u_b: 3045 case Mips::BI__builtin_msa_slli_b: 3046 case Mips::BI__builtin_msa_srai_b: 3047 case Mips::BI__builtin_msa_srari_b: 3048 case Mips::BI__builtin_msa_srli_b: 3049 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3050 case Mips::BI__builtin_msa_binsli_b: 3051 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3052 // These intrinsics take an unsigned 4 bit immediate. 3053 case Mips::BI__builtin_msa_bclri_h: 3054 case Mips::BI__builtin_msa_bnegi_h: 3055 case Mips::BI__builtin_msa_bseti_h: 3056 case Mips::BI__builtin_msa_sat_s_h: 3057 case Mips::BI__builtin_msa_sat_u_h: 3058 case Mips::BI__builtin_msa_slli_h: 3059 case Mips::BI__builtin_msa_srai_h: 3060 case Mips::BI__builtin_msa_srari_h: 3061 case Mips::BI__builtin_msa_srli_h: 3062 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3063 case Mips::BI__builtin_msa_binsli_h: 3064 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3065 // These intrinsics take an unsigned 5 bit immediate. 3066 // The first block of intrinsics actually have an unsigned 5 bit field, 3067 // not a df/n field. 3068 case Mips::BI__builtin_msa_cfcmsa: 3069 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3070 case Mips::BI__builtin_msa_clei_u_b: 3071 case Mips::BI__builtin_msa_clei_u_h: 3072 case Mips::BI__builtin_msa_clei_u_w: 3073 case Mips::BI__builtin_msa_clei_u_d: 3074 case Mips::BI__builtin_msa_clti_u_b: 3075 case Mips::BI__builtin_msa_clti_u_h: 3076 case Mips::BI__builtin_msa_clti_u_w: 3077 case Mips::BI__builtin_msa_clti_u_d: 3078 case Mips::BI__builtin_msa_maxi_u_b: 3079 case Mips::BI__builtin_msa_maxi_u_h: 3080 case Mips::BI__builtin_msa_maxi_u_w: 3081 case Mips::BI__builtin_msa_maxi_u_d: 3082 case Mips::BI__builtin_msa_mini_u_b: 3083 case Mips::BI__builtin_msa_mini_u_h: 3084 case Mips::BI__builtin_msa_mini_u_w: 3085 case Mips::BI__builtin_msa_mini_u_d: 3086 case Mips::BI__builtin_msa_addvi_b: 3087 case Mips::BI__builtin_msa_addvi_h: 3088 case Mips::BI__builtin_msa_addvi_w: 3089 case Mips::BI__builtin_msa_addvi_d: 3090 case Mips::BI__builtin_msa_bclri_w: 3091 case Mips::BI__builtin_msa_bnegi_w: 3092 case Mips::BI__builtin_msa_bseti_w: 3093 case Mips::BI__builtin_msa_sat_s_w: 3094 case Mips::BI__builtin_msa_sat_u_w: 3095 case Mips::BI__builtin_msa_slli_w: 3096 case Mips::BI__builtin_msa_srai_w: 3097 case Mips::BI__builtin_msa_srari_w: 3098 case Mips::BI__builtin_msa_srli_w: 3099 case Mips::BI__builtin_msa_srlri_w: 3100 case Mips::BI__builtin_msa_subvi_b: 3101 case Mips::BI__builtin_msa_subvi_h: 3102 case Mips::BI__builtin_msa_subvi_w: 3103 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3104 case Mips::BI__builtin_msa_binsli_w: 3105 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3106 // These intrinsics take an unsigned 6 bit immediate. 3107 case Mips::BI__builtin_msa_bclri_d: 3108 case Mips::BI__builtin_msa_bnegi_d: 3109 case Mips::BI__builtin_msa_bseti_d: 3110 case Mips::BI__builtin_msa_sat_s_d: 3111 case Mips::BI__builtin_msa_sat_u_d: 3112 case Mips::BI__builtin_msa_slli_d: 3113 case Mips::BI__builtin_msa_srai_d: 3114 case Mips::BI__builtin_msa_srari_d: 3115 case Mips::BI__builtin_msa_srli_d: 3116 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3117 case Mips::BI__builtin_msa_binsli_d: 3118 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3119 // These intrinsics take a signed 5 bit immediate. 3120 case Mips::BI__builtin_msa_ceqi_b: 3121 case Mips::BI__builtin_msa_ceqi_h: 3122 case Mips::BI__builtin_msa_ceqi_w: 3123 case Mips::BI__builtin_msa_ceqi_d: 3124 case Mips::BI__builtin_msa_clti_s_b: 3125 case Mips::BI__builtin_msa_clti_s_h: 3126 case Mips::BI__builtin_msa_clti_s_w: 3127 case Mips::BI__builtin_msa_clti_s_d: 3128 case Mips::BI__builtin_msa_clei_s_b: 3129 case Mips::BI__builtin_msa_clei_s_h: 3130 case Mips::BI__builtin_msa_clei_s_w: 3131 case Mips::BI__builtin_msa_clei_s_d: 3132 case Mips::BI__builtin_msa_maxi_s_b: 3133 case Mips::BI__builtin_msa_maxi_s_h: 3134 case Mips::BI__builtin_msa_maxi_s_w: 3135 case Mips::BI__builtin_msa_maxi_s_d: 3136 case Mips::BI__builtin_msa_mini_s_b: 3137 case Mips::BI__builtin_msa_mini_s_h: 3138 case Mips::BI__builtin_msa_mini_s_w: 3139 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3140 // These intrinsics take an unsigned 8 bit immediate. 3141 case Mips::BI__builtin_msa_andi_b: 3142 case Mips::BI__builtin_msa_nori_b: 3143 case Mips::BI__builtin_msa_ori_b: 3144 case Mips::BI__builtin_msa_shf_b: 3145 case Mips::BI__builtin_msa_shf_h: 3146 case Mips::BI__builtin_msa_shf_w: 3147 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3148 case Mips::BI__builtin_msa_bseli_b: 3149 case Mips::BI__builtin_msa_bmnzi_b: 3150 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3151 // df/n format 3152 // These intrinsics take an unsigned 4 bit immediate. 3153 case Mips::BI__builtin_msa_copy_s_b: 3154 case Mips::BI__builtin_msa_copy_u_b: 3155 case Mips::BI__builtin_msa_insve_b: 3156 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3157 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3158 // These intrinsics take an unsigned 3 bit immediate. 3159 case Mips::BI__builtin_msa_copy_s_h: 3160 case Mips::BI__builtin_msa_copy_u_h: 3161 case Mips::BI__builtin_msa_insve_h: 3162 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3163 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3164 // These intrinsics take an unsigned 2 bit immediate. 3165 case Mips::BI__builtin_msa_copy_s_w: 3166 case Mips::BI__builtin_msa_copy_u_w: 3167 case Mips::BI__builtin_msa_insve_w: 3168 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3169 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3170 // These intrinsics take an unsigned 1 bit immediate. 3171 case Mips::BI__builtin_msa_copy_s_d: 3172 case Mips::BI__builtin_msa_copy_u_d: 3173 case Mips::BI__builtin_msa_insve_d: 3174 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3175 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3176 // Memory offsets and immediate loads. 3177 // These intrinsics take a signed 10 bit immediate. 3178 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3179 case Mips::BI__builtin_msa_ldi_h: 3180 case Mips::BI__builtin_msa_ldi_w: 3181 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3182 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3183 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3184 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3185 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3186 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3187 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3188 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3189 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3190 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3191 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3192 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3193 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3194 } 3195 3196 if (!m) 3197 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3198 3199 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3200 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3201 } 3202 3203 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3204 /// advancing the pointer over the consumed characters. The decoded type is 3205 /// returned. If the decoded type represents a constant integer with a 3206 /// constraint on its value then Mask is set to that value. The type descriptors 3207 /// used in Str are specific to PPC MMA builtins and are documented in the file 3208 /// defining the PPC builtins. 3209 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3210 unsigned &Mask) { 3211 bool RequireICE = false; 3212 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3213 switch (*Str++) { 3214 case 'V': 3215 return Context.getVectorType(Context.UnsignedCharTy, 16, 3216 VectorType::VectorKind::AltiVecVector); 3217 case 'i': { 3218 char *End; 3219 unsigned size = strtoul(Str, &End, 10); 3220 assert(End != Str && "Missing constant parameter constraint"); 3221 Str = End; 3222 Mask = size; 3223 return Context.IntTy; 3224 } 3225 case 'W': { 3226 char *End; 3227 unsigned size = strtoul(Str, &End, 10); 3228 assert(End != Str && "Missing PowerPC MMA type size"); 3229 Str = End; 3230 QualType Type; 3231 switch (size) { 3232 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3233 case size: Type = Context.Id##Ty; break; 3234 #include "clang/Basic/PPCTypes.def" 3235 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3236 } 3237 bool CheckVectorArgs = false; 3238 while (!CheckVectorArgs) { 3239 switch (*Str++) { 3240 case '*': 3241 Type = Context.getPointerType(Type); 3242 break; 3243 case 'C': 3244 Type = Type.withConst(); 3245 break; 3246 default: 3247 CheckVectorArgs = true; 3248 --Str; 3249 break; 3250 } 3251 } 3252 return Type; 3253 } 3254 default: 3255 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3256 } 3257 } 3258 3259 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3260 CallExpr *TheCall) { 3261 unsigned i = 0, l = 0, u = 0; 3262 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3263 BuiltinID == PPC::BI__builtin_divdeu || 3264 BuiltinID == PPC::BI__builtin_bpermd; 3265 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3266 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3267 BuiltinID == PPC::BI__builtin_divweu || 3268 BuiltinID == PPC::BI__builtin_divde || 3269 BuiltinID == PPC::BI__builtin_divdeu; 3270 3271 if (Is64BitBltin && !IsTarget64Bit) 3272 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3273 << TheCall->getSourceRange(); 3274 3275 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3276 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3277 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3278 << TheCall->getSourceRange(); 3279 3280 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3281 if (!TI.hasFeature("vsx")) 3282 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3283 << TheCall->getSourceRange(); 3284 return false; 3285 }; 3286 3287 switch (BuiltinID) { 3288 default: return false; 3289 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3290 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3291 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3292 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3293 case PPC::BI__builtin_altivec_dss: 3294 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3295 case PPC::BI__builtin_tbegin: 3296 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3297 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3298 case PPC::BI__builtin_tabortwc: 3299 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3300 case PPC::BI__builtin_tabortwci: 3301 case PPC::BI__builtin_tabortdci: 3302 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3303 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3304 case PPC::BI__builtin_altivec_dst: 3305 case PPC::BI__builtin_altivec_dstt: 3306 case PPC::BI__builtin_altivec_dstst: 3307 case PPC::BI__builtin_altivec_dststt: 3308 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3309 case PPC::BI__builtin_vsx_xxpermdi: 3310 case PPC::BI__builtin_vsx_xxsldwi: 3311 return SemaBuiltinVSX(TheCall); 3312 case PPC::BI__builtin_unpack_vector_int128: 3313 return SemaVSXCheck(TheCall) || 3314 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3315 case PPC::BI__builtin_pack_vector_int128: 3316 return SemaVSXCheck(TheCall); 3317 case PPC::BI__builtin_altivec_vgnb: 3318 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3319 case PPC::BI__builtin_altivec_vec_replace_elt: 3320 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3321 QualType VecTy = TheCall->getArg(0)->getType(); 3322 QualType EltTy = TheCall->getArg(1)->getType(); 3323 unsigned Width = Context.getIntWidth(EltTy); 3324 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3325 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3326 } 3327 case PPC::BI__builtin_vsx_xxeval: 3328 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3329 case PPC::BI__builtin_altivec_vsldbi: 3330 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3331 case PPC::BI__builtin_altivec_vsrdbi: 3332 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3333 case PPC::BI__builtin_vsx_xxpermx: 3334 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3335 #define CUSTOM_BUILTIN(Name, Types, Acc) \ 3336 case PPC::BI__builtin_##Name: \ 3337 return SemaBuiltinPPCMMACall(TheCall, Types); 3338 #include "clang/Basic/BuiltinsPPC.def" 3339 } 3340 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3341 } 3342 3343 // Check if the given type is a non-pointer PPC MMA type. This function is used 3344 // in Sema to prevent invalid uses of restricted PPC MMA types. 3345 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3346 if (Type->isPointerType() || Type->isArrayType()) 3347 return false; 3348 3349 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3350 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3351 if (false 3352 #include "clang/Basic/PPCTypes.def" 3353 ) { 3354 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3355 return true; 3356 } 3357 return false; 3358 } 3359 3360 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3361 CallExpr *TheCall) { 3362 // position of memory order and scope arguments in the builtin 3363 unsigned OrderIndex, ScopeIndex; 3364 switch (BuiltinID) { 3365 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3366 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3367 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3368 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3369 OrderIndex = 2; 3370 ScopeIndex = 3; 3371 break; 3372 case AMDGPU::BI__builtin_amdgcn_fence: 3373 OrderIndex = 0; 3374 ScopeIndex = 1; 3375 break; 3376 default: 3377 return false; 3378 } 3379 3380 ExprResult Arg = TheCall->getArg(OrderIndex); 3381 auto ArgExpr = Arg.get(); 3382 Expr::EvalResult ArgResult; 3383 3384 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3385 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3386 << ArgExpr->getType(); 3387 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3388 3389 // Check valididty of memory ordering as per C11 / C++11's memody model. 3390 // Only fence needs check. Atomic dec/inc allow all memory orders. 3391 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3392 return Diag(ArgExpr->getBeginLoc(), 3393 diag::warn_atomic_op_has_invalid_memory_order) 3394 << ArgExpr->getSourceRange(); 3395 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3396 case llvm::AtomicOrderingCABI::relaxed: 3397 case llvm::AtomicOrderingCABI::consume: 3398 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3399 return Diag(ArgExpr->getBeginLoc(), 3400 diag::warn_atomic_op_has_invalid_memory_order) 3401 << ArgExpr->getSourceRange(); 3402 break; 3403 case llvm::AtomicOrderingCABI::acquire: 3404 case llvm::AtomicOrderingCABI::release: 3405 case llvm::AtomicOrderingCABI::acq_rel: 3406 case llvm::AtomicOrderingCABI::seq_cst: 3407 break; 3408 } 3409 3410 Arg = TheCall->getArg(ScopeIndex); 3411 ArgExpr = Arg.get(); 3412 Expr::EvalResult ArgResult1; 3413 // Check that sync scope is a constant literal 3414 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3415 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3416 << ArgExpr->getType(); 3417 3418 return false; 3419 } 3420 3421 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3422 unsigned BuiltinID, 3423 CallExpr *TheCall) { 3424 // CodeGenFunction can also detect this, but this gives a better error 3425 // message. 3426 bool FeatureMissing = false; 3427 SmallVector<StringRef> ReqFeatures; 3428 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3429 Features.split(ReqFeatures, ','); 3430 3431 // Check if each required feature is included 3432 for (StringRef F : ReqFeatures) { 3433 if (TI.hasFeature(F)) 3434 continue; 3435 3436 // If the feature is 64bit, alter the string so it will print better in 3437 // the diagnostic. 3438 if (F == "64bit") 3439 F = "RV64"; 3440 3441 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3442 F.consume_front("experimental-"); 3443 std::string FeatureStr = F.str(); 3444 FeatureStr[0] = std::toupper(FeatureStr[0]); 3445 3446 // Error message 3447 FeatureMissing = true; 3448 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3449 << TheCall->getSourceRange() << StringRef(FeatureStr); 3450 } 3451 3452 return FeatureMissing; 3453 } 3454 3455 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3456 CallExpr *TheCall) { 3457 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3458 Expr *Arg = TheCall->getArg(0); 3459 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3460 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3461 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3462 << Arg->getSourceRange(); 3463 } 3464 3465 // For intrinsics which take an immediate value as part of the instruction, 3466 // range check them here. 3467 unsigned i = 0, l = 0, u = 0; 3468 switch (BuiltinID) { 3469 default: return false; 3470 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3471 case SystemZ::BI__builtin_s390_verimb: 3472 case SystemZ::BI__builtin_s390_verimh: 3473 case SystemZ::BI__builtin_s390_verimf: 3474 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3475 case SystemZ::BI__builtin_s390_vfaeb: 3476 case SystemZ::BI__builtin_s390_vfaeh: 3477 case SystemZ::BI__builtin_s390_vfaef: 3478 case SystemZ::BI__builtin_s390_vfaebs: 3479 case SystemZ::BI__builtin_s390_vfaehs: 3480 case SystemZ::BI__builtin_s390_vfaefs: 3481 case SystemZ::BI__builtin_s390_vfaezb: 3482 case SystemZ::BI__builtin_s390_vfaezh: 3483 case SystemZ::BI__builtin_s390_vfaezf: 3484 case SystemZ::BI__builtin_s390_vfaezbs: 3485 case SystemZ::BI__builtin_s390_vfaezhs: 3486 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3487 case SystemZ::BI__builtin_s390_vfisb: 3488 case SystemZ::BI__builtin_s390_vfidb: 3489 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3490 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3491 case SystemZ::BI__builtin_s390_vftcisb: 3492 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3493 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3494 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3495 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3496 case SystemZ::BI__builtin_s390_vstrcb: 3497 case SystemZ::BI__builtin_s390_vstrch: 3498 case SystemZ::BI__builtin_s390_vstrcf: 3499 case SystemZ::BI__builtin_s390_vstrczb: 3500 case SystemZ::BI__builtin_s390_vstrczh: 3501 case SystemZ::BI__builtin_s390_vstrczf: 3502 case SystemZ::BI__builtin_s390_vstrcbs: 3503 case SystemZ::BI__builtin_s390_vstrchs: 3504 case SystemZ::BI__builtin_s390_vstrcfs: 3505 case SystemZ::BI__builtin_s390_vstrczbs: 3506 case SystemZ::BI__builtin_s390_vstrczhs: 3507 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3508 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3509 case SystemZ::BI__builtin_s390_vfminsb: 3510 case SystemZ::BI__builtin_s390_vfmaxsb: 3511 case SystemZ::BI__builtin_s390_vfmindb: 3512 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3513 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3514 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3515 } 3516 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3517 } 3518 3519 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3520 /// This checks that the target supports __builtin_cpu_supports and 3521 /// that the string argument is constant and valid. 3522 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3523 CallExpr *TheCall) { 3524 Expr *Arg = TheCall->getArg(0); 3525 3526 // Check if the argument is a string literal. 3527 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3528 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3529 << Arg->getSourceRange(); 3530 3531 // Check the contents of the string. 3532 StringRef Feature = 3533 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3534 if (!TI.validateCpuSupports(Feature)) 3535 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3536 << Arg->getSourceRange(); 3537 return false; 3538 } 3539 3540 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3541 /// This checks that the target supports __builtin_cpu_is and 3542 /// that the string argument is constant and valid. 3543 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3544 Expr *Arg = TheCall->getArg(0); 3545 3546 // Check if the argument is a string literal. 3547 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3548 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3549 << Arg->getSourceRange(); 3550 3551 // Check the contents of the string. 3552 StringRef Feature = 3553 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3554 if (!TI.validateCpuIs(Feature)) 3555 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3556 << Arg->getSourceRange(); 3557 return false; 3558 } 3559 3560 // Check if the rounding mode is legal. 3561 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3562 // Indicates if this instruction has rounding control or just SAE. 3563 bool HasRC = false; 3564 3565 unsigned ArgNum = 0; 3566 switch (BuiltinID) { 3567 default: 3568 return false; 3569 case X86::BI__builtin_ia32_vcvttsd2si32: 3570 case X86::BI__builtin_ia32_vcvttsd2si64: 3571 case X86::BI__builtin_ia32_vcvttsd2usi32: 3572 case X86::BI__builtin_ia32_vcvttsd2usi64: 3573 case X86::BI__builtin_ia32_vcvttss2si32: 3574 case X86::BI__builtin_ia32_vcvttss2si64: 3575 case X86::BI__builtin_ia32_vcvttss2usi32: 3576 case X86::BI__builtin_ia32_vcvttss2usi64: 3577 ArgNum = 1; 3578 break; 3579 case X86::BI__builtin_ia32_maxpd512: 3580 case X86::BI__builtin_ia32_maxps512: 3581 case X86::BI__builtin_ia32_minpd512: 3582 case X86::BI__builtin_ia32_minps512: 3583 ArgNum = 2; 3584 break; 3585 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3586 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3587 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3588 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3589 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3590 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3591 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3592 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3593 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3594 case X86::BI__builtin_ia32_exp2pd_mask: 3595 case X86::BI__builtin_ia32_exp2ps_mask: 3596 case X86::BI__builtin_ia32_getexppd512_mask: 3597 case X86::BI__builtin_ia32_getexpps512_mask: 3598 case X86::BI__builtin_ia32_rcp28pd_mask: 3599 case X86::BI__builtin_ia32_rcp28ps_mask: 3600 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3601 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3602 case X86::BI__builtin_ia32_vcomisd: 3603 case X86::BI__builtin_ia32_vcomiss: 3604 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3605 ArgNum = 3; 3606 break; 3607 case X86::BI__builtin_ia32_cmppd512_mask: 3608 case X86::BI__builtin_ia32_cmpps512_mask: 3609 case X86::BI__builtin_ia32_cmpsd_mask: 3610 case X86::BI__builtin_ia32_cmpss_mask: 3611 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3612 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3613 case X86::BI__builtin_ia32_getexpss128_round_mask: 3614 case X86::BI__builtin_ia32_getmantpd512_mask: 3615 case X86::BI__builtin_ia32_getmantps512_mask: 3616 case X86::BI__builtin_ia32_maxsd_round_mask: 3617 case X86::BI__builtin_ia32_maxss_round_mask: 3618 case X86::BI__builtin_ia32_minsd_round_mask: 3619 case X86::BI__builtin_ia32_minss_round_mask: 3620 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3621 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3622 case X86::BI__builtin_ia32_reducepd512_mask: 3623 case X86::BI__builtin_ia32_reduceps512_mask: 3624 case X86::BI__builtin_ia32_rndscalepd_mask: 3625 case X86::BI__builtin_ia32_rndscaleps_mask: 3626 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3627 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3628 ArgNum = 4; 3629 break; 3630 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3631 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3632 case X86::BI__builtin_ia32_fixupimmps512_mask: 3633 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3634 case X86::BI__builtin_ia32_fixupimmsd_mask: 3635 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3636 case X86::BI__builtin_ia32_fixupimmss_mask: 3637 case X86::BI__builtin_ia32_fixupimmss_maskz: 3638 case X86::BI__builtin_ia32_getmantsd_round_mask: 3639 case X86::BI__builtin_ia32_getmantss_round_mask: 3640 case X86::BI__builtin_ia32_rangepd512_mask: 3641 case X86::BI__builtin_ia32_rangeps512_mask: 3642 case X86::BI__builtin_ia32_rangesd128_round_mask: 3643 case X86::BI__builtin_ia32_rangess128_round_mask: 3644 case X86::BI__builtin_ia32_reducesd_mask: 3645 case X86::BI__builtin_ia32_reducess_mask: 3646 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3647 case X86::BI__builtin_ia32_rndscaless_round_mask: 3648 ArgNum = 5; 3649 break; 3650 case X86::BI__builtin_ia32_vcvtsd2si64: 3651 case X86::BI__builtin_ia32_vcvtsd2si32: 3652 case X86::BI__builtin_ia32_vcvtsd2usi32: 3653 case X86::BI__builtin_ia32_vcvtsd2usi64: 3654 case X86::BI__builtin_ia32_vcvtss2si32: 3655 case X86::BI__builtin_ia32_vcvtss2si64: 3656 case X86::BI__builtin_ia32_vcvtss2usi32: 3657 case X86::BI__builtin_ia32_vcvtss2usi64: 3658 case X86::BI__builtin_ia32_sqrtpd512: 3659 case X86::BI__builtin_ia32_sqrtps512: 3660 ArgNum = 1; 3661 HasRC = true; 3662 break; 3663 case X86::BI__builtin_ia32_addpd512: 3664 case X86::BI__builtin_ia32_addps512: 3665 case X86::BI__builtin_ia32_divpd512: 3666 case X86::BI__builtin_ia32_divps512: 3667 case X86::BI__builtin_ia32_mulpd512: 3668 case X86::BI__builtin_ia32_mulps512: 3669 case X86::BI__builtin_ia32_subpd512: 3670 case X86::BI__builtin_ia32_subps512: 3671 case X86::BI__builtin_ia32_cvtsi2sd64: 3672 case X86::BI__builtin_ia32_cvtsi2ss32: 3673 case X86::BI__builtin_ia32_cvtsi2ss64: 3674 case X86::BI__builtin_ia32_cvtusi2sd64: 3675 case X86::BI__builtin_ia32_cvtusi2ss32: 3676 case X86::BI__builtin_ia32_cvtusi2ss64: 3677 ArgNum = 2; 3678 HasRC = true; 3679 break; 3680 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3681 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3682 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3683 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3684 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3685 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3686 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3687 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3688 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3689 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3690 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3691 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3692 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3693 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3694 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3695 ArgNum = 3; 3696 HasRC = true; 3697 break; 3698 case X86::BI__builtin_ia32_addss_round_mask: 3699 case X86::BI__builtin_ia32_addsd_round_mask: 3700 case X86::BI__builtin_ia32_divss_round_mask: 3701 case X86::BI__builtin_ia32_divsd_round_mask: 3702 case X86::BI__builtin_ia32_mulss_round_mask: 3703 case X86::BI__builtin_ia32_mulsd_round_mask: 3704 case X86::BI__builtin_ia32_subss_round_mask: 3705 case X86::BI__builtin_ia32_subsd_round_mask: 3706 case X86::BI__builtin_ia32_scalefpd512_mask: 3707 case X86::BI__builtin_ia32_scalefps512_mask: 3708 case X86::BI__builtin_ia32_scalefsd_round_mask: 3709 case X86::BI__builtin_ia32_scalefss_round_mask: 3710 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3711 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3712 case X86::BI__builtin_ia32_sqrtss_round_mask: 3713 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3714 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3715 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3716 case X86::BI__builtin_ia32_vfmaddss3_mask: 3717 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3718 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3719 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3720 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3721 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3722 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3723 case X86::BI__builtin_ia32_vfmaddps512_mask: 3724 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3725 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3726 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3727 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3728 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3729 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3730 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3731 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3732 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3733 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3734 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3735 ArgNum = 4; 3736 HasRC = true; 3737 break; 3738 } 3739 3740 llvm::APSInt Result; 3741 3742 // We can't check the value of a dependent argument. 3743 Expr *Arg = TheCall->getArg(ArgNum); 3744 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3745 return false; 3746 3747 // Check constant-ness first. 3748 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3749 return true; 3750 3751 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3752 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3753 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3754 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3755 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3756 Result == 8/*ROUND_NO_EXC*/ || 3757 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3758 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3759 return false; 3760 3761 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3762 << Arg->getSourceRange(); 3763 } 3764 3765 // Check if the gather/scatter scale is legal. 3766 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3767 CallExpr *TheCall) { 3768 unsigned ArgNum = 0; 3769 switch (BuiltinID) { 3770 default: 3771 return false; 3772 case X86::BI__builtin_ia32_gatherpfdpd: 3773 case X86::BI__builtin_ia32_gatherpfdps: 3774 case X86::BI__builtin_ia32_gatherpfqpd: 3775 case X86::BI__builtin_ia32_gatherpfqps: 3776 case X86::BI__builtin_ia32_scatterpfdpd: 3777 case X86::BI__builtin_ia32_scatterpfdps: 3778 case X86::BI__builtin_ia32_scatterpfqpd: 3779 case X86::BI__builtin_ia32_scatterpfqps: 3780 ArgNum = 3; 3781 break; 3782 case X86::BI__builtin_ia32_gatherd_pd: 3783 case X86::BI__builtin_ia32_gatherd_pd256: 3784 case X86::BI__builtin_ia32_gatherq_pd: 3785 case X86::BI__builtin_ia32_gatherq_pd256: 3786 case X86::BI__builtin_ia32_gatherd_ps: 3787 case X86::BI__builtin_ia32_gatherd_ps256: 3788 case X86::BI__builtin_ia32_gatherq_ps: 3789 case X86::BI__builtin_ia32_gatherq_ps256: 3790 case X86::BI__builtin_ia32_gatherd_q: 3791 case X86::BI__builtin_ia32_gatherd_q256: 3792 case X86::BI__builtin_ia32_gatherq_q: 3793 case X86::BI__builtin_ia32_gatherq_q256: 3794 case X86::BI__builtin_ia32_gatherd_d: 3795 case X86::BI__builtin_ia32_gatherd_d256: 3796 case X86::BI__builtin_ia32_gatherq_d: 3797 case X86::BI__builtin_ia32_gatherq_d256: 3798 case X86::BI__builtin_ia32_gather3div2df: 3799 case X86::BI__builtin_ia32_gather3div2di: 3800 case X86::BI__builtin_ia32_gather3div4df: 3801 case X86::BI__builtin_ia32_gather3div4di: 3802 case X86::BI__builtin_ia32_gather3div4sf: 3803 case X86::BI__builtin_ia32_gather3div4si: 3804 case X86::BI__builtin_ia32_gather3div8sf: 3805 case X86::BI__builtin_ia32_gather3div8si: 3806 case X86::BI__builtin_ia32_gather3siv2df: 3807 case X86::BI__builtin_ia32_gather3siv2di: 3808 case X86::BI__builtin_ia32_gather3siv4df: 3809 case X86::BI__builtin_ia32_gather3siv4di: 3810 case X86::BI__builtin_ia32_gather3siv4sf: 3811 case X86::BI__builtin_ia32_gather3siv4si: 3812 case X86::BI__builtin_ia32_gather3siv8sf: 3813 case X86::BI__builtin_ia32_gather3siv8si: 3814 case X86::BI__builtin_ia32_gathersiv8df: 3815 case X86::BI__builtin_ia32_gathersiv16sf: 3816 case X86::BI__builtin_ia32_gatherdiv8df: 3817 case X86::BI__builtin_ia32_gatherdiv16sf: 3818 case X86::BI__builtin_ia32_gathersiv8di: 3819 case X86::BI__builtin_ia32_gathersiv16si: 3820 case X86::BI__builtin_ia32_gatherdiv8di: 3821 case X86::BI__builtin_ia32_gatherdiv16si: 3822 case X86::BI__builtin_ia32_scatterdiv2df: 3823 case X86::BI__builtin_ia32_scatterdiv2di: 3824 case X86::BI__builtin_ia32_scatterdiv4df: 3825 case X86::BI__builtin_ia32_scatterdiv4di: 3826 case X86::BI__builtin_ia32_scatterdiv4sf: 3827 case X86::BI__builtin_ia32_scatterdiv4si: 3828 case X86::BI__builtin_ia32_scatterdiv8sf: 3829 case X86::BI__builtin_ia32_scatterdiv8si: 3830 case X86::BI__builtin_ia32_scattersiv2df: 3831 case X86::BI__builtin_ia32_scattersiv2di: 3832 case X86::BI__builtin_ia32_scattersiv4df: 3833 case X86::BI__builtin_ia32_scattersiv4di: 3834 case X86::BI__builtin_ia32_scattersiv4sf: 3835 case X86::BI__builtin_ia32_scattersiv4si: 3836 case X86::BI__builtin_ia32_scattersiv8sf: 3837 case X86::BI__builtin_ia32_scattersiv8si: 3838 case X86::BI__builtin_ia32_scattersiv8df: 3839 case X86::BI__builtin_ia32_scattersiv16sf: 3840 case X86::BI__builtin_ia32_scatterdiv8df: 3841 case X86::BI__builtin_ia32_scatterdiv16sf: 3842 case X86::BI__builtin_ia32_scattersiv8di: 3843 case X86::BI__builtin_ia32_scattersiv16si: 3844 case X86::BI__builtin_ia32_scatterdiv8di: 3845 case X86::BI__builtin_ia32_scatterdiv16si: 3846 ArgNum = 4; 3847 break; 3848 } 3849 3850 llvm::APSInt Result; 3851 3852 // We can't check the value of a dependent argument. 3853 Expr *Arg = TheCall->getArg(ArgNum); 3854 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3855 return false; 3856 3857 // Check constant-ness first. 3858 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3859 return true; 3860 3861 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3862 return false; 3863 3864 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3865 << Arg->getSourceRange(); 3866 } 3867 3868 enum { TileRegLow = 0, TileRegHigh = 7 }; 3869 3870 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 3871 ArrayRef<int> ArgNums) { 3872 for (int ArgNum : ArgNums) { 3873 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 3874 return true; 3875 } 3876 return false; 3877 } 3878 3879 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 3880 ArrayRef<int> ArgNums) { 3881 // Because the max number of tile register is TileRegHigh + 1, so here we use 3882 // each bit to represent the usage of them in bitset. 3883 std::bitset<TileRegHigh + 1> ArgValues; 3884 for (int ArgNum : ArgNums) { 3885 Expr *Arg = TheCall->getArg(ArgNum); 3886 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3887 continue; 3888 3889 llvm::APSInt Result; 3890 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3891 return true; 3892 int ArgExtValue = Result.getExtValue(); 3893 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 3894 "Incorrect tile register num."); 3895 if (ArgValues.test(ArgExtValue)) 3896 return Diag(TheCall->getBeginLoc(), 3897 diag::err_x86_builtin_tile_arg_duplicate) 3898 << TheCall->getArg(ArgNum)->getSourceRange(); 3899 ArgValues.set(ArgExtValue); 3900 } 3901 return false; 3902 } 3903 3904 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 3905 ArrayRef<int> ArgNums) { 3906 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 3907 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 3908 } 3909 3910 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 3911 switch (BuiltinID) { 3912 default: 3913 return false; 3914 case X86::BI__builtin_ia32_tileloadd64: 3915 case X86::BI__builtin_ia32_tileloaddt164: 3916 case X86::BI__builtin_ia32_tilestored64: 3917 case X86::BI__builtin_ia32_tilezero: 3918 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 3919 case X86::BI__builtin_ia32_tdpbssd: 3920 case X86::BI__builtin_ia32_tdpbsud: 3921 case X86::BI__builtin_ia32_tdpbusd: 3922 case X86::BI__builtin_ia32_tdpbuud: 3923 case X86::BI__builtin_ia32_tdpbf16ps: 3924 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 3925 } 3926 } 3927 static bool isX86_32Builtin(unsigned BuiltinID) { 3928 // These builtins only work on x86-32 targets. 3929 switch (BuiltinID) { 3930 case X86::BI__builtin_ia32_readeflags_u32: 3931 case X86::BI__builtin_ia32_writeeflags_u32: 3932 return true; 3933 } 3934 3935 return false; 3936 } 3937 3938 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3939 CallExpr *TheCall) { 3940 if (BuiltinID == X86::BI__builtin_cpu_supports) 3941 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3942 3943 if (BuiltinID == X86::BI__builtin_cpu_is) 3944 return SemaBuiltinCpuIs(*this, TI, TheCall); 3945 3946 // Check for 32-bit only builtins on a 64-bit target. 3947 const llvm::Triple &TT = TI.getTriple(); 3948 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3949 return Diag(TheCall->getCallee()->getBeginLoc(), 3950 diag::err_32_bit_builtin_64_bit_tgt); 3951 3952 // If the intrinsic has rounding or SAE make sure its valid. 3953 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3954 return true; 3955 3956 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3957 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3958 return true; 3959 3960 // If the intrinsic has a tile arguments, make sure they are valid. 3961 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 3962 return true; 3963 3964 // For intrinsics which take an immediate value as part of the instruction, 3965 // range check them here. 3966 int i = 0, l = 0, u = 0; 3967 switch (BuiltinID) { 3968 default: 3969 return false; 3970 case X86::BI__builtin_ia32_vec_ext_v2si: 3971 case X86::BI__builtin_ia32_vec_ext_v2di: 3972 case X86::BI__builtin_ia32_vextractf128_pd256: 3973 case X86::BI__builtin_ia32_vextractf128_ps256: 3974 case X86::BI__builtin_ia32_vextractf128_si256: 3975 case X86::BI__builtin_ia32_extract128i256: 3976 case X86::BI__builtin_ia32_extractf64x4_mask: 3977 case X86::BI__builtin_ia32_extracti64x4_mask: 3978 case X86::BI__builtin_ia32_extractf32x8_mask: 3979 case X86::BI__builtin_ia32_extracti32x8_mask: 3980 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3981 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3982 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3983 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3984 i = 1; l = 0; u = 1; 3985 break; 3986 case X86::BI__builtin_ia32_vec_set_v2di: 3987 case X86::BI__builtin_ia32_vinsertf128_pd256: 3988 case X86::BI__builtin_ia32_vinsertf128_ps256: 3989 case X86::BI__builtin_ia32_vinsertf128_si256: 3990 case X86::BI__builtin_ia32_insert128i256: 3991 case X86::BI__builtin_ia32_insertf32x8: 3992 case X86::BI__builtin_ia32_inserti32x8: 3993 case X86::BI__builtin_ia32_insertf64x4: 3994 case X86::BI__builtin_ia32_inserti64x4: 3995 case X86::BI__builtin_ia32_insertf64x2_256: 3996 case X86::BI__builtin_ia32_inserti64x2_256: 3997 case X86::BI__builtin_ia32_insertf32x4_256: 3998 case X86::BI__builtin_ia32_inserti32x4_256: 3999 i = 2; l = 0; u = 1; 4000 break; 4001 case X86::BI__builtin_ia32_vpermilpd: 4002 case X86::BI__builtin_ia32_vec_ext_v4hi: 4003 case X86::BI__builtin_ia32_vec_ext_v4si: 4004 case X86::BI__builtin_ia32_vec_ext_v4sf: 4005 case X86::BI__builtin_ia32_vec_ext_v4di: 4006 case X86::BI__builtin_ia32_extractf32x4_mask: 4007 case X86::BI__builtin_ia32_extracti32x4_mask: 4008 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4009 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4010 i = 1; l = 0; u = 3; 4011 break; 4012 case X86::BI_mm_prefetch: 4013 case X86::BI__builtin_ia32_vec_ext_v8hi: 4014 case X86::BI__builtin_ia32_vec_ext_v8si: 4015 i = 1; l = 0; u = 7; 4016 break; 4017 case X86::BI__builtin_ia32_sha1rnds4: 4018 case X86::BI__builtin_ia32_blendpd: 4019 case X86::BI__builtin_ia32_shufpd: 4020 case X86::BI__builtin_ia32_vec_set_v4hi: 4021 case X86::BI__builtin_ia32_vec_set_v4si: 4022 case X86::BI__builtin_ia32_vec_set_v4di: 4023 case X86::BI__builtin_ia32_shuf_f32x4_256: 4024 case X86::BI__builtin_ia32_shuf_f64x2_256: 4025 case X86::BI__builtin_ia32_shuf_i32x4_256: 4026 case X86::BI__builtin_ia32_shuf_i64x2_256: 4027 case X86::BI__builtin_ia32_insertf64x2_512: 4028 case X86::BI__builtin_ia32_inserti64x2_512: 4029 case X86::BI__builtin_ia32_insertf32x4: 4030 case X86::BI__builtin_ia32_inserti32x4: 4031 i = 2; l = 0; u = 3; 4032 break; 4033 case X86::BI__builtin_ia32_vpermil2pd: 4034 case X86::BI__builtin_ia32_vpermil2pd256: 4035 case X86::BI__builtin_ia32_vpermil2ps: 4036 case X86::BI__builtin_ia32_vpermil2ps256: 4037 i = 3; l = 0; u = 3; 4038 break; 4039 case X86::BI__builtin_ia32_cmpb128_mask: 4040 case X86::BI__builtin_ia32_cmpw128_mask: 4041 case X86::BI__builtin_ia32_cmpd128_mask: 4042 case X86::BI__builtin_ia32_cmpq128_mask: 4043 case X86::BI__builtin_ia32_cmpb256_mask: 4044 case X86::BI__builtin_ia32_cmpw256_mask: 4045 case X86::BI__builtin_ia32_cmpd256_mask: 4046 case X86::BI__builtin_ia32_cmpq256_mask: 4047 case X86::BI__builtin_ia32_cmpb512_mask: 4048 case X86::BI__builtin_ia32_cmpw512_mask: 4049 case X86::BI__builtin_ia32_cmpd512_mask: 4050 case X86::BI__builtin_ia32_cmpq512_mask: 4051 case X86::BI__builtin_ia32_ucmpb128_mask: 4052 case X86::BI__builtin_ia32_ucmpw128_mask: 4053 case X86::BI__builtin_ia32_ucmpd128_mask: 4054 case X86::BI__builtin_ia32_ucmpq128_mask: 4055 case X86::BI__builtin_ia32_ucmpb256_mask: 4056 case X86::BI__builtin_ia32_ucmpw256_mask: 4057 case X86::BI__builtin_ia32_ucmpd256_mask: 4058 case X86::BI__builtin_ia32_ucmpq256_mask: 4059 case X86::BI__builtin_ia32_ucmpb512_mask: 4060 case X86::BI__builtin_ia32_ucmpw512_mask: 4061 case X86::BI__builtin_ia32_ucmpd512_mask: 4062 case X86::BI__builtin_ia32_ucmpq512_mask: 4063 case X86::BI__builtin_ia32_vpcomub: 4064 case X86::BI__builtin_ia32_vpcomuw: 4065 case X86::BI__builtin_ia32_vpcomud: 4066 case X86::BI__builtin_ia32_vpcomuq: 4067 case X86::BI__builtin_ia32_vpcomb: 4068 case X86::BI__builtin_ia32_vpcomw: 4069 case X86::BI__builtin_ia32_vpcomd: 4070 case X86::BI__builtin_ia32_vpcomq: 4071 case X86::BI__builtin_ia32_vec_set_v8hi: 4072 case X86::BI__builtin_ia32_vec_set_v8si: 4073 i = 2; l = 0; u = 7; 4074 break; 4075 case X86::BI__builtin_ia32_vpermilpd256: 4076 case X86::BI__builtin_ia32_roundps: 4077 case X86::BI__builtin_ia32_roundpd: 4078 case X86::BI__builtin_ia32_roundps256: 4079 case X86::BI__builtin_ia32_roundpd256: 4080 case X86::BI__builtin_ia32_getmantpd128_mask: 4081 case X86::BI__builtin_ia32_getmantpd256_mask: 4082 case X86::BI__builtin_ia32_getmantps128_mask: 4083 case X86::BI__builtin_ia32_getmantps256_mask: 4084 case X86::BI__builtin_ia32_getmantpd512_mask: 4085 case X86::BI__builtin_ia32_getmantps512_mask: 4086 case X86::BI__builtin_ia32_vec_ext_v16qi: 4087 case X86::BI__builtin_ia32_vec_ext_v16hi: 4088 i = 1; l = 0; u = 15; 4089 break; 4090 case X86::BI__builtin_ia32_pblendd128: 4091 case X86::BI__builtin_ia32_blendps: 4092 case X86::BI__builtin_ia32_blendpd256: 4093 case X86::BI__builtin_ia32_shufpd256: 4094 case X86::BI__builtin_ia32_roundss: 4095 case X86::BI__builtin_ia32_roundsd: 4096 case X86::BI__builtin_ia32_rangepd128_mask: 4097 case X86::BI__builtin_ia32_rangepd256_mask: 4098 case X86::BI__builtin_ia32_rangepd512_mask: 4099 case X86::BI__builtin_ia32_rangeps128_mask: 4100 case X86::BI__builtin_ia32_rangeps256_mask: 4101 case X86::BI__builtin_ia32_rangeps512_mask: 4102 case X86::BI__builtin_ia32_getmantsd_round_mask: 4103 case X86::BI__builtin_ia32_getmantss_round_mask: 4104 case X86::BI__builtin_ia32_vec_set_v16qi: 4105 case X86::BI__builtin_ia32_vec_set_v16hi: 4106 i = 2; l = 0; u = 15; 4107 break; 4108 case X86::BI__builtin_ia32_vec_ext_v32qi: 4109 i = 1; l = 0; u = 31; 4110 break; 4111 case X86::BI__builtin_ia32_cmpps: 4112 case X86::BI__builtin_ia32_cmpss: 4113 case X86::BI__builtin_ia32_cmppd: 4114 case X86::BI__builtin_ia32_cmpsd: 4115 case X86::BI__builtin_ia32_cmpps256: 4116 case X86::BI__builtin_ia32_cmppd256: 4117 case X86::BI__builtin_ia32_cmpps128_mask: 4118 case X86::BI__builtin_ia32_cmppd128_mask: 4119 case X86::BI__builtin_ia32_cmpps256_mask: 4120 case X86::BI__builtin_ia32_cmppd256_mask: 4121 case X86::BI__builtin_ia32_cmpps512_mask: 4122 case X86::BI__builtin_ia32_cmppd512_mask: 4123 case X86::BI__builtin_ia32_cmpsd_mask: 4124 case X86::BI__builtin_ia32_cmpss_mask: 4125 case X86::BI__builtin_ia32_vec_set_v32qi: 4126 i = 2; l = 0; u = 31; 4127 break; 4128 case X86::BI__builtin_ia32_permdf256: 4129 case X86::BI__builtin_ia32_permdi256: 4130 case X86::BI__builtin_ia32_permdf512: 4131 case X86::BI__builtin_ia32_permdi512: 4132 case X86::BI__builtin_ia32_vpermilps: 4133 case X86::BI__builtin_ia32_vpermilps256: 4134 case X86::BI__builtin_ia32_vpermilpd512: 4135 case X86::BI__builtin_ia32_vpermilps512: 4136 case X86::BI__builtin_ia32_pshufd: 4137 case X86::BI__builtin_ia32_pshufd256: 4138 case X86::BI__builtin_ia32_pshufd512: 4139 case X86::BI__builtin_ia32_pshufhw: 4140 case X86::BI__builtin_ia32_pshufhw256: 4141 case X86::BI__builtin_ia32_pshufhw512: 4142 case X86::BI__builtin_ia32_pshuflw: 4143 case X86::BI__builtin_ia32_pshuflw256: 4144 case X86::BI__builtin_ia32_pshuflw512: 4145 case X86::BI__builtin_ia32_vcvtps2ph: 4146 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4147 case X86::BI__builtin_ia32_vcvtps2ph256: 4148 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4149 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4150 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4151 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4152 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4153 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4154 case X86::BI__builtin_ia32_rndscaleps_mask: 4155 case X86::BI__builtin_ia32_rndscalepd_mask: 4156 case X86::BI__builtin_ia32_reducepd128_mask: 4157 case X86::BI__builtin_ia32_reducepd256_mask: 4158 case X86::BI__builtin_ia32_reducepd512_mask: 4159 case X86::BI__builtin_ia32_reduceps128_mask: 4160 case X86::BI__builtin_ia32_reduceps256_mask: 4161 case X86::BI__builtin_ia32_reduceps512_mask: 4162 case X86::BI__builtin_ia32_prold512: 4163 case X86::BI__builtin_ia32_prolq512: 4164 case X86::BI__builtin_ia32_prold128: 4165 case X86::BI__builtin_ia32_prold256: 4166 case X86::BI__builtin_ia32_prolq128: 4167 case X86::BI__builtin_ia32_prolq256: 4168 case X86::BI__builtin_ia32_prord512: 4169 case X86::BI__builtin_ia32_prorq512: 4170 case X86::BI__builtin_ia32_prord128: 4171 case X86::BI__builtin_ia32_prord256: 4172 case X86::BI__builtin_ia32_prorq128: 4173 case X86::BI__builtin_ia32_prorq256: 4174 case X86::BI__builtin_ia32_fpclasspd128_mask: 4175 case X86::BI__builtin_ia32_fpclasspd256_mask: 4176 case X86::BI__builtin_ia32_fpclassps128_mask: 4177 case X86::BI__builtin_ia32_fpclassps256_mask: 4178 case X86::BI__builtin_ia32_fpclassps512_mask: 4179 case X86::BI__builtin_ia32_fpclasspd512_mask: 4180 case X86::BI__builtin_ia32_fpclasssd_mask: 4181 case X86::BI__builtin_ia32_fpclassss_mask: 4182 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4183 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4184 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4185 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4186 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4187 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4188 case X86::BI__builtin_ia32_kshiftliqi: 4189 case X86::BI__builtin_ia32_kshiftlihi: 4190 case X86::BI__builtin_ia32_kshiftlisi: 4191 case X86::BI__builtin_ia32_kshiftlidi: 4192 case X86::BI__builtin_ia32_kshiftriqi: 4193 case X86::BI__builtin_ia32_kshiftrihi: 4194 case X86::BI__builtin_ia32_kshiftrisi: 4195 case X86::BI__builtin_ia32_kshiftridi: 4196 i = 1; l = 0; u = 255; 4197 break; 4198 case X86::BI__builtin_ia32_vperm2f128_pd256: 4199 case X86::BI__builtin_ia32_vperm2f128_ps256: 4200 case X86::BI__builtin_ia32_vperm2f128_si256: 4201 case X86::BI__builtin_ia32_permti256: 4202 case X86::BI__builtin_ia32_pblendw128: 4203 case X86::BI__builtin_ia32_pblendw256: 4204 case X86::BI__builtin_ia32_blendps256: 4205 case X86::BI__builtin_ia32_pblendd256: 4206 case X86::BI__builtin_ia32_palignr128: 4207 case X86::BI__builtin_ia32_palignr256: 4208 case X86::BI__builtin_ia32_palignr512: 4209 case X86::BI__builtin_ia32_alignq512: 4210 case X86::BI__builtin_ia32_alignd512: 4211 case X86::BI__builtin_ia32_alignd128: 4212 case X86::BI__builtin_ia32_alignd256: 4213 case X86::BI__builtin_ia32_alignq128: 4214 case X86::BI__builtin_ia32_alignq256: 4215 case X86::BI__builtin_ia32_vcomisd: 4216 case X86::BI__builtin_ia32_vcomiss: 4217 case X86::BI__builtin_ia32_shuf_f32x4: 4218 case X86::BI__builtin_ia32_shuf_f64x2: 4219 case X86::BI__builtin_ia32_shuf_i32x4: 4220 case X86::BI__builtin_ia32_shuf_i64x2: 4221 case X86::BI__builtin_ia32_shufpd512: 4222 case X86::BI__builtin_ia32_shufps: 4223 case X86::BI__builtin_ia32_shufps256: 4224 case X86::BI__builtin_ia32_shufps512: 4225 case X86::BI__builtin_ia32_dbpsadbw128: 4226 case X86::BI__builtin_ia32_dbpsadbw256: 4227 case X86::BI__builtin_ia32_dbpsadbw512: 4228 case X86::BI__builtin_ia32_vpshldd128: 4229 case X86::BI__builtin_ia32_vpshldd256: 4230 case X86::BI__builtin_ia32_vpshldd512: 4231 case X86::BI__builtin_ia32_vpshldq128: 4232 case X86::BI__builtin_ia32_vpshldq256: 4233 case X86::BI__builtin_ia32_vpshldq512: 4234 case X86::BI__builtin_ia32_vpshldw128: 4235 case X86::BI__builtin_ia32_vpshldw256: 4236 case X86::BI__builtin_ia32_vpshldw512: 4237 case X86::BI__builtin_ia32_vpshrdd128: 4238 case X86::BI__builtin_ia32_vpshrdd256: 4239 case X86::BI__builtin_ia32_vpshrdd512: 4240 case X86::BI__builtin_ia32_vpshrdq128: 4241 case X86::BI__builtin_ia32_vpshrdq256: 4242 case X86::BI__builtin_ia32_vpshrdq512: 4243 case X86::BI__builtin_ia32_vpshrdw128: 4244 case X86::BI__builtin_ia32_vpshrdw256: 4245 case X86::BI__builtin_ia32_vpshrdw512: 4246 i = 2; l = 0; u = 255; 4247 break; 4248 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4249 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4250 case X86::BI__builtin_ia32_fixupimmps512_mask: 4251 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4252 case X86::BI__builtin_ia32_fixupimmsd_mask: 4253 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4254 case X86::BI__builtin_ia32_fixupimmss_mask: 4255 case X86::BI__builtin_ia32_fixupimmss_maskz: 4256 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4257 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4258 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4259 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4260 case X86::BI__builtin_ia32_fixupimmps128_mask: 4261 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4262 case X86::BI__builtin_ia32_fixupimmps256_mask: 4263 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4264 case X86::BI__builtin_ia32_pternlogd512_mask: 4265 case X86::BI__builtin_ia32_pternlogd512_maskz: 4266 case X86::BI__builtin_ia32_pternlogq512_mask: 4267 case X86::BI__builtin_ia32_pternlogq512_maskz: 4268 case X86::BI__builtin_ia32_pternlogd128_mask: 4269 case X86::BI__builtin_ia32_pternlogd128_maskz: 4270 case X86::BI__builtin_ia32_pternlogd256_mask: 4271 case X86::BI__builtin_ia32_pternlogd256_maskz: 4272 case X86::BI__builtin_ia32_pternlogq128_mask: 4273 case X86::BI__builtin_ia32_pternlogq128_maskz: 4274 case X86::BI__builtin_ia32_pternlogq256_mask: 4275 case X86::BI__builtin_ia32_pternlogq256_maskz: 4276 i = 3; l = 0; u = 255; 4277 break; 4278 case X86::BI__builtin_ia32_gatherpfdpd: 4279 case X86::BI__builtin_ia32_gatherpfdps: 4280 case X86::BI__builtin_ia32_gatherpfqpd: 4281 case X86::BI__builtin_ia32_gatherpfqps: 4282 case X86::BI__builtin_ia32_scatterpfdpd: 4283 case X86::BI__builtin_ia32_scatterpfdps: 4284 case X86::BI__builtin_ia32_scatterpfqpd: 4285 case X86::BI__builtin_ia32_scatterpfqps: 4286 i = 4; l = 2; u = 3; 4287 break; 4288 case X86::BI__builtin_ia32_reducesd_mask: 4289 case X86::BI__builtin_ia32_reducess_mask: 4290 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4291 case X86::BI__builtin_ia32_rndscaless_round_mask: 4292 i = 4; l = 0; u = 255; 4293 break; 4294 } 4295 4296 // Note that we don't force a hard error on the range check here, allowing 4297 // template-generated or macro-generated dead code to potentially have out-of- 4298 // range values. These need to code generate, but don't need to necessarily 4299 // make any sense. We use a warning that defaults to an error. 4300 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4301 } 4302 4303 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4304 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4305 /// Returns true when the format fits the function and the FormatStringInfo has 4306 /// been populated. 4307 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4308 FormatStringInfo *FSI) { 4309 FSI->HasVAListArg = Format->getFirstArg() == 0; 4310 FSI->FormatIdx = Format->getFormatIdx() - 1; 4311 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4312 4313 // The way the format attribute works in GCC, the implicit this argument 4314 // of member functions is counted. However, it doesn't appear in our own 4315 // lists, so decrement format_idx in that case. 4316 if (IsCXXMember) { 4317 if(FSI->FormatIdx == 0) 4318 return false; 4319 --FSI->FormatIdx; 4320 if (FSI->FirstDataArg != 0) 4321 --FSI->FirstDataArg; 4322 } 4323 return true; 4324 } 4325 4326 /// Checks if a the given expression evaluates to null. 4327 /// 4328 /// Returns true if the value evaluates to null. 4329 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4330 // If the expression has non-null type, it doesn't evaluate to null. 4331 if (auto nullability 4332 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4333 if (*nullability == NullabilityKind::NonNull) 4334 return false; 4335 } 4336 4337 // As a special case, transparent unions initialized with zero are 4338 // considered null for the purposes of the nonnull attribute. 4339 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4340 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4341 if (const CompoundLiteralExpr *CLE = 4342 dyn_cast<CompoundLiteralExpr>(Expr)) 4343 if (const InitListExpr *ILE = 4344 dyn_cast<InitListExpr>(CLE->getInitializer())) 4345 Expr = ILE->getInit(0); 4346 } 4347 4348 bool Result; 4349 return (!Expr->isValueDependent() && 4350 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4351 !Result); 4352 } 4353 4354 static void CheckNonNullArgument(Sema &S, 4355 const Expr *ArgExpr, 4356 SourceLocation CallSiteLoc) { 4357 if (CheckNonNullExpr(S, ArgExpr)) 4358 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4359 S.PDiag(diag::warn_null_arg) 4360 << ArgExpr->getSourceRange()); 4361 } 4362 4363 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4364 FormatStringInfo FSI; 4365 if ((GetFormatStringType(Format) == FST_NSString) && 4366 getFormatStringInfo(Format, false, &FSI)) { 4367 Idx = FSI.FormatIdx; 4368 return true; 4369 } 4370 return false; 4371 } 4372 4373 /// Diagnose use of %s directive in an NSString which is being passed 4374 /// as formatting string to formatting method. 4375 static void 4376 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4377 const NamedDecl *FDecl, 4378 Expr **Args, 4379 unsigned NumArgs) { 4380 unsigned Idx = 0; 4381 bool Format = false; 4382 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4383 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4384 Idx = 2; 4385 Format = true; 4386 } 4387 else 4388 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4389 if (S.GetFormatNSStringIdx(I, Idx)) { 4390 Format = true; 4391 break; 4392 } 4393 } 4394 if (!Format || NumArgs <= Idx) 4395 return; 4396 const Expr *FormatExpr = Args[Idx]; 4397 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4398 FormatExpr = CSCE->getSubExpr(); 4399 const StringLiteral *FormatString; 4400 if (const ObjCStringLiteral *OSL = 4401 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4402 FormatString = OSL->getString(); 4403 else 4404 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4405 if (!FormatString) 4406 return; 4407 if (S.FormatStringHasSArg(FormatString)) { 4408 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4409 << "%s" << 1 << 1; 4410 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4411 << FDecl->getDeclName(); 4412 } 4413 } 4414 4415 /// Determine whether the given type has a non-null nullability annotation. 4416 static bool isNonNullType(ASTContext &ctx, QualType type) { 4417 if (auto nullability = type->getNullability(ctx)) 4418 return *nullability == NullabilityKind::NonNull; 4419 4420 return false; 4421 } 4422 4423 static void CheckNonNullArguments(Sema &S, 4424 const NamedDecl *FDecl, 4425 const FunctionProtoType *Proto, 4426 ArrayRef<const Expr *> Args, 4427 SourceLocation CallSiteLoc) { 4428 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4429 4430 // Already checked by by constant evaluator. 4431 if (S.isConstantEvaluated()) 4432 return; 4433 // Check the attributes attached to the method/function itself. 4434 llvm::SmallBitVector NonNullArgs; 4435 if (FDecl) { 4436 // Handle the nonnull attribute on the function/method declaration itself. 4437 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4438 if (!NonNull->args_size()) { 4439 // Easy case: all pointer arguments are nonnull. 4440 for (const auto *Arg : Args) 4441 if (S.isValidPointerAttrType(Arg->getType())) 4442 CheckNonNullArgument(S, Arg, CallSiteLoc); 4443 return; 4444 } 4445 4446 for (const ParamIdx &Idx : NonNull->args()) { 4447 unsigned IdxAST = Idx.getASTIndex(); 4448 if (IdxAST >= Args.size()) 4449 continue; 4450 if (NonNullArgs.empty()) 4451 NonNullArgs.resize(Args.size()); 4452 NonNullArgs.set(IdxAST); 4453 } 4454 } 4455 } 4456 4457 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4458 // Handle the nonnull attribute on the parameters of the 4459 // function/method. 4460 ArrayRef<ParmVarDecl*> parms; 4461 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4462 parms = FD->parameters(); 4463 else 4464 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4465 4466 unsigned ParamIndex = 0; 4467 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4468 I != E; ++I, ++ParamIndex) { 4469 const ParmVarDecl *PVD = *I; 4470 if (PVD->hasAttr<NonNullAttr>() || 4471 isNonNullType(S.Context, PVD->getType())) { 4472 if (NonNullArgs.empty()) 4473 NonNullArgs.resize(Args.size()); 4474 4475 NonNullArgs.set(ParamIndex); 4476 } 4477 } 4478 } else { 4479 // If we have a non-function, non-method declaration but no 4480 // function prototype, try to dig out the function prototype. 4481 if (!Proto) { 4482 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4483 QualType type = VD->getType().getNonReferenceType(); 4484 if (auto pointerType = type->getAs<PointerType>()) 4485 type = pointerType->getPointeeType(); 4486 else if (auto blockType = type->getAs<BlockPointerType>()) 4487 type = blockType->getPointeeType(); 4488 // FIXME: data member pointers? 4489 4490 // Dig out the function prototype, if there is one. 4491 Proto = type->getAs<FunctionProtoType>(); 4492 } 4493 } 4494 4495 // Fill in non-null argument information from the nullability 4496 // information on the parameter types (if we have them). 4497 if (Proto) { 4498 unsigned Index = 0; 4499 for (auto paramType : Proto->getParamTypes()) { 4500 if (isNonNullType(S.Context, paramType)) { 4501 if (NonNullArgs.empty()) 4502 NonNullArgs.resize(Args.size()); 4503 4504 NonNullArgs.set(Index); 4505 } 4506 4507 ++Index; 4508 } 4509 } 4510 } 4511 4512 // Check for non-null arguments. 4513 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4514 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4515 if (NonNullArgs[ArgIndex]) 4516 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4517 } 4518 } 4519 4520 /// Warn if a pointer or reference argument passed to a function points to an 4521 /// object that is less aligned than the parameter. This can happen when 4522 /// creating a typedef with a lower alignment than the original type and then 4523 /// calling functions defined in terms of the original type. 4524 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4525 StringRef ParamName, QualType ArgTy, 4526 QualType ParamTy) { 4527 4528 // If a function accepts a pointer or reference type 4529 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4530 return; 4531 4532 // If the parameter is a pointer type, get the pointee type for the 4533 // argument too. If the parameter is a reference type, don't try to get 4534 // the pointee type for the argument. 4535 if (ParamTy->isPointerType()) 4536 ArgTy = ArgTy->getPointeeType(); 4537 4538 // Remove reference or pointer 4539 ParamTy = ParamTy->getPointeeType(); 4540 4541 // Find expected alignment, and the actual alignment of the passed object. 4542 // getTypeAlignInChars requires complete types 4543 if (ParamTy->isIncompleteType() || ArgTy->isIncompleteType()) 4544 return; 4545 4546 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 4547 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 4548 4549 // If the argument is less aligned than the parameter, there is a 4550 // potential alignment issue. 4551 if (ArgAlign < ParamAlign) 4552 Diag(Loc, diag::warn_param_mismatched_alignment) 4553 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 4554 << ParamName << FDecl; 4555 } 4556 4557 /// Handles the checks for format strings, non-POD arguments to vararg 4558 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4559 /// attributes. 4560 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4561 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4562 bool IsMemberFunction, SourceLocation Loc, 4563 SourceRange Range, VariadicCallType CallType) { 4564 // FIXME: We should check as much as we can in the template definition. 4565 if (CurContext->isDependentContext()) 4566 return; 4567 4568 // Printf and scanf checking. 4569 llvm::SmallBitVector CheckedVarArgs; 4570 if (FDecl) { 4571 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4572 // Only create vector if there are format attributes. 4573 CheckedVarArgs.resize(Args.size()); 4574 4575 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4576 CheckedVarArgs); 4577 } 4578 } 4579 4580 // Refuse POD arguments that weren't caught by the format string 4581 // checks above. 4582 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4583 if (CallType != VariadicDoesNotApply && 4584 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4585 unsigned NumParams = Proto ? Proto->getNumParams() 4586 : FDecl && isa<FunctionDecl>(FDecl) 4587 ? cast<FunctionDecl>(FDecl)->getNumParams() 4588 : FDecl && isa<ObjCMethodDecl>(FDecl) 4589 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4590 : 0; 4591 4592 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4593 // Args[ArgIdx] can be null in malformed code. 4594 if (const Expr *Arg = Args[ArgIdx]) { 4595 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4596 checkVariadicArgument(Arg, CallType); 4597 } 4598 } 4599 } 4600 4601 if (FDecl || Proto) { 4602 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4603 4604 // Type safety checking. 4605 if (FDecl) { 4606 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4607 CheckArgumentWithTypeTag(I, Args, Loc); 4608 } 4609 } 4610 4611 // Check that passed arguments match the alignment of original arguments. 4612 // Try to get the missing prototype from the declaration. 4613 if (!Proto && FDecl) { 4614 const auto *FT = FDecl->getFunctionType(); 4615 if (isa_and_nonnull<FunctionProtoType>(FT)) 4616 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 4617 } 4618 if (Proto) { 4619 // For variadic functions, we may have more args than parameters. 4620 // For some K&R functions, we may have less args than parameters. 4621 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 4622 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 4623 // Args[ArgIdx] can be null in malformed code. 4624 if (const Expr *Arg = Args[ArgIdx]) { 4625 QualType ParamTy = Proto->getParamType(ArgIdx); 4626 QualType ArgTy = Arg->getType(); 4627 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 4628 ArgTy, ParamTy); 4629 } 4630 } 4631 } 4632 4633 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4634 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4635 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4636 if (!Arg->isValueDependent()) { 4637 Expr::EvalResult Align; 4638 if (Arg->EvaluateAsInt(Align, Context)) { 4639 const llvm::APSInt &I = Align.Val.getInt(); 4640 if (!I.isPowerOf2()) 4641 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4642 << Arg->getSourceRange(); 4643 4644 if (I > Sema::MaximumAlignment) 4645 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4646 << Arg->getSourceRange() << Sema::MaximumAlignment; 4647 } 4648 } 4649 } 4650 4651 if (FD) 4652 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4653 } 4654 4655 /// CheckConstructorCall - Check a constructor call for correctness and safety 4656 /// properties not enforced by the C type system. 4657 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 4658 ArrayRef<const Expr *> Args, 4659 const FunctionProtoType *Proto, 4660 SourceLocation Loc) { 4661 VariadicCallType CallType = 4662 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4663 4664 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 4665 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 4666 Context.getPointerType(Ctor->getThisObjectType())); 4667 4668 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4669 Loc, SourceRange(), CallType); 4670 } 4671 4672 /// CheckFunctionCall - Check a direct function call for various correctness 4673 /// and safety properties not strictly enforced by the C type system. 4674 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4675 const FunctionProtoType *Proto) { 4676 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4677 isa<CXXMethodDecl>(FDecl); 4678 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4679 IsMemberOperatorCall; 4680 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4681 TheCall->getCallee()); 4682 Expr** Args = TheCall->getArgs(); 4683 unsigned NumArgs = TheCall->getNumArgs(); 4684 4685 Expr *ImplicitThis = nullptr; 4686 if (IsMemberOperatorCall) { 4687 // If this is a call to a member operator, hide the first argument 4688 // from checkCall. 4689 // FIXME: Our choice of AST representation here is less than ideal. 4690 ImplicitThis = Args[0]; 4691 ++Args; 4692 --NumArgs; 4693 } else if (IsMemberFunction) 4694 ImplicitThis = 4695 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4696 4697 if (ImplicitThis) { 4698 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 4699 // used. 4700 QualType ThisType = ImplicitThis->getType(); 4701 if (!ThisType->isPointerType()) { 4702 assert(!ThisType->isReferenceType()); 4703 ThisType = Context.getPointerType(ThisType); 4704 } 4705 4706 QualType ThisTypeFromDecl = 4707 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 4708 4709 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 4710 ThisTypeFromDecl); 4711 } 4712 4713 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4714 IsMemberFunction, TheCall->getRParenLoc(), 4715 TheCall->getCallee()->getSourceRange(), CallType); 4716 4717 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4718 // None of the checks below are needed for functions that don't have 4719 // simple names (e.g., C++ conversion functions). 4720 if (!FnInfo) 4721 return false; 4722 4723 CheckTCBEnforcement(TheCall, FDecl); 4724 4725 CheckAbsoluteValueFunction(TheCall, FDecl); 4726 CheckMaxUnsignedZero(TheCall, FDecl); 4727 4728 if (getLangOpts().ObjC) 4729 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4730 4731 unsigned CMId = FDecl->getMemoryFunctionKind(); 4732 4733 // Handle memory setting and copying functions. 4734 switch (CMId) { 4735 case 0: 4736 return false; 4737 case Builtin::BIstrlcpy: // fallthrough 4738 case Builtin::BIstrlcat: 4739 CheckStrlcpycatArguments(TheCall, FnInfo); 4740 break; 4741 case Builtin::BIstrncat: 4742 CheckStrncatArguments(TheCall, FnInfo); 4743 break; 4744 case Builtin::BIfree: 4745 CheckFreeArguments(TheCall); 4746 break; 4747 default: 4748 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4749 } 4750 4751 return false; 4752 } 4753 4754 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4755 ArrayRef<const Expr *> Args) { 4756 VariadicCallType CallType = 4757 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4758 4759 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4760 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4761 CallType); 4762 4763 return false; 4764 } 4765 4766 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4767 const FunctionProtoType *Proto) { 4768 QualType Ty; 4769 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4770 Ty = V->getType().getNonReferenceType(); 4771 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4772 Ty = F->getType().getNonReferenceType(); 4773 else 4774 return false; 4775 4776 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4777 !Ty->isFunctionProtoType()) 4778 return false; 4779 4780 VariadicCallType CallType; 4781 if (!Proto || !Proto->isVariadic()) { 4782 CallType = VariadicDoesNotApply; 4783 } else if (Ty->isBlockPointerType()) { 4784 CallType = VariadicBlock; 4785 } else { // Ty->isFunctionPointerType() 4786 CallType = VariadicFunction; 4787 } 4788 4789 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4790 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4791 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4792 TheCall->getCallee()->getSourceRange(), CallType); 4793 4794 return false; 4795 } 4796 4797 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4798 /// such as function pointers returned from functions. 4799 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4800 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4801 TheCall->getCallee()); 4802 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4803 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4804 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4805 TheCall->getCallee()->getSourceRange(), CallType); 4806 4807 return false; 4808 } 4809 4810 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4811 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4812 return false; 4813 4814 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4815 switch (Op) { 4816 case AtomicExpr::AO__c11_atomic_init: 4817 case AtomicExpr::AO__opencl_atomic_init: 4818 llvm_unreachable("There is no ordering argument for an init"); 4819 4820 case AtomicExpr::AO__c11_atomic_load: 4821 case AtomicExpr::AO__opencl_atomic_load: 4822 case AtomicExpr::AO__atomic_load_n: 4823 case AtomicExpr::AO__atomic_load: 4824 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4825 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4826 4827 case AtomicExpr::AO__c11_atomic_store: 4828 case AtomicExpr::AO__opencl_atomic_store: 4829 case AtomicExpr::AO__atomic_store: 4830 case AtomicExpr::AO__atomic_store_n: 4831 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4832 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4833 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4834 4835 default: 4836 return true; 4837 } 4838 } 4839 4840 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4841 AtomicExpr::AtomicOp Op) { 4842 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4843 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4844 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4845 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4846 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4847 Op); 4848 } 4849 4850 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4851 SourceLocation RParenLoc, MultiExprArg Args, 4852 AtomicExpr::AtomicOp Op, 4853 AtomicArgumentOrder ArgOrder) { 4854 // All the non-OpenCL operations take one of the following forms. 4855 // The OpenCL operations take the __c11 forms with one extra argument for 4856 // synchronization scope. 4857 enum { 4858 // C __c11_atomic_init(A *, C) 4859 Init, 4860 4861 // C __c11_atomic_load(A *, int) 4862 Load, 4863 4864 // void __atomic_load(A *, CP, int) 4865 LoadCopy, 4866 4867 // void __atomic_store(A *, CP, int) 4868 Copy, 4869 4870 // C __c11_atomic_add(A *, M, int) 4871 Arithmetic, 4872 4873 // C __atomic_exchange_n(A *, CP, int) 4874 Xchg, 4875 4876 // void __atomic_exchange(A *, C *, CP, int) 4877 GNUXchg, 4878 4879 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4880 C11CmpXchg, 4881 4882 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4883 GNUCmpXchg 4884 } Form = Init; 4885 4886 const unsigned NumForm = GNUCmpXchg + 1; 4887 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4888 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4889 // where: 4890 // C is an appropriate type, 4891 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4892 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4893 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4894 // the int parameters are for orderings. 4895 4896 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4897 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4898 "need to update code for modified forms"); 4899 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4900 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4901 AtomicExpr::AO__atomic_load, 4902 "need to update code for modified C11 atomics"); 4903 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4904 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4905 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4906 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4907 IsOpenCL; 4908 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4909 Op == AtomicExpr::AO__atomic_store_n || 4910 Op == AtomicExpr::AO__atomic_exchange_n || 4911 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4912 bool IsAddSub = false; 4913 4914 switch (Op) { 4915 case AtomicExpr::AO__c11_atomic_init: 4916 case AtomicExpr::AO__opencl_atomic_init: 4917 Form = Init; 4918 break; 4919 4920 case AtomicExpr::AO__c11_atomic_load: 4921 case AtomicExpr::AO__opencl_atomic_load: 4922 case AtomicExpr::AO__atomic_load_n: 4923 Form = Load; 4924 break; 4925 4926 case AtomicExpr::AO__atomic_load: 4927 Form = LoadCopy; 4928 break; 4929 4930 case AtomicExpr::AO__c11_atomic_store: 4931 case AtomicExpr::AO__opencl_atomic_store: 4932 case AtomicExpr::AO__atomic_store: 4933 case AtomicExpr::AO__atomic_store_n: 4934 Form = Copy; 4935 break; 4936 4937 case AtomicExpr::AO__c11_atomic_fetch_add: 4938 case AtomicExpr::AO__c11_atomic_fetch_sub: 4939 case AtomicExpr::AO__opencl_atomic_fetch_add: 4940 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4941 case AtomicExpr::AO__atomic_fetch_add: 4942 case AtomicExpr::AO__atomic_fetch_sub: 4943 case AtomicExpr::AO__atomic_add_fetch: 4944 case AtomicExpr::AO__atomic_sub_fetch: 4945 IsAddSub = true; 4946 Form = Arithmetic; 4947 break; 4948 case AtomicExpr::AO__c11_atomic_fetch_and: 4949 case AtomicExpr::AO__c11_atomic_fetch_or: 4950 case AtomicExpr::AO__c11_atomic_fetch_xor: 4951 case AtomicExpr::AO__opencl_atomic_fetch_and: 4952 case AtomicExpr::AO__opencl_atomic_fetch_or: 4953 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4954 case AtomicExpr::AO__atomic_fetch_and: 4955 case AtomicExpr::AO__atomic_fetch_or: 4956 case AtomicExpr::AO__atomic_fetch_xor: 4957 case AtomicExpr::AO__atomic_fetch_nand: 4958 case AtomicExpr::AO__atomic_and_fetch: 4959 case AtomicExpr::AO__atomic_or_fetch: 4960 case AtomicExpr::AO__atomic_xor_fetch: 4961 case AtomicExpr::AO__atomic_nand_fetch: 4962 Form = Arithmetic; 4963 break; 4964 case AtomicExpr::AO__c11_atomic_fetch_min: 4965 case AtomicExpr::AO__c11_atomic_fetch_max: 4966 case AtomicExpr::AO__opencl_atomic_fetch_min: 4967 case AtomicExpr::AO__opencl_atomic_fetch_max: 4968 case AtomicExpr::AO__atomic_min_fetch: 4969 case AtomicExpr::AO__atomic_max_fetch: 4970 case AtomicExpr::AO__atomic_fetch_min: 4971 case AtomicExpr::AO__atomic_fetch_max: 4972 Form = Arithmetic; 4973 break; 4974 4975 case AtomicExpr::AO__c11_atomic_exchange: 4976 case AtomicExpr::AO__opencl_atomic_exchange: 4977 case AtomicExpr::AO__atomic_exchange_n: 4978 Form = Xchg; 4979 break; 4980 4981 case AtomicExpr::AO__atomic_exchange: 4982 Form = GNUXchg; 4983 break; 4984 4985 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4986 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4987 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4988 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4989 Form = C11CmpXchg; 4990 break; 4991 4992 case AtomicExpr::AO__atomic_compare_exchange: 4993 case AtomicExpr::AO__atomic_compare_exchange_n: 4994 Form = GNUCmpXchg; 4995 break; 4996 } 4997 4998 unsigned AdjustedNumArgs = NumArgs[Form]; 4999 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 5000 ++AdjustedNumArgs; 5001 // Check we have the right number of arguments. 5002 if (Args.size() < AdjustedNumArgs) { 5003 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5004 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5005 << ExprRange; 5006 return ExprError(); 5007 } else if (Args.size() > AdjustedNumArgs) { 5008 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5009 diag::err_typecheck_call_too_many_args) 5010 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5011 << ExprRange; 5012 return ExprError(); 5013 } 5014 5015 // Inspect the first argument of the atomic operation. 5016 Expr *Ptr = Args[0]; 5017 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5018 if (ConvertedPtr.isInvalid()) 5019 return ExprError(); 5020 5021 Ptr = ConvertedPtr.get(); 5022 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5023 if (!pointerType) { 5024 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5025 << Ptr->getType() << Ptr->getSourceRange(); 5026 return ExprError(); 5027 } 5028 5029 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5030 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5031 QualType ValType = AtomTy; // 'C' 5032 if (IsC11) { 5033 if (!AtomTy->isAtomicType()) { 5034 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5035 << Ptr->getType() << Ptr->getSourceRange(); 5036 return ExprError(); 5037 } 5038 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5039 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5040 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5041 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5042 << Ptr->getSourceRange(); 5043 return ExprError(); 5044 } 5045 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5046 } else if (Form != Load && Form != LoadCopy) { 5047 if (ValType.isConstQualified()) { 5048 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5049 << Ptr->getType() << Ptr->getSourceRange(); 5050 return ExprError(); 5051 } 5052 } 5053 5054 // For an arithmetic operation, the implied arithmetic must be well-formed. 5055 if (Form == Arithmetic) { 5056 // gcc does not enforce these rules for GNU atomics, but we do so for 5057 // sanity. 5058 auto IsAllowedValueType = [&](QualType ValType) { 5059 if (ValType->isIntegerType()) 5060 return true; 5061 if (ValType->isPointerType()) 5062 return true; 5063 if (!ValType->isFloatingType()) 5064 return false; 5065 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5066 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5067 &Context.getTargetInfo().getLongDoubleFormat() == 5068 &llvm::APFloat::x87DoubleExtended()) 5069 return false; 5070 return true; 5071 }; 5072 if (IsAddSub && !IsAllowedValueType(ValType)) { 5073 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5074 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5075 return ExprError(); 5076 } 5077 if (!IsAddSub && !ValType->isIntegerType()) { 5078 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5079 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5080 return ExprError(); 5081 } 5082 if (IsC11 && ValType->isPointerType() && 5083 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5084 diag::err_incomplete_type)) { 5085 return ExprError(); 5086 } 5087 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5088 // For __atomic_*_n operations, the value type must be a scalar integral or 5089 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5090 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5091 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5092 return ExprError(); 5093 } 5094 5095 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5096 !AtomTy->isScalarType()) { 5097 // For GNU atomics, require a trivially-copyable type. This is not part of 5098 // the GNU atomics specification, but we enforce it for sanity. 5099 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5100 << Ptr->getType() << Ptr->getSourceRange(); 5101 return ExprError(); 5102 } 5103 5104 switch (ValType.getObjCLifetime()) { 5105 case Qualifiers::OCL_None: 5106 case Qualifiers::OCL_ExplicitNone: 5107 // okay 5108 break; 5109 5110 case Qualifiers::OCL_Weak: 5111 case Qualifiers::OCL_Strong: 5112 case Qualifiers::OCL_Autoreleasing: 5113 // FIXME: Can this happen? By this point, ValType should be known 5114 // to be trivially copyable. 5115 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5116 << ValType << Ptr->getSourceRange(); 5117 return ExprError(); 5118 } 5119 5120 // All atomic operations have an overload which takes a pointer to a volatile 5121 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5122 // into the result or the other operands. Similarly atomic_load takes a 5123 // pointer to a const 'A'. 5124 ValType.removeLocalVolatile(); 5125 ValType.removeLocalConst(); 5126 QualType ResultType = ValType; 5127 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5128 Form == Init) 5129 ResultType = Context.VoidTy; 5130 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5131 ResultType = Context.BoolTy; 5132 5133 // The type of a parameter passed 'by value'. In the GNU atomics, such 5134 // arguments are actually passed as pointers. 5135 QualType ByValType = ValType; // 'CP' 5136 bool IsPassedByAddress = false; 5137 if (!IsC11 && !IsN) { 5138 ByValType = Ptr->getType(); 5139 IsPassedByAddress = true; 5140 } 5141 5142 SmallVector<Expr *, 5> APIOrderedArgs; 5143 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5144 APIOrderedArgs.push_back(Args[0]); 5145 switch (Form) { 5146 case Init: 5147 case Load: 5148 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5149 break; 5150 case LoadCopy: 5151 case Copy: 5152 case Arithmetic: 5153 case Xchg: 5154 APIOrderedArgs.push_back(Args[2]); // Val1 5155 APIOrderedArgs.push_back(Args[1]); // Order 5156 break; 5157 case GNUXchg: 5158 APIOrderedArgs.push_back(Args[2]); // Val1 5159 APIOrderedArgs.push_back(Args[3]); // Val2 5160 APIOrderedArgs.push_back(Args[1]); // Order 5161 break; 5162 case C11CmpXchg: 5163 APIOrderedArgs.push_back(Args[2]); // Val1 5164 APIOrderedArgs.push_back(Args[4]); // Val2 5165 APIOrderedArgs.push_back(Args[1]); // Order 5166 APIOrderedArgs.push_back(Args[3]); // OrderFail 5167 break; 5168 case GNUCmpXchg: 5169 APIOrderedArgs.push_back(Args[2]); // Val1 5170 APIOrderedArgs.push_back(Args[4]); // Val2 5171 APIOrderedArgs.push_back(Args[5]); // Weak 5172 APIOrderedArgs.push_back(Args[1]); // Order 5173 APIOrderedArgs.push_back(Args[3]); // OrderFail 5174 break; 5175 } 5176 } else 5177 APIOrderedArgs.append(Args.begin(), Args.end()); 5178 5179 // The first argument's non-CV pointer type is used to deduce the type of 5180 // subsequent arguments, except for: 5181 // - weak flag (always converted to bool) 5182 // - memory order (always converted to int) 5183 // - scope (always converted to int) 5184 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5185 QualType Ty; 5186 if (i < NumVals[Form] + 1) { 5187 switch (i) { 5188 case 0: 5189 // The first argument is always a pointer. It has a fixed type. 5190 // It is always dereferenced, a nullptr is undefined. 5191 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5192 // Nothing else to do: we already know all we want about this pointer. 5193 continue; 5194 case 1: 5195 // The second argument is the non-atomic operand. For arithmetic, this 5196 // is always passed by value, and for a compare_exchange it is always 5197 // passed by address. For the rest, GNU uses by-address and C11 uses 5198 // by-value. 5199 assert(Form != Load); 5200 if (Form == Arithmetic && ValType->isPointerType()) 5201 Ty = Context.getPointerDiffType(); 5202 else if (Form == Init || Form == Arithmetic) 5203 Ty = ValType; 5204 else if (Form == Copy || Form == Xchg) { 5205 if (IsPassedByAddress) { 5206 // The value pointer is always dereferenced, a nullptr is undefined. 5207 CheckNonNullArgument(*this, APIOrderedArgs[i], 5208 ExprRange.getBegin()); 5209 } 5210 Ty = ByValType; 5211 } else { 5212 Expr *ValArg = APIOrderedArgs[i]; 5213 // The value pointer is always dereferenced, a nullptr is undefined. 5214 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5215 LangAS AS = LangAS::Default; 5216 // Keep address space of non-atomic pointer type. 5217 if (const PointerType *PtrTy = 5218 ValArg->getType()->getAs<PointerType>()) { 5219 AS = PtrTy->getPointeeType().getAddressSpace(); 5220 } 5221 Ty = Context.getPointerType( 5222 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5223 } 5224 break; 5225 case 2: 5226 // The third argument to compare_exchange / GNU exchange is the desired 5227 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5228 if (IsPassedByAddress) 5229 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5230 Ty = ByValType; 5231 break; 5232 case 3: 5233 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5234 Ty = Context.BoolTy; 5235 break; 5236 } 5237 } else { 5238 // The order(s) and scope are always converted to int. 5239 Ty = Context.IntTy; 5240 } 5241 5242 InitializedEntity Entity = 5243 InitializedEntity::InitializeParameter(Context, Ty, false); 5244 ExprResult Arg = APIOrderedArgs[i]; 5245 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5246 if (Arg.isInvalid()) 5247 return true; 5248 APIOrderedArgs[i] = Arg.get(); 5249 } 5250 5251 // Permute the arguments into a 'consistent' order. 5252 SmallVector<Expr*, 5> SubExprs; 5253 SubExprs.push_back(Ptr); 5254 switch (Form) { 5255 case Init: 5256 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5257 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5258 break; 5259 case Load: 5260 SubExprs.push_back(APIOrderedArgs[1]); // Order 5261 break; 5262 case LoadCopy: 5263 case Copy: 5264 case Arithmetic: 5265 case Xchg: 5266 SubExprs.push_back(APIOrderedArgs[2]); // Order 5267 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5268 break; 5269 case GNUXchg: 5270 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5271 SubExprs.push_back(APIOrderedArgs[3]); // Order 5272 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5273 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5274 break; 5275 case C11CmpXchg: 5276 SubExprs.push_back(APIOrderedArgs[3]); // Order 5277 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5278 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5279 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5280 break; 5281 case GNUCmpXchg: 5282 SubExprs.push_back(APIOrderedArgs[4]); // Order 5283 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5284 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5285 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5286 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5287 break; 5288 } 5289 5290 if (SubExprs.size() >= 2 && Form != Init) { 5291 if (Optional<llvm::APSInt> Result = 5292 SubExprs[1]->getIntegerConstantExpr(Context)) 5293 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5294 Diag(SubExprs[1]->getBeginLoc(), 5295 diag::warn_atomic_op_has_invalid_memory_order) 5296 << SubExprs[1]->getSourceRange(); 5297 } 5298 5299 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5300 auto *Scope = Args[Args.size() - 1]; 5301 if (Optional<llvm::APSInt> Result = 5302 Scope->getIntegerConstantExpr(Context)) { 5303 if (!ScopeModel->isValid(Result->getZExtValue())) 5304 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5305 << Scope->getSourceRange(); 5306 } 5307 SubExprs.push_back(Scope); 5308 } 5309 5310 AtomicExpr *AE = new (Context) 5311 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5312 5313 if ((Op == AtomicExpr::AO__c11_atomic_load || 5314 Op == AtomicExpr::AO__c11_atomic_store || 5315 Op == AtomicExpr::AO__opencl_atomic_load || 5316 Op == AtomicExpr::AO__opencl_atomic_store ) && 5317 Context.AtomicUsesUnsupportedLibcall(AE)) 5318 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5319 << ((Op == AtomicExpr::AO__c11_atomic_load || 5320 Op == AtomicExpr::AO__opencl_atomic_load) 5321 ? 0 5322 : 1); 5323 5324 if (ValType->isExtIntType()) { 5325 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5326 return ExprError(); 5327 } 5328 5329 return AE; 5330 } 5331 5332 /// checkBuiltinArgument - Given a call to a builtin function, perform 5333 /// normal type-checking on the given argument, updating the call in 5334 /// place. This is useful when a builtin function requires custom 5335 /// type-checking for some of its arguments but not necessarily all of 5336 /// them. 5337 /// 5338 /// Returns true on error. 5339 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5340 FunctionDecl *Fn = E->getDirectCallee(); 5341 assert(Fn && "builtin call without direct callee!"); 5342 5343 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5344 InitializedEntity Entity = 5345 InitializedEntity::InitializeParameter(S.Context, Param); 5346 5347 ExprResult Arg = E->getArg(0); 5348 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5349 if (Arg.isInvalid()) 5350 return true; 5351 5352 E->setArg(ArgIndex, Arg.get()); 5353 return false; 5354 } 5355 5356 /// We have a call to a function like __sync_fetch_and_add, which is an 5357 /// overloaded function based on the pointer type of its first argument. 5358 /// The main BuildCallExpr routines have already promoted the types of 5359 /// arguments because all of these calls are prototyped as void(...). 5360 /// 5361 /// This function goes through and does final semantic checking for these 5362 /// builtins, as well as generating any warnings. 5363 ExprResult 5364 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5365 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5366 Expr *Callee = TheCall->getCallee(); 5367 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5368 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5369 5370 // Ensure that we have at least one argument to do type inference from. 5371 if (TheCall->getNumArgs() < 1) { 5372 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5373 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5374 return ExprError(); 5375 } 5376 5377 // Inspect the first argument of the atomic builtin. This should always be 5378 // a pointer type, whose element is an integral scalar or pointer type. 5379 // Because it is a pointer type, we don't have to worry about any implicit 5380 // casts here. 5381 // FIXME: We don't allow floating point scalars as input. 5382 Expr *FirstArg = TheCall->getArg(0); 5383 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5384 if (FirstArgResult.isInvalid()) 5385 return ExprError(); 5386 FirstArg = FirstArgResult.get(); 5387 TheCall->setArg(0, FirstArg); 5388 5389 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5390 if (!pointerType) { 5391 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5392 << FirstArg->getType() << FirstArg->getSourceRange(); 5393 return ExprError(); 5394 } 5395 5396 QualType ValType = pointerType->getPointeeType(); 5397 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5398 !ValType->isBlockPointerType()) { 5399 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5400 << FirstArg->getType() << FirstArg->getSourceRange(); 5401 return ExprError(); 5402 } 5403 5404 if (ValType.isConstQualified()) { 5405 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5406 << FirstArg->getType() << FirstArg->getSourceRange(); 5407 return ExprError(); 5408 } 5409 5410 switch (ValType.getObjCLifetime()) { 5411 case Qualifiers::OCL_None: 5412 case Qualifiers::OCL_ExplicitNone: 5413 // okay 5414 break; 5415 5416 case Qualifiers::OCL_Weak: 5417 case Qualifiers::OCL_Strong: 5418 case Qualifiers::OCL_Autoreleasing: 5419 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5420 << ValType << FirstArg->getSourceRange(); 5421 return ExprError(); 5422 } 5423 5424 // Strip any qualifiers off ValType. 5425 ValType = ValType.getUnqualifiedType(); 5426 5427 // The majority of builtins return a value, but a few have special return 5428 // types, so allow them to override appropriately below. 5429 QualType ResultType = ValType; 5430 5431 // We need to figure out which concrete builtin this maps onto. For example, 5432 // __sync_fetch_and_add with a 2 byte object turns into 5433 // __sync_fetch_and_add_2. 5434 #define BUILTIN_ROW(x) \ 5435 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5436 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5437 5438 static const unsigned BuiltinIndices[][5] = { 5439 BUILTIN_ROW(__sync_fetch_and_add), 5440 BUILTIN_ROW(__sync_fetch_and_sub), 5441 BUILTIN_ROW(__sync_fetch_and_or), 5442 BUILTIN_ROW(__sync_fetch_and_and), 5443 BUILTIN_ROW(__sync_fetch_and_xor), 5444 BUILTIN_ROW(__sync_fetch_and_nand), 5445 5446 BUILTIN_ROW(__sync_add_and_fetch), 5447 BUILTIN_ROW(__sync_sub_and_fetch), 5448 BUILTIN_ROW(__sync_and_and_fetch), 5449 BUILTIN_ROW(__sync_or_and_fetch), 5450 BUILTIN_ROW(__sync_xor_and_fetch), 5451 BUILTIN_ROW(__sync_nand_and_fetch), 5452 5453 BUILTIN_ROW(__sync_val_compare_and_swap), 5454 BUILTIN_ROW(__sync_bool_compare_and_swap), 5455 BUILTIN_ROW(__sync_lock_test_and_set), 5456 BUILTIN_ROW(__sync_lock_release), 5457 BUILTIN_ROW(__sync_swap) 5458 }; 5459 #undef BUILTIN_ROW 5460 5461 // Determine the index of the size. 5462 unsigned SizeIndex; 5463 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5464 case 1: SizeIndex = 0; break; 5465 case 2: SizeIndex = 1; break; 5466 case 4: SizeIndex = 2; break; 5467 case 8: SizeIndex = 3; break; 5468 case 16: SizeIndex = 4; break; 5469 default: 5470 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5471 << FirstArg->getType() << FirstArg->getSourceRange(); 5472 return ExprError(); 5473 } 5474 5475 // Each of these builtins has one pointer argument, followed by some number of 5476 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5477 // that we ignore. Find out which row of BuiltinIndices to read from as well 5478 // as the number of fixed args. 5479 unsigned BuiltinID = FDecl->getBuiltinID(); 5480 unsigned BuiltinIndex, NumFixed = 1; 5481 bool WarnAboutSemanticsChange = false; 5482 switch (BuiltinID) { 5483 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5484 case Builtin::BI__sync_fetch_and_add: 5485 case Builtin::BI__sync_fetch_and_add_1: 5486 case Builtin::BI__sync_fetch_and_add_2: 5487 case Builtin::BI__sync_fetch_and_add_4: 5488 case Builtin::BI__sync_fetch_and_add_8: 5489 case Builtin::BI__sync_fetch_and_add_16: 5490 BuiltinIndex = 0; 5491 break; 5492 5493 case Builtin::BI__sync_fetch_and_sub: 5494 case Builtin::BI__sync_fetch_and_sub_1: 5495 case Builtin::BI__sync_fetch_and_sub_2: 5496 case Builtin::BI__sync_fetch_and_sub_4: 5497 case Builtin::BI__sync_fetch_and_sub_8: 5498 case Builtin::BI__sync_fetch_and_sub_16: 5499 BuiltinIndex = 1; 5500 break; 5501 5502 case Builtin::BI__sync_fetch_and_or: 5503 case Builtin::BI__sync_fetch_and_or_1: 5504 case Builtin::BI__sync_fetch_and_or_2: 5505 case Builtin::BI__sync_fetch_and_or_4: 5506 case Builtin::BI__sync_fetch_and_or_8: 5507 case Builtin::BI__sync_fetch_and_or_16: 5508 BuiltinIndex = 2; 5509 break; 5510 5511 case Builtin::BI__sync_fetch_and_and: 5512 case Builtin::BI__sync_fetch_and_and_1: 5513 case Builtin::BI__sync_fetch_and_and_2: 5514 case Builtin::BI__sync_fetch_and_and_4: 5515 case Builtin::BI__sync_fetch_and_and_8: 5516 case Builtin::BI__sync_fetch_and_and_16: 5517 BuiltinIndex = 3; 5518 break; 5519 5520 case Builtin::BI__sync_fetch_and_xor: 5521 case Builtin::BI__sync_fetch_and_xor_1: 5522 case Builtin::BI__sync_fetch_and_xor_2: 5523 case Builtin::BI__sync_fetch_and_xor_4: 5524 case Builtin::BI__sync_fetch_and_xor_8: 5525 case Builtin::BI__sync_fetch_and_xor_16: 5526 BuiltinIndex = 4; 5527 break; 5528 5529 case Builtin::BI__sync_fetch_and_nand: 5530 case Builtin::BI__sync_fetch_and_nand_1: 5531 case Builtin::BI__sync_fetch_and_nand_2: 5532 case Builtin::BI__sync_fetch_and_nand_4: 5533 case Builtin::BI__sync_fetch_and_nand_8: 5534 case Builtin::BI__sync_fetch_and_nand_16: 5535 BuiltinIndex = 5; 5536 WarnAboutSemanticsChange = true; 5537 break; 5538 5539 case Builtin::BI__sync_add_and_fetch: 5540 case Builtin::BI__sync_add_and_fetch_1: 5541 case Builtin::BI__sync_add_and_fetch_2: 5542 case Builtin::BI__sync_add_and_fetch_4: 5543 case Builtin::BI__sync_add_and_fetch_8: 5544 case Builtin::BI__sync_add_and_fetch_16: 5545 BuiltinIndex = 6; 5546 break; 5547 5548 case Builtin::BI__sync_sub_and_fetch: 5549 case Builtin::BI__sync_sub_and_fetch_1: 5550 case Builtin::BI__sync_sub_and_fetch_2: 5551 case Builtin::BI__sync_sub_and_fetch_4: 5552 case Builtin::BI__sync_sub_and_fetch_8: 5553 case Builtin::BI__sync_sub_and_fetch_16: 5554 BuiltinIndex = 7; 5555 break; 5556 5557 case Builtin::BI__sync_and_and_fetch: 5558 case Builtin::BI__sync_and_and_fetch_1: 5559 case Builtin::BI__sync_and_and_fetch_2: 5560 case Builtin::BI__sync_and_and_fetch_4: 5561 case Builtin::BI__sync_and_and_fetch_8: 5562 case Builtin::BI__sync_and_and_fetch_16: 5563 BuiltinIndex = 8; 5564 break; 5565 5566 case Builtin::BI__sync_or_and_fetch: 5567 case Builtin::BI__sync_or_and_fetch_1: 5568 case Builtin::BI__sync_or_and_fetch_2: 5569 case Builtin::BI__sync_or_and_fetch_4: 5570 case Builtin::BI__sync_or_and_fetch_8: 5571 case Builtin::BI__sync_or_and_fetch_16: 5572 BuiltinIndex = 9; 5573 break; 5574 5575 case Builtin::BI__sync_xor_and_fetch: 5576 case Builtin::BI__sync_xor_and_fetch_1: 5577 case Builtin::BI__sync_xor_and_fetch_2: 5578 case Builtin::BI__sync_xor_and_fetch_4: 5579 case Builtin::BI__sync_xor_and_fetch_8: 5580 case Builtin::BI__sync_xor_and_fetch_16: 5581 BuiltinIndex = 10; 5582 break; 5583 5584 case Builtin::BI__sync_nand_and_fetch: 5585 case Builtin::BI__sync_nand_and_fetch_1: 5586 case Builtin::BI__sync_nand_and_fetch_2: 5587 case Builtin::BI__sync_nand_and_fetch_4: 5588 case Builtin::BI__sync_nand_and_fetch_8: 5589 case Builtin::BI__sync_nand_and_fetch_16: 5590 BuiltinIndex = 11; 5591 WarnAboutSemanticsChange = true; 5592 break; 5593 5594 case Builtin::BI__sync_val_compare_and_swap: 5595 case Builtin::BI__sync_val_compare_and_swap_1: 5596 case Builtin::BI__sync_val_compare_and_swap_2: 5597 case Builtin::BI__sync_val_compare_and_swap_4: 5598 case Builtin::BI__sync_val_compare_and_swap_8: 5599 case Builtin::BI__sync_val_compare_and_swap_16: 5600 BuiltinIndex = 12; 5601 NumFixed = 2; 5602 break; 5603 5604 case Builtin::BI__sync_bool_compare_and_swap: 5605 case Builtin::BI__sync_bool_compare_and_swap_1: 5606 case Builtin::BI__sync_bool_compare_and_swap_2: 5607 case Builtin::BI__sync_bool_compare_and_swap_4: 5608 case Builtin::BI__sync_bool_compare_and_swap_8: 5609 case Builtin::BI__sync_bool_compare_and_swap_16: 5610 BuiltinIndex = 13; 5611 NumFixed = 2; 5612 ResultType = Context.BoolTy; 5613 break; 5614 5615 case Builtin::BI__sync_lock_test_and_set: 5616 case Builtin::BI__sync_lock_test_and_set_1: 5617 case Builtin::BI__sync_lock_test_and_set_2: 5618 case Builtin::BI__sync_lock_test_and_set_4: 5619 case Builtin::BI__sync_lock_test_and_set_8: 5620 case Builtin::BI__sync_lock_test_and_set_16: 5621 BuiltinIndex = 14; 5622 break; 5623 5624 case Builtin::BI__sync_lock_release: 5625 case Builtin::BI__sync_lock_release_1: 5626 case Builtin::BI__sync_lock_release_2: 5627 case Builtin::BI__sync_lock_release_4: 5628 case Builtin::BI__sync_lock_release_8: 5629 case Builtin::BI__sync_lock_release_16: 5630 BuiltinIndex = 15; 5631 NumFixed = 0; 5632 ResultType = Context.VoidTy; 5633 break; 5634 5635 case Builtin::BI__sync_swap: 5636 case Builtin::BI__sync_swap_1: 5637 case Builtin::BI__sync_swap_2: 5638 case Builtin::BI__sync_swap_4: 5639 case Builtin::BI__sync_swap_8: 5640 case Builtin::BI__sync_swap_16: 5641 BuiltinIndex = 16; 5642 break; 5643 } 5644 5645 // Now that we know how many fixed arguments we expect, first check that we 5646 // have at least that many. 5647 if (TheCall->getNumArgs() < 1+NumFixed) { 5648 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5649 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5650 << Callee->getSourceRange(); 5651 return ExprError(); 5652 } 5653 5654 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5655 << Callee->getSourceRange(); 5656 5657 if (WarnAboutSemanticsChange) { 5658 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5659 << Callee->getSourceRange(); 5660 } 5661 5662 // Get the decl for the concrete builtin from this, we can tell what the 5663 // concrete integer type we should convert to is. 5664 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5665 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5666 FunctionDecl *NewBuiltinDecl; 5667 if (NewBuiltinID == BuiltinID) 5668 NewBuiltinDecl = FDecl; 5669 else { 5670 // Perform builtin lookup to avoid redeclaring it. 5671 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5672 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5673 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5674 assert(Res.getFoundDecl()); 5675 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5676 if (!NewBuiltinDecl) 5677 return ExprError(); 5678 } 5679 5680 // The first argument --- the pointer --- has a fixed type; we 5681 // deduce the types of the rest of the arguments accordingly. Walk 5682 // the remaining arguments, converting them to the deduced value type. 5683 for (unsigned i = 0; i != NumFixed; ++i) { 5684 ExprResult Arg = TheCall->getArg(i+1); 5685 5686 // GCC does an implicit conversion to the pointer or integer ValType. This 5687 // can fail in some cases (1i -> int**), check for this error case now. 5688 // Initialize the argument. 5689 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5690 ValType, /*consume*/ false); 5691 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5692 if (Arg.isInvalid()) 5693 return ExprError(); 5694 5695 // Okay, we have something that *can* be converted to the right type. Check 5696 // to see if there is a potentially weird extension going on here. This can 5697 // happen when you do an atomic operation on something like an char* and 5698 // pass in 42. The 42 gets converted to char. This is even more strange 5699 // for things like 45.123 -> char, etc. 5700 // FIXME: Do this check. 5701 TheCall->setArg(i+1, Arg.get()); 5702 } 5703 5704 // Create a new DeclRefExpr to refer to the new decl. 5705 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5706 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5707 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5708 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5709 5710 // Set the callee in the CallExpr. 5711 // FIXME: This loses syntactic information. 5712 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5713 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5714 CK_BuiltinFnToFnPtr); 5715 TheCall->setCallee(PromotedCall.get()); 5716 5717 // Change the result type of the call to match the original value type. This 5718 // is arbitrary, but the codegen for these builtins ins design to handle it 5719 // gracefully. 5720 TheCall->setType(ResultType); 5721 5722 // Prohibit use of _ExtInt with atomic builtins. 5723 // The arguments would have already been converted to the first argument's 5724 // type, so only need to check the first argument. 5725 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5726 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5727 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5728 return ExprError(); 5729 } 5730 5731 return TheCallResult; 5732 } 5733 5734 /// SemaBuiltinNontemporalOverloaded - We have a call to 5735 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5736 /// overloaded function based on the pointer type of its last argument. 5737 /// 5738 /// This function goes through and does final semantic checking for these 5739 /// builtins. 5740 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5741 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5742 DeclRefExpr *DRE = 5743 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5744 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5745 unsigned BuiltinID = FDecl->getBuiltinID(); 5746 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5747 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5748 "Unexpected nontemporal load/store builtin!"); 5749 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5750 unsigned numArgs = isStore ? 2 : 1; 5751 5752 // Ensure that we have the proper number of arguments. 5753 if (checkArgCount(*this, TheCall, numArgs)) 5754 return ExprError(); 5755 5756 // Inspect the last argument of the nontemporal builtin. This should always 5757 // be a pointer type, from which we imply the type of the memory access. 5758 // Because it is a pointer type, we don't have to worry about any implicit 5759 // casts here. 5760 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5761 ExprResult PointerArgResult = 5762 DefaultFunctionArrayLvalueConversion(PointerArg); 5763 5764 if (PointerArgResult.isInvalid()) 5765 return ExprError(); 5766 PointerArg = PointerArgResult.get(); 5767 TheCall->setArg(numArgs - 1, PointerArg); 5768 5769 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5770 if (!pointerType) { 5771 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5772 << PointerArg->getType() << PointerArg->getSourceRange(); 5773 return ExprError(); 5774 } 5775 5776 QualType ValType = pointerType->getPointeeType(); 5777 5778 // Strip any qualifiers off ValType. 5779 ValType = ValType.getUnqualifiedType(); 5780 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5781 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5782 !ValType->isVectorType()) { 5783 Diag(DRE->getBeginLoc(), 5784 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5785 << PointerArg->getType() << PointerArg->getSourceRange(); 5786 return ExprError(); 5787 } 5788 5789 if (!isStore) { 5790 TheCall->setType(ValType); 5791 return TheCallResult; 5792 } 5793 5794 ExprResult ValArg = TheCall->getArg(0); 5795 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5796 Context, ValType, /*consume*/ false); 5797 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5798 if (ValArg.isInvalid()) 5799 return ExprError(); 5800 5801 TheCall->setArg(0, ValArg.get()); 5802 TheCall->setType(Context.VoidTy); 5803 return TheCallResult; 5804 } 5805 5806 /// CheckObjCString - Checks that the argument to the builtin 5807 /// CFString constructor is correct 5808 /// Note: It might also make sense to do the UTF-16 conversion here (would 5809 /// simplify the backend). 5810 bool Sema::CheckObjCString(Expr *Arg) { 5811 Arg = Arg->IgnoreParenCasts(); 5812 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5813 5814 if (!Literal || !Literal->isAscii()) { 5815 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5816 << Arg->getSourceRange(); 5817 return true; 5818 } 5819 5820 if (Literal->containsNonAsciiOrNull()) { 5821 StringRef String = Literal->getString(); 5822 unsigned NumBytes = String.size(); 5823 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5824 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5825 llvm::UTF16 *ToPtr = &ToBuf[0]; 5826 5827 llvm::ConversionResult Result = 5828 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5829 ToPtr + NumBytes, llvm::strictConversion); 5830 // Check for conversion failure. 5831 if (Result != llvm::conversionOK) 5832 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5833 << Arg->getSourceRange(); 5834 } 5835 return false; 5836 } 5837 5838 /// CheckObjCString - Checks that the format string argument to the os_log() 5839 /// and os_trace() functions is correct, and converts it to const char *. 5840 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5841 Arg = Arg->IgnoreParenCasts(); 5842 auto *Literal = dyn_cast<StringLiteral>(Arg); 5843 if (!Literal) { 5844 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5845 Literal = ObjcLiteral->getString(); 5846 } 5847 } 5848 5849 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5850 return ExprError( 5851 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5852 << Arg->getSourceRange()); 5853 } 5854 5855 ExprResult Result(Literal); 5856 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5857 InitializedEntity Entity = 5858 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5859 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5860 return Result; 5861 } 5862 5863 /// Check that the user is calling the appropriate va_start builtin for the 5864 /// target and calling convention. 5865 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5866 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5867 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5868 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5869 TT.getArch() == llvm::Triple::aarch64_32); 5870 bool IsWindows = TT.isOSWindows(); 5871 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5872 if (IsX64 || IsAArch64) { 5873 CallingConv CC = CC_C; 5874 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5875 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5876 if (IsMSVAStart) { 5877 // Don't allow this in System V ABI functions. 5878 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5879 return S.Diag(Fn->getBeginLoc(), 5880 diag::err_ms_va_start_used_in_sysv_function); 5881 } else { 5882 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5883 // On x64 Windows, don't allow this in System V ABI functions. 5884 // (Yes, that means there's no corresponding way to support variadic 5885 // System V ABI functions on Windows.) 5886 if ((IsWindows && CC == CC_X86_64SysV) || 5887 (!IsWindows && CC == CC_Win64)) 5888 return S.Diag(Fn->getBeginLoc(), 5889 diag::err_va_start_used_in_wrong_abi_function) 5890 << !IsWindows; 5891 } 5892 return false; 5893 } 5894 5895 if (IsMSVAStart) 5896 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5897 return false; 5898 } 5899 5900 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5901 ParmVarDecl **LastParam = nullptr) { 5902 // Determine whether the current function, block, or obj-c method is variadic 5903 // and get its parameter list. 5904 bool IsVariadic = false; 5905 ArrayRef<ParmVarDecl *> Params; 5906 DeclContext *Caller = S.CurContext; 5907 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5908 IsVariadic = Block->isVariadic(); 5909 Params = Block->parameters(); 5910 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5911 IsVariadic = FD->isVariadic(); 5912 Params = FD->parameters(); 5913 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5914 IsVariadic = MD->isVariadic(); 5915 // FIXME: This isn't correct for methods (results in bogus warning). 5916 Params = MD->parameters(); 5917 } else if (isa<CapturedDecl>(Caller)) { 5918 // We don't support va_start in a CapturedDecl. 5919 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5920 return true; 5921 } else { 5922 // This must be some other declcontext that parses exprs. 5923 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5924 return true; 5925 } 5926 5927 if (!IsVariadic) { 5928 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5929 return true; 5930 } 5931 5932 if (LastParam) 5933 *LastParam = Params.empty() ? nullptr : Params.back(); 5934 5935 return false; 5936 } 5937 5938 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5939 /// for validity. Emit an error and return true on failure; return false 5940 /// on success. 5941 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5942 Expr *Fn = TheCall->getCallee(); 5943 5944 if (checkVAStartABI(*this, BuiltinID, Fn)) 5945 return true; 5946 5947 if (checkArgCount(*this, TheCall, 2)) 5948 return true; 5949 5950 // Type-check the first argument normally. 5951 if (checkBuiltinArgument(*this, TheCall, 0)) 5952 return true; 5953 5954 // Check that the current function is variadic, and get its last parameter. 5955 ParmVarDecl *LastParam; 5956 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5957 return true; 5958 5959 // Verify that the second argument to the builtin is the last argument of the 5960 // current function or method. 5961 bool SecondArgIsLastNamedArgument = false; 5962 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5963 5964 // These are valid if SecondArgIsLastNamedArgument is false after the next 5965 // block. 5966 QualType Type; 5967 SourceLocation ParamLoc; 5968 bool IsCRegister = false; 5969 5970 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5971 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5972 SecondArgIsLastNamedArgument = PV == LastParam; 5973 5974 Type = PV->getType(); 5975 ParamLoc = PV->getLocation(); 5976 IsCRegister = 5977 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5978 } 5979 } 5980 5981 if (!SecondArgIsLastNamedArgument) 5982 Diag(TheCall->getArg(1)->getBeginLoc(), 5983 diag::warn_second_arg_of_va_start_not_last_named_param); 5984 else if (IsCRegister || Type->isReferenceType() || 5985 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5986 // Promotable integers are UB, but enumerations need a bit of 5987 // extra checking to see what their promotable type actually is. 5988 if (!Type->isPromotableIntegerType()) 5989 return false; 5990 if (!Type->isEnumeralType()) 5991 return true; 5992 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5993 return !(ED && 5994 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5995 }()) { 5996 unsigned Reason = 0; 5997 if (Type->isReferenceType()) Reason = 1; 5998 else if (IsCRegister) Reason = 2; 5999 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6000 Diag(ParamLoc, diag::note_parameter_type) << Type; 6001 } 6002 6003 TheCall->setType(Context.VoidTy); 6004 return false; 6005 } 6006 6007 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6008 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6009 // const char *named_addr); 6010 6011 Expr *Func = Call->getCallee(); 6012 6013 if (Call->getNumArgs() < 3) 6014 return Diag(Call->getEndLoc(), 6015 diag::err_typecheck_call_too_few_args_at_least) 6016 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6017 6018 // Type-check the first argument normally. 6019 if (checkBuiltinArgument(*this, Call, 0)) 6020 return true; 6021 6022 // Check that the current function is variadic. 6023 if (checkVAStartIsInVariadicFunction(*this, Func)) 6024 return true; 6025 6026 // __va_start on Windows does not validate the parameter qualifiers 6027 6028 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6029 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6030 6031 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6032 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6033 6034 const QualType &ConstCharPtrTy = 6035 Context.getPointerType(Context.CharTy.withConst()); 6036 if (!Arg1Ty->isPointerType() || 6037 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 6038 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6039 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6040 << 0 /* qualifier difference */ 6041 << 3 /* parameter mismatch */ 6042 << 2 << Arg1->getType() << ConstCharPtrTy; 6043 6044 const QualType SizeTy = Context.getSizeType(); 6045 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6046 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6047 << Arg2->getType() << SizeTy << 1 /* different class */ 6048 << 0 /* qualifier difference */ 6049 << 3 /* parameter mismatch */ 6050 << 3 << Arg2->getType() << SizeTy; 6051 6052 return false; 6053 } 6054 6055 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6056 /// friends. This is declared to take (...), so we have to check everything. 6057 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6058 if (checkArgCount(*this, TheCall, 2)) 6059 return true; 6060 6061 ExprResult OrigArg0 = TheCall->getArg(0); 6062 ExprResult OrigArg1 = TheCall->getArg(1); 6063 6064 // Do standard promotions between the two arguments, returning their common 6065 // type. 6066 QualType Res = UsualArithmeticConversions( 6067 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6068 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6069 return true; 6070 6071 // Make sure any conversions are pushed back into the call; this is 6072 // type safe since unordered compare builtins are declared as "_Bool 6073 // foo(...)". 6074 TheCall->setArg(0, OrigArg0.get()); 6075 TheCall->setArg(1, OrigArg1.get()); 6076 6077 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6078 return false; 6079 6080 // If the common type isn't a real floating type, then the arguments were 6081 // invalid for this operation. 6082 if (Res.isNull() || !Res->isRealFloatingType()) 6083 return Diag(OrigArg0.get()->getBeginLoc(), 6084 diag::err_typecheck_call_invalid_ordered_compare) 6085 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6086 << SourceRange(OrigArg0.get()->getBeginLoc(), 6087 OrigArg1.get()->getEndLoc()); 6088 6089 return false; 6090 } 6091 6092 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6093 /// __builtin_isnan and friends. This is declared to take (...), so we have 6094 /// to check everything. We expect the last argument to be a floating point 6095 /// value. 6096 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6097 if (checkArgCount(*this, TheCall, NumArgs)) 6098 return true; 6099 6100 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6101 // on all preceding parameters just being int. Try all of those. 6102 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6103 Expr *Arg = TheCall->getArg(i); 6104 6105 if (Arg->isTypeDependent()) 6106 return false; 6107 6108 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6109 6110 if (Res.isInvalid()) 6111 return true; 6112 TheCall->setArg(i, Res.get()); 6113 } 6114 6115 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6116 6117 if (OrigArg->isTypeDependent()) 6118 return false; 6119 6120 // Usual Unary Conversions will convert half to float, which we want for 6121 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6122 // type how it is, but do normal L->Rvalue conversions. 6123 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6124 OrigArg = UsualUnaryConversions(OrigArg).get(); 6125 else 6126 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6127 TheCall->setArg(NumArgs - 1, OrigArg); 6128 6129 // This operation requires a non-_Complex floating-point number. 6130 if (!OrigArg->getType()->isRealFloatingType()) 6131 return Diag(OrigArg->getBeginLoc(), 6132 diag::err_typecheck_call_invalid_unary_fp) 6133 << OrigArg->getType() << OrigArg->getSourceRange(); 6134 6135 return false; 6136 } 6137 6138 /// Perform semantic analysis for a call to __builtin_complex. 6139 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6140 if (checkArgCount(*this, TheCall, 2)) 6141 return true; 6142 6143 bool Dependent = false; 6144 for (unsigned I = 0; I != 2; ++I) { 6145 Expr *Arg = TheCall->getArg(I); 6146 QualType T = Arg->getType(); 6147 if (T->isDependentType()) { 6148 Dependent = true; 6149 continue; 6150 } 6151 6152 // Despite supporting _Complex int, GCC requires a real floating point type 6153 // for the operands of __builtin_complex. 6154 if (!T->isRealFloatingType()) { 6155 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6156 << Arg->getType() << Arg->getSourceRange(); 6157 } 6158 6159 ExprResult Converted = DefaultLvalueConversion(Arg); 6160 if (Converted.isInvalid()) 6161 return true; 6162 TheCall->setArg(I, Converted.get()); 6163 } 6164 6165 if (Dependent) { 6166 TheCall->setType(Context.DependentTy); 6167 return false; 6168 } 6169 6170 Expr *Real = TheCall->getArg(0); 6171 Expr *Imag = TheCall->getArg(1); 6172 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6173 return Diag(Real->getBeginLoc(), 6174 diag::err_typecheck_call_different_arg_types) 6175 << Real->getType() << Imag->getType() 6176 << Real->getSourceRange() << Imag->getSourceRange(); 6177 } 6178 6179 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6180 // don't allow this builtin to form those types either. 6181 // FIXME: Should we allow these types? 6182 if (Real->getType()->isFloat16Type()) 6183 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6184 << "_Float16"; 6185 if (Real->getType()->isHalfType()) 6186 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6187 << "half"; 6188 6189 TheCall->setType(Context.getComplexType(Real->getType())); 6190 return false; 6191 } 6192 6193 // Customized Sema Checking for VSX builtins that have the following signature: 6194 // vector [...] builtinName(vector [...], vector [...], const int); 6195 // Which takes the same type of vectors (any legal vector type) for the first 6196 // two arguments and takes compile time constant for the third argument. 6197 // Example builtins are : 6198 // vector double vec_xxpermdi(vector double, vector double, int); 6199 // vector short vec_xxsldwi(vector short, vector short, int); 6200 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6201 unsigned ExpectedNumArgs = 3; 6202 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6203 return true; 6204 6205 // Check the third argument is a compile time constant 6206 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6207 return Diag(TheCall->getBeginLoc(), 6208 diag::err_vsx_builtin_nonconstant_argument) 6209 << 3 /* argument index */ << TheCall->getDirectCallee() 6210 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6211 TheCall->getArg(2)->getEndLoc()); 6212 6213 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6214 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6215 6216 // Check the type of argument 1 and argument 2 are vectors. 6217 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6218 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6219 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6220 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6221 << TheCall->getDirectCallee() 6222 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6223 TheCall->getArg(1)->getEndLoc()); 6224 } 6225 6226 // Check the first two arguments are the same type. 6227 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6228 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6229 << TheCall->getDirectCallee() 6230 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6231 TheCall->getArg(1)->getEndLoc()); 6232 } 6233 6234 // When default clang type checking is turned off and the customized type 6235 // checking is used, the returning type of the function must be explicitly 6236 // set. Otherwise it is _Bool by default. 6237 TheCall->setType(Arg1Ty); 6238 6239 return false; 6240 } 6241 6242 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6243 // This is declared to take (...), so we have to check everything. 6244 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6245 if (TheCall->getNumArgs() < 2) 6246 return ExprError(Diag(TheCall->getEndLoc(), 6247 diag::err_typecheck_call_too_few_args_at_least) 6248 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6249 << TheCall->getSourceRange()); 6250 6251 // Determine which of the following types of shufflevector we're checking: 6252 // 1) unary, vector mask: (lhs, mask) 6253 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6254 QualType resType = TheCall->getArg(0)->getType(); 6255 unsigned numElements = 0; 6256 6257 if (!TheCall->getArg(0)->isTypeDependent() && 6258 !TheCall->getArg(1)->isTypeDependent()) { 6259 QualType LHSType = TheCall->getArg(0)->getType(); 6260 QualType RHSType = TheCall->getArg(1)->getType(); 6261 6262 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6263 return ExprError( 6264 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6265 << TheCall->getDirectCallee() 6266 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6267 TheCall->getArg(1)->getEndLoc())); 6268 6269 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6270 unsigned numResElements = TheCall->getNumArgs() - 2; 6271 6272 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6273 // with mask. If so, verify that RHS is an integer vector type with the 6274 // same number of elts as lhs. 6275 if (TheCall->getNumArgs() == 2) { 6276 if (!RHSType->hasIntegerRepresentation() || 6277 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6278 return ExprError(Diag(TheCall->getBeginLoc(), 6279 diag::err_vec_builtin_incompatible_vector) 6280 << TheCall->getDirectCallee() 6281 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6282 TheCall->getArg(1)->getEndLoc())); 6283 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6284 return ExprError(Diag(TheCall->getBeginLoc(), 6285 diag::err_vec_builtin_incompatible_vector) 6286 << TheCall->getDirectCallee() 6287 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6288 TheCall->getArg(1)->getEndLoc())); 6289 } else if (numElements != numResElements) { 6290 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6291 resType = Context.getVectorType(eltType, numResElements, 6292 VectorType::GenericVector); 6293 } 6294 } 6295 6296 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6297 if (TheCall->getArg(i)->isTypeDependent() || 6298 TheCall->getArg(i)->isValueDependent()) 6299 continue; 6300 6301 Optional<llvm::APSInt> Result; 6302 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6303 return ExprError(Diag(TheCall->getBeginLoc(), 6304 diag::err_shufflevector_nonconstant_argument) 6305 << TheCall->getArg(i)->getSourceRange()); 6306 6307 // Allow -1 which will be translated to undef in the IR. 6308 if (Result->isSigned() && Result->isAllOnesValue()) 6309 continue; 6310 6311 if (Result->getActiveBits() > 64 || 6312 Result->getZExtValue() >= numElements * 2) 6313 return ExprError(Diag(TheCall->getBeginLoc(), 6314 diag::err_shufflevector_argument_too_large) 6315 << TheCall->getArg(i)->getSourceRange()); 6316 } 6317 6318 SmallVector<Expr*, 32> exprs; 6319 6320 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6321 exprs.push_back(TheCall->getArg(i)); 6322 TheCall->setArg(i, nullptr); 6323 } 6324 6325 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6326 TheCall->getCallee()->getBeginLoc(), 6327 TheCall->getRParenLoc()); 6328 } 6329 6330 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6331 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6332 SourceLocation BuiltinLoc, 6333 SourceLocation RParenLoc) { 6334 ExprValueKind VK = VK_RValue; 6335 ExprObjectKind OK = OK_Ordinary; 6336 QualType DstTy = TInfo->getType(); 6337 QualType SrcTy = E->getType(); 6338 6339 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6340 return ExprError(Diag(BuiltinLoc, 6341 diag::err_convertvector_non_vector) 6342 << E->getSourceRange()); 6343 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6344 return ExprError(Diag(BuiltinLoc, 6345 diag::err_convertvector_non_vector_type)); 6346 6347 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6348 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6349 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6350 if (SrcElts != DstElts) 6351 return ExprError(Diag(BuiltinLoc, 6352 diag::err_convertvector_incompatible_vector) 6353 << E->getSourceRange()); 6354 } 6355 6356 return new (Context) 6357 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6358 } 6359 6360 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6361 // This is declared to take (const void*, ...) and can take two 6362 // optional constant int args. 6363 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6364 unsigned NumArgs = TheCall->getNumArgs(); 6365 6366 if (NumArgs > 3) 6367 return Diag(TheCall->getEndLoc(), 6368 diag::err_typecheck_call_too_many_args_at_most) 6369 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6370 6371 // Argument 0 is checked for us and the remaining arguments must be 6372 // constant integers. 6373 for (unsigned i = 1; i != NumArgs; ++i) 6374 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6375 return true; 6376 6377 return false; 6378 } 6379 6380 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6381 // __assume does not evaluate its arguments, and should warn if its argument 6382 // has side effects. 6383 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6384 Expr *Arg = TheCall->getArg(0); 6385 if (Arg->isInstantiationDependent()) return false; 6386 6387 if (Arg->HasSideEffects(Context)) 6388 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6389 << Arg->getSourceRange() 6390 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6391 6392 return false; 6393 } 6394 6395 /// Handle __builtin_alloca_with_align. This is declared 6396 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6397 /// than 8. 6398 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6399 // The alignment must be a constant integer. 6400 Expr *Arg = TheCall->getArg(1); 6401 6402 // We can't check the value of a dependent argument. 6403 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6404 if (const auto *UE = 6405 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6406 if (UE->getKind() == UETT_AlignOf || 6407 UE->getKind() == UETT_PreferredAlignOf) 6408 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6409 << Arg->getSourceRange(); 6410 6411 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6412 6413 if (!Result.isPowerOf2()) 6414 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6415 << Arg->getSourceRange(); 6416 6417 if (Result < Context.getCharWidth()) 6418 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6419 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6420 6421 if (Result > std::numeric_limits<int32_t>::max()) 6422 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6423 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6424 } 6425 6426 return false; 6427 } 6428 6429 /// Handle __builtin_assume_aligned. This is declared 6430 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6431 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6432 unsigned NumArgs = TheCall->getNumArgs(); 6433 6434 if (NumArgs > 3) 6435 return Diag(TheCall->getEndLoc(), 6436 diag::err_typecheck_call_too_many_args_at_most) 6437 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6438 6439 // The alignment must be a constant integer. 6440 Expr *Arg = TheCall->getArg(1); 6441 6442 // We can't check the value of a dependent argument. 6443 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6444 llvm::APSInt Result; 6445 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6446 return true; 6447 6448 if (!Result.isPowerOf2()) 6449 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6450 << Arg->getSourceRange(); 6451 6452 if (Result > Sema::MaximumAlignment) 6453 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6454 << Arg->getSourceRange() << Sema::MaximumAlignment; 6455 } 6456 6457 if (NumArgs > 2) { 6458 ExprResult Arg(TheCall->getArg(2)); 6459 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6460 Context.getSizeType(), false); 6461 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6462 if (Arg.isInvalid()) return true; 6463 TheCall->setArg(2, Arg.get()); 6464 } 6465 6466 return false; 6467 } 6468 6469 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6470 unsigned BuiltinID = 6471 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6472 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6473 6474 unsigned NumArgs = TheCall->getNumArgs(); 6475 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6476 if (NumArgs < NumRequiredArgs) { 6477 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6478 << 0 /* function call */ << NumRequiredArgs << NumArgs 6479 << TheCall->getSourceRange(); 6480 } 6481 if (NumArgs >= NumRequiredArgs + 0x100) { 6482 return Diag(TheCall->getEndLoc(), 6483 diag::err_typecheck_call_too_many_args_at_most) 6484 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6485 << TheCall->getSourceRange(); 6486 } 6487 unsigned i = 0; 6488 6489 // For formatting call, check buffer arg. 6490 if (!IsSizeCall) { 6491 ExprResult Arg(TheCall->getArg(i)); 6492 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6493 Context, Context.VoidPtrTy, false); 6494 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6495 if (Arg.isInvalid()) 6496 return true; 6497 TheCall->setArg(i, Arg.get()); 6498 i++; 6499 } 6500 6501 // Check string literal arg. 6502 unsigned FormatIdx = i; 6503 { 6504 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6505 if (Arg.isInvalid()) 6506 return true; 6507 TheCall->setArg(i, Arg.get()); 6508 i++; 6509 } 6510 6511 // Make sure variadic args are scalar. 6512 unsigned FirstDataArg = i; 6513 while (i < NumArgs) { 6514 ExprResult Arg = DefaultVariadicArgumentPromotion( 6515 TheCall->getArg(i), VariadicFunction, nullptr); 6516 if (Arg.isInvalid()) 6517 return true; 6518 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6519 if (ArgSize.getQuantity() >= 0x100) { 6520 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6521 << i << (int)ArgSize.getQuantity() << 0xff 6522 << TheCall->getSourceRange(); 6523 } 6524 TheCall->setArg(i, Arg.get()); 6525 i++; 6526 } 6527 6528 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6529 // call to avoid duplicate diagnostics. 6530 if (!IsSizeCall) { 6531 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6532 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6533 bool Success = CheckFormatArguments( 6534 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6535 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6536 CheckedVarArgs); 6537 if (!Success) 6538 return true; 6539 } 6540 6541 if (IsSizeCall) { 6542 TheCall->setType(Context.getSizeType()); 6543 } else { 6544 TheCall->setType(Context.VoidPtrTy); 6545 } 6546 return false; 6547 } 6548 6549 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6550 /// TheCall is a constant expression. 6551 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6552 llvm::APSInt &Result) { 6553 Expr *Arg = TheCall->getArg(ArgNum); 6554 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6555 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6556 6557 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6558 6559 Optional<llvm::APSInt> R; 6560 if (!(R = Arg->getIntegerConstantExpr(Context))) 6561 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6562 << FDecl->getDeclName() << Arg->getSourceRange(); 6563 Result = *R; 6564 return false; 6565 } 6566 6567 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6568 /// TheCall is a constant expression in the range [Low, High]. 6569 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6570 int Low, int High, bool RangeIsError) { 6571 if (isConstantEvaluated()) 6572 return false; 6573 llvm::APSInt Result; 6574 6575 // We can't check the value of a dependent argument. 6576 Expr *Arg = TheCall->getArg(ArgNum); 6577 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6578 return false; 6579 6580 // Check constant-ness first. 6581 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6582 return true; 6583 6584 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6585 if (RangeIsError) 6586 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6587 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6588 else 6589 // Defer the warning until we know if the code will be emitted so that 6590 // dead code can ignore this. 6591 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6592 PDiag(diag::warn_argument_invalid_range) 6593 << Result.toString(10) << Low << High 6594 << Arg->getSourceRange()); 6595 } 6596 6597 return false; 6598 } 6599 6600 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6601 /// TheCall is a constant expression is a multiple of Num.. 6602 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6603 unsigned Num) { 6604 llvm::APSInt Result; 6605 6606 // We can't check the value of a dependent argument. 6607 Expr *Arg = TheCall->getArg(ArgNum); 6608 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6609 return false; 6610 6611 // Check constant-ness first. 6612 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6613 return true; 6614 6615 if (Result.getSExtValue() % Num != 0) 6616 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6617 << Num << Arg->getSourceRange(); 6618 6619 return false; 6620 } 6621 6622 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6623 /// constant expression representing a power of 2. 6624 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6625 llvm::APSInt Result; 6626 6627 // We can't check the value of a dependent argument. 6628 Expr *Arg = TheCall->getArg(ArgNum); 6629 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6630 return false; 6631 6632 // Check constant-ness first. 6633 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6634 return true; 6635 6636 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6637 // and only if x is a power of 2. 6638 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6639 return false; 6640 6641 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6642 << Arg->getSourceRange(); 6643 } 6644 6645 static bool IsShiftedByte(llvm::APSInt Value) { 6646 if (Value.isNegative()) 6647 return false; 6648 6649 // Check if it's a shifted byte, by shifting it down 6650 while (true) { 6651 // If the value fits in the bottom byte, the check passes. 6652 if (Value < 0x100) 6653 return true; 6654 6655 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6656 // fails. 6657 if ((Value & 0xFF) != 0) 6658 return false; 6659 6660 // If the bottom 8 bits are all 0, but something above that is nonzero, 6661 // then shifting the value right by 8 bits won't affect whether it's a 6662 // shifted byte or not. So do that, and go round again. 6663 Value >>= 8; 6664 } 6665 } 6666 6667 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6668 /// a constant expression representing an arbitrary byte value shifted left by 6669 /// a multiple of 8 bits. 6670 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6671 unsigned ArgBits) { 6672 llvm::APSInt Result; 6673 6674 // We can't check the value of a dependent argument. 6675 Expr *Arg = TheCall->getArg(ArgNum); 6676 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6677 return false; 6678 6679 // Check constant-ness first. 6680 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6681 return true; 6682 6683 // Truncate to the given size. 6684 Result = Result.getLoBits(ArgBits); 6685 Result.setIsUnsigned(true); 6686 6687 if (IsShiftedByte(Result)) 6688 return false; 6689 6690 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6691 << Arg->getSourceRange(); 6692 } 6693 6694 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6695 /// TheCall is a constant expression representing either a shifted byte value, 6696 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6697 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6698 /// Arm MVE intrinsics. 6699 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6700 int ArgNum, 6701 unsigned ArgBits) { 6702 llvm::APSInt Result; 6703 6704 // We can't check the value of a dependent argument. 6705 Expr *Arg = TheCall->getArg(ArgNum); 6706 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6707 return false; 6708 6709 // Check constant-ness first. 6710 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6711 return true; 6712 6713 // Truncate to the given size. 6714 Result = Result.getLoBits(ArgBits); 6715 Result.setIsUnsigned(true); 6716 6717 // Check to see if it's in either of the required forms. 6718 if (IsShiftedByte(Result) || 6719 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6720 return false; 6721 6722 return Diag(TheCall->getBeginLoc(), 6723 diag::err_argument_not_shifted_byte_or_xxff) 6724 << Arg->getSourceRange(); 6725 } 6726 6727 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6728 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6729 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6730 if (checkArgCount(*this, TheCall, 2)) 6731 return true; 6732 Expr *Arg0 = TheCall->getArg(0); 6733 Expr *Arg1 = TheCall->getArg(1); 6734 6735 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6736 if (FirstArg.isInvalid()) 6737 return true; 6738 QualType FirstArgType = FirstArg.get()->getType(); 6739 if (!FirstArgType->isAnyPointerType()) 6740 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6741 << "first" << FirstArgType << Arg0->getSourceRange(); 6742 TheCall->setArg(0, FirstArg.get()); 6743 6744 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6745 if (SecArg.isInvalid()) 6746 return true; 6747 QualType SecArgType = SecArg.get()->getType(); 6748 if (!SecArgType->isIntegerType()) 6749 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6750 << "second" << SecArgType << Arg1->getSourceRange(); 6751 6752 // Derive the return type from the pointer argument. 6753 TheCall->setType(FirstArgType); 6754 return false; 6755 } 6756 6757 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6758 if (checkArgCount(*this, TheCall, 2)) 6759 return true; 6760 6761 Expr *Arg0 = TheCall->getArg(0); 6762 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6763 if (FirstArg.isInvalid()) 6764 return true; 6765 QualType FirstArgType = FirstArg.get()->getType(); 6766 if (!FirstArgType->isAnyPointerType()) 6767 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6768 << "first" << FirstArgType << Arg0->getSourceRange(); 6769 TheCall->setArg(0, FirstArg.get()); 6770 6771 // Derive the return type from the pointer argument. 6772 TheCall->setType(FirstArgType); 6773 6774 // Second arg must be an constant in range [0,15] 6775 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6776 } 6777 6778 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6779 if (checkArgCount(*this, TheCall, 2)) 6780 return true; 6781 Expr *Arg0 = TheCall->getArg(0); 6782 Expr *Arg1 = TheCall->getArg(1); 6783 6784 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6785 if (FirstArg.isInvalid()) 6786 return true; 6787 QualType FirstArgType = FirstArg.get()->getType(); 6788 if (!FirstArgType->isAnyPointerType()) 6789 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6790 << "first" << FirstArgType << Arg0->getSourceRange(); 6791 6792 QualType SecArgType = Arg1->getType(); 6793 if (!SecArgType->isIntegerType()) 6794 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6795 << "second" << SecArgType << Arg1->getSourceRange(); 6796 TheCall->setType(Context.IntTy); 6797 return false; 6798 } 6799 6800 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6801 BuiltinID == AArch64::BI__builtin_arm_stg) { 6802 if (checkArgCount(*this, TheCall, 1)) 6803 return true; 6804 Expr *Arg0 = TheCall->getArg(0); 6805 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6806 if (FirstArg.isInvalid()) 6807 return true; 6808 6809 QualType FirstArgType = FirstArg.get()->getType(); 6810 if (!FirstArgType->isAnyPointerType()) 6811 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6812 << "first" << FirstArgType << Arg0->getSourceRange(); 6813 TheCall->setArg(0, FirstArg.get()); 6814 6815 // Derive the return type from the pointer argument. 6816 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6817 TheCall->setType(FirstArgType); 6818 return false; 6819 } 6820 6821 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6822 Expr *ArgA = TheCall->getArg(0); 6823 Expr *ArgB = TheCall->getArg(1); 6824 6825 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6826 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6827 6828 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6829 return true; 6830 6831 QualType ArgTypeA = ArgExprA.get()->getType(); 6832 QualType ArgTypeB = ArgExprB.get()->getType(); 6833 6834 auto isNull = [&] (Expr *E) -> bool { 6835 return E->isNullPointerConstant( 6836 Context, Expr::NPC_ValueDependentIsNotNull); }; 6837 6838 // argument should be either a pointer or null 6839 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6840 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6841 << "first" << ArgTypeA << ArgA->getSourceRange(); 6842 6843 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6844 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6845 << "second" << ArgTypeB << ArgB->getSourceRange(); 6846 6847 // Ensure Pointee types are compatible 6848 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6849 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6850 QualType pointeeA = ArgTypeA->getPointeeType(); 6851 QualType pointeeB = ArgTypeB->getPointeeType(); 6852 if (!Context.typesAreCompatible( 6853 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6854 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6855 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6856 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6857 << ArgB->getSourceRange(); 6858 } 6859 } 6860 6861 // at least one argument should be pointer type 6862 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6863 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6864 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6865 6866 if (isNull(ArgA)) // adopt type of the other pointer 6867 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6868 6869 if (isNull(ArgB)) 6870 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6871 6872 TheCall->setArg(0, ArgExprA.get()); 6873 TheCall->setArg(1, ArgExprB.get()); 6874 TheCall->setType(Context.LongLongTy); 6875 return false; 6876 } 6877 assert(false && "Unhandled ARM MTE intrinsic"); 6878 return true; 6879 } 6880 6881 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6882 /// TheCall is an ARM/AArch64 special register string literal. 6883 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6884 int ArgNum, unsigned ExpectedFieldNum, 6885 bool AllowName) { 6886 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6887 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6888 BuiltinID == ARM::BI__builtin_arm_rsr || 6889 BuiltinID == ARM::BI__builtin_arm_rsrp || 6890 BuiltinID == ARM::BI__builtin_arm_wsr || 6891 BuiltinID == ARM::BI__builtin_arm_wsrp; 6892 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6893 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6894 BuiltinID == AArch64::BI__builtin_arm_rsr || 6895 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6896 BuiltinID == AArch64::BI__builtin_arm_wsr || 6897 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6898 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6899 6900 // We can't check the value of a dependent argument. 6901 Expr *Arg = TheCall->getArg(ArgNum); 6902 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6903 return false; 6904 6905 // Check if the argument is a string literal. 6906 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6907 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6908 << Arg->getSourceRange(); 6909 6910 // Check the type of special register given. 6911 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6912 SmallVector<StringRef, 6> Fields; 6913 Reg.split(Fields, ":"); 6914 6915 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6916 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6917 << Arg->getSourceRange(); 6918 6919 // If the string is the name of a register then we cannot check that it is 6920 // valid here but if the string is of one the forms described in ACLE then we 6921 // can check that the supplied fields are integers and within the valid 6922 // ranges. 6923 if (Fields.size() > 1) { 6924 bool FiveFields = Fields.size() == 5; 6925 6926 bool ValidString = true; 6927 if (IsARMBuiltin) { 6928 ValidString &= Fields[0].startswith_lower("cp") || 6929 Fields[0].startswith_lower("p"); 6930 if (ValidString) 6931 Fields[0] = 6932 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6933 6934 ValidString &= Fields[2].startswith_lower("c"); 6935 if (ValidString) 6936 Fields[2] = Fields[2].drop_front(1); 6937 6938 if (FiveFields) { 6939 ValidString &= Fields[3].startswith_lower("c"); 6940 if (ValidString) 6941 Fields[3] = Fields[3].drop_front(1); 6942 } 6943 } 6944 6945 SmallVector<int, 5> Ranges; 6946 if (FiveFields) 6947 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6948 else 6949 Ranges.append({15, 7, 15}); 6950 6951 for (unsigned i=0; i<Fields.size(); ++i) { 6952 int IntField; 6953 ValidString &= !Fields[i].getAsInteger(10, IntField); 6954 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6955 } 6956 6957 if (!ValidString) 6958 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6959 << Arg->getSourceRange(); 6960 } else if (IsAArch64Builtin && Fields.size() == 1) { 6961 // If the register name is one of those that appear in the condition below 6962 // and the special register builtin being used is one of the write builtins, 6963 // then we require that the argument provided for writing to the register 6964 // is an integer constant expression. This is because it will be lowered to 6965 // an MSR (immediate) instruction, so we need to know the immediate at 6966 // compile time. 6967 if (TheCall->getNumArgs() != 2) 6968 return false; 6969 6970 std::string RegLower = Reg.lower(); 6971 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6972 RegLower != "pan" && RegLower != "uao") 6973 return false; 6974 6975 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6976 } 6977 6978 return false; 6979 } 6980 6981 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 6982 /// Emit an error and return true on failure; return false on success. 6983 /// TypeStr is a string containing the type descriptor of the value returned by 6984 /// the builtin and the descriptors of the expected type of the arguments. 6985 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 6986 6987 assert((TypeStr[0] != '\0') && 6988 "Invalid types in PPC MMA builtin declaration"); 6989 6990 unsigned Mask = 0; 6991 unsigned ArgNum = 0; 6992 6993 // The first type in TypeStr is the type of the value returned by the 6994 // builtin. So we first read that type and change the type of TheCall. 6995 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 6996 TheCall->setType(type); 6997 6998 while (*TypeStr != '\0') { 6999 Mask = 0; 7000 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7001 if (ArgNum >= TheCall->getNumArgs()) { 7002 ArgNum++; 7003 break; 7004 } 7005 7006 Expr *Arg = TheCall->getArg(ArgNum); 7007 QualType ArgType = Arg->getType(); 7008 7009 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 7010 (!ExpectedType->isVoidPointerType() && 7011 ArgType.getCanonicalType() != ExpectedType)) 7012 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 7013 << ArgType << ExpectedType << 1 << 0 << 0; 7014 7015 // If the value of the Mask is not 0, we have a constraint in the size of 7016 // the integer argument so here we ensure the argument is a constant that 7017 // is in the valid range. 7018 if (Mask != 0 && 7019 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7020 return true; 7021 7022 ArgNum++; 7023 } 7024 7025 // In case we exited early from the previous loop, there are other types to 7026 // read from TypeStr. So we need to read them all to ensure we have the right 7027 // number of arguments in TheCall and if it is not the case, to display a 7028 // better error message. 7029 while (*TypeStr != '\0') { 7030 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7031 ArgNum++; 7032 } 7033 if (checkArgCount(*this, TheCall, ArgNum)) 7034 return true; 7035 7036 return false; 7037 } 7038 7039 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7040 /// This checks that the target supports __builtin_longjmp and 7041 /// that val is a constant 1. 7042 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7043 if (!Context.getTargetInfo().hasSjLjLowering()) 7044 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7045 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7046 7047 Expr *Arg = TheCall->getArg(1); 7048 llvm::APSInt Result; 7049 7050 // TODO: This is less than ideal. Overload this to take a value. 7051 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7052 return true; 7053 7054 if (Result != 1) 7055 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7056 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7057 7058 return false; 7059 } 7060 7061 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7062 /// This checks that the target supports __builtin_setjmp. 7063 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7064 if (!Context.getTargetInfo().hasSjLjLowering()) 7065 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7066 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7067 return false; 7068 } 7069 7070 namespace { 7071 7072 class UncoveredArgHandler { 7073 enum { Unknown = -1, AllCovered = -2 }; 7074 7075 signed FirstUncoveredArg = Unknown; 7076 SmallVector<const Expr *, 4> DiagnosticExprs; 7077 7078 public: 7079 UncoveredArgHandler() = default; 7080 7081 bool hasUncoveredArg() const { 7082 return (FirstUncoveredArg >= 0); 7083 } 7084 7085 unsigned getUncoveredArg() const { 7086 assert(hasUncoveredArg() && "no uncovered argument"); 7087 return FirstUncoveredArg; 7088 } 7089 7090 void setAllCovered() { 7091 // A string has been found with all arguments covered, so clear out 7092 // the diagnostics. 7093 DiagnosticExprs.clear(); 7094 FirstUncoveredArg = AllCovered; 7095 } 7096 7097 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7098 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7099 7100 // Don't update if a previous string covers all arguments. 7101 if (FirstUncoveredArg == AllCovered) 7102 return; 7103 7104 // UncoveredArgHandler tracks the highest uncovered argument index 7105 // and with it all the strings that match this index. 7106 if (NewFirstUncoveredArg == FirstUncoveredArg) 7107 DiagnosticExprs.push_back(StrExpr); 7108 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7109 DiagnosticExprs.clear(); 7110 DiagnosticExprs.push_back(StrExpr); 7111 FirstUncoveredArg = NewFirstUncoveredArg; 7112 } 7113 } 7114 7115 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7116 }; 7117 7118 enum StringLiteralCheckType { 7119 SLCT_NotALiteral, 7120 SLCT_UncheckedLiteral, 7121 SLCT_CheckedLiteral 7122 }; 7123 7124 } // namespace 7125 7126 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7127 BinaryOperatorKind BinOpKind, 7128 bool AddendIsRight) { 7129 unsigned BitWidth = Offset.getBitWidth(); 7130 unsigned AddendBitWidth = Addend.getBitWidth(); 7131 // There might be negative interim results. 7132 if (Addend.isUnsigned()) { 7133 Addend = Addend.zext(++AddendBitWidth); 7134 Addend.setIsSigned(true); 7135 } 7136 // Adjust the bit width of the APSInts. 7137 if (AddendBitWidth > BitWidth) { 7138 Offset = Offset.sext(AddendBitWidth); 7139 BitWidth = AddendBitWidth; 7140 } else if (BitWidth > AddendBitWidth) { 7141 Addend = Addend.sext(BitWidth); 7142 } 7143 7144 bool Ov = false; 7145 llvm::APSInt ResOffset = Offset; 7146 if (BinOpKind == BO_Add) 7147 ResOffset = Offset.sadd_ov(Addend, Ov); 7148 else { 7149 assert(AddendIsRight && BinOpKind == BO_Sub && 7150 "operator must be add or sub with addend on the right"); 7151 ResOffset = Offset.ssub_ov(Addend, Ov); 7152 } 7153 7154 // We add an offset to a pointer here so we should support an offset as big as 7155 // possible. 7156 if (Ov) { 7157 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7158 "index (intermediate) result too big"); 7159 Offset = Offset.sext(2 * BitWidth); 7160 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7161 return; 7162 } 7163 7164 Offset = ResOffset; 7165 } 7166 7167 namespace { 7168 7169 // This is a wrapper class around StringLiteral to support offsetted string 7170 // literals as format strings. It takes the offset into account when returning 7171 // the string and its length or the source locations to display notes correctly. 7172 class FormatStringLiteral { 7173 const StringLiteral *FExpr; 7174 int64_t Offset; 7175 7176 public: 7177 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7178 : FExpr(fexpr), Offset(Offset) {} 7179 7180 StringRef getString() const { 7181 return FExpr->getString().drop_front(Offset); 7182 } 7183 7184 unsigned getByteLength() const { 7185 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7186 } 7187 7188 unsigned getLength() const { return FExpr->getLength() - Offset; } 7189 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7190 7191 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7192 7193 QualType getType() const { return FExpr->getType(); } 7194 7195 bool isAscii() const { return FExpr->isAscii(); } 7196 bool isWide() const { return FExpr->isWide(); } 7197 bool isUTF8() const { return FExpr->isUTF8(); } 7198 bool isUTF16() const { return FExpr->isUTF16(); } 7199 bool isUTF32() const { return FExpr->isUTF32(); } 7200 bool isPascal() const { return FExpr->isPascal(); } 7201 7202 SourceLocation getLocationOfByte( 7203 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7204 const TargetInfo &Target, unsigned *StartToken = nullptr, 7205 unsigned *StartTokenByteOffset = nullptr) const { 7206 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7207 StartToken, StartTokenByteOffset); 7208 } 7209 7210 SourceLocation getBeginLoc() const LLVM_READONLY { 7211 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7212 } 7213 7214 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7215 }; 7216 7217 } // namespace 7218 7219 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7220 const Expr *OrigFormatExpr, 7221 ArrayRef<const Expr *> Args, 7222 bool HasVAListArg, unsigned format_idx, 7223 unsigned firstDataArg, 7224 Sema::FormatStringType Type, 7225 bool inFunctionCall, 7226 Sema::VariadicCallType CallType, 7227 llvm::SmallBitVector &CheckedVarArgs, 7228 UncoveredArgHandler &UncoveredArg, 7229 bool IgnoreStringsWithoutSpecifiers); 7230 7231 // Determine if an expression is a string literal or constant string. 7232 // If this function returns false on the arguments to a function expecting a 7233 // format string, we will usually need to emit a warning. 7234 // True string literals are then checked by CheckFormatString. 7235 static StringLiteralCheckType 7236 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7237 bool HasVAListArg, unsigned format_idx, 7238 unsigned firstDataArg, Sema::FormatStringType Type, 7239 Sema::VariadicCallType CallType, bool InFunctionCall, 7240 llvm::SmallBitVector &CheckedVarArgs, 7241 UncoveredArgHandler &UncoveredArg, 7242 llvm::APSInt Offset, 7243 bool IgnoreStringsWithoutSpecifiers = false) { 7244 if (S.isConstantEvaluated()) 7245 return SLCT_NotALiteral; 7246 tryAgain: 7247 assert(Offset.isSigned() && "invalid offset"); 7248 7249 if (E->isTypeDependent() || E->isValueDependent()) 7250 return SLCT_NotALiteral; 7251 7252 E = E->IgnoreParenCasts(); 7253 7254 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7255 // Technically -Wformat-nonliteral does not warn about this case. 7256 // The behavior of printf and friends in this case is implementation 7257 // dependent. Ideally if the format string cannot be null then 7258 // it should have a 'nonnull' attribute in the function prototype. 7259 return SLCT_UncheckedLiteral; 7260 7261 switch (E->getStmtClass()) { 7262 case Stmt::BinaryConditionalOperatorClass: 7263 case Stmt::ConditionalOperatorClass: { 7264 // The expression is a literal if both sub-expressions were, and it was 7265 // completely checked only if both sub-expressions were checked. 7266 const AbstractConditionalOperator *C = 7267 cast<AbstractConditionalOperator>(E); 7268 7269 // Determine whether it is necessary to check both sub-expressions, for 7270 // example, because the condition expression is a constant that can be 7271 // evaluated at compile time. 7272 bool CheckLeft = true, CheckRight = true; 7273 7274 bool Cond; 7275 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7276 S.isConstantEvaluated())) { 7277 if (Cond) 7278 CheckRight = false; 7279 else 7280 CheckLeft = false; 7281 } 7282 7283 // We need to maintain the offsets for the right and the left hand side 7284 // separately to check if every possible indexed expression is a valid 7285 // string literal. They might have different offsets for different string 7286 // literals in the end. 7287 StringLiteralCheckType Left; 7288 if (!CheckLeft) 7289 Left = SLCT_UncheckedLiteral; 7290 else { 7291 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7292 HasVAListArg, format_idx, firstDataArg, 7293 Type, CallType, InFunctionCall, 7294 CheckedVarArgs, UncoveredArg, Offset, 7295 IgnoreStringsWithoutSpecifiers); 7296 if (Left == SLCT_NotALiteral || !CheckRight) { 7297 return Left; 7298 } 7299 } 7300 7301 StringLiteralCheckType Right = checkFormatStringExpr( 7302 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7303 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7304 IgnoreStringsWithoutSpecifiers); 7305 7306 return (CheckLeft && Left < Right) ? Left : Right; 7307 } 7308 7309 case Stmt::ImplicitCastExprClass: 7310 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7311 goto tryAgain; 7312 7313 case Stmt::OpaqueValueExprClass: 7314 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7315 E = src; 7316 goto tryAgain; 7317 } 7318 return SLCT_NotALiteral; 7319 7320 case Stmt::PredefinedExprClass: 7321 // While __func__, etc., are technically not string literals, they 7322 // cannot contain format specifiers and thus are not a security 7323 // liability. 7324 return SLCT_UncheckedLiteral; 7325 7326 case Stmt::DeclRefExprClass: { 7327 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7328 7329 // As an exception, do not flag errors for variables binding to 7330 // const string literals. 7331 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7332 bool isConstant = false; 7333 QualType T = DR->getType(); 7334 7335 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7336 isConstant = AT->getElementType().isConstant(S.Context); 7337 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7338 isConstant = T.isConstant(S.Context) && 7339 PT->getPointeeType().isConstant(S.Context); 7340 } else if (T->isObjCObjectPointerType()) { 7341 // In ObjC, there is usually no "const ObjectPointer" type, 7342 // so don't check if the pointee type is constant. 7343 isConstant = T.isConstant(S.Context); 7344 } 7345 7346 if (isConstant) { 7347 if (const Expr *Init = VD->getAnyInitializer()) { 7348 // Look through initializers like const char c[] = { "foo" } 7349 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7350 if (InitList->isStringLiteralInit()) 7351 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7352 } 7353 return checkFormatStringExpr(S, Init, Args, 7354 HasVAListArg, format_idx, 7355 firstDataArg, Type, CallType, 7356 /*InFunctionCall*/ false, CheckedVarArgs, 7357 UncoveredArg, Offset); 7358 } 7359 } 7360 7361 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7362 // special check to see if the format string is a function parameter 7363 // of the function calling the printf function. If the function 7364 // has an attribute indicating it is a printf-like function, then we 7365 // should suppress warnings concerning non-literals being used in a call 7366 // to a vprintf function. For example: 7367 // 7368 // void 7369 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7370 // va_list ap; 7371 // va_start(ap, fmt); 7372 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7373 // ... 7374 // } 7375 if (HasVAListArg) { 7376 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7377 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7378 int PVIndex = PV->getFunctionScopeIndex() + 1; 7379 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7380 // adjust for implicit parameter 7381 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7382 if (MD->isInstance()) 7383 ++PVIndex; 7384 // We also check if the formats are compatible. 7385 // We can't pass a 'scanf' string to a 'printf' function. 7386 if (PVIndex == PVFormat->getFormatIdx() && 7387 Type == S.GetFormatStringType(PVFormat)) 7388 return SLCT_UncheckedLiteral; 7389 } 7390 } 7391 } 7392 } 7393 } 7394 7395 return SLCT_NotALiteral; 7396 } 7397 7398 case Stmt::CallExprClass: 7399 case Stmt::CXXMemberCallExprClass: { 7400 const CallExpr *CE = cast<CallExpr>(E); 7401 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7402 bool IsFirst = true; 7403 StringLiteralCheckType CommonResult; 7404 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7405 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7406 StringLiteralCheckType Result = checkFormatStringExpr( 7407 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7408 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7409 IgnoreStringsWithoutSpecifiers); 7410 if (IsFirst) { 7411 CommonResult = Result; 7412 IsFirst = false; 7413 } 7414 } 7415 if (!IsFirst) 7416 return CommonResult; 7417 7418 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7419 unsigned BuiltinID = FD->getBuiltinID(); 7420 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7421 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7422 const Expr *Arg = CE->getArg(0); 7423 return checkFormatStringExpr(S, Arg, Args, 7424 HasVAListArg, format_idx, 7425 firstDataArg, Type, CallType, 7426 InFunctionCall, CheckedVarArgs, 7427 UncoveredArg, Offset, 7428 IgnoreStringsWithoutSpecifiers); 7429 } 7430 } 7431 } 7432 7433 return SLCT_NotALiteral; 7434 } 7435 case Stmt::ObjCMessageExprClass: { 7436 const auto *ME = cast<ObjCMessageExpr>(E); 7437 if (const auto *MD = ME->getMethodDecl()) { 7438 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7439 // As a special case heuristic, if we're using the method -[NSBundle 7440 // localizedStringForKey:value:table:], ignore any key strings that lack 7441 // format specifiers. The idea is that if the key doesn't have any 7442 // format specifiers then its probably just a key to map to the 7443 // localized strings. If it does have format specifiers though, then its 7444 // likely that the text of the key is the format string in the 7445 // programmer's language, and should be checked. 7446 const ObjCInterfaceDecl *IFace; 7447 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7448 IFace->getIdentifier()->isStr("NSBundle") && 7449 MD->getSelector().isKeywordSelector( 7450 {"localizedStringForKey", "value", "table"})) { 7451 IgnoreStringsWithoutSpecifiers = true; 7452 } 7453 7454 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7455 return checkFormatStringExpr( 7456 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7457 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7458 IgnoreStringsWithoutSpecifiers); 7459 } 7460 } 7461 7462 return SLCT_NotALiteral; 7463 } 7464 case Stmt::ObjCStringLiteralClass: 7465 case Stmt::StringLiteralClass: { 7466 const StringLiteral *StrE = nullptr; 7467 7468 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7469 StrE = ObjCFExpr->getString(); 7470 else 7471 StrE = cast<StringLiteral>(E); 7472 7473 if (StrE) { 7474 if (Offset.isNegative() || Offset > StrE->getLength()) { 7475 // TODO: It would be better to have an explicit warning for out of 7476 // bounds literals. 7477 return SLCT_NotALiteral; 7478 } 7479 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7480 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7481 firstDataArg, Type, InFunctionCall, CallType, 7482 CheckedVarArgs, UncoveredArg, 7483 IgnoreStringsWithoutSpecifiers); 7484 return SLCT_CheckedLiteral; 7485 } 7486 7487 return SLCT_NotALiteral; 7488 } 7489 case Stmt::BinaryOperatorClass: { 7490 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7491 7492 // A string literal + an int offset is still a string literal. 7493 if (BinOp->isAdditiveOp()) { 7494 Expr::EvalResult LResult, RResult; 7495 7496 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7497 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7498 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7499 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7500 7501 if (LIsInt != RIsInt) { 7502 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7503 7504 if (LIsInt) { 7505 if (BinOpKind == BO_Add) { 7506 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7507 E = BinOp->getRHS(); 7508 goto tryAgain; 7509 } 7510 } else { 7511 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7512 E = BinOp->getLHS(); 7513 goto tryAgain; 7514 } 7515 } 7516 } 7517 7518 return SLCT_NotALiteral; 7519 } 7520 case Stmt::UnaryOperatorClass: { 7521 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7522 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7523 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7524 Expr::EvalResult IndexResult; 7525 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7526 Expr::SE_NoSideEffects, 7527 S.isConstantEvaluated())) { 7528 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7529 /*RHS is int*/ true); 7530 E = ASE->getBase(); 7531 goto tryAgain; 7532 } 7533 } 7534 7535 return SLCT_NotALiteral; 7536 } 7537 7538 default: 7539 return SLCT_NotALiteral; 7540 } 7541 } 7542 7543 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7544 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7545 .Case("scanf", FST_Scanf) 7546 .Cases("printf", "printf0", FST_Printf) 7547 .Cases("NSString", "CFString", FST_NSString) 7548 .Case("strftime", FST_Strftime) 7549 .Case("strfmon", FST_Strfmon) 7550 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7551 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7552 .Case("os_trace", FST_OSLog) 7553 .Case("os_log", FST_OSLog) 7554 .Default(FST_Unknown); 7555 } 7556 7557 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7558 /// functions) for correct use of format strings. 7559 /// Returns true if a format string has been fully checked. 7560 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7561 ArrayRef<const Expr *> Args, 7562 bool IsCXXMember, 7563 VariadicCallType CallType, 7564 SourceLocation Loc, SourceRange Range, 7565 llvm::SmallBitVector &CheckedVarArgs) { 7566 FormatStringInfo FSI; 7567 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7568 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7569 FSI.FirstDataArg, GetFormatStringType(Format), 7570 CallType, Loc, Range, CheckedVarArgs); 7571 return false; 7572 } 7573 7574 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7575 bool HasVAListArg, unsigned format_idx, 7576 unsigned firstDataArg, FormatStringType Type, 7577 VariadicCallType CallType, 7578 SourceLocation Loc, SourceRange Range, 7579 llvm::SmallBitVector &CheckedVarArgs) { 7580 // CHECK: printf/scanf-like function is called with no format string. 7581 if (format_idx >= Args.size()) { 7582 Diag(Loc, diag::warn_missing_format_string) << Range; 7583 return false; 7584 } 7585 7586 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7587 7588 // CHECK: format string is not a string literal. 7589 // 7590 // Dynamically generated format strings are difficult to 7591 // automatically vet at compile time. Requiring that format strings 7592 // are string literals: (1) permits the checking of format strings by 7593 // the compiler and thereby (2) can practically remove the source of 7594 // many format string exploits. 7595 7596 // Format string can be either ObjC string (e.g. @"%d") or 7597 // C string (e.g. "%d") 7598 // ObjC string uses the same format specifiers as C string, so we can use 7599 // the same format string checking logic for both ObjC and C strings. 7600 UncoveredArgHandler UncoveredArg; 7601 StringLiteralCheckType CT = 7602 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7603 format_idx, firstDataArg, Type, CallType, 7604 /*IsFunctionCall*/ true, CheckedVarArgs, 7605 UncoveredArg, 7606 /*no string offset*/ llvm::APSInt(64, false) = 0); 7607 7608 // Generate a diagnostic where an uncovered argument is detected. 7609 if (UncoveredArg.hasUncoveredArg()) { 7610 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7611 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7612 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7613 } 7614 7615 if (CT != SLCT_NotALiteral) 7616 // Literal format string found, check done! 7617 return CT == SLCT_CheckedLiteral; 7618 7619 // Strftime is particular as it always uses a single 'time' argument, 7620 // so it is safe to pass a non-literal string. 7621 if (Type == FST_Strftime) 7622 return false; 7623 7624 // Do not emit diag when the string param is a macro expansion and the 7625 // format is either NSString or CFString. This is a hack to prevent 7626 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7627 // which are usually used in place of NS and CF string literals. 7628 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7629 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7630 return false; 7631 7632 // If there are no arguments specified, warn with -Wformat-security, otherwise 7633 // warn only with -Wformat-nonliteral. 7634 if (Args.size() == firstDataArg) { 7635 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7636 << OrigFormatExpr->getSourceRange(); 7637 switch (Type) { 7638 default: 7639 break; 7640 case FST_Kprintf: 7641 case FST_FreeBSDKPrintf: 7642 case FST_Printf: 7643 Diag(FormatLoc, diag::note_format_security_fixit) 7644 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7645 break; 7646 case FST_NSString: 7647 Diag(FormatLoc, diag::note_format_security_fixit) 7648 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7649 break; 7650 } 7651 } else { 7652 Diag(FormatLoc, diag::warn_format_nonliteral) 7653 << OrigFormatExpr->getSourceRange(); 7654 } 7655 return false; 7656 } 7657 7658 namespace { 7659 7660 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7661 protected: 7662 Sema &S; 7663 const FormatStringLiteral *FExpr; 7664 const Expr *OrigFormatExpr; 7665 const Sema::FormatStringType FSType; 7666 const unsigned FirstDataArg; 7667 const unsigned NumDataArgs; 7668 const char *Beg; // Start of format string. 7669 const bool HasVAListArg; 7670 ArrayRef<const Expr *> Args; 7671 unsigned FormatIdx; 7672 llvm::SmallBitVector CoveredArgs; 7673 bool usesPositionalArgs = false; 7674 bool atFirstArg = true; 7675 bool inFunctionCall; 7676 Sema::VariadicCallType CallType; 7677 llvm::SmallBitVector &CheckedVarArgs; 7678 UncoveredArgHandler &UncoveredArg; 7679 7680 public: 7681 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7682 const Expr *origFormatExpr, 7683 const Sema::FormatStringType type, unsigned firstDataArg, 7684 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7685 ArrayRef<const Expr *> Args, unsigned formatIdx, 7686 bool inFunctionCall, Sema::VariadicCallType callType, 7687 llvm::SmallBitVector &CheckedVarArgs, 7688 UncoveredArgHandler &UncoveredArg) 7689 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7690 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7691 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7692 inFunctionCall(inFunctionCall), CallType(callType), 7693 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7694 CoveredArgs.resize(numDataArgs); 7695 CoveredArgs.reset(); 7696 } 7697 7698 void DoneProcessing(); 7699 7700 void HandleIncompleteSpecifier(const char *startSpecifier, 7701 unsigned specifierLen) override; 7702 7703 void HandleInvalidLengthModifier( 7704 const analyze_format_string::FormatSpecifier &FS, 7705 const analyze_format_string::ConversionSpecifier &CS, 7706 const char *startSpecifier, unsigned specifierLen, 7707 unsigned DiagID); 7708 7709 void HandleNonStandardLengthModifier( 7710 const analyze_format_string::FormatSpecifier &FS, 7711 const char *startSpecifier, unsigned specifierLen); 7712 7713 void HandleNonStandardConversionSpecifier( 7714 const analyze_format_string::ConversionSpecifier &CS, 7715 const char *startSpecifier, unsigned specifierLen); 7716 7717 void HandlePosition(const char *startPos, unsigned posLen) override; 7718 7719 void HandleInvalidPosition(const char *startSpecifier, 7720 unsigned specifierLen, 7721 analyze_format_string::PositionContext p) override; 7722 7723 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7724 7725 void HandleNullChar(const char *nullCharacter) override; 7726 7727 template <typename Range> 7728 static void 7729 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7730 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7731 bool IsStringLocation, Range StringRange, 7732 ArrayRef<FixItHint> Fixit = None); 7733 7734 protected: 7735 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7736 const char *startSpec, 7737 unsigned specifierLen, 7738 const char *csStart, unsigned csLen); 7739 7740 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7741 const char *startSpec, 7742 unsigned specifierLen); 7743 7744 SourceRange getFormatStringRange(); 7745 CharSourceRange getSpecifierRange(const char *startSpecifier, 7746 unsigned specifierLen); 7747 SourceLocation getLocationOfByte(const char *x); 7748 7749 const Expr *getDataArg(unsigned i) const; 7750 7751 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7752 const analyze_format_string::ConversionSpecifier &CS, 7753 const char *startSpecifier, unsigned specifierLen, 7754 unsigned argIndex); 7755 7756 template <typename Range> 7757 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7758 bool IsStringLocation, Range StringRange, 7759 ArrayRef<FixItHint> Fixit = None); 7760 }; 7761 7762 } // namespace 7763 7764 SourceRange CheckFormatHandler::getFormatStringRange() { 7765 return OrigFormatExpr->getSourceRange(); 7766 } 7767 7768 CharSourceRange CheckFormatHandler:: 7769 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7770 SourceLocation Start = getLocationOfByte(startSpecifier); 7771 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7772 7773 // Advance the end SourceLocation by one due to half-open ranges. 7774 End = End.getLocWithOffset(1); 7775 7776 return CharSourceRange::getCharRange(Start, End); 7777 } 7778 7779 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7780 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7781 S.getLangOpts(), S.Context.getTargetInfo()); 7782 } 7783 7784 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7785 unsigned specifierLen){ 7786 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7787 getLocationOfByte(startSpecifier), 7788 /*IsStringLocation*/true, 7789 getSpecifierRange(startSpecifier, specifierLen)); 7790 } 7791 7792 void CheckFormatHandler::HandleInvalidLengthModifier( 7793 const analyze_format_string::FormatSpecifier &FS, 7794 const analyze_format_string::ConversionSpecifier &CS, 7795 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7796 using namespace analyze_format_string; 7797 7798 const LengthModifier &LM = FS.getLengthModifier(); 7799 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7800 7801 // See if we know how to fix this length modifier. 7802 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7803 if (FixedLM) { 7804 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7805 getLocationOfByte(LM.getStart()), 7806 /*IsStringLocation*/true, 7807 getSpecifierRange(startSpecifier, specifierLen)); 7808 7809 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7810 << FixedLM->toString() 7811 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7812 7813 } else { 7814 FixItHint Hint; 7815 if (DiagID == diag::warn_format_nonsensical_length) 7816 Hint = FixItHint::CreateRemoval(LMRange); 7817 7818 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7819 getLocationOfByte(LM.getStart()), 7820 /*IsStringLocation*/true, 7821 getSpecifierRange(startSpecifier, specifierLen), 7822 Hint); 7823 } 7824 } 7825 7826 void CheckFormatHandler::HandleNonStandardLengthModifier( 7827 const analyze_format_string::FormatSpecifier &FS, 7828 const char *startSpecifier, unsigned specifierLen) { 7829 using namespace analyze_format_string; 7830 7831 const LengthModifier &LM = FS.getLengthModifier(); 7832 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7833 7834 // See if we know how to fix this length modifier. 7835 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7836 if (FixedLM) { 7837 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7838 << LM.toString() << 0, 7839 getLocationOfByte(LM.getStart()), 7840 /*IsStringLocation*/true, 7841 getSpecifierRange(startSpecifier, specifierLen)); 7842 7843 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7844 << FixedLM->toString() 7845 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7846 7847 } else { 7848 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7849 << LM.toString() << 0, 7850 getLocationOfByte(LM.getStart()), 7851 /*IsStringLocation*/true, 7852 getSpecifierRange(startSpecifier, specifierLen)); 7853 } 7854 } 7855 7856 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7857 const analyze_format_string::ConversionSpecifier &CS, 7858 const char *startSpecifier, unsigned specifierLen) { 7859 using namespace analyze_format_string; 7860 7861 // See if we know how to fix this conversion specifier. 7862 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7863 if (FixedCS) { 7864 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7865 << CS.toString() << /*conversion specifier*/1, 7866 getLocationOfByte(CS.getStart()), 7867 /*IsStringLocation*/true, 7868 getSpecifierRange(startSpecifier, specifierLen)); 7869 7870 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7871 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7872 << FixedCS->toString() 7873 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7874 } else { 7875 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7876 << CS.toString() << /*conversion specifier*/1, 7877 getLocationOfByte(CS.getStart()), 7878 /*IsStringLocation*/true, 7879 getSpecifierRange(startSpecifier, specifierLen)); 7880 } 7881 } 7882 7883 void CheckFormatHandler::HandlePosition(const char *startPos, 7884 unsigned posLen) { 7885 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7886 getLocationOfByte(startPos), 7887 /*IsStringLocation*/true, 7888 getSpecifierRange(startPos, posLen)); 7889 } 7890 7891 void 7892 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7893 analyze_format_string::PositionContext p) { 7894 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7895 << (unsigned) p, 7896 getLocationOfByte(startPos), /*IsStringLocation*/true, 7897 getSpecifierRange(startPos, posLen)); 7898 } 7899 7900 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7901 unsigned posLen) { 7902 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7903 getLocationOfByte(startPos), 7904 /*IsStringLocation*/true, 7905 getSpecifierRange(startPos, posLen)); 7906 } 7907 7908 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7909 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7910 // The presence of a null character is likely an error. 7911 EmitFormatDiagnostic( 7912 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7913 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7914 getFormatStringRange()); 7915 } 7916 } 7917 7918 // Note that this may return NULL if there was an error parsing or building 7919 // one of the argument expressions. 7920 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7921 return Args[FirstDataArg + i]; 7922 } 7923 7924 void CheckFormatHandler::DoneProcessing() { 7925 // Does the number of data arguments exceed the number of 7926 // format conversions in the format string? 7927 if (!HasVAListArg) { 7928 // Find any arguments that weren't covered. 7929 CoveredArgs.flip(); 7930 signed notCoveredArg = CoveredArgs.find_first(); 7931 if (notCoveredArg >= 0) { 7932 assert((unsigned)notCoveredArg < NumDataArgs); 7933 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7934 } else { 7935 UncoveredArg.setAllCovered(); 7936 } 7937 } 7938 } 7939 7940 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7941 const Expr *ArgExpr) { 7942 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7943 "Invalid state"); 7944 7945 if (!ArgExpr) 7946 return; 7947 7948 SourceLocation Loc = ArgExpr->getBeginLoc(); 7949 7950 if (S.getSourceManager().isInSystemMacro(Loc)) 7951 return; 7952 7953 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7954 for (auto E : DiagnosticExprs) 7955 PDiag << E->getSourceRange(); 7956 7957 CheckFormatHandler::EmitFormatDiagnostic( 7958 S, IsFunctionCall, DiagnosticExprs[0], 7959 PDiag, Loc, /*IsStringLocation*/false, 7960 DiagnosticExprs[0]->getSourceRange()); 7961 } 7962 7963 bool 7964 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7965 SourceLocation Loc, 7966 const char *startSpec, 7967 unsigned specifierLen, 7968 const char *csStart, 7969 unsigned csLen) { 7970 bool keepGoing = true; 7971 if (argIndex < NumDataArgs) { 7972 // Consider the argument coverered, even though the specifier doesn't 7973 // make sense. 7974 CoveredArgs.set(argIndex); 7975 } 7976 else { 7977 // If argIndex exceeds the number of data arguments we 7978 // don't issue a warning because that is just a cascade of warnings (and 7979 // they may have intended '%%' anyway). We don't want to continue processing 7980 // the format string after this point, however, as we will like just get 7981 // gibberish when trying to match arguments. 7982 keepGoing = false; 7983 } 7984 7985 StringRef Specifier(csStart, csLen); 7986 7987 // If the specifier in non-printable, it could be the first byte of a UTF-8 7988 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7989 // hex value. 7990 std::string CodePointStr; 7991 if (!llvm::sys::locale::isPrint(*csStart)) { 7992 llvm::UTF32 CodePoint; 7993 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7994 const llvm::UTF8 *E = 7995 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7996 llvm::ConversionResult Result = 7997 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7998 7999 if (Result != llvm::conversionOK) { 8000 unsigned char FirstChar = *csStart; 8001 CodePoint = (llvm::UTF32)FirstChar; 8002 } 8003 8004 llvm::raw_string_ostream OS(CodePointStr); 8005 if (CodePoint < 256) 8006 OS << "\\x" << llvm::format("%02x", CodePoint); 8007 else if (CodePoint <= 0xFFFF) 8008 OS << "\\u" << llvm::format("%04x", CodePoint); 8009 else 8010 OS << "\\U" << llvm::format("%08x", CodePoint); 8011 OS.flush(); 8012 Specifier = CodePointStr; 8013 } 8014 8015 EmitFormatDiagnostic( 8016 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8017 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8018 8019 return keepGoing; 8020 } 8021 8022 void 8023 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8024 const char *startSpec, 8025 unsigned specifierLen) { 8026 EmitFormatDiagnostic( 8027 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8028 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8029 } 8030 8031 bool 8032 CheckFormatHandler::CheckNumArgs( 8033 const analyze_format_string::FormatSpecifier &FS, 8034 const analyze_format_string::ConversionSpecifier &CS, 8035 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8036 8037 if (argIndex >= NumDataArgs) { 8038 PartialDiagnostic PDiag = FS.usesPositionalArg() 8039 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8040 << (argIndex+1) << NumDataArgs) 8041 : S.PDiag(diag::warn_printf_insufficient_data_args); 8042 EmitFormatDiagnostic( 8043 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8044 getSpecifierRange(startSpecifier, specifierLen)); 8045 8046 // Since more arguments than conversion tokens are given, by extension 8047 // all arguments are covered, so mark this as so. 8048 UncoveredArg.setAllCovered(); 8049 return false; 8050 } 8051 return true; 8052 } 8053 8054 template<typename Range> 8055 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8056 SourceLocation Loc, 8057 bool IsStringLocation, 8058 Range StringRange, 8059 ArrayRef<FixItHint> FixIt) { 8060 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8061 Loc, IsStringLocation, StringRange, FixIt); 8062 } 8063 8064 /// If the format string is not within the function call, emit a note 8065 /// so that the function call and string are in diagnostic messages. 8066 /// 8067 /// \param InFunctionCall if true, the format string is within the function 8068 /// call and only one diagnostic message will be produced. Otherwise, an 8069 /// extra note will be emitted pointing to location of the format string. 8070 /// 8071 /// \param ArgumentExpr the expression that is passed as the format string 8072 /// argument in the function call. Used for getting locations when two 8073 /// diagnostics are emitted. 8074 /// 8075 /// \param PDiag the callee should already have provided any strings for the 8076 /// diagnostic message. This function only adds locations and fixits 8077 /// to diagnostics. 8078 /// 8079 /// \param Loc primary location for diagnostic. If two diagnostics are 8080 /// required, one will be at Loc and a new SourceLocation will be created for 8081 /// the other one. 8082 /// 8083 /// \param IsStringLocation if true, Loc points to the format string should be 8084 /// used for the note. Otherwise, Loc points to the argument list and will 8085 /// be used with PDiag. 8086 /// 8087 /// \param StringRange some or all of the string to highlight. This is 8088 /// templated so it can accept either a CharSourceRange or a SourceRange. 8089 /// 8090 /// \param FixIt optional fix it hint for the format string. 8091 template <typename Range> 8092 void CheckFormatHandler::EmitFormatDiagnostic( 8093 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8094 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8095 Range StringRange, ArrayRef<FixItHint> FixIt) { 8096 if (InFunctionCall) { 8097 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8098 D << StringRange; 8099 D << FixIt; 8100 } else { 8101 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8102 << ArgumentExpr->getSourceRange(); 8103 8104 const Sema::SemaDiagnosticBuilder &Note = 8105 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8106 diag::note_format_string_defined); 8107 8108 Note << StringRange; 8109 Note << FixIt; 8110 } 8111 } 8112 8113 //===--- CHECK: Printf format string checking ------------------------------===// 8114 8115 namespace { 8116 8117 class CheckPrintfHandler : public CheckFormatHandler { 8118 public: 8119 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8120 const Expr *origFormatExpr, 8121 const Sema::FormatStringType type, unsigned firstDataArg, 8122 unsigned numDataArgs, bool isObjC, const char *beg, 8123 bool hasVAListArg, ArrayRef<const Expr *> Args, 8124 unsigned formatIdx, bool inFunctionCall, 8125 Sema::VariadicCallType CallType, 8126 llvm::SmallBitVector &CheckedVarArgs, 8127 UncoveredArgHandler &UncoveredArg) 8128 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8129 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8130 inFunctionCall, CallType, CheckedVarArgs, 8131 UncoveredArg) {} 8132 8133 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8134 8135 /// Returns true if '%@' specifiers are allowed in the format string. 8136 bool allowsObjCArg() const { 8137 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8138 FSType == Sema::FST_OSTrace; 8139 } 8140 8141 bool HandleInvalidPrintfConversionSpecifier( 8142 const analyze_printf::PrintfSpecifier &FS, 8143 const char *startSpecifier, 8144 unsigned specifierLen) override; 8145 8146 void handleInvalidMaskType(StringRef MaskType) override; 8147 8148 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8149 const char *startSpecifier, 8150 unsigned specifierLen) override; 8151 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8152 const char *StartSpecifier, 8153 unsigned SpecifierLen, 8154 const Expr *E); 8155 8156 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8157 const char *startSpecifier, unsigned specifierLen); 8158 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8159 const analyze_printf::OptionalAmount &Amt, 8160 unsigned type, 8161 const char *startSpecifier, unsigned specifierLen); 8162 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8163 const analyze_printf::OptionalFlag &flag, 8164 const char *startSpecifier, unsigned specifierLen); 8165 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8166 const analyze_printf::OptionalFlag &ignoredFlag, 8167 const analyze_printf::OptionalFlag &flag, 8168 const char *startSpecifier, unsigned specifierLen); 8169 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8170 const Expr *E); 8171 8172 void HandleEmptyObjCModifierFlag(const char *startFlag, 8173 unsigned flagLen) override; 8174 8175 void HandleInvalidObjCModifierFlag(const char *startFlag, 8176 unsigned flagLen) override; 8177 8178 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8179 const char *flagsEnd, 8180 const char *conversionPosition) 8181 override; 8182 }; 8183 8184 } // namespace 8185 8186 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8187 const analyze_printf::PrintfSpecifier &FS, 8188 const char *startSpecifier, 8189 unsigned specifierLen) { 8190 const analyze_printf::PrintfConversionSpecifier &CS = 8191 FS.getConversionSpecifier(); 8192 8193 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8194 getLocationOfByte(CS.getStart()), 8195 startSpecifier, specifierLen, 8196 CS.getStart(), CS.getLength()); 8197 } 8198 8199 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8200 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8201 } 8202 8203 bool CheckPrintfHandler::HandleAmount( 8204 const analyze_format_string::OptionalAmount &Amt, 8205 unsigned k, const char *startSpecifier, 8206 unsigned specifierLen) { 8207 if (Amt.hasDataArgument()) { 8208 if (!HasVAListArg) { 8209 unsigned argIndex = Amt.getArgIndex(); 8210 if (argIndex >= NumDataArgs) { 8211 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8212 << k, 8213 getLocationOfByte(Amt.getStart()), 8214 /*IsStringLocation*/true, 8215 getSpecifierRange(startSpecifier, specifierLen)); 8216 // Don't do any more checking. We will just emit 8217 // spurious errors. 8218 return false; 8219 } 8220 8221 // Type check the data argument. It should be an 'int'. 8222 // Although not in conformance with C99, we also allow the argument to be 8223 // an 'unsigned int' as that is a reasonably safe case. GCC also 8224 // doesn't emit a warning for that case. 8225 CoveredArgs.set(argIndex); 8226 const Expr *Arg = getDataArg(argIndex); 8227 if (!Arg) 8228 return false; 8229 8230 QualType T = Arg->getType(); 8231 8232 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8233 assert(AT.isValid()); 8234 8235 if (!AT.matchesType(S.Context, T)) { 8236 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8237 << k << AT.getRepresentativeTypeName(S.Context) 8238 << T << Arg->getSourceRange(), 8239 getLocationOfByte(Amt.getStart()), 8240 /*IsStringLocation*/true, 8241 getSpecifierRange(startSpecifier, specifierLen)); 8242 // Don't do any more checking. We will just emit 8243 // spurious errors. 8244 return false; 8245 } 8246 } 8247 } 8248 return true; 8249 } 8250 8251 void CheckPrintfHandler::HandleInvalidAmount( 8252 const analyze_printf::PrintfSpecifier &FS, 8253 const analyze_printf::OptionalAmount &Amt, 8254 unsigned type, 8255 const char *startSpecifier, 8256 unsigned specifierLen) { 8257 const analyze_printf::PrintfConversionSpecifier &CS = 8258 FS.getConversionSpecifier(); 8259 8260 FixItHint fixit = 8261 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8262 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8263 Amt.getConstantLength())) 8264 : FixItHint(); 8265 8266 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8267 << type << CS.toString(), 8268 getLocationOfByte(Amt.getStart()), 8269 /*IsStringLocation*/true, 8270 getSpecifierRange(startSpecifier, specifierLen), 8271 fixit); 8272 } 8273 8274 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8275 const analyze_printf::OptionalFlag &flag, 8276 const char *startSpecifier, 8277 unsigned specifierLen) { 8278 // Warn about pointless flag with a fixit removal. 8279 const analyze_printf::PrintfConversionSpecifier &CS = 8280 FS.getConversionSpecifier(); 8281 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8282 << flag.toString() << CS.toString(), 8283 getLocationOfByte(flag.getPosition()), 8284 /*IsStringLocation*/true, 8285 getSpecifierRange(startSpecifier, specifierLen), 8286 FixItHint::CreateRemoval( 8287 getSpecifierRange(flag.getPosition(), 1))); 8288 } 8289 8290 void CheckPrintfHandler::HandleIgnoredFlag( 8291 const analyze_printf::PrintfSpecifier &FS, 8292 const analyze_printf::OptionalFlag &ignoredFlag, 8293 const analyze_printf::OptionalFlag &flag, 8294 const char *startSpecifier, 8295 unsigned specifierLen) { 8296 // Warn about ignored flag with a fixit removal. 8297 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8298 << ignoredFlag.toString() << flag.toString(), 8299 getLocationOfByte(ignoredFlag.getPosition()), 8300 /*IsStringLocation*/true, 8301 getSpecifierRange(startSpecifier, specifierLen), 8302 FixItHint::CreateRemoval( 8303 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8304 } 8305 8306 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8307 unsigned flagLen) { 8308 // Warn about an empty flag. 8309 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8310 getLocationOfByte(startFlag), 8311 /*IsStringLocation*/true, 8312 getSpecifierRange(startFlag, flagLen)); 8313 } 8314 8315 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8316 unsigned flagLen) { 8317 // Warn about an invalid flag. 8318 auto Range = getSpecifierRange(startFlag, flagLen); 8319 StringRef flag(startFlag, flagLen); 8320 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8321 getLocationOfByte(startFlag), 8322 /*IsStringLocation*/true, 8323 Range, FixItHint::CreateRemoval(Range)); 8324 } 8325 8326 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8327 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8328 // Warn about using '[...]' without a '@' conversion. 8329 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8330 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8331 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8332 getLocationOfByte(conversionPosition), 8333 /*IsStringLocation*/true, 8334 Range, FixItHint::CreateRemoval(Range)); 8335 } 8336 8337 // Determines if the specified is a C++ class or struct containing 8338 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8339 // "c_str()"). 8340 template<typename MemberKind> 8341 static llvm::SmallPtrSet<MemberKind*, 1> 8342 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8343 const RecordType *RT = Ty->getAs<RecordType>(); 8344 llvm::SmallPtrSet<MemberKind*, 1> Results; 8345 8346 if (!RT) 8347 return Results; 8348 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8349 if (!RD || !RD->getDefinition()) 8350 return Results; 8351 8352 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8353 Sema::LookupMemberName); 8354 R.suppressDiagnostics(); 8355 8356 // We just need to include all members of the right kind turned up by the 8357 // filter, at this point. 8358 if (S.LookupQualifiedName(R, RT->getDecl())) 8359 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8360 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8361 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8362 Results.insert(FK); 8363 } 8364 return Results; 8365 } 8366 8367 /// Check if we could call '.c_str()' on an object. 8368 /// 8369 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8370 /// allow the call, or if it would be ambiguous). 8371 bool Sema::hasCStrMethod(const Expr *E) { 8372 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8373 8374 MethodSet Results = 8375 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8376 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8377 MI != ME; ++MI) 8378 if ((*MI)->getMinRequiredArguments() == 0) 8379 return true; 8380 return false; 8381 } 8382 8383 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8384 // better diagnostic if so. AT is assumed to be valid. 8385 // Returns true when a c_str() conversion method is found. 8386 bool CheckPrintfHandler::checkForCStrMembers( 8387 const analyze_printf::ArgType &AT, const Expr *E) { 8388 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8389 8390 MethodSet Results = 8391 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8392 8393 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8394 MI != ME; ++MI) { 8395 const CXXMethodDecl *Method = *MI; 8396 if (Method->getMinRequiredArguments() == 0 && 8397 AT.matchesType(S.Context, Method->getReturnType())) { 8398 // FIXME: Suggest parens if the expression needs them. 8399 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8400 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8401 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8402 return true; 8403 } 8404 } 8405 8406 return false; 8407 } 8408 8409 bool 8410 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8411 &FS, 8412 const char *startSpecifier, 8413 unsigned specifierLen) { 8414 using namespace analyze_format_string; 8415 using namespace analyze_printf; 8416 8417 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8418 8419 if (FS.consumesDataArgument()) { 8420 if (atFirstArg) { 8421 atFirstArg = false; 8422 usesPositionalArgs = FS.usesPositionalArg(); 8423 } 8424 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8425 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8426 startSpecifier, specifierLen); 8427 return false; 8428 } 8429 } 8430 8431 // First check if the field width, precision, and conversion specifier 8432 // have matching data arguments. 8433 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8434 startSpecifier, specifierLen)) { 8435 return false; 8436 } 8437 8438 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8439 startSpecifier, specifierLen)) { 8440 return false; 8441 } 8442 8443 if (!CS.consumesDataArgument()) { 8444 // FIXME: Technically specifying a precision or field width here 8445 // makes no sense. Worth issuing a warning at some point. 8446 return true; 8447 } 8448 8449 // Consume the argument. 8450 unsigned argIndex = FS.getArgIndex(); 8451 if (argIndex < NumDataArgs) { 8452 // The check to see if the argIndex is valid will come later. 8453 // We set the bit here because we may exit early from this 8454 // function if we encounter some other error. 8455 CoveredArgs.set(argIndex); 8456 } 8457 8458 // FreeBSD kernel extensions. 8459 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8460 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8461 // We need at least two arguments. 8462 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8463 return false; 8464 8465 // Claim the second argument. 8466 CoveredArgs.set(argIndex + 1); 8467 8468 // Type check the first argument (int for %b, pointer for %D) 8469 const Expr *Ex = getDataArg(argIndex); 8470 const analyze_printf::ArgType &AT = 8471 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8472 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8473 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8474 EmitFormatDiagnostic( 8475 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8476 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8477 << false << Ex->getSourceRange(), 8478 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8479 getSpecifierRange(startSpecifier, specifierLen)); 8480 8481 // Type check the second argument (char * for both %b and %D) 8482 Ex = getDataArg(argIndex + 1); 8483 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8484 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8485 EmitFormatDiagnostic( 8486 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8487 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8488 << false << Ex->getSourceRange(), 8489 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8490 getSpecifierRange(startSpecifier, specifierLen)); 8491 8492 return true; 8493 } 8494 8495 // Check for using an Objective-C specific conversion specifier 8496 // in a non-ObjC literal. 8497 if (!allowsObjCArg() && CS.isObjCArg()) { 8498 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8499 specifierLen); 8500 } 8501 8502 // %P can only be used with os_log. 8503 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8504 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8505 specifierLen); 8506 } 8507 8508 // %n is not allowed with os_log. 8509 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8510 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8511 getLocationOfByte(CS.getStart()), 8512 /*IsStringLocation*/ false, 8513 getSpecifierRange(startSpecifier, specifierLen)); 8514 8515 return true; 8516 } 8517 8518 // Only scalars are allowed for os_trace. 8519 if (FSType == Sema::FST_OSTrace && 8520 (CS.getKind() == ConversionSpecifier::PArg || 8521 CS.getKind() == ConversionSpecifier::sArg || 8522 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8523 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8524 specifierLen); 8525 } 8526 8527 // Check for use of public/private annotation outside of os_log(). 8528 if (FSType != Sema::FST_OSLog) { 8529 if (FS.isPublic().isSet()) { 8530 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8531 << "public", 8532 getLocationOfByte(FS.isPublic().getPosition()), 8533 /*IsStringLocation*/ false, 8534 getSpecifierRange(startSpecifier, specifierLen)); 8535 } 8536 if (FS.isPrivate().isSet()) { 8537 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8538 << "private", 8539 getLocationOfByte(FS.isPrivate().getPosition()), 8540 /*IsStringLocation*/ false, 8541 getSpecifierRange(startSpecifier, specifierLen)); 8542 } 8543 } 8544 8545 // Check for invalid use of field width 8546 if (!FS.hasValidFieldWidth()) { 8547 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8548 startSpecifier, specifierLen); 8549 } 8550 8551 // Check for invalid use of precision 8552 if (!FS.hasValidPrecision()) { 8553 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8554 startSpecifier, specifierLen); 8555 } 8556 8557 // Precision is mandatory for %P specifier. 8558 if (CS.getKind() == ConversionSpecifier::PArg && 8559 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8560 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8561 getLocationOfByte(startSpecifier), 8562 /*IsStringLocation*/ false, 8563 getSpecifierRange(startSpecifier, specifierLen)); 8564 } 8565 8566 // Check each flag does not conflict with any other component. 8567 if (!FS.hasValidThousandsGroupingPrefix()) 8568 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8569 if (!FS.hasValidLeadingZeros()) 8570 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8571 if (!FS.hasValidPlusPrefix()) 8572 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8573 if (!FS.hasValidSpacePrefix()) 8574 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8575 if (!FS.hasValidAlternativeForm()) 8576 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8577 if (!FS.hasValidLeftJustified()) 8578 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8579 8580 // Check that flags are not ignored by another flag 8581 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8582 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8583 startSpecifier, specifierLen); 8584 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8585 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8586 startSpecifier, specifierLen); 8587 8588 // Check the length modifier is valid with the given conversion specifier. 8589 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8590 S.getLangOpts())) 8591 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8592 diag::warn_format_nonsensical_length); 8593 else if (!FS.hasStandardLengthModifier()) 8594 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8595 else if (!FS.hasStandardLengthConversionCombination()) 8596 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8597 diag::warn_format_non_standard_conversion_spec); 8598 8599 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8600 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8601 8602 // The remaining checks depend on the data arguments. 8603 if (HasVAListArg) 8604 return true; 8605 8606 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8607 return false; 8608 8609 const Expr *Arg = getDataArg(argIndex); 8610 if (!Arg) 8611 return true; 8612 8613 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8614 } 8615 8616 static bool requiresParensToAddCast(const Expr *E) { 8617 // FIXME: We should have a general way to reason about operator 8618 // precedence and whether parens are actually needed here. 8619 // Take care of a few common cases where they aren't. 8620 const Expr *Inside = E->IgnoreImpCasts(); 8621 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8622 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8623 8624 switch (Inside->getStmtClass()) { 8625 case Stmt::ArraySubscriptExprClass: 8626 case Stmt::CallExprClass: 8627 case Stmt::CharacterLiteralClass: 8628 case Stmt::CXXBoolLiteralExprClass: 8629 case Stmt::DeclRefExprClass: 8630 case Stmt::FloatingLiteralClass: 8631 case Stmt::IntegerLiteralClass: 8632 case Stmt::MemberExprClass: 8633 case Stmt::ObjCArrayLiteralClass: 8634 case Stmt::ObjCBoolLiteralExprClass: 8635 case Stmt::ObjCBoxedExprClass: 8636 case Stmt::ObjCDictionaryLiteralClass: 8637 case Stmt::ObjCEncodeExprClass: 8638 case Stmt::ObjCIvarRefExprClass: 8639 case Stmt::ObjCMessageExprClass: 8640 case Stmt::ObjCPropertyRefExprClass: 8641 case Stmt::ObjCStringLiteralClass: 8642 case Stmt::ObjCSubscriptRefExprClass: 8643 case Stmt::ParenExprClass: 8644 case Stmt::StringLiteralClass: 8645 case Stmt::UnaryOperatorClass: 8646 return false; 8647 default: 8648 return true; 8649 } 8650 } 8651 8652 static std::pair<QualType, StringRef> 8653 shouldNotPrintDirectly(const ASTContext &Context, 8654 QualType IntendedTy, 8655 const Expr *E) { 8656 // Use a 'while' to peel off layers of typedefs. 8657 QualType TyTy = IntendedTy; 8658 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8659 StringRef Name = UserTy->getDecl()->getName(); 8660 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8661 .Case("CFIndex", Context.getNSIntegerType()) 8662 .Case("NSInteger", Context.getNSIntegerType()) 8663 .Case("NSUInteger", Context.getNSUIntegerType()) 8664 .Case("SInt32", Context.IntTy) 8665 .Case("UInt32", Context.UnsignedIntTy) 8666 .Default(QualType()); 8667 8668 if (!CastTy.isNull()) 8669 return std::make_pair(CastTy, Name); 8670 8671 TyTy = UserTy->desugar(); 8672 } 8673 8674 // Strip parens if necessary. 8675 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8676 return shouldNotPrintDirectly(Context, 8677 PE->getSubExpr()->getType(), 8678 PE->getSubExpr()); 8679 8680 // If this is a conditional expression, then its result type is constructed 8681 // via usual arithmetic conversions and thus there might be no necessary 8682 // typedef sugar there. Recurse to operands to check for NSInteger & 8683 // Co. usage condition. 8684 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8685 QualType TrueTy, FalseTy; 8686 StringRef TrueName, FalseName; 8687 8688 std::tie(TrueTy, TrueName) = 8689 shouldNotPrintDirectly(Context, 8690 CO->getTrueExpr()->getType(), 8691 CO->getTrueExpr()); 8692 std::tie(FalseTy, FalseName) = 8693 shouldNotPrintDirectly(Context, 8694 CO->getFalseExpr()->getType(), 8695 CO->getFalseExpr()); 8696 8697 if (TrueTy == FalseTy) 8698 return std::make_pair(TrueTy, TrueName); 8699 else if (TrueTy.isNull()) 8700 return std::make_pair(FalseTy, FalseName); 8701 else if (FalseTy.isNull()) 8702 return std::make_pair(TrueTy, TrueName); 8703 } 8704 8705 return std::make_pair(QualType(), StringRef()); 8706 } 8707 8708 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8709 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8710 /// type do not count. 8711 static bool 8712 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8713 QualType From = ICE->getSubExpr()->getType(); 8714 QualType To = ICE->getType(); 8715 // It's an integer promotion if the destination type is the promoted 8716 // source type. 8717 if (ICE->getCastKind() == CK_IntegralCast && 8718 From->isPromotableIntegerType() && 8719 S.Context.getPromotedIntegerType(From) == To) 8720 return true; 8721 // Look through vector types, since we do default argument promotion for 8722 // those in OpenCL. 8723 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8724 From = VecTy->getElementType(); 8725 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8726 To = VecTy->getElementType(); 8727 // It's a floating promotion if the source type is a lower rank. 8728 return ICE->getCastKind() == CK_FloatingCast && 8729 S.Context.getFloatingTypeOrder(From, To) < 0; 8730 } 8731 8732 bool 8733 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8734 const char *StartSpecifier, 8735 unsigned SpecifierLen, 8736 const Expr *E) { 8737 using namespace analyze_format_string; 8738 using namespace analyze_printf; 8739 8740 // Now type check the data expression that matches the 8741 // format specifier. 8742 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8743 if (!AT.isValid()) 8744 return true; 8745 8746 QualType ExprTy = E->getType(); 8747 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8748 ExprTy = TET->getUnderlyingExpr()->getType(); 8749 } 8750 8751 // Diagnose attempts to print a boolean value as a character. Unlike other 8752 // -Wformat diagnostics, this is fine from a type perspective, but it still 8753 // doesn't make sense. 8754 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8755 E->isKnownToHaveBooleanValue()) { 8756 const CharSourceRange &CSR = 8757 getSpecifierRange(StartSpecifier, SpecifierLen); 8758 SmallString<4> FSString; 8759 llvm::raw_svector_ostream os(FSString); 8760 FS.toString(os); 8761 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8762 << FSString, 8763 E->getExprLoc(), false, CSR); 8764 return true; 8765 } 8766 8767 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8768 if (Match == analyze_printf::ArgType::Match) 8769 return true; 8770 8771 // Look through argument promotions for our error message's reported type. 8772 // This includes the integral and floating promotions, but excludes array 8773 // and function pointer decay (seeing that an argument intended to be a 8774 // string has type 'char [6]' is probably more confusing than 'char *') and 8775 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8776 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8777 if (isArithmeticArgumentPromotion(S, ICE)) { 8778 E = ICE->getSubExpr(); 8779 ExprTy = E->getType(); 8780 8781 // Check if we didn't match because of an implicit cast from a 'char' 8782 // or 'short' to an 'int'. This is done because printf is a varargs 8783 // function. 8784 if (ICE->getType() == S.Context.IntTy || 8785 ICE->getType() == S.Context.UnsignedIntTy) { 8786 // All further checking is done on the subexpression 8787 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8788 AT.matchesType(S.Context, ExprTy); 8789 if (ImplicitMatch == analyze_printf::ArgType::Match) 8790 return true; 8791 if (ImplicitMatch == ArgType::NoMatchPedantic || 8792 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8793 Match = ImplicitMatch; 8794 } 8795 } 8796 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8797 // Special case for 'a', which has type 'int' in C. 8798 // Note, however, that we do /not/ want to treat multibyte constants like 8799 // 'MooV' as characters! This form is deprecated but still exists. In 8800 // addition, don't treat expressions as of type 'char' if one byte length 8801 // modifier is provided. 8802 if (ExprTy == S.Context.IntTy && 8803 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 8804 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8805 ExprTy = S.Context.CharTy; 8806 } 8807 8808 // Look through enums to their underlying type. 8809 bool IsEnum = false; 8810 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8811 ExprTy = EnumTy->getDecl()->getIntegerType(); 8812 IsEnum = true; 8813 } 8814 8815 // %C in an Objective-C context prints a unichar, not a wchar_t. 8816 // If the argument is an integer of some kind, believe the %C and suggest 8817 // a cast instead of changing the conversion specifier. 8818 QualType IntendedTy = ExprTy; 8819 if (isObjCContext() && 8820 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8821 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8822 !ExprTy->isCharType()) { 8823 // 'unichar' is defined as a typedef of unsigned short, but we should 8824 // prefer using the typedef if it is visible. 8825 IntendedTy = S.Context.UnsignedShortTy; 8826 8827 // While we are here, check if the value is an IntegerLiteral that happens 8828 // to be within the valid range. 8829 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8830 const llvm::APInt &V = IL->getValue(); 8831 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8832 return true; 8833 } 8834 8835 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8836 Sema::LookupOrdinaryName); 8837 if (S.LookupName(Result, S.getCurScope())) { 8838 NamedDecl *ND = Result.getFoundDecl(); 8839 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8840 if (TD->getUnderlyingType() == IntendedTy) 8841 IntendedTy = S.Context.getTypedefType(TD); 8842 } 8843 } 8844 } 8845 8846 // Special-case some of Darwin's platform-independence types by suggesting 8847 // casts to primitive types that are known to be large enough. 8848 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8849 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8850 QualType CastTy; 8851 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8852 if (!CastTy.isNull()) { 8853 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8854 // (long in ASTContext). Only complain to pedants. 8855 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8856 (AT.isSizeT() || AT.isPtrdiffT()) && 8857 AT.matchesType(S.Context, CastTy)) 8858 Match = ArgType::NoMatchPedantic; 8859 IntendedTy = CastTy; 8860 ShouldNotPrintDirectly = true; 8861 } 8862 } 8863 8864 // We may be able to offer a FixItHint if it is a supported type. 8865 PrintfSpecifier fixedFS = FS; 8866 bool Success = 8867 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8868 8869 if (Success) { 8870 // Get the fix string from the fixed format specifier 8871 SmallString<16> buf; 8872 llvm::raw_svector_ostream os(buf); 8873 fixedFS.toString(os); 8874 8875 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8876 8877 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8878 unsigned Diag; 8879 switch (Match) { 8880 case ArgType::Match: llvm_unreachable("expected non-matching"); 8881 case ArgType::NoMatchPedantic: 8882 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8883 break; 8884 case ArgType::NoMatchTypeConfusion: 8885 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8886 break; 8887 case ArgType::NoMatch: 8888 Diag = diag::warn_format_conversion_argument_type_mismatch; 8889 break; 8890 } 8891 8892 // In this case, the specifier is wrong and should be changed to match 8893 // the argument. 8894 EmitFormatDiagnostic(S.PDiag(Diag) 8895 << AT.getRepresentativeTypeName(S.Context) 8896 << IntendedTy << IsEnum << E->getSourceRange(), 8897 E->getBeginLoc(), 8898 /*IsStringLocation*/ false, SpecRange, 8899 FixItHint::CreateReplacement(SpecRange, os.str())); 8900 } else { 8901 // The canonical type for formatting this value is different from the 8902 // actual type of the expression. (This occurs, for example, with Darwin's 8903 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8904 // should be printed as 'long' for 64-bit compatibility.) 8905 // Rather than emitting a normal format/argument mismatch, we want to 8906 // add a cast to the recommended type (and correct the format string 8907 // if necessary). 8908 SmallString<16> CastBuf; 8909 llvm::raw_svector_ostream CastFix(CastBuf); 8910 CastFix << "("; 8911 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8912 CastFix << ")"; 8913 8914 SmallVector<FixItHint,4> Hints; 8915 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8916 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8917 8918 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8919 // If there's already a cast present, just replace it. 8920 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8921 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8922 8923 } else if (!requiresParensToAddCast(E)) { 8924 // If the expression has high enough precedence, 8925 // just write the C-style cast. 8926 Hints.push_back( 8927 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8928 } else { 8929 // Otherwise, add parens around the expression as well as the cast. 8930 CastFix << "("; 8931 Hints.push_back( 8932 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8933 8934 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8935 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8936 } 8937 8938 if (ShouldNotPrintDirectly) { 8939 // The expression has a type that should not be printed directly. 8940 // We extract the name from the typedef because we don't want to show 8941 // the underlying type in the diagnostic. 8942 StringRef Name; 8943 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8944 Name = TypedefTy->getDecl()->getName(); 8945 else 8946 Name = CastTyName; 8947 unsigned Diag = Match == ArgType::NoMatchPedantic 8948 ? diag::warn_format_argument_needs_cast_pedantic 8949 : diag::warn_format_argument_needs_cast; 8950 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8951 << E->getSourceRange(), 8952 E->getBeginLoc(), /*IsStringLocation=*/false, 8953 SpecRange, Hints); 8954 } else { 8955 // In this case, the expression could be printed using a different 8956 // specifier, but we've decided that the specifier is probably correct 8957 // and we should cast instead. Just use the normal warning message. 8958 EmitFormatDiagnostic( 8959 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8960 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8961 << E->getSourceRange(), 8962 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8963 } 8964 } 8965 } else { 8966 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8967 SpecifierLen); 8968 // Since the warning for passing non-POD types to variadic functions 8969 // was deferred until now, we emit a warning for non-POD 8970 // arguments here. 8971 switch (S.isValidVarArgType(ExprTy)) { 8972 case Sema::VAK_Valid: 8973 case Sema::VAK_ValidInCXX11: { 8974 unsigned Diag; 8975 switch (Match) { 8976 case ArgType::Match: llvm_unreachable("expected non-matching"); 8977 case ArgType::NoMatchPedantic: 8978 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8979 break; 8980 case ArgType::NoMatchTypeConfusion: 8981 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8982 break; 8983 case ArgType::NoMatch: 8984 Diag = diag::warn_format_conversion_argument_type_mismatch; 8985 break; 8986 } 8987 8988 EmitFormatDiagnostic( 8989 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8990 << IsEnum << CSR << E->getSourceRange(), 8991 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8992 break; 8993 } 8994 case Sema::VAK_Undefined: 8995 case Sema::VAK_MSVCUndefined: 8996 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8997 << S.getLangOpts().CPlusPlus11 << ExprTy 8998 << CallType 8999 << AT.getRepresentativeTypeName(S.Context) << CSR 9000 << E->getSourceRange(), 9001 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9002 checkForCStrMembers(AT, E); 9003 break; 9004 9005 case Sema::VAK_Invalid: 9006 if (ExprTy->isObjCObjectType()) 9007 EmitFormatDiagnostic( 9008 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9009 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9010 << AT.getRepresentativeTypeName(S.Context) << CSR 9011 << E->getSourceRange(), 9012 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9013 else 9014 // FIXME: If this is an initializer list, suggest removing the braces 9015 // or inserting a cast to the target type. 9016 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9017 << isa<InitListExpr>(E) << ExprTy << CallType 9018 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9019 break; 9020 } 9021 9022 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9023 "format string specifier index out of range"); 9024 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9025 } 9026 9027 return true; 9028 } 9029 9030 //===--- CHECK: Scanf format string checking ------------------------------===// 9031 9032 namespace { 9033 9034 class CheckScanfHandler : public CheckFormatHandler { 9035 public: 9036 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9037 const Expr *origFormatExpr, Sema::FormatStringType type, 9038 unsigned firstDataArg, unsigned numDataArgs, 9039 const char *beg, bool hasVAListArg, 9040 ArrayRef<const Expr *> Args, unsigned formatIdx, 9041 bool inFunctionCall, Sema::VariadicCallType CallType, 9042 llvm::SmallBitVector &CheckedVarArgs, 9043 UncoveredArgHandler &UncoveredArg) 9044 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9045 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9046 inFunctionCall, CallType, CheckedVarArgs, 9047 UncoveredArg) {} 9048 9049 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9050 const char *startSpecifier, 9051 unsigned specifierLen) override; 9052 9053 bool HandleInvalidScanfConversionSpecifier( 9054 const analyze_scanf::ScanfSpecifier &FS, 9055 const char *startSpecifier, 9056 unsigned specifierLen) override; 9057 9058 void HandleIncompleteScanList(const char *start, const char *end) override; 9059 }; 9060 9061 } // namespace 9062 9063 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9064 const char *end) { 9065 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9066 getLocationOfByte(end), /*IsStringLocation*/true, 9067 getSpecifierRange(start, end - start)); 9068 } 9069 9070 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9071 const analyze_scanf::ScanfSpecifier &FS, 9072 const char *startSpecifier, 9073 unsigned specifierLen) { 9074 const analyze_scanf::ScanfConversionSpecifier &CS = 9075 FS.getConversionSpecifier(); 9076 9077 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9078 getLocationOfByte(CS.getStart()), 9079 startSpecifier, specifierLen, 9080 CS.getStart(), CS.getLength()); 9081 } 9082 9083 bool CheckScanfHandler::HandleScanfSpecifier( 9084 const analyze_scanf::ScanfSpecifier &FS, 9085 const char *startSpecifier, 9086 unsigned specifierLen) { 9087 using namespace analyze_scanf; 9088 using namespace analyze_format_string; 9089 9090 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9091 9092 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9093 // be used to decide if we are using positional arguments consistently. 9094 if (FS.consumesDataArgument()) { 9095 if (atFirstArg) { 9096 atFirstArg = false; 9097 usesPositionalArgs = FS.usesPositionalArg(); 9098 } 9099 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9100 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9101 startSpecifier, specifierLen); 9102 return false; 9103 } 9104 } 9105 9106 // Check if the field with is non-zero. 9107 const OptionalAmount &Amt = FS.getFieldWidth(); 9108 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9109 if (Amt.getConstantAmount() == 0) { 9110 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9111 Amt.getConstantLength()); 9112 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9113 getLocationOfByte(Amt.getStart()), 9114 /*IsStringLocation*/true, R, 9115 FixItHint::CreateRemoval(R)); 9116 } 9117 } 9118 9119 if (!FS.consumesDataArgument()) { 9120 // FIXME: Technically specifying a precision or field width here 9121 // makes no sense. Worth issuing a warning at some point. 9122 return true; 9123 } 9124 9125 // Consume the argument. 9126 unsigned argIndex = FS.getArgIndex(); 9127 if (argIndex < NumDataArgs) { 9128 // The check to see if the argIndex is valid will come later. 9129 // We set the bit here because we may exit early from this 9130 // function if we encounter some other error. 9131 CoveredArgs.set(argIndex); 9132 } 9133 9134 // Check the length modifier is valid with the given conversion specifier. 9135 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9136 S.getLangOpts())) 9137 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9138 diag::warn_format_nonsensical_length); 9139 else if (!FS.hasStandardLengthModifier()) 9140 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9141 else if (!FS.hasStandardLengthConversionCombination()) 9142 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9143 diag::warn_format_non_standard_conversion_spec); 9144 9145 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9146 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9147 9148 // The remaining checks depend on the data arguments. 9149 if (HasVAListArg) 9150 return true; 9151 9152 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9153 return false; 9154 9155 // Check that the argument type matches the format specifier. 9156 const Expr *Ex = getDataArg(argIndex); 9157 if (!Ex) 9158 return true; 9159 9160 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9161 9162 if (!AT.isValid()) { 9163 return true; 9164 } 9165 9166 analyze_format_string::ArgType::MatchKind Match = 9167 AT.matchesType(S.Context, Ex->getType()); 9168 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9169 if (Match == analyze_format_string::ArgType::Match) 9170 return true; 9171 9172 ScanfSpecifier fixedFS = FS; 9173 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9174 S.getLangOpts(), S.Context); 9175 9176 unsigned Diag = 9177 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9178 : diag::warn_format_conversion_argument_type_mismatch; 9179 9180 if (Success) { 9181 // Get the fix string from the fixed format specifier. 9182 SmallString<128> buf; 9183 llvm::raw_svector_ostream os(buf); 9184 fixedFS.toString(os); 9185 9186 EmitFormatDiagnostic( 9187 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9188 << Ex->getType() << false << Ex->getSourceRange(), 9189 Ex->getBeginLoc(), 9190 /*IsStringLocation*/ false, 9191 getSpecifierRange(startSpecifier, specifierLen), 9192 FixItHint::CreateReplacement( 9193 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9194 } else { 9195 EmitFormatDiagnostic(S.PDiag(Diag) 9196 << AT.getRepresentativeTypeName(S.Context) 9197 << Ex->getType() << false << Ex->getSourceRange(), 9198 Ex->getBeginLoc(), 9199 /*IsStringLocation*/ false, 9200 getSpecifierRange(startSpecifier, specifierLen)); 9201 } 9202 9203 return true; 9204 } 9205 9206 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9207 const Expr *OrigFormatExpr, 9208 ArrayRef<const Expr *> Args, 9209 bool HasVAListArg, unsigned format_idx, 9210 unsigned firstDataArg, 9211 Sema::FormatStringType Type, 9212 bool inFunctionCall, 9213 Sema::VariadicCallType CallType, 9214 llvm::SmallBitVector &CheckedVarArgs, 9215 UncoveredArgHandler &UncoveredArg, 9216 bool IgnoreStringsWithoutSpecifiers) { 9217 // CHECK: is the format string a wide literal? 9218 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9219 CheckFormatHandler::EmitFormatDiagnostic( 9220 S, inFunctionCall, Args[format_idx], 9221 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9222 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9223 return; 9224 } 9225 9226 // Str - The format string. NOTE: this is NOT null-terminated! 9227 StringRef StrRef = FExpr->getString(); 9228 const char *Str = StrRef.data(); 9229 // Account for cases where the string literal is truncated in a declaration. 9230 const ConstantArrayType *T = 9231 S.Context.getAsConstantArrayType(FExpr->getType()); 9232 assert(T && "String literal not of constant array type!"); 9233 size_t TypeSize = T->getSize().getZExtValue(); 9234 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9235 const unsigned numDataArgs = Args.size() - firstDataArg; 9236 9237 if (IgnoreStringsWithoutSpecifiers && 9238 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9239 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9240 return; 9241 9242 // Emit a warning if the string literal is truncated and does not contain an 9243 // embedded null character. 9244 if (TypeSize <= StrRef.size() && 9245 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9246 CheckFormatHandler::EmitFormatDiagnostic( 9247 S, inFunctionCall, Args[format_idx], 9248 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9249 FExpr->getBeginLoc(), 9250 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9251 return; 9252 } 9253 9254 // CHECK: empty format string? 9255 if (StrLen == 0 && numDataArgs > 0) { 9256 CheckFormatHandler::EmitFormatDiagnostic( 9257 S, inFunctionCall, Args[format_idx], 9258 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9259 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9260 return; 9261 } 9262 9263 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9264 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9265 Type == Sema::FST_OSTrace) { 9266 CheckPrintfHandler H( 9267 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9268 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9269 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9270 CheckedVarArgs, UncoveredArg); 9271 9272 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9273 S.getLangOpts(), 9274 S.Context.getTargetInfo(), 9275 Type == Sema::FST_FreeBSDKPrintf)) 9276 H.DoneProcessing(); 9277 } else if (Type == Sema::FST_Scanf) { 9278 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9279 numDataArgs, Str, HasVAListArg, Args, format_idx, 9280 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9281 9282 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9283 S.getLangOpts(), 9284 S.Context.getTargetInfo())) 9285 H.DoneProcessing(); 9286 } // TODO: handle other formats 9287 } 9288 9289 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9290 // Str - The format string. NOTE: this is NOT null-terminated! 9291 StringRef StrRef = FExpr->getString(); 9292 const char *Str = StrRef.data(); 9293 // Account for cases where the string literal is truncated in a declaration. 9294 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9295 assert(T && "String literal not of constant array type!"); 9296 size_t TypeSize = T->getSize().getZExtValue(); 9297 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9298 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9299 getLangOpts(), 9300 Context.getTargetInfo()); 9301 } 9302 9303 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9304 9305 // Returns the related absolute value function that is larger, of 0 if one 9306 // does not exist. 9307 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9308 switch (AbsFunction) { 9309 default: 9310 return 0; 9311 9312 case Builtin::BI__builtin_abs: 9313 return Builtin::BI__builtin_labs; 9314 case Builtin::BI__builtin_labs: 9315 return Builtin::BI__builtin_llabs; 9316 case Builtin::BI__builtin_llabs: 9317 return 0; 9318 9319 case Builtin::BI__builtin_fabsf: 9320 return Builtin::BI__builtin_fabs; 9321 case Builtin::BI__builtin_fabs: 9322 return Builtin::BI__builtin_fabsl; 9323 case Builtin::BI__builtin_fabsl: 9324 return 0; 9325 9326 case Builtin::BI__builtin_cabsf: 9327 return Builtin::BI__builtin_cabs; 9328 case Builtin::BI__builtin_cabs: 9329 return Builtin::BI__builtin_cabsl; 9330 case Builtin::BI__builtin_cabsl: 9331 return 0; 9332 9333 case Builtin::BIabs: 9334 return Builtin::BIlabs; 9335 case Builtin::BIlabs: 9336 return Builtin::BIllabs; 9337 case Builtin::BIllabs: 9338 return 0; 9339 9340 case Builtin::BIfabsf: 9341 return Builtin::BIfabs; 9342 case Builtin::BIfabs: 9343 return Builtin::BIfabsl; 9344 case Builtin::BIfabsl: 9345 return 0; 9346 9347 case Builtin::BIcabsf: 9348 return Builtin::BIcabs; 9349 case Builtin::BIcabs: 9350 return Builtin::BIcabsl; 9351 case Builtin::BIcabsl: 9352 return 0; 9353 } 9354 } 9355 9356 // Returns the argument type of the absolute value function. 9357 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9358 unsigned AbsType) { 9359 if (AbsType == 0) 9360 return QualType(); 9361 9362 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9363 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9364 if (Error != ASTContext::GE_None) 9365 return QualType(); 9366 9367 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9368 if (!FT) 9369 return QualType(); 9370 9371 if (FT->getNumParams() != 1) 9372 return QualType(); 9373 9374 return FT->getParamType(0); 9375 } 9376 9377 // Returns the best absolute value function, or zero, based on type and 9378 // current absolute value function. 9379 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9380 unsigned AbsFunctionKind) { 9381 unsigned BestKind = 0; 9382 uint64_t ArgSize = Context.getTypeSize(ArgType); 9383 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9384 Kind = getLargerAbsoluteValueFunction(Kind)) { 9385 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9386 if (Context.getTypeSize(ParamType) >= ArgSize) { 9387 if (BestKind == 0) 9388 BestKind = Kind; 9389 else if (Context.hasSameType(ParamType, ArgType)) { 9390 BestKind = Kind; 9391 break; 9392 } 9393 } 9394 } 9395 return BestKind; 9396 } 9397 9398 enum AbsoluteValueKind { 9399 AVK_Integer, 9400 AVK_Floating, 9401 AVK_Complex 9402 }; 9403 9404 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9405 if (T->isIntegralOrEnumerationType()) 9406 return AVK_Integer; 9407 if (T->isRealFloatingType()) 9408 return AVK_Floating; 9409 if (T->isAnyComplexType()) 9410 return AVK_Complex; 9411 9412 llvm_unreachable("Type not integer, floating, or complex"); 9413 } 9414 9415 // Changes the absolute value function to a different type. Preserves whether 9416 // the function is a builtin. 9417 static unsigned changeAbsFunction(unsigned AbsKind, 9418 AbsoluteValueKind ValueKind) { 9419 switch (ValueKind) { 9420 case AVK_Integer: 9421 switch (AbsKind) { 9422 default: 9423 return 0; 9424 case Builtin::BI__builtin_fabsf: 9425 case Builtin::BI__builtin_fabs: 9426 case Builtin::BI__builtin_fabsl: 9427 case Builtin::BI__builtin_cabsf: 9428 case Builtin::BI__builtin_cabs: 9429 case Builtin::BI__builtin_cabsl: 9430 return Builtin::BI__builtin_abs; 9431 case Builtin::BIfabsf: 9432 case Builtin::BIfabs: 9433 case Builtin::BIfabsl: 9434 case Builtin::BIcabsf: 9435 case Builtin::BIcabs: 9436 case Builtin::BIcabsl: 9437 return Builtin::BIabs; 9438 } 9439 case AVK_Floating: 9440 switch (AbsKind) { 9441 default: 9442 return 0; 9443 case Builtin::BI__builtin_abs: 9444 case Builtin::BI__builtin_labs: 9445 case Builtin::BI__builtin_llabs: 9446 case Builtin::BI__builtin_cabsf: 9447 case Builtin::BI__builtin_cabs: 9448 case Builtin::BI__builtin_cabsl: 9449 return Builtin::BI__builtin_fabsf; 9450 case Builtin::BIabs: 9451 case Builtin::BIlabs: 9452 case Builtin::BIllabs: 9453 case Builtin::BIcabsf: 9454 case Builtin::BIcabs: 9455 case Builtin::BIcabsl: 9456 return Builtin::BIfabsf; 9457 } 9458 case AVK_Complex: 9459 switch (AbsKind) { 9460 default: 9461 return 0; 9462 case Builtin::BI__builtin_abs: 9463 case Builtin::BI__builtin_labs: 9464 case Builtin::BI__builtin_llabs: 9465 case Builtin::BI__builtin_fabsf: 9466 case Builtin::BI__builtin_fabs: 9467 case Builtin::BI__builtin_fabsl: 9468 return Builtin::BI__builtin_cabsf; 9469 case Builtin::BIabs: 9470 case Builtin::BIlabs: 9471 case Builtin::BIllabs: 9472 case Builtin::BIfabsf: 9473 case Builtin::BIfabs: 9474 case Builtin::BIfabsl: 9475 return Builtin::BIcabsf; 9476 } 9477 } 9478 llvm_unreachable("Unable to convert function"); 9479 } 9480 9481 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9482 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9483 if (!FnInfo) 9484 return 0; 9485 9486 switch (FDecl->getBuiltinID()) { 9487 default: 9488 return 0; 9489 case Builtin::BI__builtin_abs: 9490 case Builtin::BI__builtin_fabs: 9491 case Builtin::BI__builtin_fabsf: 9492 case Builtin::BI__builtin_fabsl: 9493 case Builtin::BI__builtin_labs: 9494 case Builtin::BI__builtin_llabs: 9495 case Builtin::BI__builtin_cabs: 9496 case Builtin::BI__builtin_cabsf: 9497 case Builtin::BI__builtin_cabsl: 9498 case Builtin::BIabs: 9499 case Builtin::BIlabs: 9500 case Builtin::BIllabs: 9501 case Builtin::BIfabs: 9502 case Builtin::BIfabsf: 9503 case Builtin::BIfabsl: 9504 case Builtin::BIcabs: 9505 case Builtin::BIcabsf: 9506 case Builtin::BIcabsl: 9507 return FDecl->getBuiltinID(); 9508 } 9509 llvm_unreachable("Unknown Builtin type"); 9510 } 9511 9512 // If the replacement is valid, emit a note with replacement function. 9513 // Additionally, suggest including the proper header if not already included. 9514 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9515 unsigned AbsKind, QualType ArgType) { 9516 bool EmitHeaderHint = true; 9517 const char *HeaderName = nullptr; 9518 const char *FunctionName = nullptr; 9519 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9520 FunctionName = "std::abs"; 9521 if (ArgType->isIntegralOrEnumerationType()) { 9522 HeaderName = "cstdlib"; 9523 } else if (ArgType->isRealFloatingType()) { 9524 HeaderName = "cmath"; 9525 } else { 9526 llvm_unreachable("Invalid Type"); 9527 } 9528 9529 // Lookup all std::abs 9530 if (NamespaceDecl *Std = S.getStdNamespace()) { 9531 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9532 R.suppressDiagnostics(); 9533 S.LookupQualifiedName(R, Std); 9534 9535 for (const auto *I : R) { 9536 const FunctionDecl *FDecl = nullptr; 9537 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9538 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9539 } else { 9540 FDecl = dyn_cast<FunctionDecl>(I); 9541 } 9542 if (!FDecl) 9543 continue; 9544 9545 // Found std::abs(), check that they are the right ones. 9546 if (FDecl->getNumParams() != 1) 9547 continue; 9548 9549 // Check that the parameter type can handle the argument. 9550 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9551 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9552 S.Context.getTypeSize(ArgType) <= 9553 S.Context.getTypeSize(ParamType)) { 9554 // Found a function, don't need the header hint. 9555 EmitHeaderHint = false; 9556 break; 9557 } 9558 } 9559 } 9560 } else { 9561 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9562 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9563 9564 if (HeaderName) { 9565 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9566 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9567 R.suppressDiagnostics(); 9568 S.LookupName(R, S.getCurScope()); 9569 9570 if (R.isSingleResult()) { 9571 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9572 if (FD && FD->getBuiltinID() == AbsKind) { 9573 EmitHeaderHint = false; 9574 } else { 9575 return; 9576 } 9577 } else if (!R.empty()) { 9578 return; 9579 } 9580 } 9581 } 9582 9583 S.Diag(Loc, diag::note_replace_abs_function) 9584 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9585 9586 if (!HeaderName) 9587 return; 9588 9589 if (!EmitHeaderHint) 9590 return; 9591 9592 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9593 << FunctionName; 9594 } 9595 9596 template <std::size_t StrLen> 9597 static bool IsStdFunction(const FunctionDecl *FDecl, 9598 const char (&Str)[StrLen]) { 9599 if (!FDecl) 9600 return false; 9601 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9602 return false; 9603 if (!FDecl->isInStdNamespace()) 9604 return false; 9605 9606 return true; 9607 } 9608 9609 // Warn when using the wrong abs() function. 9610 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9611 const FunctionDecl *FDecl) { 9612 if (Call->getNumArgs() != 1) 9613 return; 9614 9615 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9616 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9617 if (AbsKind == 0 && !IsStdAbs) 9618 return; 9619 9620 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9621 QualType ParamType = Call->getArg(0)->getType(); 9622 9623 // Unsigned types cannot be negative. Suggest removing the absolute value 9624 // function call. 9625 if (ArgType->isUnsignedIntegerType()) { 9626 const char *FunctionName = 9627 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9628 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9629 Diag(Call->getExprLoc(), diag::note_remove_abs) 9630 << FunctionName 9631 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9632 return; 9633 } 9634 9635 // Taking the absolute value of a pointer is very suspicious, they probably 9636 // wanted to index into an array, dereference a pointer, call a function, etc. 9637 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9638 unsigned DiagType = 0; 9639 if (ArgType->isFunctionType()) 9640 DiagType = 1; 9641 else if (ArgType->isArrayType()) 9642 DiagType = 2; 9643 9644 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9645 return; 9646 } 9647 9648 // std::abs has overloads which prevent most of the absolute value problems 9649 // from occurring. 9650 if (IsStdAbs) 9651 return; 9652 9653 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9654 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9655 9656 // The argument and parameter are the same kind. Check if they are the right 9657 // size. 9658 if (ArgValueKind == ParamValueKind) { 9659 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9660 return; 9661 9662 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9663 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9664 << FDecl << ArgType << ParamType; 9665 9666 if (NewAbsKind == 0) 9667 return; 9668 9669 emitReplacement(*this, Call->getExprLoc(), 9670 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9671 return; 9672 } 9673 9674 // ArgValueKind != ParamValueKind 9675 // The wrong type of absolute value function was used. Attempt to find the 9676 // proper one. 9677 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9678 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9679 if (NewAbsKind == 0) 9680 return; 9681 9682 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9683 << FDecl << ParamValueKind << ArgValueKind; 9684 9685 emitReplacement(*this, Call->getExprLoc(), 9686 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9687 } 9688 9689 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9690 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9691 const FunctionDecl *FDecl) { 9692 if (!Call || !FDecl) return; 9693 9694 // Ignore template specializations and macros. 9695 if (inTemplateInstantiation()) return; 9696 if (Call->getExprLoc().isMacroID()) return; 9697 9698 // Only care about the one template argument, two function parameter std::max 9699 if (Call->getNumArgs() != 2) return; 9700 if (!IsStdFunction(FDecl, "max")) return; 9701 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9702 if (!ArgList) return; 9703 if (ArgList->size() != 1) return; 9704 9705 // Check that template type argument is unsigned integer. 9706 const auto& TA = ArgList->get(0); 9707 if (TA.getKind() != TemplateArgument::Type) return; 9708 QualType ArgType = TA.getAsType(); 9709 if (!ArgType->isUnsignedIntegerType()) return; 9710 9711 // See if either argument is a literal zero. 9712 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9713 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9714 if (!MTE) return false; 9715 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9716 if (!Num) return false; 9717 if (Num->getValue() != 0) return false; 9718 return true; 9719 }; 9720 9721 const Expr *FirstArg = Call->getArg(0); 9722 const Expr *SecondArg = Call->getArg(1); 9723 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9724 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9725 9726 // Only warn when exactly one argument is zero. 9727 if (IsFirstArgZero == IsSecondArgZero) return; 9728 9729 SourceRange FirstRange = FirstArg->getSourceRange(); 9730 SourceRange SecondRange = SecondArg->getSourceRange(); 9731 9732 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9733 9734 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9735 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9736 9737 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9738 SourceRange RemovalRange; 9739 if (IsFirstArgZero) { 9740 RemovalRange = SourceRange(FirstRange.getBegin(), 9741 SecondRange.getBegin().getLocWithOffset(-1)); 9742 } else { 9743 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9744 SecondRange.getEnd()); 9745 } 9746 9747 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9748 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9749 << FixItHint::CreateRemoval(RemovalRange); 9750 } 9751 9752 //===--- CHECK: Standard memory functions ---------------------------------===// 9753 9754 /// Takes the expression passed to the size_t parameter of functions 9755 /// such as memcmp, strncat, etc and warns if it's a comparison. 9756 /// 9757 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9758 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9759 IdentifierInfo *FnName, 9760 SourceLocation FnLoc, 9761 SourceLocation RParenLoc) { 9762 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9763 if (!Size) 9764 return false; 9765 9766 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9767 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9768 return false; 9769 9770 SourceRange SizeRange = Size->getSourceRange(); 9771 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9772 << SizeRange << FnName; 9773 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9774 << FnName 9775 << FixItHint::CreateInsertion( 9776 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9777 << FixItHint::CreateRemoval(RParenLoc); 9778 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9779 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9780 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9781 ")"); 9782 9783 return true; 9784 } 9785 9786 /// Determine whether the given type is or contains a dynamic class type 9787 /// (e.g., whether it has a vtable). 9788 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9789 bool &IsContained) { 9790 // Look through array types while ignoring qualifiers. 9791 const Type *Ty = T->getBaseElementTypeUnsafe(); 9792 IsContained = false; 9793 9794 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9795 RD = RD ? RD->getDefinition() : nullptr; 9796 if (!RD || RD->isInvalidDecl()) 9797 return nullptr; 9798 9799 if (RD->isDynamicClass()) 9800 return RD; 9801 9802 // Check all the fields. If any bases were dynamic, the class is dynamic. 9803 // It's impossible for a class to transitively contain itself by value, so 9804 // infinite recursion is impossible. 9805 for (auto *FD : RD->fields()) { 9806 bool SubContained; 9807 if (const CXXRecordDecl *ContainedRD = 9808 getContainedDynamicClass(FD->getType(), SubContained)) { 9809 IsContained = true; 9810 return ContainedRD; 9811 } 9812 } 9813 9814 return nullptr; 9815 } 9816 9817 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9818 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9819 if (Unary->getKind() == UETT_SizeOf) 9820 return Unary; 9821 return nullptr; 9822 } 9823 9824 /// If E is a sizeof expression, returns its argument expression, 9825 /// otherwise returns NULL. 9826 static const Expr *getSizeOfExprArg(const Expr *E) { 9827 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9828 if (!SizeOf->isArgumentType()) 9829 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9830 return nullptr; 9831 } 9832 9833 /// If E is a sizeof expression, returns its argument type. 9834 static QualType getSizeOfArgType(const Expr *E) { 9835 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9836 return SizeOf->getTypeOfArgument(); 9837 return QualType(); 9838 } 9839 9840 namespace { 9841 9842 struct SearchNonTrivialToInitializeField 9843 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9844 using Super = 9845 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9846 9847 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9848 9849 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9850 SourceLocation SL) { 9851 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9852 asDerived().visitArray(PDIK, AT, SL); 9853 return; 9854 } 9855 9856 Super::visitWithKind(PDIK, FT, SL); 9857 } 9858 9859 void visitARCStrong(QualType FT, SourceLocation SL) { 9860 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9861 } 9862 void visitARCWeak(QualType FT, SourceLocation SL) { 9863 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9864 } 9865 void visitStruct(QualType FT, SourceLocation SL) { 9866 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9867 visit(FD->getType(), FD->getLocation()); 9868 } 9869 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9870 const ArrayType *AT, SourceLocation SL) { 9871 visit(getContext().getBaseElementType(AT), SL); 9872 } 9873 void visitTrivial(QualType FT, SourceLocation SL) {} 9874 9875 static void diag(QualType RT, const Expr *E, Sema &S) { 9876 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9877 } 9878 9879 ASTContext &getContext() { return S.getASTContext(); } 9880 9881 const Expr *E; 9882 Sema &S; 9883 }; 9884 9885 struct SearchNonTrivialToCopyField 9886 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9887 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9888 9889 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9890 9891 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9892 SourceLocation SL) { 9893 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9894 asDerived().visitArray(PCK, AT, SL); 9895 return; 9896 } 9897 9898 Super::visitWithKind(PCK, FT, SL); 9899 } 9900 9901 void visitARCStrong(QualType FT, SourceLocation SL) { 9902 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9903 } 9904 void visitARCWeak(QualType FT, SourceLocation SL) { 9905 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9906 } 9907 void visitStruct(QualType FT, SourceLocation SL) { 9908 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9909 visit(FD->getType(), FD->getLocation()); 9910 } 9911 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9912 SourceLocation SL) { 9913 visit(getContext().getBaseElementType(AT), SL); 9914 } 9915 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9916 SourceLocation SL) {} 9917 void visitTrivial(QualType FT, SourceLocation SL) {} 9918 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9919 9920 static void diag(QualType RT, const Expr *E, Sema &S) { 9921 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9922 } 9923 9924 ASTContext &getContext() { return S.getASTContext(); } 9925 9926 const Expr *E; 9927 Sema &S; 9928 }; 9929 9930 } 9931 9932 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9933 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9934 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9935 9936 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9937 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9938 return false; 9939 9940 return doesExprLikelyComputeSize(BO->getLHS()) || 9941 doesExprLikelyComputeSize(BO->getRHS()); 9942 } 9943 9944 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9945 } 9946 9947 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9948 /// 9949 /// \code 9950 /// #define MACRO 0 9951 /// foo(MACRO); 9952 /// foo(0); 9953 /// \endcode 9954 /// 9955 /// This should return true for the first call to foo, but not for the second 9956 /// (regardless of whether foo is a macro or function). 9957 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9958 SourceLocation CallLoc, 9959 SourceLocation ArgLoc) { 9960 if (!CallLoc.isMacroID()) 9961 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9962 9963 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9964 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9965 } 9966 9967 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9968 /// last two arguments transposed. 9969 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9970 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9971 return; 9972 9973 const Expr *SizeArg = 9974 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9975 9976 auto isLiteralZero = [](const Expr *E) { 9977 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9978 }; 9979 9980 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9981 SourceLocation CallLoc = Call->getRParenLoc(); 9982 SourceManager &SM = S.getSourceManager(); 9983 if (isLiteralZero(SizeArg) && 9984 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9985 9986 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9987 9988 // Some platforms #define bzero to __builtin_memset. See if this is the 9989 // case, and if so, emit a better diagnostic. 9990 if (BId == Builtin::BIbzero || 9991 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9992 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9993 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9994 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9995 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9996 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9997 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9998 } 9999 return; 10000 } 10001 10002 // If the second argument to a memset is a sizeof expression and the third 10003 // isn't, this is also likely an error. This should catch 10004 // 'memset(buf, sizeof(buf), 0xff)'. 10005 if (BId == Builtin::BImemset && 10006 doesExprLikelyComputeSize(Call->getArg(1)) && 10007 !doesExprLikelyComputeSize(Call->getArg(2))) { 10008 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10009 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10010 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10011 return; 10012 } 10013 } 10014 10015 /// Check for dangerous or invalid arguments to memset(). 10016 /// 10017 /// This issues warnings on known problematic, dangerous or unspecified 10018 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10019 /// function calls. 10020 /// 10021 /// \param Call The call expression to diagnose. 10022 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10023 unsigned BId, 10024 IdentifierInfo *FnName) { 10025 assert(BId != 0); 10026 10027 // It is possible to have a non-standard definition of memset. Validate 10028 // we have enough arguments, and if not, abort further checking. 10029 unsigned ExpectedNumArgs = 10030 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10031 if (Call->getNumArgs() < ExpectedNumArgs) 10032 return; 10033 10034 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10035 BId == Builtin::BIstrndup ? 1 : 2); 10036 unsigned LenArg = 10037 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10038 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10039 10040 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10041 Call->getBeginLoc(), Call->getRParenLoc())) 10042 return; 10043 10044 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10045 CheckMemaccessSize(*this, BId, Call); 10046 10047 // We have special checking when the length is a sizeof expression. 10048 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10049 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10050 llvm::FoldingSetNodeID SizeOfArgID; 10051 10052 // Although widely used, 'bzero' is not a standard function. Be more strict 10053 // with the argument types before allowing diagnostics and only allow the 10054 // form bzero(ptr, sizeof(...)). 10055 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10056 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10057 return; 10058 10059 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10060 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10061 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10062 10063 QualType DestTy = Dest->getType(); 10064 QualType PointeeTy; 10065 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10066 PointeeTy = DestPtrTy->getPointeeType(); 10067 10068 // Never warn about void type pointers. This can be used to suppress 10069 // false positives. 10070 if (PointeeTy->isVoidType()) 10071 continue; 10072 10073 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10074 // actually comparing the expressions for equality. Because computing the 10075 // expression IDs can be expensive, we only do this if the diagnostic is 10076 // enabled. 10077 if (SizeOfArg && 10078 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10079 SizeOfArg->getExprLoc())) { 10080 // We only compute IDs for expressions if the warning is enabled, and 10081 // cache the sizeof arg's ID. 10082 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10083 SizeOfArg->Profile(SizeOfArgID, Context, true); 10084 llvm::FoldingSetNodeID DestID; 10085 Dest->Profile(DestID, Context, true); 10086 if (DestID == SizeOfArgID) { 10087 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10088 // over sizeof(src) as well. 10089 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10090 StringRef ReadableName = FnName->getName(); 10091 10092 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10093 if (UnaryOp->getOpcode() == UO_AddrOf) 10094 ActionIdx = 1; // If its an address-of operator, just remove it. 10095 if (!PointeeTy->isIncompleteType() && 10096 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10097 ActionIdx = 2; // If the pointee's size is sizeof(char), 10098 // suggest an explicit length. 10099 10100 // If the function is defined as a builtin macro, do not show macro 10101 // expansion. 10102 SourceLocation SL = SizeOfArg->getExprLoc(); 10103 SourceRange DSR = Dest->getSourceRange(); 10104 SourceRange SSR = SizeOfArg->getSourceRange(); 10105 SourceManager &SM = getSourceManager(); 10106 10107 if (SM.isMacroArgExpansion(SL)) { 10108 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10109 SL = SM.getSpellingLoc(SL); 10110 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10111 SM.getSpellingLoc(DSR.getEnd())); 10112 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10113 SM.getSpellingLoc(SSR.getEnd())); 10114 } 10115 10116 DiagRuntimeBehavior(SL, SizeOfArg, 10117 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10118 << ReadableName 10119 << PointeeTy 10120 << DestTy 10121 << DSR 10122 << SSR); 10123 DiagRuntimeBehavior(SL, SizeOfArg, 10124 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10125 << ActionIdx 10126 << SSR); 10127 10128 break; 10129 } 10130 } 10131 10132 // Also check for cases where the sizeof argument is the exact same 10133 // type as the memory argument, and where it points to a user-defined 10134 // record type. 10135 if (SizeOfArgTy != QualType()) { 10136 if (PointeeTy->isRecordType() && 10137 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10138 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10139 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10140 << FnName << SizeOfArgTy << ArgIdx 10141 << PointeeTy << Dest->getSourceRange() 10142 << LenExpr->getSourceRange()); 10143 break; 10144 } 10145 } 10146 } else if (DestTy->isArrayType()) { 10147 PointeeTy = DestTy; 10148 } 10149 10150 if (PointeeTy == QualType()) 10151 continue; 10152 10153 // Always complain about dynamic classes. 10154 bool IsContained; 10155 if (const CXXRecordDecl *ContainedRD = 10156 getContainedDynamicClass(PointeeTy, IsContained)) { 10157 10158 unsigned OperationType = 0; 10159 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10160 // "overwritten" if we're warning about the destination for any call 10161 // but memcmp; otherwise a verb appropriate to the call. 10162 if (ArgIdx != 0 || IsCmp) { 10163 if (BId == Builtin::BImemcpy) 10164 OperationType = 1; 10165 else if(BId == Builtin::BImemmove) 10166 OperationType = 2; 10167 else if (IsCmp) 10168 OperationType = 3; 10169 } 10170 10171 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10172 PDiag(diag::warn_dyn_class_memaccess) 10173 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10174 << IsContained << ContainedRD << OperationType 10175 << Call->getCallee()->getSourceRange()); 10176 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10177 BId != Builtin::BImemset) 10178 DiagRuntimeBehavior( 10179 Dest->getExprLoc(), Dest, 10180 PDiag(diag::warn_arc_object_memaccess) 10181 << ArgIdx << FnName << PointeeTy 10182 << Call->getCallee()->getSourceRange()); 10183 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10184 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10185 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10186 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10187 PDiag(diag::warn_cstruct_memaccess) 10188 << ArgIdx << FnName << PointeeTy << 0); 10189 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10190 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10191 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10192 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10193 PDiag(diag::warn_cstruct_memaccess) 10194 << ArgIdx << FnName << PointeeTy << 1); 10195 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10196 } else { 10197 continue; 10198 } 10199 } else 10200 continue; 10201 10202 DiagRuntimeBehavior( 10203 Dest->getExprLoc(), Dest, 10204 PDiag(diag::note_bad_memaccess_silence) 10205 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10206 break; 10207 } 10208 } 10209 10210 // A little helper routine: ignore addition and subtraction of integer literals. 10211 // This intentionally does not ignore all integer constant expressions because 10212 // we don't want to remove sizeof(). 10213 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10214 Ex = Ex->IgnoreParenCasts(); 10215 10216 while (true) { 10217 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10218 if (!BO || !BO->isAdditiveOp()) 10219 break; 10220 10221 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10222 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10223 10224 if (isa<IntegerLiteral>(RHS)) 10225 Ex = LHS; 10226 else if (isa<IntegerLiteral>(LHS)) 10227 Ex = RHS; 10228 else 10229 break; 10230 } 10231 10232 return Ex; 10233 } 10234 10235 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10236 ASTContext &Context) { 10237 // Only handle constant-sized or VLAs, but not flexible members. 10238 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10239 // Only issue the FIXIT for arrays of size > 1. 10240 if (CAT->getSize().getSExtValue() <= 1) 10241 return false; 10242 } else if (!Ty->isVariableArrayType()) { 10243 return false; 10244 } 10245 return true; 10246 } 10247 10248 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10249 // be the size of the source, instead of the destination. 10250 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10251 IdentifierInfo *FnName) { 10252 10253 // Don't crash if the user has the wrong number of arguments 10254 unsigned NumArgs = Call->getNumArgs(); 10255 if ((NumArgs != 3) && (NumArgs != 4)) 10256 return; 10257 10258 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10259 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10260 const Expr *CompareWithSrc = nullptr; 10261 10262 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10263 Call->getBeginLoc(), Call->getRParenLoc())) 10264 return; 10265 10266 // Look for 'strlcpy(dst, x, sizeof(x))' 10267 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10268 CompareWithSrc = Ex; 10269 else { 10270 // Look for 'strlcpy(dst, x, strlen(x))' 10271 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10272 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10273 SizeCall->getNumArgs() == 1) 10274 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10275 } 10276 } 10277 10278 if (!CompareWithSrc) 10279 return; 10280 10281 // Determine if the argument to sizeof/strlen is equal to the source 10282 // argument. In principle there's all kinds of things you could do 10283 // here, for instance creating an == expression and evaluating it with 10284 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10285 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10286 if (!SrcArgDRE) 10287 return; 10288 10289 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10290 if (!CompareWithSrcDRE || 10291 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10292 return; 10293 10294 const Expr *OriginalSizeArg = Call->getArg(2); 10295 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10296 << OriginalSizeArg->getSourceRange() << FnName; 10297 10298 // Output a FIXIT hint if the destination is an array (rather than a 10299 // pointer to an array). This could be enhanced to handle some 10300 // pointers if we know the actual size, like if DstArg is 'array+2' 10301 // we could say 'sizeof(array)-2'. 10302 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10303 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10304 return; 10305 10306 SmallString<128> sizeString; 10307 llvm::raw_svector_ostream OS(sizeString); 10308 OS << "sizeof("; 10309 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10310 OS << ")"; 10311 10312 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10313 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10314 OS.str()); 10315 } 10316 10317 /// Check if two expressions refer to the same declaration. 10318 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10319 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10320 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10321 return D1->getDecl() == D2->getDecl(); 10322 return false; 10323 } 10324 10325 static const Expr *getStrlenExprArg(const Expr *E) { 10326 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10327 const FunctionDecl *FD = CE->getDirectCallee(); 10328 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10329 return nullptr; 10330 return CE->getArg(0)->IgnoreParenCasts(); 10331 } 10332 return nullptr; 10333 } 10334 10335 // Warn on anti-patterns as the 'size' argument to strncat. 10336 // The correct size argument should look like following: 10337 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10338 void Sema::CheckStrncatArguments(const CallExpr *CE, 10339 IdentifierInfo *FnName) { 10340 // Don't crash if the user has the wrong number of arguments. 10341 if (CE->getNumArgs() < 3) 10342 return; 10343 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10344 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10345 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10346 10347 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10348 CE->getRParenLoc())) 10349 return; 10350 10351 // Identify common expressions, which are wrongly used as the size argument 10352 // to strncat and may lead to buffer overflows. 10353 unsigned PatternType = 0; 10354 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10355 // - sizeof(dst) 10356 if (referToTheSameDecl(SizeOfArg, DstArg)) 10357 PatternType = 1; 10358 // - sizeof(src) 10359 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10360 PatternType = 2; 10361 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10362 if (BE->getOpcode() == BO_Sub) { 10363 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10364 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10365 // - sizeof(dst) - strlen(dst) 10366 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10367 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10368 PatternType = 1; 10369 // - sizeof(src) - (anything) 10370 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10371 PatternType = 2; 10372 } 10373 } 10374 10375 if (PatternType == 0) 10376 return; 10377 10378 // Generate the diagnostic. 10379 SourceLocation SL = LenArg->getBeginLoc(); 10380 SourceRange SR = LenArg->getSourceRange(); 10381 SourceManager &SM = getSourceManager(); 10382 10383 // If the function is defined as a builtin macro, do not show macro expansion. 10384 if (SM.isMacroArgExpansion(SL)) { 10385 SL = SM.getSpellingLoc(SL); 10386 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10387 SM.getSpellingLoc(SR.getEnd())); 10388 } 10389 10390 // Check if the destination is an array (rather than a pointer to an array). 10391 QualType DstTy = DstArg->getType(); 10392 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10393 Context); 10394 if (!isKnownSizeArray) { 10395 if (PatternType == 1) 10396 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10397 else 10398 Diag(SL, diag::warn_strncat_src_size) << SR; 10399 return; 10400 } 10401 10402 if (PatternType == 1) 10403 Diag(SL, diag::warn_strncat_large_size) << SR; 10404 else 10405 Diag(SL, diag::warn_strncat_src_size) << SR; 10406 10407 SmallString<128> sizeString; 10408 llvm::raw_svector_ostream OS(sizeString); 10409 OS << "sizeof("; 10410 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10411 OS << ") - "; 10412 OS << "strlen("; 10413 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10414 OS << ") - 1"; 10415 10416 Diag(SL, diag::note_strncat_wrong_size) 10417 << FixItHint::CreateReplacement(SR, OS.str()); 10418 } 10419 10420 namespace { 10421 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10422 const UnaryOperator *UnaryExpr, const Decl *D) { 10423 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10424 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10425 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10426 return; 10427 } 10428 } 10429 10430 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10431 const UnaryOperator *UnaryExpr) { 10432 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10433 const Decl *D = Lvalue->getDecl(); 10434 if (isa<VarDecl, FunctionDecl>(D)) 10435 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10436 } 10437 10438 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10439 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10440 Lvalue->getMemberDecl()); 10441 } 10442 10443 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10444 const UnaryOperator *UnaryExpr) { 10445 const auto *Lambda = dyn_cast<LambdaExpr>( 10446 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10447 if (!Lambda) 10448 return; 10449 10450 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10451 << CalleeName << 2 /*object: lambda expression*/; 10452 } 10453 10454 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10455 const DeclRefExpr *Lvalue) { 10456 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10457 if (Var == nullptr) 10458 return; 10459 10460 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10461 << CalleeName << 0 /*object: */ << Var; 10462 } 10463 10464 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10465 const CastExpr *Cast) { 10466 SmallString<128> SizeString; 10467 llvm::raw_svector_ostream OS(SizeString); 10468 10469 clang::CastKind Kind = Cast->getCastKind(); 10470 if (Kind == clang::CK_BitCast && 10471 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10472 return; 10473 if (Kind == clang::CK_IntegralToPointer && 10474 !isa<IntegerLiteral>( 10475 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10476 return; 10477 10478 switch (Cast->getCastKind()) { 10479 case clang::CK_BitCast: 10480 case clang::CK_IntegralToPointer: 10481 case clang::CK_FunctionToPointerDecay: 10482 OS << '\''; 10483 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10484 OS << '\''; 10485 break; 10486 default: 10487 return; 10488 } 10489 10490 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10491 << CalleeName << 0 /*object: */ << OS.str(); 10492 } 10493 } // namespace 10494 10495 /// Alerts the user that they are attempting to free a non-malloc'd object. 10496 void Sema::CheckFreeArguments(const CallExpr *E) { 10497 const std::string CalleeName = 10498 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10499 10500 { // Prefer something that doesn't involve a cast to make things simpler. 10501 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10502 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10503 switch (UnaryExpr->getOpcode()) { 10504 case UnaryOperator::Opcode::UO_AddrOf: 10505 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10506 case UnaryOperator::Opcode::UO_Plus: 10507 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 10508 default: 10509 break; 10510 } 10511 10512 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 10513 if (Lvalue->getType()->isArrayType()) 10514 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 10515 10516 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 10517 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 10518 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 10519 return; 10520 } 10521 10522 if (isa<BlockExpr>(Arg)) { 10523 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 10524 << CalleeName << 1 /*object: block*/; 10525 return; 10526 } 10527 } 10528 // Maybe the cast was important, check after the other cases. 10529 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 10530 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 10531 } 10532 10533 void 10534 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10535 SourceLocation ReturnLoc, 10536 bool isObjCMethod, 10537 const AttrVec *Attrs, 10538 const FunctionDecl *FD) { 10539 // Check if the return value is null but should not be. 10540 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10541 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10542 CheckNonNullExpr(*this, RetValExp)) 10543 Diag(ReturnLoc, diag::warn_null_ret) 10544 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10545 10546 // C++11 [basic.stc.dynamic.allocation]p4: 10547 // If an allocation function declared with a non-throwing 10548 // exception-specification fails to allocate storage, it shall return 10549 // a null pointer. Any other allocation function that fails to allocate 10550 // storage shall indicate failure only by throwing an exception [...] 10551 if (FD) { 10552 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10553 if (Op == OO_New || Op == OO_Array_New) { 10554 const FunctionProtoType *Proto 10555 = FD->getType()->castAs<FunctionProtoType>(); 10556 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10557 CheckNonNullExpr(*this, RetValExp)) 10558 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10559 << FD << getLangOpts().CPlusPlus11; 10560 } 10561 } 10562 10563 // PPC MMA non-pointer types are not allowed as return type. Checking the type 10564 // here prevent the user from using a PPC MMA type as trailing return type. 10565 if (Context.getTargetInfo().getTriple().isPPC64()) 10566 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 10567 } 10568 10569 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10570 10571 /// Check for comparisons of floating point operands using != and ==. 10572 /// Issue a warning if these are no self-comparisons, as they are not likely 10573 /// to do what the programmer intended. 10574 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10575 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10576 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10577 10578 // Special case: check for x == x (which is OK). 10579 // Do not emit warnings for such cases. 10580 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10581 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10582 if (DRL->getDecl() == DRR->getDecl()) 10583 return; 10584 10585 // Special case: check for comparisons against literals that can be exactly 10586 // represented by APFloat. In such cases, do not emit a warning. This 10587 // is a heuristic: often comparison against such literals are used to 10588 // detect if a value in a variable has not changed. This clearly can 10589 // lead to false negatives. 10590 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10591 if (FLL->isExact()) 10592 return; 10593 } else 10594 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10595 if (FLR->isExact()) 10596 return; 10597 10598 // Check for comparisons with builtin types. 10599 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10600 if (CL->getBuiltinCallee()) 10601 return; 10602 10603 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10604 if (CR->getBuiltinCallee()) 10605 return; 10606 10607 // Emit the diagnostic. 10608 Diag(Loc, diag::warn_floatingpoint_eq) 10609 << LHS->getSourceRange() << RHS->getSourceRange(); 10610 } 10611 10612 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10613 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10614 10615 namespace { 10616 10617 /// Structure recording the 'active' range of an integer-valued 10618 /// expression. 10619 struct IntRange { 10620 /// The number of bits active in the int. Note that this includes exactly one 10621 /// sign bit if !NonNegative. 10622 unsigned Width; 10623 10624 /// True if the int is known not to have negative values. If so, all leading 10625 /// bits before Width are known zero, otherwise they are known to be the 10626 /// same as the MSB within Width. 10627 bool NonNegative; 10628 10629 IntRange(unsigned Width, bool NonNegative) 10630 : Width(Width), NonNegative(NonNegative) {} 10631 10632 /// Number of bits excluding the sign bit. 10633 unsigned valueBits() const { 10634 return NonNegative ? Width : Width - 1; 10635 } 10636 10637 /// Returns the range of the bool type. 10638 static IntRange forBoolType() { 10639 return IntRange(1, true); 10640 } 10641 10642 /// Returns the range of an opaque value of the given integral type. 10643 static IntRange forValueOfType(ASTContext &C, QualType T) { 10644 return forValueOfCanonicalType(C, 10645 T->getCanonicalTypeInternal().getTypePtr()); 10646 } 10647 10648 /// Returns the range of an opaque value of a canonical integral type. 10649 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10650 assert(T->isCanonicalUnqualified()); 10651 10652 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10653 T = VT->getElementType().getTypePtr(); 10654 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10655 T = CT->getElementType().getTypePtr(); 10656 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10657 T = AT->getValueType().getTypePtr(); 10658 10659 if (!C.getLangOpts().CPlusPlus) { 10660 // For enum types in C code, use the underlying datatype. 10661 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10662 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10663 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10664 // For enum types in C++, use the known bit width of the enumerators. 10665 EnumDecl *Enum = ET->getDecl(); 10666 // In C++11, enums can have a fixed underlying type. Use this type to 10667 // compute the range. 10668 if (Enum->isFixed()) { 10669 return IntRange(C.getIntWidth(QualType(T, 0)), 10670 !ET->isSignedIntegerOrEnumerationType()); 10671 } 10672 10673 unsigned NumPositive = Enum->getNumPositiveBits(); 10674 unsigned NumNegative = Enum->getNumNegativeBits(); 10675 10676 if (NumNegative == 0) 10677 return IntRange(NumPositive, true/*NonNegative*/); 10678 else 10679 return IntRange(std::max(NumPositive + 1, NumNegative), 10680 false/*NonNegative*/); 10681 } 10682 10683 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10684 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10685 10686 const BuiltinType *BT = cast<BuiltinType>(T); 10687 assert(BT->isInteger()); 10688 10689 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10690 } 10691 10692 /// Returns the "target" range of a canonical integral type, i.e. 10693 /// the range of values expressible in the type. 10694 /// 10695 /// This matches forValueOfCanonicalType except that enums have the 10696 /// full range of their type, not the range of their enumerators. 10697 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10698 assert(T->isCanonicalUnqualified()); 10699 10700 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10701 T = VT->getElementType().getTypePtr(); 10702 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10703 T = CT->getElementType().getTypePtr(); 10704 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10705 T = AT->getValueType().getTypePtr(); 10706 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10707 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10708 10709 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10710 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10711 10712 const BuiltinType *BT = cast<BuiltinType>(T); 10713 assert(BT->isInteger()); 10714 10715 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10716 } 10717 10718 /// Returns the supremum of two ranges: i.e. their conservative merge. 10719 static IntRange join(IntRange L, IntRange R) { 10720 bool Unsigned = L.NonNegative && R.NonNegative; 10721 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 10722 L.NonNegative && R.NonNegative); 10723 } 10724 10725 /// Return the range of a bitwise-AND of the two ranges. 10726 static IntRange bit_and(IntRange L, IntRange R) { 10727 unsigned Bits = std::max(L.Width, R.Width); 10728 bool NonNegative = false; 10729 if (L.NonNegative) { 10730 Bits = std::min(Bits, L.Width); 10731 NonNegative = true; 10732 } 10733 if (R.NonNegative) { 10734 Bits = std::min(Bits, R.Width); 10735 NonNegative = true; 10736 } 10737 return IntRange(Bits, NonNegative); 10738 } 10739 10740 /// Return the range of a sum of the two ranges. 10741 static IntRange sum(IntRange L, IntRange R) { 10742 bool Unsigned = L.NonNegative && R.NonNegative; 10743 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 10744 Unsigned); 10745 } 10746 10747 /// Return the range of a difference of the two ranges. 10748 static IntRange difference(IntRange L, IntRange R) { 10749 // We need a 1-bit-wider range if: 10750 // 1) LHS can be negative: least value can be reduced. 10751 // 2) RHS can be negative: greatest value can be increased. 10752 bool CanWiden = !L.NonNegative || !R.NonNegative; 10753 bool Unsigned = L.NonNegative && R.Width == 0; 10754 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 10755 !Unsigned, 10756 Unsigned); 10757 } 10758 10759 /// Return the range of a product of the two ranges. 10760 static IntRange product(IntRange L, IntRange R) { 10761 // If both LHS and RHS can be negative, we can form 10762 // -2^L * -2^R = 2^(L + R) 10763 // which requires L + R + 1 value bits to represent. 10764 bool CanWiden = !L.NonNegative && !R.NonNegative; 10765 bool Unsigned = L.NonNegative && R.NonNegative; 10766 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 10767 Unsigned); 10768 } 10769 10770 /// Return the range of a remainder operation between the two ranges. 10771 static IntRange rem(IntRange L, IntRange R) { 10772 // The result of a remainder can't be larger than the result of 10773 // either side. The sign of the result is the sign of the LHS. 10774 bool Unsigned = L.NonNegative; 10775 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 10776 Unsigned); 10777 } 10778 }; 10779 10780 } // namespace 10781 10782 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10783 unsigned MaxWidth) { 10784 if (value.isSigned() && value.isNegative()) 10785 return IntRange(value.getMinSignedBits(), false); 10786 10787 if (value.getBitWidth() > MaxWidth) 10788 value = value.trunc(MaxWidth); 10789 10790 // isNonNegative() just checks the sign bit without considering 10791 // signedness. 10792 return IntRange(value.getActiveBits(), true); 10793 } 10794 10795 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10796 unsigned MaxWidth) { 10797 if (result.isInt()) 10798 return GetValueRange(C, result.getInt(), MaxWidth); 10799 10800 if (result.isVector()) { 10801 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10802 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10803 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10804 R = IntRange::join(R, El); 10805 } 10806 return R; 10807 } 10808 10809 if (result.isComplexInt()) { 10810 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10811 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10812 return IntRange::join(R, I); 10813 } 10814 10815 // This can happen with lossless casts to intptr_t of "based" lvalues. 10816 // Assume it might use arbitrary bits. 10817 // FIXME: The only reason we need to pass the type in here is to get 10818 // the sign right on this one case. It would be nice if APValue 10819 // preserved this. 10820 assert(result.isLValue() || result.isAddrLabelDiff()); 10821 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10822 } 10823 10824 static QualType GetExprType(const Expr *E) { 10825 QualType Ty = E->getType(); 10826 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10827 Ty = AtomicRHS->getValueType(); 10828 return Ty; 10829 } 10830 10831 /// Pseudo-evaluate the given integer expression, estimating the 10832 /// range of values it might take. 10833 /// 10834 /// \param MaxWidth The width to which the value will be truncated. 10835 /// \param Approximate If \c true, return a likely range for the result: in 10836 /// particular, assume that aritmetic on narrower types doesn't leave 10837 /// those types. If \c false, return a range including all possible 10838 /// result values. 10839 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10840 bool InConstantContext, bool Approximate) { 10841 E = E->IgnoreParens(); 10842 10843 // Try a full evaluation first. 10844 Expr::EvalResult result; 10845 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10846 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10847 10848 // I think we only want to look through implicit casts here; if the 10849 // user has an explicit widening cast, we should treat the value as 10850 // being of the new, wider type. 10851 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10852 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10853 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 10854 Approximate); 10855 10856 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10857 10858 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10859 CE->getCastKind() == CK_BooleanToSignedIntegral; 10860 10861 // Assume that non-integer casts can span the full range of the type. 10862 if (!isIntegerCast) 10863 return OutputTypeRange; 10864 10865 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10866 std::min(MaxWidth, OutputTypeRange.Width), 10867 InConstantContext, Approximate); 10868 10869 // Bail out if the subexpr's range is as wide as the cast type. 10870 if (SubRange.Width >= OutputTypeRange.Width) 10871 return OutputTypeRange; 10872 10873 // Otherwise, we take the smaller width, and we're non-negative if 10874 // either the output type or the subexpr is. 10875 return IntRange(SubRange.Width, 10876 SubRange.NonNegative || OutputTypeRange.NonNegative); 10877 } 10878 10879 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10880 // If we can fold the condition, just take that operand. 10881 bool CondResult; 10882 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10883 return GetExprRange(C, 10884 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10885 MaxWidth, InConstantContext, Approximate); 10886 10887 // Otherwise, conservatively merge. 10888 // GetExprRange requires an integer expression, but a throw expression 10889 // results in a void type. 10890 Expr *E = CO->getTrueExpr(); 10891 IntRange L = E->getType()->isVoidType() 10892 ? IntRange{0, true} 10893 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10894 E = CO->getFalseExpr(); 10895 IntRange R = E->getType()->isVoidType() 10896 ? IntRange{0, true} 10897 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 10898 return IntRange::join(L, R); 10899 } 10900 10901 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10902 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 10903 10904 switch (BO->getOpcode()) { 10905 case BO_Cmp: 10906 llvm_unreachable("builtin <=> should have class type"); 10907 10908 // Boolean-valued operations are single-bit and positive. 10909 case BO_LAnd: 10910 case BO_LOr: 10911 case BO_LT: 10912 case BO_GT: 10913 case BO_LE: 10914 case BO_GE: 10915 case BO_EQ: 10916 case BO_NE: 10917 return IntRange::forBoolType(); 10918 10919 // The type of the assignments is the type of the LHS, so the RHS 10920 // is not necessarily the same type. 10921 case BO_MulAssign: 10922 case BO_DivAssign: 10923 case BO_RemAssign: 10924 case BO_AddAssign: 10925 case BO_SubAssign: 10926 case BO_XorAssign: 10927 case BO_OrAssign: 10928 // TODO: bitfields? 10929 return IntRange::forValueOfType(C, GetExprType(E)); 10930 10931 // Simple assignments just pass through the RHS, which will have 10932 // been coerced to the LHS type. 10933 case BO_Assign: 10934 // TODO: bitfields? 10935 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10936 Approximate); 10937 10938 // Operations with opaque sources are black-listed. 10939 case BO_PtrMemD: 10940 case BO_PtrMemI: 10941 return IntRange::forValueOfType(C, GetExprType(E)); 10942 10943 // Bitwise-and uses the *infinum* of the two source ranges. 10944 case BO_And: 10945 case BO_AndAssign: 10946 Combine = IntRange::bit_and; 10947 break; 10948 10949 // Left shift gets black-listed based on a judgement call. 10950 case BO_Shl: 10951 // ...except that we want to treat '1 << (blah)' as logically 10952 // positive. It's an important idiom. 10953 if (IntegerLiteral *I 10954 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10955 if (I->getValue() == 1) { 10956 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10957 return IntRange(R.Width, /*NonNegative*/ true); 10958 } 10959 } 10960 LLVM_FALLTHROUGH; 10961 10962 case BO_ShlAssign: 10963 return IntRange::forValueOfType(C, GetExprType(E)); 10964 10965 // Right shift by a constant can narrow its left argument. 10966 case BO_Shr: 10967 case BO_ShrAssign: { 10968 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 10969 Approximate); 10970 10971 // If the shift amount is a positive constant, drop the width by 10972 // that much. 10973 if (Optional<llvm::APSInt> shift = 10974 BO->getRHS()->getIntegerConstantExpr(C)) { 10975 if (shift->isNonNegative()) { 10976 unsigned zext = shift->getZExtValue(); 10977 if (zext >= L.Width) 10978 L.Width = (L.NonNegative ? 0 : 1); 10979 else 10980 L.Width -= zext; 10981 } 10982 } 10983 10984 return L; 10985 } 10986 10987 // Comma acts as its right operand. 10988 case BO_Comma: 10989 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 10990 Approximate); 10991 10992 case BO_Add: 10993 if (!Approximate) 10994 Combine = IntRange::sum; 10995 break; 10996 10997 case BO_Sub: 10998 if (BO->getLHS()->getType()->isPointerType()) 10999 return IntRange::forValueOfType(C, GetExprType(E)); 11000 if (!Approximate) 11001 Combine = IntRange::difference; 11002 break; 11003 11004 case BO_Mul: 11005 if (!Approximate) 11006 Combine = IntRange::product; 11007 break; 11008 11009 // The width of a division result is mostly determined by the size 11010 // of the LHS. 11011 case BO_Div: { 11012 // Don't 'pre-truncate' the operands. 11013 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11014 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11015 Approximate); 11016 11017 // If the divisor is constant, use that. 11018 if (Optional<llvm::APSInt> divisor = 11019 BO->getRHS()->getIntegerConstantExpr(C)) { 11020 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11021 if (log2 >= L.Width) 11022 L.Width = (L.NonNegative ? 0 : 1); 11023 else 11024 L.Width = std::min(L.Width - log2, MaxWidth); 11025 return L; 11026 } 11027 11028 // Otherwise, just use the LHS's width. 11029 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11030 // could be -1. 11031 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11032 Approximate); 11033 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11034 } 11035 11036 case BO_Rem: 11037 Combine = IntRange::rem; 11038 break; 11039 11040 // The default behavior is okay for these. 11041 case BO_Xor: 11042 case BO_Or: 11043 break; 11044 } 11045 11046 // Combine the two ranges, but limit the result to the type in which we 11047 // performed the computation. 11048 QualType T = GetExprType(E); 11049 unsigned opWidth = C.getIntWidth(T); 11050 IntRange L = 11051 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11052 IntRange R = 11053 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11054 IntRange C = Combine(L, R); 11055 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11056 C.Width = std::min(C.Width, MaxWidth); 11057 return C; 11058 } 11059 11060 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11061 switch (UO->getOpcode()) { 11062 // Boolean-valued operations are white-listed. 11063 case UO_LNot: 11064 return IntRange::forBoolType(); 11065 11066 // Operations with opaque sources are black-listed. 11067 case UO_Deref: 11068 case UO_AddrOf: // should be impossible 11069 return IntRange::forValueOfType(C, GetExprType(E)); 11070 11071 default: 11072 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11073 Approximate); 11074 } 11075 } 11076 11077 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11078 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11079 Approximate); 11080 11081 if (const auto *BitField = E->getSourceBitField()) 11082 return IntRange(BitField->getBitWidthValue(C), 11083 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11084 11085 return IntRange::forValueOfType(C, GetExprType(E)); 11086 } 11087 11088 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11089 bool InConstantContext, bool Approximate) { 11090 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11091 Approximate); 11092 } 11093 11094 /// Checks whether the given value, which currently has the given 11095 /// source semantics, has the same value when coerced through the 11096 /// target semantics. 11097 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11098 const llvm::fltSemantics &Src, 11099 const llvm::fltSemantics &Tgt) { 11100 llvm::APFloat truncated = value; 11101 11102 bool ignored; 11103 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11104 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11105 11106 return truncated.bitwiseIsEqual(value); 11107 } 11108 11109 /// Checks whether the given value, which currently has the given 11110 /// source semantics, has the same value when coerced through the 11111 /// target semantics. 11112 /// 11113 /// The value might be a vector of floats (or a complex number). 11114 static bool IsSameFloatAfterCast(const APValue &value, 11115 const llvm::fltSemantics &Src, 11116 const llvm::fltSemantics &Tgt) { 11117 if (value.isFloat()) 11118 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11119 11120 if (value.isVector()) { 11121 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11122 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11123 return false; 11124 return true; 11125 } 11126 11127 assert(value.isComplexFloat()); 11128 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11129 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11130 } 11131 11132 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11133 bool IsListInit = false); 11134 11135 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11136 // Suppress cases where we are comparing against an enum constant. 11137 if (const DeclRefExpr *DR = 11138 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11139 if (isa<EnumConstantDecl>(DR->getDecl())) 11140 return true; 11141 11142 // Suppress cases where the value is expanded from a macro, unless that macro 11143 // is how a language represents a boolean literal. This is the case in both C 11144 // and Objective-C. 11145 SourceLocation BeginLoc = E->getBeginLoc(); 11146 if (BeginLoc.isMacroID()) { 11147 StringRef MacroName = Lexer::getImmediateMacroName( 11148 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11149 return MacroName != "YES" && MacroName != "NO" && 11150 MacroName != "true" && MacroName != "false"; 11151 } 11152 11153 return false; 11154 } 11155 11156 static bool isKnownToHaveUnsignedValue(Expr *E) { 11157 return E->getType()->isIntegerType() && 11158 (!E->getType()->isSignedIntegerType() || 11159 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11160 } 11161 11162 namespace { 11163 /// The promoted range of values of a type. In general this has the 11164 /// following structure: 11165 /// 11166 /// |-----------| . . . |-----------| 11167 /// ^ ^ ^ ^ 11168 /// Min HoleMin HoleMax Max 11169 /// 11170 /// ... where there is only a hole if a signed type is promoted to unsigned 11171 /// (in which case Min and Max are the smallest and largest representable 11172 /// values). 11173 struct PromotedRange { 11174 // Min, or HoleMax if there is a hole. 11175 llvm::APSInt PromotedMin; 11176 // Max, or HoleMin if there is a hole. 11177 llvm::APSInt PromotedMax; 11178 11179 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11180 if (R.Width == 0) 11181 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11182 else if (R.Width >= BitWidth && !Unsigned) { 11183 // Promotion made the type *narrower*. This happens when promoting 11184 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11185 // Treat all values of 'signed int' as being in range for now. 11186 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11187 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11188 } else { 11189 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11190 .extOrTrunc(BitWidth); 11191 PromotedMin.setIsUnsigned(Unsigned); 11192 11193 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11194 .extOrTrunc(BitWidth); 11195 PromotedMax.setIsUnsigned(Unsigned); 11196 } 11197 } 11198 11199 // Determine whether this range is contiguous (has no hole). 11200 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11201 11202 // Where a constant value is within the range. 11203 enum ComparisonResult { 11204 LT = 0x1, 11205 LE = 0x2, 11206 GT = 0x4, 11207 GE = 0x8, 11208 EQ = 0x10, 11209 NE = 0x20, 11210 InRangeFlag = 0x40, 11211 11212 Less = LE | LT | NE, 11213 Min = LE | InRangeFlag, 11214 InRange = InRangeFlag, 11215 Max = GE | InRangeFlag, 11216 Greater = GE | GT | NE, 11217 11218 OnlyValue = LE | GE | EQ | InRangeFlag, 11219 InHole = NE 11220 }; 11221 11222 ComparisonResult compare(const llvm::APSInt &Value) const { 11223 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11224 Value.isUnsigned() == PromotedMin.isUnsigned()); 11225 if (!isContiguous()) { 11226 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11227 if (Value.isMinValue()) return Min; 11228 if (Value.isMaxValue()) return Max; 11229 if (Value >= PromotedMin) return InRange; 11230 if (Value <= PromotedMax) return InRange; 11231 return InHole; 11232 } 11233 11234 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11235 case -1: return Less; 11236 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11237 case 1: 11238 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11239 case -1: return InRange; 11240 case 0: return Max; 11241 case 1: return Greater; 11242 } 11243 } 11244 11245 llvm_unreachable("impossible compare result"); 11246 } 11247 11248 static llvm::Optional<StringRef> 11249 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11250 if (Op == BO_Cmp) { 11251 ComparisonResult LTFlag = LT, GTFlag = GT; 11252 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11253 11254 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11255 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11256 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11257 return llvm::None; 11258 } 11259 11260 ComparisonResult TrueFlag, FalseFlag; 11261 if (Op == BO_EQ) { 11262 TrueFlag = EQ; 11263 FalseFlag = NE; 11264 } else if (Op == BO_NE) { 11265 TrueFlag = NE; 11266 FalseFlag = EQ; 11267 } else { 11268 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11269 TrueFlag = LT; 11270 FalseFlag = GE; 11271 } else { 11272 TrueFlag = GT; 11273 FalseFlag = LE; 11274 } 11275 if (Op == BO_GE || Op == BO_LE) 11276 std::swap(TrueFlag, FalseFlag); 11277 } 11278 if (R & TrueFlag) 11279 return StringRef("true"); 11280 if (R & FalseFlag) 11281 return StringRef("false"); 11282 return llvm::None; 11283 } 11284 }; 11285 } 11286 11287 static bool HasEnumType(Expr *E) { 11288 // Strip off implicit integral promotions. 11289 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11290 if (ICE->getCastKind() != CK_IntegralCast && 11291 ICE->getCastKind() != CK_NoOp) 11292 break; 11293 E = ICE->getSubExpr(); 11294 } 11295 11296 return E->getType()->isEnumeralType(); 11297 } 11298 11299 static int classifyConstantValue(Expr *Constant) { 11300 // The values of this enumeration are used in the diagnostics 11301 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11302 enum ConstantValueKind { 11303 Miscellaneous = 0, 11304 LiteralTrue, 11305 LiteralFalse 11306 }; 11307 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11308 return BL->getValue() ? ConstantValueKind::LiteralTrue 11309 : ConstantValueKind::LiteralFalse; 11310 return ConstantValueKind::Miscellaneous; 11311 } 11312 11313 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11314 Expr *Constant, Expr *Other, 11315 const llvm::APSInt &Value, 11316 bool RhsConstant) { 11317 if (S.inTemplateInstantiation()) 11318 return false; 11319 11320 Expr *OriginalOther = Other; 11321 11322 Constant = Constant->IgnoreParenImpCasts(); 11323 Other = Other->IgnoreParenImpCasts(); 11324 11325 // Suppress warnings on tautological comparisons between values of the same 11326 // enumeration type. There are only two ways we could warn on this: 11327 // - If the constant is outside the range of representable values of 11328 // the enumeration. In such a case, we should warn about the cast 11329 // to enumeration type, not about the comparison. 11330 // - If the constant is the maximum / minimum in-range value. For an 11331 // enumeratin type, such comparisons can be meaningful and useful. 11332 if (Constant->getType()->isEnumeralType() && 11333 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11334 return false; 11335 11336 IntRange OtherValueRange = GetExprRange( 11337 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11338 11339 QualType OtherT = Other->getType(); 11340 if (const auto *AT = OtherT->getAs<AtomicType>()) 11341 OtherT = AT->getValueType(); 11342 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11343 11344 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11345 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11346 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11347 S.NSAPIObj->isObjCBOOLType(OtherT) && 11348 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11349 11350 // Whether we're treating Other as being a bool because of the form of 11351 // expression despite it having another type (typically 'int' in C). 11352 bool OtherIsBooleanDespiteType = 11353 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11354 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11355 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11356 11357 // Check if all values in the range of possible values of this expression 11358 // lead to the same comparison outcome. 11359 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11360 Value.isUnsigned()); 11361 auto Cmp = OtherPromotedValueRange.compare(Value); 11362 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11363 if (!Result) 11364 return false; 11365 11366 // Also consider the range determined by the type alone. This allows us to 11367 // classify the warning under the proper diagnostic group. 11368 bool TautologicalTypeCompare = false; 11369 { 11370 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11371 Value.isUnsigned()); 11372 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11373 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11374 RhsConstant)) { 11375 TautologicalTypeCompare = true; 11376 Cmp = TypeCmp; 11377 Result = TypeResult; 11378 } 11379 } 11380 11381 // Don't warn if the non-constant operand actually always evaluates to the 11382 // same value. 11383 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11384 return false; 11385 11386 // Suppress the diagnostic for an in-range comparison if the constant comes 11387 // from a macro or enumerator. We don't want to diagnose 11388 // 11389 // some_long_value <= INT_MAX 11390 // 11391 // when sizeof(int) == sizeof(long). 11392 bool InRange = Cmp & PromotedRange::InRangeFlag; 11393 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11394 return false; 11395 11396 // A comparison of an unsigned bit-field against 0 is really a type problem, 11397 // even though at the type level the bit-field might promote to 'signed int'. 11398 if (Other->refersToBitField() && InRange && Value == 0 && 11399 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11400 TautologicalTypeCompare = true; 11401 11402 // If this is a comparison to an enum constant, include that 11403 // constant in the diagnostic. 11404 const EnumConstantDecl *ED = nullptr; 11405 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11406 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11407 11408 // Should be enough for uint128 (39 decimal digits) 11409 SmallString<64> PrettySourceValue; 11410 llvm::raw_svector_ostream OS(PrettySourceValue); 11411 if (ED) { 11412 OS << '\'' << *ED << "' (" << Value << ")"; 11413 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11414 Constant->IgnoreParenImpCasts())) { 11415 OS << (BL->getValue() ? "YES" : "NO"); 11416 } else { 11417 OS << Value; 11418 } 11419 11420 if (!TautologicalTypeCompare) { 11421 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11422 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11423 << E->getOpcodeStr() << OS.str() << *Result 11424 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11425 return true; 11426 } 11427 11428 if (IsObjCSignedCharBool) { 11429 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11430 S.PDiag(diag::warn_tautological_compare_objc_bool) 11431 << OS.str() << *Result); 11432 return true; 11433 } 11434 11435 // FIXME: We use a somewhat different formatting for the in-range cases and 11436 // cases involving boolean values for historical reasons. We should pick a 11437 // consistent way of presenting these diagnostics. 11438 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11439 11440 S.DiagRuntimeBehavior( 11441 E->getOperatorLoc(), E, 11442 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11443 : diag::warn_tautological_bool_compare) 11444 << OS.str() << classifyConstantValue(Constant) << OtherT 11445 << OtherIsBooleanDespiteType << *Result 11446 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11447 } else { 11448 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11449 unsigned Diag = 11450 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11451 ? (HasEnumType(OriginalOther) 11452 ? diag::warn_unsigned_enum_always_true_comparison 11453 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 11454 : diag::warn_unsigned_always_true_comparison) 11455 : diag::warn_tautological_constant_compare; 11456 11457 S.Diag(E->getOperatorLoc(), Diag) 11458 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11459 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11460 } 11461 11462 return true; 11463 } 11464 11465 /// Analyze the operands of the given comparison. Implements the 11466 /// fallback case from AnalyzeComparison. 11467 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11468 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11469 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11470 } 11471 11472 /// Implements -Wsign-compare. 11473 /// 11474 /// \param E the binary operator to check for warnings 11475 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11476 // The type the comparison is being performed in. 11477 QualType T = E->getLHS()->getType(); 11478 11479 // Only analyze comparison operators where both sides have been converted to 11480 // the same type. 11481 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11482 return AnalyzeImpConvsInComparison(S, E); 11483 11484 // Don't analyze value-dependent comparisons directly. 11485 if (E->isValueDependent()) 11486 return AnalyzeImpConvsInComparison(S, E); 11487 11488 Expr *LHS = E->getLHS(); 11489 Expr *RHS = E->getRHS(); 11490 11491 if (T->isIntegralType(S.Context)) { 11492 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11493 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11494 11495 // We don't care about expressions whose result is a constant. 11496 if (RHSValue && LHSValue) 11497 return AnalyzeImpConvsInComparison(S, E); 11498 11499 // We only care about expressions where just one side is literal 11500 if ((bool)RHSValue ^ (bool)LHSValue) { 11501 // Is the constant on the RHS or LHS? 11502 const bool RhsConstant = (bool)RHSValue; 11503 Expr *Const = RhsConstant ? RHS : LHS; 11504 Expr *Other = RhsConstant ? LHS : RHS; 11505 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11506 11507 // Check whether an integer constant comparison results in a value 11508 // of 'true' or 'false'. 11509 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 11510 return AnalyzeImpConvsInComparison(S, E); 11511 } 11512 } 11513 11514 if (!T->hasUnsignedIntegerRepresentation()) { 11515 // We don't do anything special if this isn't an unsigned integral 11516 // comparison: we're only interested in integral comparisons, and 11517 // signed comparisons only happen in cases we don't care to warn about. 11518 return AnalyzeImpConvsInComparison(S, E); 11519 } 11520 11521 LHS = LHS->IgnoreParenImpCasts(); 11522 RHS = RHS->IgnoreParenImpCasts(); 11523 11524 if (!S.getLangOpts().CPlusPlus) { 11525 // Avoid warning about comparison of integers with different signs when 11526 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 11527 // the type of `E`. 11528 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 11529 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11530 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 11531 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 11532 } 11533 11534 // Check to see if one of the (unmodified) operands is of different 11535 // signedness. 11536 Expr *signedOperand, *unsignedOperand; 11537 if (LHS->getType()->hasSignedIntegerRepresentation()) { 11538 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 11539 "unsigned comparison between two signed integer expressions?"); 11540 signedOperand = LHS; 11541 unsignedOperand = RHS; 11542 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 11543 signedOperand = RHS; 11544 unsignedOperand = LHS; 11545 } else { 11546 return AnalyzeImpConvsInComparison(S, E); 11547 } 11548 11549 // Otherwise, calculate the effective range of the signed operand. 11550 IntRange signedRange = GetExprRange( 11551 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 11552 11553 // Go ahead and analyze implicit conversions in the operands. Note 11554 // that we skip the implicit conversions on both sides. 11555 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 11556 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 11557 11558 // If the signed range is non-negative, -Wsign-compare won't fire. 11559 if (signedRange.NonNegative) 11560 return; 11561 11562 // For (in)equality comparisons, if the unsigned operand is a 11563 // constant which cannot collide with a overflowed signed operand, 11564 // then reinterpreting the signed operand as unsigned will not 11565 // change the result of the comparison. 11566 if (E->isEqualityOp()) { 11567 unsigned comparisonWidth = S.Context.getIntWidth(T); 11568 IntRange unsignedRange = 11569 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 11570 /*Approximate*/ true); 11571 11572 // We should never be unable to prove that the unsigned operand is 11573 // non-negative. 11574 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 11575 11576 if (unsignedRange.Width < comparisonWidth) 11577 return; 11578 } 11579 11580 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11581 S.PDiag(diag::warn_mixed_sign_comparison) 11582 << LHS->getType() << RHS->getType() 11583 << LHS->getSourceRange() << RHS->getSourceRange()); 11584 } 11585 11586 /// Analyzes an attempt to assign the given value to a bitfield. 11587 /// 11588 /// Returns true if there was something fishy about the attempt. 11589 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 11590 SourceLocation InitLoc) { 11591 assert(Bitfield->isBitField()); 11592 if (Bitfield->isInvalidDecl()) 11593 return false; 11594 11595 // White-list bool bitfields. 11596 QualType BitfieldType = Bitfield->getType(); 11597 if (BitfieldType->isBooleanType()) 11598 return false; 11599 11600 if (BitfieldType->isEnumeralType()) { 11601 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 11602 // If the underlying enum type was not explicitly specified as an unsigned 11603 // type and the enum contain only positive values, MSVC++ will cause an 11604 // inconsistency by storing this as a signed type. 11605 if (S.getLangOpts().CPlusPlus11 && 11606 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 11607 BitfieldEnumDecl->getNumPositiveBits() > 0 && 11608 BitfieldEnumDecl->getNumNegativeBits() == 0) { 11609 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 11610 << BitfieldEnumDecl; 11611 } 11612 } 11613 11614 if (Bitfield->getType()->isBooleanType()) 11615 return false; 11616 11617 // Ignore value- or type-dependent expressions. 11618 if (Bitfield->getBitWidth()->isValueDependent() || 11619 Bitfield->getBitWidth()->isTypeDependent() || 11620 Init->isValueDependent() || 11621 Init->isTypeDependent()) 11622 return false; 11623 11624 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 11625 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 11626 11627 Expr::EvalResult Result; 11628 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 11629 Expr::SE_AllowSideEffects)) { 11630 // The RHS is not constant. If the RHS has an enum type, make sure the 11631 // bitfield is wide enough to hold all the values of the enum without 11632 // truncation. 11633 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 11634 EnumDecl *ED = EnumTy->getDecl(); 11635 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 11636 11637 // Enum types are implicitly signed on Windows, so check if there are any 11638 // negative enumerators to see if the enum was intended to be signed or 11639 // not. 11640 bool SignedEnum = ED->getNumNegativeBits() > 0; 11641 11642 // Check for surprising sign changes when assigning enum values to a 11643 // bitfield of different signedness. If the bitfield is signed and we 11644 // have exactly the right number of bits to store this unsigned enum, 11645 // suggest changing the enum to an unsigned type. This typically happens 11646 // on Windows where unfixed enums always use an underlying type of 'int'. 11647 unsigned DiagID = 0; 11648 if (SignedEnum && !SignedBitfield) { 11649 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11650 } else if (SignedBitfield && !SignedEnum && 11651 ED->getNumPositiveBits() == FieldWidth) { 11652 DiagID = diag::warn_signed_bitfield_enum_conversion; 11653 } 11654 11655 if (DiagID) { 11656 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11657 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11658 SourceRange TypeRange = 11659 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11660 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11661 << SignedEnum << TypeRange; 11662 } 11663 11664 // Compute the required bitwidth. If the enum has negative values, we need 11665 // one more bit than the normal number of positive bits to represent the 11666 // sign bit. 11667 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11668 ED->getNumNegativeBits()) 11669 : ED->getNumPositiveBits(); 11670 11671 // Check the bitwidth. 11672 if (BitsNeeded > FieldWidth) { 11673 Expr *WidthExpr = Bitfield->getBitWidth(); 11674 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11675 << Bitfield << ED; 11676 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11677 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11678 } 11679 } 11680 11681 return false; 11682 } 11683 11684 llvm::APSInt Value = Result.Val.getInt(); 11685 11686 unsigned OriginalWidth = Value.getBitWidth(); 11687 11688 if (!Value.isSigned() || Value.isNegative()) 11689 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11690 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11691 OriginalWidth = Value.getMinSignedBits(); 11692 11693 if (OriginalWidth <= FieldWidth) 11694 return false; 11695 11696 // Compute the value which the bitfield will contain. 11697 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11698 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11699 11700 // Check whether the stored value is equal to the original value. 11701 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11702 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11703 return false; 11704 11705 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11706 // therefore don't strictly fit into a signed bitfield of width 1. 11707 if (FieldWidth == 1 && Value == 1) 11708 return false; 11709 11710 std::string PrettyValue = Value.toString(10); 11711 std::string PrettyTrunc = TruncatedValue.toString(10); 11712 11713 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11714 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11715 << Init->getSourceRange(); 11716 11717 return true; 11718 } 11719 11720 /// Analyze the given simple or compound assignment for warning-worthy 11721 /// operations. 11722 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11723 // Just recurse on the LHS. 11724 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11725 11726 // We want to recurse on the RHS as normal unless we're assigning to 11727 // a bitfield. 11728 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11729 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11730 E->getOperatorLoc())) { 11731 // Recurse, ignoring any implicit conversions on the RHS. 11732 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11733 E->getOperatorLoc()); 11734 } 11735 } 11736 11737 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11738 11739 // Diagnose implicitly sequentially-consistent atomic assignment. 11740 if (E->getLHS()->getType()->isAtomicType()) 11741 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11742 } 11743 11744 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11745 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11746 SourceLocation CContext, unsigned diag, 11747 bool pruneControlFlow = false) { 11748 if (pruneControlFlow) { 11749 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11750 S.PDiag(diag) 11751 << SourceType << T << E->getSourceRange() 11752 << SourceRange(CContext)); 11753 return; 11754 } 11755 S.Diag(E->getExprLoc(), diag) 11756 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11757 } 11758 11759 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11760 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11761 SourceLocation CContext, 11762 unsigned diag, bool pruneControlFlow = false) { 11763 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11764 } 11765 11766 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11767 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11768 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11769 } 11770 11771 static void adornObjCBoolConversionDiagWithTernaryFixit( 11772 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11773 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11774 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11775 Ignored = OVE->getSourceExpr(); 11776 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11777 isa<BinaryOperator>(Ignored) || 11778 isa<CXXOperatorCallExpr>(Ignored); 11779 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11780 if (NeedsParens) 11781 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11782 << FixItHint::CreateInsertion(EndLoc, ")"); 11783 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11784 } 11785 11786 /// Diagnose an implicit cast from a floating point value to an integer value. 11787 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11788 SourceLocation CContext) { 11789 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11790 const bool PruneWarnings = S.inTemplateInstantiation(); 11791 11792 Expr *InnerE = E->IgnoreParenImpCasts(); 11793 // We also want to warn on, e.g., "int i = -1.234" 11794 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11795 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11796 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11797 11798 const bool IsLiteral = 11799 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11800 11801 llvm::APFloat Value(0.0); 11802 bool IsConstant = 11803 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11804 if (!IsConstant) { 11805 if (isObjCSignedCharBool(S, T)) { 11806 return adornObjCBoolConversionDiagWithTernaryFixit( 11807 S, E, 11808 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11809 << E->getType()); 11810 } 11811 11812 return DiagnoseImpCast(S, E, T, CContext, 11813 diag::warn_impcast_float_integer, PruneWarnings); 11814 } 11815 11816 bool isExact = false; 11817 11818 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11819 T->hasUnsignedIntegerRepresentation()); 11820 llvm::APFloat::opStatus Result = Value.convertToInteger( 11821 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11822 11823 // FIXME: Force the precision of the source value down so we don't print 11824 // digits which are usually useless (we don't really care here if we 11825 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11826 // would automatically print the shortest representation, but it's a bit 11827 // tricky to implement. 11828 SmallString<16> PrettySourceValue; 11829 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11830 precision = (precision * 59 + 195) / 196; 11831 Value.toString(PrettySourceValue, precision); 11832 11833 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11834 return adornObjCBoolConversionDiagWithTernaryFixit( 11835 S, E, 11836 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11837 << PrettySourceValue); 11838 } 11839 11840 if (Result == llvm::APFloat::opOK && isExact) { 11841 if (IsLiteral) return; 11842 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11843 PruneWarnings); 11844 } 11845 11846 // Conversion of a floating-point value to a non-bool integer where the 11847 // integral part cannot be represented by the integer type is undefined. 11848 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11849 return DiagnoseImpCast( 11850 S, E, T, CContext, 11851 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11852 : diag::warn_impcast_float_to_integer_out_of_range, 11853 PruneWarnings); 11854 11855 unsigned DiagID = 0; 11856 if (IsLiteral) { 11857 // Warn on floating point literal to integer. 11858 DiagID = diag::warn_impcast_literal_float_to_integer; 11859 } else if (IntegerValue == 0) { 11860 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11861 return DiagnoseImpCast(S, E, T, CContext, 11862 diag::warn_impcast_float_integer, PruneWarnings); 11863 } 11864 // Warn on non-zero to zero conversion. 11865 DiagID = diag::warn_impcast_float_to_integer_zero; 11866 } else { 11867 if (IntegerValue.isUnsigned()) { 11868 if (!IntegerValue.isMaxValue()) { 11869 return DiagnoseImpCast(S, E, T, CContext, 11870 diag::warn_impcast_float_integer, PruneWarnings); 11871 } 11872 } else { // IntegerValue.isSigned() 11873 if (!IntegerValue.isMaxSignedValue() && 11874 !IntegerValue.isMinSignedValue()) { 11875 return DiagnoseImpCast(S, E, T, CContext, 11876 diag::warn_impcast_float_integer, PruneWarnings); 11877 } 11878 } 11879 // Warn on evaluatable floating point expression to integer conversion. 11880 DiagID = diag::warn_impcast_float_to_integer; 11881 } 11882 11883 SmallString<16> PrettyTargetValue; 11884 if (IsBool) 11885 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11886 else 11887 IntegerValue.toString(PrettyTargetValue); 11888 11889 if (PruneWarnings) { 11890 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11891 S.PDiag(DiagID) 11892 << E->getType() << T.getUnqualifiedType() 11893 << PrettySourceValue << PrettyTargetValue 11894 << E->getSourceRange() << SourceRange(CContext)); 11895 } else { 11896 S.Diag(E->getExprLoc(), DiagID) 11897 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11898 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11899 } 11900 } 11901 11902 /// Analyze the given compound assignment for the possible losing of 11903 /// floating-point precision. 11904 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11905 assert(isa<CompoundAssignOperator>(E) && 11906 "Must be compound assignment operation"); 11907 // Recurse on the LHS and RHS in here 11908 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11909 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11910 11911 if (E->getLHS()->getType()->isAtomicType()) 11912 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11913 11914 // Now check the outermost expression 11915 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11916 const auto *RBT = cast<CompoundAssignOperator>(E) 11917 ->getComputationResultType() 11918 ->getAs<BuiltinType>(); 11919 11920 // The below checks assume source is floating point. 11921 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11922 11923 // If source is floating point but target is an integer. 11924 if (ResultBT->isInteger()) 11925 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11926 E->getExprLoc(), diag::warn_impcast_float_integer); 11927 11928 if (!ResultBT->isFloatingPoint()) 11929 return; 11930 11931 // If both source and target are floating points, warn about losing precision. 11932 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11933 QualType(ResultBT, 0), QualType(RBT, 0)); 11934 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11935 // warn about dropping FP rank. 11936 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11937 diag::warn_impcast_float_result_precision); 11938 } 11939 11940 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11941 IntRange Range) { 11942 if (!Range.Width) return "0"; 11943 11944 llvm::APSInt ValueInRange = Value; 11945 ValueInRange.setIsSigned(!Range.NonNegative); 11946 ValueInRange = ValueInRange.trunc(Range.Width); 11947 return ValueInRange.toString(10); 11948 } 11949 11950 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11951 if (!isa<ImplicitCastExpr>(Ex)) 11952 return false; 11953 11954 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11955 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11956 const Type *Source = 11957 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11958 if (Target->isDependentType()) 11959 return false; 11960 11961 const BuiltinType *FloatCandidateBT = 11962 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11963 const Type *BoolCandidateType = ToBool ? Target : Source; 11964 11965 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11966 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11967 } 11968 11969 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11970 SourceLocation CC) { 11971 unsigned NumArgs = TheCall->getNumArgs(); 11972 for (unsigned i = 0; i < NumArgs; ++i) { 11973 Expr *CurrA = TheCall->getArg(i); 11974 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11975 continue; 11976 11977 bool IsSwapped = ((i > 0) && 11978 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11979 IsSwapped |= ((i < (NumArgs - 1)) && 11980 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11981 if (IsSwapped) { 11982 // Warn on this floating-point to bool conversion. 11983 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11984 CurrA->getType(), CC, 11985 diag::warn_impcast_floating_point_to_bool); 11986 } 11987 } 11988 } 11989 11990 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11991 SourceLocation CC) { 11992 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11993 E->getExprLoc())) 11994 return; 11995 11996 // Don't warn on functions which have return type nullptr_t. 11997 if (isa<CallExpr>(E)) 11998 return; 11999 12000 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12001 const Expr::NullPointerConstantKind NullKind = 12002 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12003 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12004 return; 12005 12006 // Return if target type is a safe conversion. 12007 if (T->isAnyPointerType() || T->isBlockPointerType() || 12008 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12009 return; 12010 12011 SourceLocation Loc = E->getSourceRange().getBegin(); 12012 12013 // Venture through the macro stacks to get to the source of macro arguments. 12014 // The new location is a better location than the complete location that was 12015 // passed in. 12016 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12017 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12018 12019 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12020 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12021 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12022 Loc, S.SourceMgr, S.getLangOpts()); 12023 if (MacroName == "NULL") 12024 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12025 } 12026 12027 // Only warn if the null and context location are in the same macro expansion. 12028 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12029 return; 12030 12031 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12032 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12033 << FixItHint::CreateReplacement(Loc, 12034 S.getFixItZeroLiteralForType(T, Loc)); 12035 } 12036 12037 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12038 ObjCArrayLiteral *ArrayLiteral); 12039 12040 static void 12041 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12042 ObjCDictionaryLiteral *DictionaryLiteral); 12043 12044 /// Check a single element within a collection literal against the 12045 /// target element type. 12046 static void checkObjCCollectionLiteralElement(Sema &S, 12047 QualType TargetElementType, 12048 Expr *Element, 12049 unsigned ElementKind) { 12050 // Skip a bitcast to 'id' or qualified 'id'. 12051 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12052 if (ICE->getCastKind() == CK_BitCast && 12053 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12054 Element = ICE->getSubExpr(); 12055 } 12056 12057 QualType ElementType = Element->getType(); 12058 ExprResult ElementResult(Element); 12059 if (ElementType->getAs<ObjCObjectPointerType>() && 12060 S.CheckSingleAssignmentConstraints(TargetElementType, 12061 ElementResult, 12062 false, false) 12063 != Sema::Compatible) { 12064 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12065 << ElementType << ElementKind << TargetElementType 12066 << Element->getSourceRange(); 12067 } 12068 12069 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12070 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12071 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12072 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12073 } 12074 12075 /// Check an Objective-C array literal being converted to the given 12076 /// target type. 12077 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12078 ObjCArrayLiteral *ArrayLiteral) { 12079 if (!S.NSArrayDecl) 12080 return; 12081 12082 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12083 if (!TargetObjCPtr) 12084 return; 12085 12086 if (TargetObjCPtr->isUnspecialized() || 12087 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12088 != S.NSArrayDecl->getCanonicalDecl()) 12089 return; 12090 12091 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12092 if (TypeArgs.size() != 1) 12093 return; 12094 12095 QualType TargetElementType = TypeArgs[0]; 12096 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12097 checkObjCCollectionLiteralElement(S, TargetElementType, 12098 ArrayLiteral->getElement(I), 12099 0); 12100 } 12101 } 12102 12103 /// Check an Objective-C dictionary literal being converted to the given 12104 /// target type. 12105 static void 12106 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12107 ObjCDictionaryLiteral *DictionaryLiteral) { 12108 if (!S.NSDictionaryDecl) 12109 return; 12110 12111 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12112 if (!TargetObjCPtr) 12113 return; 12114 12115 if (TargetObjCPtr->isUnspecialized() || 12116 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12117 != S.NSDictionaryDecl->getCanonicalDecl()) 12118 return; 12119 12120 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12121 if (TypeArgs.size() != 2) 12122 return; 12123 12124 QualType TargetKeyType = TypeArgs[0]; 12125 QualType TargetObjectType = TypeArgs[1]; 12126 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12127 auto Element = DictionaryLiteral->getKeyValueElement(I); 12128 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12129 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12130 } 12131 } 12132 12133 // Helper function to filter out cases for constant width constant conversion. 12134 // Don't warn on char array initialization or for non-decimal values. 12135 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12136 SourceLocation CC) { 12137 // If initializing from a constant, and the constant starts with '0', 12138 // then it is a binary, octal, or hexadecimal. Allow these constants 12139 // to fill all the bits, even if there is a sign change. 12140 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12141 const char FirstLiteralCharacter = 12142 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12143 if (FirstLiteralCharacter == '0') 12144 return false; 12145 } 12146 12147 // If the CC location points to a '{', and the type is char, then assume 12148 // assume it is an array initialization. 12149 if (CC.isValid() && T->isCharType()) { 12150 const char FirstContextCharacter = 12151 S.getSourceManager().getCharacterData(CC)[0]; 12152 if (FirstContextCharacter == '{') 12153 return false; 12154 } 12155 12156 return true; 12157 } 12158 12159 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12160 const auto *IL = dyn_cast<IntegerLiteral>(E); 12161 if (!IL) { 12162 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12163 if (UO->getOpcode() == UO_Minus) 12164 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12165 } 12166 } 12167 12168 return IL; 12169 } 12170 12171 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12172 E = E->IgnoreParenImpCasts(); 12173 SourceLocation ExprLoc = E->getExprLoc(); 12174 12175 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12176 BinaryOperator::Opcode Opc = BO->getOpcode(); 12177 Expr::EvalResult Result; 12178 // Do not diagnose unsigned shifts. 12179 if (Opc == BO_Shl) { 12180 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12181 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12182 if (LHS && LHS->getValue() == 0) 12183 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12184 else if (!E->isValueDependent() && LHS && RHS && 12185 RHS->getValue().isNonNegative() && 12186 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12187 S.Diag(ExprLoc, diag::warn_left_shift_always) 12188 << (Result.Val.getInt() != 0); 12189 else if (E->getType()->isSignedIntegerType()) 12190 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12191 } 12192 } 12193 12194 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12195 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12196 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12197 if (!LHS || !RHS) 12198 return; 12199 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12200 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12201 // Do not diagnose common idioms. 12202 return; 12203 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12204 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12205 } 12206 } 12207 12208 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12209 SourceLocation CC, 12210 bool *ICContext = nullptr, 12211 bool IsListInit = false) { 12212 if (E->isTypeDependent() || E->isValueDependent()) return; 12213 12214 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12215 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12216 if (Source == Target) return; 12217 if (Target->isDependentType()) return; 12218 12219 // If the conversion context location is invalid don't complain. We also 12220 // don't want to emit a warning if the issue occurs from the expansion of 12221 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12222 // delay this check as long as possible. Once we detect we are in that 12223 // scenario, we just return. 12224 if (CC.isInvalid()) 12225 return; 12226 12227 if (Source->isAtomicType()) 12228 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12229 12230 // Diagnose implicit casts to bool. 12231 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12232 if (isa<StringLiteral>(E)) 12233 // Warn on string literal to bool. Checks for string literals in logical 12234 // and expressions, for instance, assert(0 && "error here"), are 12235 // prevented by a check in AnalyzeImplicitConversions(). 12236 return DiagnoseImpCast(S, E, T, CC, 12237 diag::warn_impcast_string_literal_to_bool); 12238 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12239 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12240 // This covers the literal expressions that evaluate to Objective-C 12241 // objects. 12242 return DiagnoseImpCast(S, E, T, CC, 12243 diag::warn_impcast_objective_c_literal_to_bool); 12244 } 12245 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12246 // Warn on pointer to bool conversion that is always true. 12247 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12248 SourceRange(CC)); 12249 } 12250 } 12251 12252 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12253 // is a typedef for signed char (macOS), then that constant value has to be 1 12254 // or 0. 12255 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12256 Expr::EvalResult Result; 12257 if (E->EvaluateAsInt(Result, S.getASTContext(), 12258 Expr::SE_AllowSideEffects)) { 12259 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12260 adornObjCBoolConversionDiagWithTernaryFixit( 12261 S, E, 12262 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12263 << Result.Val.getInt().toString(10)); 12264 } 12265 return; 12266 } 12267 } 12268 12269 // Check implicit casts from Objective-C collection literals to specialized 12270 // collection types, e.g., NSArray<NSString *> *. 12271 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12272 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12273 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12274 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12275 12276 // Strip vector types. 12277 if (const auto *SourceVT = dyn_cast<VectorType>(Source)) { 12278 if (Target->isVLSTBuiltinType()) { 12279 auto SourceVectorKind = SourceVT->getVectorKind(); 12280 if (SourceVectorKind == VectorType::SveFixedLengthDataVector || 12281 SourceVectorKind == VectorType::SveFixedLengthPredicateVector || 12282 (SourceVectorKind == VectorType::GenericVector && 12283 S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits)) 12284 return; 12285 } 12286 12287 if (!isa<VectorType>(Target)) { 12288 if (S.SourceMgr.isInSystemMacro(CC)) 12289 return; 12290 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12291 } 12292 12293 // If the vector cast is cast between two vectors of the same size, it is 12294 // a bitcast, not a conversion. 12295 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12296 return; 12297 12298 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12299 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12300 } 12301 if (auto VecTy = dyn_cast<VectorType>(Target)) 12302 Target = VecTy->getElementType().getTypePtr(); 12303 12304 // Strip complex types. 12305 if (isa<ComplexType>(Source)) { 12306 if (!isa<ComplexType>(Target)) { 12307 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12308 return; 12309 12310 return DiagnoseImpCast(S, E, T, CC, 12311 S.getLangOpts().CPlusPlus 12312 ? diag::err_impcast_complex_scalar 12313 : diag::warn_impcast_complex_scalar); 12314 } 12315 12316 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12317 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12318 } 12319 12320 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12321 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12322 12323 // If the source is floating point... 12324 if (SourceBT && SourceBT->isFloatingPoint()) { 12325 // ...and the target is floating point... 12326 if (TargetBT && TargetBT->isFloatingPoint()) { 12327 // ...then warn if we're dropping FP rank. 12328 12329 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12330 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12331 if (Order > 0) { 12332 // Don't warn about float constants that are precisely 12333 // representable in the target type. 12334 Expr::EvalResult result; 12335 if (E->EvaluateAsRValue(result, S.Context)) { 12336 // Value might be a float, a float vector, or a float complex. 12337 if (IsSameFloatAfterCast(result.Val, 12338 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12339 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12340 return; 12341 } 12342 12343 if (S.SourceMgr.isInSystemMacro(CC)) 12344 return; 12345 12346 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12347 } 12348 // ... or possibly if we're increasing rank, too 12349 else if (Order < 0) { 12350 if (S.SourceMgr.isInSystemMacro(CC)) 12351 return; 12352 12353 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12354 } 12355 return; 12356 } 12357 12358 // If the target is integral, always warn. 12359 if (TargetBT && TargetBT->isInteger()) { 12360 if (S.SourceMgr.isInSystemMacro(CC)) 12361 return; 12362 12363 DiagnoseFloatingImpCast(S, E, T, CC); 12364 } 12365 12366 // Detect the case where a call result is converted from floating-point to 12367 // to bool, and the final argument to the call is converted from bool, to 12368 // discover this typo: 12369 // 12370 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12371 // 12372 // FIXME: This is an incredibly special case; is there some more general 12373 // way to detect this class of misplaced-parentheses bug? 12374 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12375 // Check last argument of function call to see if it is an 12376 // implicit cast from a type matching the type the result 12377 // is being cast to. 12378 CallExpr *CEx = cast<CallExpr>(E); 12379 if (unsigned NumArgs = CEx->getNumArgs()) { 12380 Expr *LastA = CEx->getArg(NumArgs - 1); 12381 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12382 if (isa<ImplicitCastExpr>(LastA) && 12383 InnerE->getType()->isBooleanType()) { 12384 // Warn on this floating-point to bool conversion 12385 DiagnoseImpCast(S, E, T, CC, 12386 diag::warn_impcast_floating_point_to_bool); 12387 } 12388 } 12389 } 12390 return; 12391 } 12392 12393 // Valid casts involving fixed point types should be accounted for here. 12394 if (Source->isFixedPointType()) { 12395 if (Target->isUnsaturatedFixedPointType()) { 12396 Expr::EvalResult Result; 12397 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12398 S.isConstantEvaluated())) { 12399 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12400 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12401 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12402 if (Value > MaxVal || Value < MinVal) { 12403 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12404 S.PDiag(diag::warn_impcast_fixed_point_range) 12405 << Value.toString() << T 12406 << E->getSourceRange() 12407 << clang::SourceRange(CC)); 12408 return; 12409 } 12410 } 12411 } else if (Target->isIntegerType()) { 12412 Expr::EvalResult Result; 12413 if (!S.isConstantEvaluated() && 12414 E->EvaluateAsFixedPoint(Result, S.Context, 12415 Expr::SE_AllowSideEffects)) { 12416 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12417 12418 bool Overflowed; 12419 llvm::APSInt IntResult = FXResult.convertToInt( 12420 S.Context.getIntWidth(T), 12421 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12422 12423 if (Overflowed) { 12424 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12425 S.PDiag(diag::warn_impcast_fixed_point_range) 12426 << FXResult.toString() << T 12427 << E->getSourceRange() 12428 << clang::SourceRange(CC)); 12429 return; 12430 } 12431 } 12432 } 12433 } else if (Target->isUnsaturatedFixedPointType()) { 12434 if (Source->isIntegerType()) { 12435 Expr::EvalResult Result; 12436 if (!S.isConstantEvaluated() && 12437 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12438 llvm::APSInt Value = Result.Val.getInt(); 12439 12440 bool Overflowed; 12441 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12442 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12443 12444 if (Overflowed) { 12445 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12446 S.PDiag(diag::warn_impcast_fixed_point_range) 12447 << Value.toString(/*Radix=*/10) << T 12448 << E->getSourceRange() 12449 << clang::SourceRange(CC)); 12450 return; 12451 } 12452 } 12453 } 12454 } 12455 12456 // If we are casting an integer type to a floating point type without 12457 // initialization-list syntax, we might lose accuracy if the floating 12458 // point type has a narrower significand than the integer type. 12459 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12460 TargetBT->isFloatingType() && !IsListInit) { 12461 // Determine the number of precision bits in the source integer type. 12462 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12463 /*Approximate*/ true); 12464 unsigned int SourcePrecision = SourceRange.Width; 12465 12466 // Determine the number of precision bits in the 12467 // target floating point type. 12468 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12469 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12470 12471 if (SourcePrecision > 0 && TargetPrecision > 0 && 12472 SourcePrecision > TargetPrecision) { 12473 12474 if (Optional<llvm::APSInt> SourceInt = 12475 E->getIntegerConstantExpr(S.Context)) { 12476 // If the source integer is a constant, convert it to the target 12477 // floating point type. Issue a warning if the value changes 12478 // during the whole conversion. 12479 llvm::APFloat TargetFloatValue( 12480 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12481 llvm::APFloat::opStatus ConversionStatus = 12482 TargetFloatValue.convertFromAPInt( 12483 *SourceInt, SourceBT->isSignedInteger(), 12484 llvm::APFloat::rmNearestTiesToEven); 12485 12486 if (ConversionStatus != llvm::APFloat::opOK) { 12487 std::string PrettySourceValue = SourceInt->toString(10); 12488 SmallString<32> PrettyTargetValue; 12489 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12490 12491 S.DiagRuntimeBehavior( 12492 E->getExprLoc(), E, 12493 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12494 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12495 << E->getSourceRange() << clang::SourceRange(CC)); 12496 } 12497 } else { 12498 // Otherwise, the implicit conversion may lose precision. 12499 DiagnoseImpCast(S, E, T, CC, 12500 diag::warn_impcast_integer_float_precision); 12501 } 12502 } 12503 } 12504 12505 DiagnoseNullConversion(S, E, T, CC); 12506 12507 S.DiscardMisalignedMemberAddress(Target, E); 12508 12509 if (Target->isBooleanType()) 12510 DiagnoseIntInBoolContext(S, E); 12511 12512 if (!Source->isIntegerType() || !Target->isIntegerType()) 12513 return; 12514 12515 // TODO: remove this early return once the false positives for constant->bool 12516 // in templates, macros, etc, are reduced or removed. 12517 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 12518 return; 12519 12520 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 12521 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 12522 return adornObjCBoolConversionDiagWithTernaryFixit( 12523 S, E, 12524 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 12525 << E->getType()); 12526 } 12527 12528 IntRange SourceTypeRange = 12529 IntRange::forTargetOfCanonicalType(S.Context, Source); 12530 IntRange LikelySourceRange = 12531 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 12532 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 12533 12534 if (LikelySourceRange.Width > TargetRange.Width) { 12535 // If the source is a constant, use a default-on diagnostic. 12536 // TODO: this should happen for bitfield stores, too. 12537 Expr::EvalResult Result; 12538 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 12539 S.isConstantEvaluated())) { 12540 llvm::APSInt Value(32); 12541 Value = Result.Val.getInt(); 12542 12543 if (S.SourceMgr.isInSystemMacro(CC)) 12544 return; 12545 12546 std::string PrettySourceValue = Value.toString(10); 12547 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12548 12549 S.DiagRuntimeBehavior( 12550 E->getExprLoc(), E, 12551 S.PDiag(diag::warn_impcast_integer_precision_constant) 12552 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12553 << E->getSourceRange() << SourceRange(CC)); 12554 return; 12555 } 12556 12557 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 12558 if (S.SourceMgr.isInSystemMacro(CC)) 12559 return; 12560 12561 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 12562 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 12563 /* pruneControlFlow */ true); 12564 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 12565 } 12566 12567 if (TargetRange.Width > SourceTypeRange.Width) { 12568 if (auto *UO = dyn_cast<UnaryOperator>(E)) 12569 if (UO->getOpcode() == UO_Minus) 12570 if (Source->isUnsignedIntegerType()) { 12571 if (Target->isUnsignedIntegerType()) 12572 return DiagnoseImpCast(S, E, T, CC, 12573 diag::warn_impcast_high_order_zero_bits); 12574 if (Target->isSignedIntegerType()) 12575 return DiagnoseImpCast(S, E, T, CC, 12576 diag::warn_impcast_nonnegative_result); 12577 } 12578 } 12579 12580 if (TargetRange.Width == LikelySourceRange.Width && 12581 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 12582 Source->isSignedIntegerType()) { 12583 // Warn when doing a signed to signed conversion, warn if the positive 12584 // source value is exactly the width of the target type, which will 12585 // cause a negative value to be stored. 12586 12587 Expr::EvalResult Result; 12588 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 12589 !S.SourceMgr.isInSystemMacro(CC)) { 12590 llvm::APSInt Value = Result.Val.getInt(); 12591 if (isSameWidthConstantConversion(S, E, T, CC)) { 12592 std::string PrettySourceValue = Value.toString(10); 12593 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 12594 12595 S.DiagRuntimeBehavior( 12596 E->getExprLoc(), E, 12597 S.PDiag(diag::warn_impcast_integer_precision_constant) 12598 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12599 << E->getSourceRange() << SourceRange(CC)); 12600 return; 12601 } 12602 } 12603 12604 // Fall through for non-constants to give a sign conversion warning. 12605 } 12606 12607 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 12608 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 12609 LikelySourceRange.Width == TargetRange.Width)) { 12610 if (S.SourceMgr.isInSystemMacro(CC)) 12611 return; 12612 12613 unsigned DiagID = diag::warn_impcast_integer_sign; 12614 12615 // Traditionally, gcc has warned about this under -Wsign-compare. 12616 // We also want to warn about it in -Wconversion. 12617 // So if -Wconversion is off, use a completely identical diagnostic 12618 // in the sign-compare group. 12619 // The conditional-checking code will 12620 if (ICContext) { 12621 DiagID = diag::warn_impcast_integer_sign_conditional; 12622 *ICContext = true; 12623 } 12624 12625 return DiagnoseImpCast(S, E, T, CC, DiagID); 12626 } 12627 12628 // Diagnose conversions between different enumeration types. 12629 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 12630 // type, to give us better diagnostics. 12631 QualType SourceType = E->getType(); 12632 if (!S.getLangOpts().CPlusPlus) { 12633 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12634 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 12635 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 12636 SourceType = S.Context.getTypeDeclType(Enum); 12637 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 12638 } 12639 } 12640 12641 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 12642 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12643 if (SourceEnum->getDecl()->hasNameForLinkage() && 12644 TargetEnum->getDecl()->hasNameForLinkage() && 12645 SourceEnum != TargetEnum) { 12646 if (S.SourceMgr.isInSystemMacro(CC)) 12647 return; 12648 12649 return DiagnoseImpCast(S, E, SourceType, T, CC, 12650 diag::warn_impcast_different_enum_types); 12651 } 12652 } 12653 12654 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12655 SourceLocation CC, QualType T); 12656 12657 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12658 SourceLocation CC, bool &ICContext) { 12659 E = E->IgnoreParenImpCasts(); 12660 12661 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12662 return CheckConditionalOperator(S, CO, CC, T); 12663 12664 AnalyzeImplicitConversions(S, E, CC); 12665 if (E->getType() != T) 12666 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12667 } 12668 12669 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12670 SourceLocation CC, QualType T) { 12671 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12672 12673 Expr *TrueExpr = E->getTrueExpr(); 12674 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12675 TrueExpr = BCO->getCommon(); 12676 12677 bool Suspicious = false; 12678 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12679 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12680 12681 if (T->isBooleanType()) 12682 DiagnoseIntInBoolContext(S, E); 12683 12684 // If -Wconversion would have warned about either of the candidates 12685 // for a signedness conversion to the context type... 12686 if (!Suspicious) return; 12687 12688 // ...but it's currently ignored... 12689 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12690 return; 12691 12692 // ...then check whether it would have warned about either of the 12693 // candidates for a signedness conversion to the condition type. 12694 if (E->getType() == T) return; 12695 12696 Suspicious = false; 12697 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12698 E->getType(), CC, &Suspicious); 12699 if (!Suspicious) 12700 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12701 E->getType(), CC, &Suspicious); 12702 } 12703 12704 /// Check conversion of given expression to boolean. 12705 /// Input argument E is a logical expression. 12706 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12707 if (S.getLangOpts().Bool) 12708 return; 12709 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12710 return; 12711 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12712 } 12713 12714 namespace { 12715 struct AnalyzeImplicitConversionsWorkItem { 12716 Expr *E; 12717 SourceLocation CC; 12718 bool IsListInit; 12719 }; 12720 } 12721 12722 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12723 /// that should be visited are added to WorkList. 12724 static void AnalyzeImplicitConversions( 12725 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12726 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12727 Expr *OrigE = Item.E; 12728 SourceLocation CC = Item.CC; 12729 12730 QualType T = OrigE->getType(); 12731 Expr *E = OrigE->IgnoreParenImpCasts(); 12732 12733 // Propagate whether we are in a C++ list initialization expression. 12734 // If so, we do not issue warnings for implicit int-float conversion 12735 // precision loss, because C++11 narrowing already handles it. 12736 bool IsListInit = Item.IsListInit || 12737 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12738 12739 if (E->isTypeDependent() || E->isValueDependent()) 12740 return; 12741 12742 Expr *SourceExpr = E; 12743 // Examine, but don't traverse into the source expression of an 12744 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12745 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12746 // evaluate it in the context of checking the specific conversion to T though. 12747 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12748 if (auto *Src = OVE->getSourceExpr()) 12749 SourceExpr = Src; 12750 12751 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12752 if (UO->getOpcode() == UO_Not && 12753 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12754 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12755 << OrigE->getSourceRange() << T->isBooleanType() 12756 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12757 12758 // For conditional operators, we analyze the arguments as if they 12759 // were being fed directly into the output. 12760 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12761 CheckConditionalOperator(S, CO, CC, T); 12762 return; 12763 } 12764 12765 // Check implicit argument conversions for function calls. 12766 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12767 CheckImplicitArgumentConversions(S, Call, CC); 12768 12769 // Go ahead and check any implicit conversions we might have skipped. 12770 // The non-canonical typecheck is just an optimization; 12771 // CheckImplicitConversion will filter out dead implicit conversions. 12772 if (SourceExpr->getType() != T) 12773 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12774 12775 // Now continue drilling into this expression. 12776 12777 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12778 // The bound subexpressions in a PseudoObjectExpr are not reachable 12779 // as transitive children. 12780 // FIXME: Use a more uniform representation for this. 12781 for (auto *SE : POE->semantics()) 12782 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12783 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12784 } 12785 12786 // Skip past explicit casts. 12787 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12788 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12789 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12790 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12791 WorkList.push_back({E, CC, IsListInit}); 12792 return; 12793 } 12794 12795 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12796 // Do a somewhat different check with comparison operators. 12797 if (BO->isComparisonOp()) 12798 return AnalyzeComparison(S, BO); 12799 12800 // And with simple assignments. 12801 if (BO->getOpcode() == BO_Assign) 12802 return AnalyzeAssignment(S, BO); 12803 // And with compound assignments. 12804 if (BO->isAssignmentOp()) 12805 return AnalyzeCompoundAssignment(S, BO); 12806 } 12807 12808 // These break the otherwise-useful invariant below. Fortunately, 12809 // we don't really need to recurse into them, because any internal 12810 // expressions should have been analyzed already when they were 12811 // built into statements. 12812 if (isa<StmtExpr>(E)) return; 12813 12814 // Don't descend into unevaluated contexts. 12815 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12816 12817 // Now just recurse over the expression's children. 12818 CC = E->getExprLoc(); 12819 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12820 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12821 for (Stmt *SubStmt : E->children()) { 12822 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12823 if (!ChildExpr) 12824 continue; 12825 12826 if (IsLogicalAndOperator && 12827 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12828 // Ignore checking string literals that are in logical and operators. 12829 // This is a common pattern for asserts. 12830 continue; 12831 WorkList.push_back({ChildExpr, CC, IsListInit}); 12832 } 12833 12834 if (BO && BO->isLogicalOp()) { 12835 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12836 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12837 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12838 12839 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12840 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12841 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12842 } 12843 12844 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12845 if (U->getOpcode() == UO_LNot) { 12846 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12847 } else if (U->getOpcode() != UO_AddrOf) { 12848 if (U->getSubExpr()->getType()->isAtomicType()) 12849 S.Diag(U->getSubExpr()->getBeginLoc(), 12850 diag::warn_atomic_implicit_seq_cst); 12851 } 12852 } 12853 } 12854 12855 /// AnalyzeImplicitConversions - Find and report any interesting 12856 /// implicit conversions in the given expression. There are a couple 12857 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12858 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12859 bool IsListInit/*= false*/) { 12860 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12861 WorkList.push_back({OrigE, CC, IsListInit}); 12862 while (!WorkList.empty()) 12863 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12864 } 12865 12866 /// Diagnose integer type and any valid implicit conversion to it. 12867 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12868 // Taking into account implicit conversions, 12869 // allow any integer. 12870 if (!E->getType()->isIntegerType()) { 12871 S.Diag(E->getBeginLoc(), 12872 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12873 return true; 12874 } 12875 // Potentially emit standard warnings for implicit conversions if enabled 12876 // using -Wconversion. 12877 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12878 return false; 12879 } 12880 12881 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12882 // Returns true when emitting a warning about taking the address of a reference. 12883 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12884 const PartialDiagnostic &PD) { 12885 E = E->IgnoreParenImpCasts(); 12886 12887 const FunctionDecl *FD = nullptr; 12888 12889 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12890 if (!DRE->getDecl()->getType()->isReferenceType()) 12891 return false; 12892 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12893 if (!M->getMemberDecl()->getType()->isReferenceType()) 12894 return false; 12895 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12896 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12897 return false; 12898 FD = Call->getDirectCallee(); 12899 } else { 12900 return false; 12901 } 12902 12903 SemaRef.Diag(E->getExprLoc(), PD); 12904 12905 // If possible, point to location of function. 12906 if (FD) { 12907 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12908 } 12909 12910 return true; 12911 } 12912 12913 // Returns true if the SourceLocation is expanded from any macro body. 12914 // Returns false if the SourceLocation is invalid, is from not in a macro 12915 // expansion, or is from expanded from a top-level macro argument. 12916 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12917 if (Loc.isInvalid()) 12918 return false; 12919 12920 while (Loc.isMacroID()) { 12921 if (SM.isMacroBodyExpansion(Loc)) 12922 return true; 12923 Loc = SM.getImmediateMacroCallerLoc(Loc); 12924 } 12925 12926 return false; 12927 } 12928 12929 /// Diagnose pointers that are always non-null. 12930 /// \param E the expression containing the pointer 12931 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12932 /// compared to a null pointer 12933 /// \param IsEqual True when the comparison is equal to a null pointer 12934 /// \param Range Extra SourceRange to highlight in the diagnostic 12935 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12936 Expr::NullPointerConstantKind NullKind, 12937 bool IsEqual, SourceRange Range) { 12938 if (!E) 12939 return; 12940 12941 // Don't warn inside macros. 12942 if (E->getExprLoc().isMacroID()) { 12943 const SourceManager &SM = getSourceManager(); 12944 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12945 IsInAnyMacroBody(SM, Range.getBegin())) 12946 return; 12947 } 12948 E = E->IgnoreImpCasts(); 12949 12950 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12951 12952 if (isa<CXXThisExpr>(E)) { 12953 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12954 : diag::warn_this_bool_conversion; 12955 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12956 return; 12957 } 12958 12959 bool IsAddressOf = false; 12960 12961 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12962 if (UO->getOpcode() != UO_AddrOf) 12963 return; 12964 IsAddressOf = true; 12965 E = UO->getSubExpr(); 12966 } 12967 12968 if (IsAddressOf) { 12969 unsigned DiagID = IsCompare 12970 ? diag::warn_address_of_reference_null_compare 12971 : diag::warn_address_of_reference_bool_conversion; 12972 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12973 << IsEqual; 12974 if (CheckForReference(*this, E, PD)) { 12975 return; 12976 } 12977 } 12978 12979 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12980 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12981 std::string Str; 12982 llvm::raw_string_ostream S(Str); 12983 E->printPretty(S, nullptr, getPrintingPolicy()); 12984 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12985 : diag::warn_cast_nonnull_to_bool; 12986 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12987 << E->getSourceRange() << Range << IsEqual; 12988 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12989 }; 12990 12991 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12992 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12993 if (auto *Callee = Call->getDirectCallee()) { 12994 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12995 ComplainAboutNonnullParamOrCall(A); 12996 return; 12997 } 12998 } 12999 } 13000 13001 // Expect to find a single Decl. Skip anything more complicated. 13002 ValueDecl *D = nullptr; 13003 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13004 D = R->getDecl(); 13005 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13006 D = M->getMemberDecl(); 13007 } 13008 13009 // Weak Decls can be null. 13010 if (!D || D->isWeak()) 13011 return; 13012 13013 // Check for parameter decl with nonnull attribute 13014 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13015 if (getCurFunction() && 13016 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13017 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13018 ComplainAboutNonnullParamOrCall(A); 13019 return; 13020 } 13021 13022 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13023 // Skip function template not specialized yet. 13024 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13025 return; 13026 auto ParamIter = llvm::find(FD->parameters(), PV); 13027 assert(ParamIter != FD->param_end()); 13028 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13029 13030 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13031 if (!NonNull->args_size()) { 13032 ComplainAboutNonnullParamOrCall(NonNull); 13033 return; 13034 } 13035 13036 for (const ParamIdx &ArgNo : NonNull->args()) { 13037 if (ArgNo.getASTIndex() == ParamNo) { 13038 ComplainAboutNonnullParamOrCall(NonNull); 13039 return; 13040 } 13041 } 13042 } 13043 } 13044 } 13045 } 13046 13047 QualType T = D->getType(); 13048 const bool IsArray = T->isArrayType(); 13049 const bool IsFunction = T->isFunctionType(); 13050 13051 // Address of function is used to silence the function warning. 13052 if (IsAddressOf && IsFunction) { 13053 return; 13054 } 13055 13056 // Found nothing. 13057 if (!IsAddressOf && !IsFunction && !IsArray) 13058 return; 13059 13060 // Pretty print the expression for the diagnostic. 13061 std::string Str; 13062 llvm::raw_string_ostream S(Str); 13063 E->printPretty(S, nullptr, getPrintingPolicy()); 13064 13065 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13066 : diag::warn_impcast_pointer_to_bool; 13067 enum { 13068 AddressOf, 13069 FunctionPointer, 13070 ArrayPointer 13071 } DiagType; 13072 if (IsAddressOf) 13073 DiagType = AddressOf; 13074 else if (IsFunction) 13075 DiagType = FunctionPointer; 13076 else if (IsArray) 13077 DiagType = ArrayPointer; 13078 else 13079 llvm_unreachable("Could not determine diagnostic."); 13080 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13081 << Range << IsEqual; 13082 13083 if (!IsFunction) 13084 return; 13085 13086 // Suggest '&' to silence the function warning. 13087 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13088 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13089 13090 // Check to see if '()' fixit should be emitted. 13091 QualType ReturnType; 13092 UnresolvedSet<4> NonTemplateOverloads; 13093 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13094 if (ReturnType.isNull()) 13095 return; 13096 13097 if (IsCompare) { 13098 // There are two cases here. If there is null constant, the only suggest 13099 // for a pointer return type. If the null is 0, then suggest if the return 13100 // type is a pointer or an integer type. 13101 if (!ReturnType->isPointerType()) { 13102 if (NullKind == Expr::NPCK_ZeroExpression || 13103 NullKind == Expr::NPCK_ZeroLiteral) { 13104 if (!ReturnType->isIntegerType()) 13105 return; 13106 } else { 13107 return; 13108 } 13109 } 13110 } else { // !IsCompare 13111 // For function to bool, only suggest if the function pointer has bool 13112 // return type. 13113 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13114 return; 13115 } 13116 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13117 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13118 } 13119 13120 /// Diagnoses "dangerous" implicit conversions within the given 13121 /// expression (which is a full expression). Implements -Wconversion 13122 /// and -Wsign-compare. 13123 /// 13124 /// \param CC the "context" location of the implicit conversion, i.e. 13125 /// the most location of the syntactic entity requiring the implicit 13126 /// conversion 13127 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13128 // Don't diagnose in unevaluated contexts. 13129 if (isUnevaluatedContext()) 13130 return; 13131 13132 // Don't diagnose for value- or type-dependent expressions. 13133 if (E->isTypeDependent() || E->isValueDependent()) 13134 return; 13135 13136 // Check for array bounds violations in cases where the check isn't triggered 13137 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13138 // ArraySubscriptExpr is on the RHS of a variable initialization. 13139 CheckArrayAccess(E); 13140 13141 // This is not the right CC for (e.g.) a variable initialization. 13142 AnalyzeImplicitConversions(*this, E, CC); 13143 } 13144 13145 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13146 /// Input argument E is a logical expression. 13147 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13148 ::CheckBoolLikeConversion(*this, E, CC); 13149 } 13150 13151 /// Diagnose when expression is an integer constant expression and its evaluation 13152 /// results in integer overflow 13153 void Sema::CheckForIntOverflow (Expr *E) { 13154 // Use a work list to deal with nested struct initializers. 13155 SmallVector<Expr *, 2> Exprs(1, E); 13156 13157 do { 13158 Expr *OriginalE = Exprs.pop_back_val(); 13159 Expr *E = OriginalE->IgnoreParenCasts(); 13160 13161 if (isa<BinaryOperator>(E)) { 13162 E->EvaluateForOverflow(Context); 13163 continue; 13164 } 13165 13166 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13167 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13168 else if (isa<ObjCBoxedExpr>(OriginalE)) 13169 E->EvaluateForOverflow(Context); 13170 else if (auto Call = dyn_cast<CallExpr>(E)) 13171 Exprs.append(Call->arg_begin(), Call->arg_end()); 13172 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13173 Exprs.append(Message->arg_begin(), Message->arg_end()); 13174 } while (!Exprs.empty()); 13175 } 13176 13177 namespace { 13178 13179 /// Visitor for expressions which looks for unsequenced operations on the 13180 /// same object. 13181 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13182 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13183 13184 /// A tree of sequenced regions within an expression. Two regions are 13185 /// unsequenced if one is an ancestor or a descendent of the other. When we 13186 /// finish processing an expression with sequencing, such as a comma 13187 /// expression, we fold its tree nodes into its parent, since they are 13188 /// unsequenced with respect to nodes we will visit later. 13189 class SequenceTree { 13190 struct Value { 13191 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13192 unsigned Parent : 31; 13193 unsigned Merged : 1; 13194 }; 13195 SmallVector<Value, 8> Values; 13196 13197 public: 13198 /// A region within an expression which may be sequenced with respect 13199 /// to some other region. 13200 class Seq { 13201 friend class SequenceTree; 13202 13203 unsigned Index; 13204 13205 explicit Seq(unsigned N) : Index(N) {} 13206 13207 public: 13208 Seq() : Index(0) {} 13209 }; 13210 13211 SequenceTree() { Values.push_back(Value(0)); } 13212 Seq root() const { return Seq(0); } 13213 13214 /// Create a new sequence of operations, which is an unsequenced 13215 /// subset of \p Parent. This sequence of operations is sequenced with 13216 /// respect to other children of \p Parent. 13217 Seq allocate(Seq Parent) { 13218 Values.push_back(Value(Parent.Index)); 13219 return Seq(Values.size() - 1); 13220 } 13221 13222 /// Merge a sequence of operations into its parent. 13223 void merge(Seq S) { 13224 Values[S.Index].Merged = true; 13225 } 13226 13227 /// Determine whether two operations are unsequenced. This operation 13228 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13229 /// should have been merged into its parent as appropriate. 13230 bool isUnsequenced(Seq Cur, Seq Old) { 13231 unsigned C = representative(Cur.Index); 13232 unsigned Target = representative(Old.Index); 13233 while (C >= Target) { 13234 if (C == Target) 13235 return true; 13236 C = Values[C].Parent; 13237 } 13238 return false; 13239 } 13240 13241 private: 13242 /// Pick a representative for a sequence. 13243 unsigned representative(unsigned K) { 13244 if (Values[K].Merged) 13245 // Perform path compression as we go. 13246 return Values[K].Parent = representative(Values[K].Parent); 13247 return K; 13248 } 13249 }; 13250 13251 /// An object for which we can track unsequenced uses. 13252 using Object = const NamedDecl *; 13253 13254 /// Different flavors of object usage which we track. We only track the 13255 /// least-sequenced usage of each kind. 13256 enum UsageKind { 13257 /// A read of an object. Multiple unsequenced reads are OK. 13258 UK_Use, 13259 13260 /// A modification of an object which is sequenced before the value 13261 /// computation of the expression, such as ++n in C++. 13262 UK_ModAsValue, 13263 13264 /// A modification of an object which is not sequenced before the value 13265 /// computation of the expression, such as n++. 13266 UK_ModAsSideEffect, 13267 13268 UK_Count = UK_ModAsSideEffect + 1 13269 }; 13270 13271 /// Bundle together a sequencing region and the expression corresponding 13272 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13273 struct Usage { 13274 const Expr *UsageExpr; 13275 SequenceTree::Seq Seq; 13276 13277 Usage() : UsageExpr(nullptr), Seq() {} 13278 }; 13279 13280 struct UsageInfo { 13281 Usage Uses[UK_Count]; 13282 13283 /// Have we issued a diagnostic for this object already? 13284 bool Diagnosed; 13285 13286 UsageInfo() : Uses(), Diagnosed(false) {} 13287 }; 13288 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13289 13290 Sema &SemaRef; 13291 13292 /// Sequenced regions within the expression. 13293 SequenceTree Tree; 13294 13295 /// Declaration modifications and references which we have seen. 13296 UsageInfoMap UsageMap; 13297 13298 /// The region we are currently within. 13299 SequenceTree::Seq Region; 13300 13301 /// Filled in with declarations which were modified as a side-effect 13302 /// (that is, post-increment operations). 13303 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13304 13305 /// Expressions to check later. We defer checking these to reduce 13306 /// stack usage. 13307 SmallVectorImpl<const Expr *> &WorkList; 13308 13309 /// RAII object wrapping the visitation of a sequenced subexpression of an 13310 /// expression. At the end of this process, the side-effects of the evaluation 13311 /// become sequenced with respect to the value computation of the result, so 13312 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13313 /// UK_ModAsValue. 13314 struct SequencedSubexpression { 13315 SequencedSubexpression(SequenceChecker &Self) 13316 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13317 Self.ModAsSideEffect = &ModAsSideEffect; 13318 } 13319 13320 ~SequencedSubexpression() { 13321 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13322 // Add a new usage with usage kind UK_ModAsValue, and then restore 13323 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13324 // the previous one was empty). 13325 UsageInfo &UI = Self.UsageMap[M.first]; 13326 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13327 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13328 SideEffectUsage = M.second; 13329 } 13330 Self.ModAsSideEffect = OldModAsSideEffect; 13331 } 13332 13333 SequenceChecker &Self; 13334 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13335 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13336 }; 13337 13338 /// RAII object wrapping the visitation of a subexpression which we might 13339 /// choose to evaluate as a constant. If any subexpression is evaluated and 13340 /// found to be non-constant, this allows us to suppress the evaluation of 13341 /// the outer expression. 13342 class EvaluationTracker { 13343 public: 13344 EvaluationTracker(SequenceChecker &Self) 13345 : Self(Self), Prev(Self.EvalTracker) { 13346 Self.EvalTracker = this; 13347 } 13348 13349 ~EvaluationTracker() { 13350 Self.EvalTracker = Prev; 13351 if (Prev) 13352 Prev->EvalOK &= EvalOK; 13353 } 13354 13355 bool evaluate(const Expr *E, bool &Result) { 13356 if (!EvalOK || E->isValueDependent()) 13357 return false; 13358 EvalOK = E->EvaluateAsBooleanCondition( 13359 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13360 return EvalOK; 13361 } 13362 13363 private: 13364 SequenceChecker &Self; 13365 EvaluationTracker *Prev; 13366 bool EvalOK = true; 13367 } *EvalTracker = nullptr; 13368 13369 /// Find the object which is produced by the specified expression, 13370 /// if any. 13371 Object getObject(const Expr *E, bool Mod) const { 13372 E = E->IgnoreParenCasts(); 13373 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13374 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13375 return getObject(UO->getSubExpr(), Mod); 13376 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13377 if (BO->getOpcode() == BO_Comma) 13378 return getObject(BO->getRHS(), Mod); 13379 if (Mod && BO->isAssignmentOp()) 13380 return getObject(BO->getLHS(), Mod); 13381 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13382 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13383 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13384 return ME->getMemberDecl(); 13385 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13386 // FIXME: If this is a reference, map through to its value. 13387 return DRE->getDecl(); 13388 return nullptr; 13389 } 13390 13391 /// Note that an object \p O was modified or used by an expression 13392 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13393 /// the object \p O as obtained via the \p UsageMap. 13394 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13395 // Get the old usage for the given object and usage kind. 13396 Usage &U = UI.Uses[UK]; 13397 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13398 // If we have a modification as side effect and are in a sequenced 13399 // subexpression, save the old Usage so that we can restore it later 13400 // in SequencedSubexpression::~SequencedSubexpression. 13401 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13402 ModAsSideEffect->push_back(std::make_pair(O, U)); 13403 // Then record the new usage with the current sequencing region. 13404 U.UsageExpr = UsageExpr; 13405 U.Seq = Region; 13406 } 13407 } 13408 13409 /// Check whether a modification or use of an object \p O in an expression 13410 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13411 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13412 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13413 /// usage and false we are checking for a mod-use unsequenced usage. 13414 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13415 UsageKind OtherKind, bool IsModMod) { 13416 if (UI.Diagnosed) 13417 return; 13418 13419 const Usage &U = UI.Uses[OtherKind]; 13420 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13421 return; 13422 13423 const Expr *Mod = U.UsageExpr; 13424 const Expr *ModOrUse = UsageExpr; 13425 if (OtherKind == UK_Use) 13426 std::swap(Mod, ModOrUse); 13427 13428 SemaRef.DiagRuntimeBehavior( 13429 Mod->getExprLoc(), {Mod, ModOrUse}, 13430 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13431 : diag::warn_unsequenced_mod_use) 13432 << O << SourceRange(ModOrUse->getExprLoc())); 13433 UI.Diagnosed = true; 13434 } 13435 13436 // A note on note{Pre, Post}{Use, Mod}: 13437 // 13438 // (It helps to follow the algorithm with an expression such as 13439 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13440 // operations before C++17 and both are well-defined in C++17). 13441 // 13442 // When visiting a node which uses/modify an object we first call notePreUse 13443 // or notePreMod before visiting its sub-expression(s). At this point the 13444 // children of the current node have not yet been visited and so the eventual 13445 // uses/modifications resulting from the children of the current node have not 13446 // been recorded yet. 13447 // 13448 // We then visit the children of the current node. After that notePostUse or 13449 // notePostMod is called. These will 1) detect an unsequenced modification 13450 // as side effect (as in "k++ + k") and 2) add a new usage with the 13451 // appropriate usage kind. 13452 // 13453 // We also have to be careful that some operation sequences modification as 13454 // side effect as well (for example: || or ,). To account for this we wrap 13455 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13456 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13457 // which record usages which are modifications as side effect, and then 13458 // downgrade them (or more accurately restore the previous usage which was a 13459 // modification as side effect) when exiting the scope of the sequenced 13460 // subexpression. 13461 13462 void notePreUse(Object O, const Expr *UseExpr) { 13463 UsageInfo &UI = UsageMap[O]; 13464 // Uses conflict with other modifications. 13465 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13466 } 13467 13468 void notePostUse(Object O, const Expr *UseExpr) { 13469 UsageInfo &UI = UsageMap[O]; 13470 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13471 /*IsModMod=*/false); 13472 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13473 } 13474 13475 void notePreMod(Object O, const Expr *ModExpr) { 13476 UsageInfo &UI = UsageMap[O]; 13477 // Modifications conflict with other modifications and with uses. 13478 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13479 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13480 } 13481 13482 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13483 UsageInfo &UI = UsageMap[O]; 13484 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13485 /*IsModMod=*/true); 13486 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13487 } 13488 13489 public: 13490 SequenceChecker(Sema &S, const Expr *E, 13491 SmallVectorImpl<const Expr *> &WorkList) 13492 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13493 Visit(E); 13494 // Silence a -Wunused-private-field since WorkList is now unused. 13495 // TODO: Evaluate if it can be used, and if not remove it. 13496 (void)this->WorkList; 13497 } 13498 13499 void VisitStmt(const Stmt *S) { 13500 // Skip all statements which aren't expressions for now. 13501 } 13502 13503 void VisitExpr(const Expr *E) { 13504 // By default, just recurse to evaluated subexpressions. 13505 Base::VisitStmt(E); 13506 } 13507 13508 void VisitCastExpr(const CastExpr *E) { 13509 Object O = Object(); 13510 if (E->getCastKind() == CK_LValueToRValue) 13511 O = getObject(E->getSubExpr(), false); 13512 13513 if (O) 13514 notePreUse(O, E); 13515 VisitExpr(E); 13516 if (O) 13517 notePostUse(O, E); 13518 } 13519 13520 void VisitSequencedExpressions(const Expr *SequencedBefore, 13521 const Expr *SequencedAfter) { 13522 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 13523 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 13524 SequenceTree::Seq OldRegion = Region; 13525 13526 { 13527 SequencedSubexpression SeqBefore(*this); 13528 Region = BeforeRegion; 13529 Visit(SequencedBefore); 13530 } 13531 13532 Region = AfterRegion; 13533 Visit(SequencedAfter); 13534 13535 Region = OldRegion; 13536 13537 Tree.merge(BeforeRegion); 13538 Tree.merge(AfterRegion); 13539 } 13540 13541 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 13542 // C++17 [expr.sub]p1: 13543 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 13544 // expression E1 is sequenced before the expression E2. 13545 if (SemaRef.getLangOpts().CPlusPlus17) 13546 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 13547 else { 13548 Visit(ASE->getLHS()); 13549 Visit(ASE->getRHS()); 13550 } 13551 } 13552 13553 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13554 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 13555 void VisitBinPtrMem(const BinaryOperator *BO) { 13556 // C++17 [expr.mptr.oper]p4: 13557 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 13558 // the expression E1 is sequenced before the expression E2. 13559 if (SemaRef.getLangOpts().CPlusPlus17) 13560 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13561 else { 13562 Visit(BO->getLHS()); 13563 Visit(BO->getRHS()); 13564 } 13565 } 13566 13567 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13568 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 13569 void VisitBinShlShr(const BinaryOperator *BO) { 13570 // C++17 [expr.shift]p4: 13571 // The expression E1 is sequenced before the expression E2. 13572 if (SemaRef.getLangOpts().CPlusPlus17) 13573 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13574 else { 13575 Visit(BO->getLHS()); 13576 Visit(BO->getRHS()); 13577 } 13578 } 13579 13580 void VisitBinComma(const BinaryOperator *BO) { 13581 // C++11 [expr.comma]p1: 13582 // Every value computation and side effect associated with the left 13583 // expression is sequenced before every value computation and side 13584 // effect associated with the right expression. 13585 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 13586 } 13587 13588 void VisitBinAssign(const BinaryOperator *BO) { 13589 SequenceTree::Seq RHSRegion; 13590 SequenceTree::Seq LHSRegion; 13591 if (SemaRef.getLangOpts().CPlusPlus17) { 13592 RHSRegion = Tree.allocate(Region); 13593 LHSRegion = Tree.allocate(Region); 13594 } else { 13595 RHSRegion = Region; 13596 LHSRegion = Region; 13597 } 13598 SequenceTree::Seq OldRegion = Region; 13599 13600 // C++11 [expr.ass]p1: 13601 // [...] the assignment is sequenced after the value computation 13602 // of the right and left operands, [...] 13603 // 13604 // so check it before inspecting the operands and update the 13605 // map afterwards. 13606 Object O = getObject(BO->getLHS(), /*Mod=*/true); 13607 if (O) 13608 notePreMod(O, BO); 13609 13610 if (SemaRef.getLangOpts().CPlusPlus17) { 13611 // C++17 [expr.ass]p1: 13612 // [...] The right operand is sequenced before the left operand. [...] 13613 { 13614 SequencedSubexpression SeqBefore(*this); 13615 Region = RHSRegion; 13616 Visit(BO->getRHS()); 13617 } 13618 13619 Region = LHSRegion; 13620 Visit(BO->getLHS()); 13621 13622 if (O && isa<CompoundAssignOperator>(BO)) 13623 notePostUse(O, BO); 13624 13625 } else { 13626 // C++11 does not specify any sequencing between the LHS and RHS. 13627 Region = LHSRegion; 13628 Visit(BO->getLHS()); 13629 13630 if (O && isa<CompoundAssignOperator>(BO)) 13631 notePostUse(O, BO); 13632 13633 Region = RHSRegion; 13634 Visit(BO->getRHS()); 13635 } 13636 13637 // C++11 [expr.ass]p1: 13638 // the assignment is sequenced [...] before the value computation of the 13639 // assignment expression. 13640 // C11 6.5.16/3 has no such rule. 13641 Region = OldRegion; 13642 if (O) 13643 notePostMod(O, BO, 13644 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13645 : UK_ModAsSideEffect); 13646 if (SemaRef.getLangOpts().CPlusPlus17) { 13647 Tree.merge(RHSRegion); 13648 Tree.merge(LHSRegion); 13649 } 13650 } 13651 13652 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 13653 VisitBinAssign(CAO); 13654 } 13655 13656 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13657 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13658 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13659 Object O = getObject(UO->getSubExpr(), true); 13660 if (!O) 13661 return VisitExpr(UO); 13662 13663 notePreMod(O, UO); 13664 Visit(UO->getSubExpr()); 13665 // C++11 [expr.pre.incr]p1: 13666 // the expression ++x is equivalent to x+=1 13667 notePostMod(O, UO, 13668 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13669 : UK_ModAsSideEffect); 13670 } 13671 13672 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13673 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13674 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13675 Object O = getObject(UO->getSubExpr(), true); 13676 if (!O) 13677 return VisitExpr(UO); 13678 13679 notePreMod(O, UO); 13680 Visit(UO->getSubExpr()); 13681 notePostMod(O, UO, UK_ModAsSideEffect); 13682 } 13683 13684 void VisitBinLOr(const BinaryOperator *BO) { 13685 // C++11 [expr.log.or]p2: 13686 // If the second expression is evaluated, every value computation and 13687 // side effect associated with the first expression is sequenced before 13688 // every value computation and side effect associated with the 13689 // second expression. 13690 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13691 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13692 SequenceTree::Seq OldRegion = Region; 13693 13694 EvaluationTracker Eval(*this); 13695 { 13696 SequencedSubexpression Sequenced(*this); 13697 Region = LHSRegion; 13698 Visit(BO->getLHS()); 13699 } 13700 13701 // C++11 [expr.log.or]p1: 13702 // [...] the second operand is not evaluated if the first operand 13703 // evaluates to true. 13704 bool EvalResult = false; 13705 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13706 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13707 if (ShouldVisitRHS) { 13708 Region = RHSRegion; 13709 Visit(BO->getRHS()); 13710 } 13711 13712 Region = OldRegion; 13713 Tree.merge(LHSRegion); 13714 Tree.merge(RHSRegion); 13715 } 13716 13717 void VisitBinLAnd(const BinaryOperator *BO) { 13718 // C++11 [expr.log.and]p2: 13719 // If the second expression is evaluated, every value computation and 13720 // side effect associated with the first expression is sequenced before 13721 // every value computation and side effect associated with the 13722 // second expression. 13723 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13724 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13725 SequenceTree::Seq OldRegion = Region; 13726 13727 EvaluationTracker Eval(*this); 13728 { 13729 SequencedSubexpression Sequenced(*this); 13730 Region = LHSRegion; 13731 Visit(BO->getLHS()); 13732 } 13733 13734 // C++11 [expr.log.and]p1: 13735 // [...] the second operand is not evaluated if the first operand is false. 13736 bool EvalResult = false; 13737 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13738 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13739 if (ShouldVisitRHS) { 13740 Region = RHSRegion; 13741 Visit(BO->getRHS()); 13742 } 13743 13744 Region = OldRegion; 13745 Tree.merge(LHSRegion); 13746 Tree.merge(RHSRegion); 13747 } 13748 13749 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13750 // C++11 [expr.cond]p1: 13751 // [...] Every value computation and side effect associated with the first 13752 // expression is sequenced before every value computation and side effect 13753 // associated with the second or third expression. 13754 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13755 13756 // No sequencing is specified between the true and false expression. 13757 // However since exactly one of both is going to be evaluated we can 13758 // consider them to be sequenced. This is needed to avoid warning on 13759 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13760 // both the true and false expressions because we can't evaluate x. 13761 // This will still allow us to detect an expression like (pre C++17) 13762 // "(x ? y += 1 : y += 2) = y". 13763 // 13764 // We don't wrap the visitation of the true and false expression with 13765 // SequencedSubexpression because we don't want to downgrade modifications 13766 // as side effect in the true and false expressions after the visition 13767 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13768 // not warn between the two "y++", but we should warn between the "y++" 13769 // and the "y". 13770 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13771 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13772 SequenceTree::Seq OldRegion = Region; 13773 13774 EvaluationTracker Eval(*this); 13775 { 13776 SequencedSubexpression Sequenced(*this); 13777 Region = ConditionRegion; 13778 Visit(CO->getCond()); 13779 } 13780 13781 // C++11 [expr.cond]p1: 13782 // [...] The first expression is contextually converted to bool (Clause 4). 13783 // It is evaluated and if it is true, the result of the conditional 13784 // expression is the value of the second expression, otherwise that of the 13785 // third expression. Only one of the second and third expressions is 13786 // evaluated. [...] 13787 bool EvalResult = false; 13788 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13789 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13790 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13791 if (ShouldVisitTrueExpr) { 13792 Region = TrueRegion; 13793 Visit(CO->getTrueExpr()); 13794 } 13795 if (ShouldVisitFalseExpr) { 13796 Region = FalseRegion; 13797 Visit(CO->getFalseExpr()); 13798 } 13799 13800 Region = OldRegion; 13801 Tree.merge(ConditionRegion); 13802 Tree.merge(TrueRegion); 13803 Tree.merge(FalseRegion); 13804 } 13805 13806 void VisitCallExpr(const CallExpr *CE) { 13807 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13808 13809 if (CE->isUnevaluatedBuiltinCall(Context)) 13810 return; 13811 13812 // C++11 [intro.execution]p15: 13813 // When calling a function [...], every value computation and side effect 13814 // associated with any argument expression, or with the postfix expression 13815 // designating the called function, is sequenced before execution of every 13816 // expression or statement in the body of the function [and thus before 13817 // the value computation of its result]. 13818 SequencedSubexpression Sequenced(*this); 13819 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13820 // C++17 [expr.call]p5 13821 // The postfix-expression is sequenced before each expression in the 13822 // expression-list and any default argument. [...] 13823 SequenceTree::Seq CalleeRegion; 13824 SequenceTree::Seq OtherRegion; 13825 if (SemaRef.getLangOpts().CPlusPlus17) { 13826 CalleeRegion = Tree.allocate(Region); 13827 OtherRegion = Tree.allocate(Region); 13828 } else { 13829 CalleeRegion = Region; 13830 OtherRegion = Region; 13831 } 13832 SequenceTree::Seq OldRegion = Region; 13833 13834 // Visit the callee expression first. 13835 Region = CalleeRegion; 13836 if (SemaRef.getLangOpts().CPlusPlus17) { 13837 SequencedSubexpression Sequenced(*this); 13838 Visit(CE->getCallee()); 13839 } else { 13840 Visit(CE->getCallee()); 13841 } 13842 13843 // Then visit the argument expressions. 13844 Region = OtherRegion; 13845 for (const Expr *Argument : CE->arguments()) 13846 Visit(Argument); 13847 13848 Region = OldRegion; 13849 if (SemaRef.getLangOpts().CPlusPlus17) { 13850 Tree.merge(CalleeRegion); 13851 Tree.merge(OtherRegion); 13852 } 13853 }); 13854 } 13855 13856 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13857 // C++17 [over.match.oper]p2: 13858 // [...] the operator notation is first transformed to the equivalent 13859 // function-call notation as summarized in Table 12 (where @ denotes one 13860 // of the operators covered in the specified subclause). However, the 13861 // operands are sequenced in the order prescribed for the built-in 13862 // operator (Clause 8). 13863 // 13864 // From the above only overloaded binary operators and overloaded call 13865 // operators have sequencing rules in C++17 that we need to handle 13866 // separately. 13867 if (!SemaRef.getLangOpts().CPlusPlus17 || 13868 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13869 return VisitCallExpr(CXXOCE); 13870 13871 enum { 13872 NoSequencing, 13873 LHSBeforeRHS, 13874 RHSBeforeLHS, 13875 LHSBeforeRest 13876 } SequencingKind; 13877 switch (CXXOCE->getOperator()) { 13878 case OO_Equal: 13879 case OO_PlusEqual: 13880 case OO_MinusEqual: 13881 case OO_StarEqual: 13882 case OO_SlashEqual: 13883 case OO_PercentEqual: 13884 case OO_CaretEqual: 13885 case OO_AmpEqual: 13886 case OO_PipeEqual: 13887 case OO_LessLessEqual: 13888 case OO_GreaterGreaterEqual: 13889 SequencingKind = RHSBeforeLHS; 13890 break; 13891 13892 case OO_LessLess: 13893 case OO_GreaterGreater: 13894 case OO_AmpAmp: 13895 case OO_PipePipe: 13896 case OO_Comma: 13897 case OO_ArrowStar: 13898 case OO_Subscript: 13899 SequencingKind = LHSBeforeRHS; 13900 break; 13901 13902 case OO_Call: 13903 SequencingKind = LHSBeforeRest; 13904 break; 13905 13906 default: 13907 SequencingKind = NoSequencing; 13908 break; 13909 } 13910 13911 if (SequencingKind == NoSequencing) 13912 return VisitCallExpr(CXXOCE); 13913 13914 // This is a call, so all subexpressions are sequenced before the result. 13915 SequencedSubexpression Sequenced(*this); 13916 13917 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13918 assert(SemaRef.getLangOpts().CPlusPlus17 && 13919 "Should only get there with C++17 and above!"); 13920 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13921 "Should only get there with an overloaded binary operator" 13922 " or an overloaded call operator!"); 13923 13924 if (SequencingKind == LHSBeforeRest) { 13925 assert(CXXOCE->getOperator() == OO_Call && 13926 "We should only have an overloaded call operator here!"); 13927 13928 // This is very similar to VisitCallExpr, except that we only have the 13929 // C++17 case. The postfix-expression is the first argument of the 13930 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13931 // are in the following arguments. 13932 // 13933 // Note that we intentionally do not visit the callee expression since 13934 // it is just a decayed reference to a function. 13935 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13936 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13937 SequenceTree::Seq OldRegion = Region; 13938 13939 assert(CXXOCE->getNumArgs() >= 1 && 13940 "An overloaded call operator must have at least one argument" 13941 " for the postfix-expression!"); 13942 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13943 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13944 CXXOCE->getNumArgs() - 1); 13945 13946 // Visit the postfix-expression first. 13947 { 13948 Region = PostfixExprRegion; 13949 SequencedSubexpression Sequenced(*this); 13950 Visit(PostfixExpr); 13951 } 13952 13953 // Then visit the argument expressions. 13954 Region = ArgsRegion; 13955 for (const Expr *Arg : Args) 13956 Visit(Arg); 13957 13958 Region = OldRegion; 13959 Tree.merge(PostfixExprRegion); 13960 Tree.merge(ArgsRegion); 13961 } else { 13962 assert(CXXOCE->getNumArgs() == 2 && 13963 "Should only have two arguments here!"); 13964 assert((SequencingKind == LHSBeforeRHS || 13965 SequencingKind == RHSBeforeLHS) && 13966 "Unexpected sequencing kind!"); 13967 13968 // We do not visit the callee expression since it is just a decayed 13969 // reference to a function. 13970 const Expr *E1 = CXXOCE->getArg(0); 13971 const Expr *E2 = CXXOCE->getArg(1); 13972 if (SequencingKind == RHSBeforeLHS) 13973 std::swap(E1, E2); 13974 13975 return VisitSequencedExpressions(E1, E2); 13976 } 13977 }); 13978 } 13979 13980 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13981 // This is a call, so all subexpressions are sequenced before the result. 13982 SequencedSubexpression Sequenced(*this); 13983 13984 if (!CCE->isListInitialization()) 13985 return VisitExpr(CCE); 13986 13987 // In C++11, list initializations are sequenced. 13988 SmallVector<SequenceTree::Seq, 32> Elts; 13989 SequenceTree::Seq Parent = Region; 13990 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13991 E = CCE->arg_end(); 13992 I != E; ++I) { 13993 Region = Tree.allocate(Parent); 13994 Elts.push_back(Region); 13995 Visit(*I); 13996 } 13997 13998 // Forget that the initializers are sequenced. 13999 Region = Parent; 14000 for (unsigned I = 0; I < Elts.size(); ++I) 14001 Tree.merge(Elts[I]); 14002 } 14003 14004 void VisitInitListExpr(const InitListExpr *ILE) { 14005 if (!SemaRef.getLangOpts().CPlusPlus11) 14006 return VisitExpr(ILE); 14007 14008 // In C++11, list initializations are sequenced. 14009 SmallVector<SequenceTree::Seq, 32> Elts; 14010 SequenceTree::Seq Parent = Region; 14011 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14012 const Expr *E = ILE->getInit(I); 14013 if (!E) 14014 continue; 14015 Region = Tree.allocate(Parent); 14016 Elts.push_back(Region); 14017 Visit(E); 14018 } 14019 14020 // Forget that the initializers are sequenced. 14021 Region = Parent; 14022 for (unsigned I = 0; I < Elts.size(); ++I) 14023 Tree.merge(Elts[I]); 14024 } 14025 }; 14026 14027 } // namespace 14028 14029 void Sema::CheckUnsequencedOperations(const Expr *E) { 14030 SmallVector<const Expr *, 8> WorkList; 14031 WorkList.push_back(E); 14032 while (!WorkList.empty()) { 14033 const Expr *Item = WorkList.pop_back_val(); 14034 SequenceChecker(*this, Item, WorkList); 14035 } 14036 } 14037 14038 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14039 bool IsConstexpr) { 14040 llvm::SaveAndRestore<bool> ConstantContext( 14041 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14042 CheckImplicitConversions(E, CheckLoc); 14043 if (!E->isInstantiationDependent()) 14044 CheckUnsequencedOperations(E); 14045 if (!IsConstexpr && !E->isValueDependent()) 14046 CheckForIntOverflow(E); 14047 DiagnoseMisalignedMembers(); 14048 } 14049 14050 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14051 FieldDecl *BitField, 14052 Expr *Init) { 14053 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14054 } 14055 14056 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14057 SourceLocation Loc) { 14058 if (!PType->isVariablyModifiedType()) 14059 return; 14060 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14061 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14062 return; 14063 } 14064 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14065 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14066 return; 14067 } 14068 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14069 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14070 return; 14071 } 14072 14073 const ArrayType *AT = S.Context.getAsArrayType(PType); 14074 if (!AT) 14075 return; 14076 14077 if (AT->getSizeModifier() != ArrayType::Star) { 14078 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14079 return; 14080 } 14081 14082 S.Diag(Loc, diag::err_array_star_in_function_definition); 14083 } 14084 14085 /// CheckParmsForFunctionDef - Check that the parameters of the given 14086 /// function are appropriate for the definition of a function. This 14087 /// takes care of any checks that cannot be performed on the 14088 /// declaration itself, e.g., that the types of each of the function 14089 /// parameters are complete. 14090 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14091 bool CheckParameterNames) { 14092 bool HasInvalidParm = false; 14093 for (ParmVarDecl *Param : Parameters) { 14094 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14095 // function declarator that is part of a function definition of 14096 // that function shall not have incomplete type. 14097 // 14098 // This is also C++ [dcl.fct]p6. 14099 if (!Param->isInvalidDecl() && 14100 RequireCompleteType(Param->getLocation(), Param->getType(), 14101 diag::err_typecheck_decl_incomplete_type)) { 14102 Param->setInvalidDecl(); 14103 HasInvalidParm = true; 14104 } 14105 14106 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14107 // declaration of each parameter shall include an identifier. 14108 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14109 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14110 // Diagnose this as an extension in C17 and earlier. 14111 if (!getLangOpts().C2x) 14112 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14113 } 14114 14115 // C99 6.7.5.3p12: 14116 // If the function declarator is not part of a definition of that 14117 // function, parameters may have incomplete type and may use the [*] 14118 // notation in their sequences of declarator specifiers to specify 14119 // variable length array types. 14120 QualType PType = Param->getOriginalType(); 14121 // FIXME: This diagnostic should point the '[*]' if source-location 14122 // information is added for it. 14123 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14124 14125 // If the parameter is a c++ class type and it has to be destructed in the 14126 // callee function, declare the destructor so that it can be called by the 14127 // callee function. Do not perform any direct access check on the dtor here. 14128 if (!Param->isInvalidDecl()) { 14129 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14130 if (!ClassDecl->isInvalidDecl() && 14131 !ClassDecl->hasIrrelevantDestructor() && 14132 !ClassDecl->isDependentContext() && 14133 ClassDecl->isParamDestroyedInCallee()) { 14134 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14135 MarkFunctionReferenced(Param->getLocation(), Destructor); 14136 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14137 } 14138 } 14139 } 14140 14141 // Parameters with the pass_object_size attribute only need to be marked 14142 // constant at function definitions. Because we lack information about 14143 // whether we're on a declaration or definition when we're instantiating the 14144 // attribute, we need to check for constness here. 14145 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14146 if (!Param->getType().isConstQualified()) 14147 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14148 << Attr->getSpelling() << 1; 14149 14150 // Check for parameter names shadowing fields from the class. 14151 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14152 // The owning context for the parameter should be the function, but we 14153 // want to see if this function's declaration context is a record. 14154 DeclContext *DC = Param->getDeclContext(); 14155 if (DC && DC->isFunctionOrMethod()) { 14156 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14157 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14158 RD, /*DeclIsField*/ false); 14159 } 14160 } 14161 } 14162 14163 return HasInvalidParm; 14164 } 14165 14166 Optional<std::pair<CharUnits, CharUnits>> 14167 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14168 14169 /// Compute the alignment and offset of the base class object given the 14170 /// derived-to-base cast expression and the alignment and offset of the derived 14171 /// class object. 14172 static std::pair<CharUnits, CharUnits> 14173 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14174 CharUnits BaseAlignment, CharUnits Offset, 14175 ASTContext &Ctx) { 14176 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14177 ++PathI) { 14178 const CXXBaseSpecifier *Base = *PathI; 14179 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14180 if (Base->isVirtual()) { 14181 // The complete object may have a lower alignment than the non-virtual 14182 // alignment of the base, in which case the base may be misaligned. Choose 14183 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14184 // conservative lower bound of the complete object alignment. 14185 CharUnits NonVirtualAlignment = 14186 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14187 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14188 Offset = CharUnits::Zero(); 14189 } else { 14190 const ASTRecordLayout &RL = 14191 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14192 Offset += RL.getBaseClassOffset(BaseDecl); 14193 } 14194 DerivedType = Base->getType(); 14195 } 14196 14197 return std::make_pair(BaseAlignment, Offset); 14198 } 14199 14200 /// Compute the alignment and offset of a binary additive operator. 14201 static Optional<std::pair<CharUnits, CharUnits>> 14202 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14203 bool IsSub, ASTContext &Ctx) { 14204 QualType PointeeType = PtrE->getType()->getPointeeType(); 14205 14206 if (!PointeeType->isConstantSizeType()) 14207 return llvm::None; 14208 14209 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14210 14211 if (!P) 14212 return llvm::None; 14213 14214 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14215 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14216 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14217 if (IsSub) 14218 Offset = -Offset; 14219 return std::make_pair(P->first, P->second + Offset); 14220 } 14221 14222 // If the integer expression isn't a constant expression, compute the lower 14223 // bound of the alignment using the alignment and offset of the pointer 14224 // expression and the element size. 14225 return std::make_pair( 14226 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14227 CharUnits::Zero()); 14228 } 14229 14230 /// This helper function takes an lvalue expression and returns the alignment of 14231 /// a VarDecl and a constant offset from the VarDecl. 14232 Optional<std::pair<CharUnits, CharUnits>> 14233 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14234 E = E->IgnoreParens(); 14235 switch (E->getStmtClass()) { 14236 default: 14237 break; 14238 case Stmt::CStyleCastExprClass: 14239 case Stmt::CXXStaticCastExprClass: 14240 case Stmt::ImplicitCastExprClass: { 14241 auto *CE = cast<CastExpr>(E); 14242 const Expr *From = CE->getSubExpr(); 14243 switch (CE->getCastKind()) { 14244 default: 14245 break; 14246 case CK_NoOp: 14247 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14248 case CK_UncheckedDerivedToBase: 14249 case CK_DerivedToBase: { 14250 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14251 if (!P) 14252 break; 14253 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14254 P->second, Ctx); 14255 } 14256 } 14257 break; 14258 } 14259 case Stmt::ArraySubscriptExprClass: { 14260 auto *ASE = cast<ArraySubscriptExpr>(E); 14261 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14262 false, Ctx); 14263 } 14264 case Stmt::DeclRefExprClass: { 14265 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14266 // FIXME: If VD is captured by copy or is an escaping __block variable, 14267 // use the alignment of VD's type. 14268 if (!VD->getType()->isReferenceType()) 14269 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14270 if (VD->hasInit()) 14271 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14272 } 14273 break; 14274 } 14275 case Stmt::MemberExprClass: { 14276 auto *ME = cast<MemberExpr>(E); 14277 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14278 if (!FD || FD->getType()->isReferenceType()) 14279 break; 14280 Optional<std::pair<CharUnits, CharUnits>> P; 14281 if (ME->isArrow()) 14282 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14283 else 14284 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14285 if (!P) 14286 break; 14287 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14288 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14289 return std::make_pair(P->first, 14290 P->second + CharUnits::fromQuantity(Offset)); 14291 } 14292 case Stmt::UnaryOperatorClass: { 14293 auto *UO = cast<UnaryOperator>(E); 14294 switch (UO->getOpcode()) { 14295 default: 14296 break; 14297 case UO_Deref: 14298 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14299 } 14300 break; 14301 } 14302 case Stmt::BinaryOperatorClass: { 14303 auto *BO = cast<BinaryOperator>(E); 14304 auto Opcode = BO->getOpcode(); 14305 switch (Opcode) { 14306 default: 14307 break; 14308 case BO_Comma: 14309 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14310 } 14311 break; 14312 } 14313 } 14314 return llvm::None; 14315 } 14316 14317 /// This helper function takes a pointer expression and returns the alignment of 14318 /// a VarDecl and a constant offset from the VarDecl. 14319 Optional<std::pair<CharUnits, CharUnits>> 14320 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14321 E = E->IgnoreParens(); 14322 switch (E->getStmtClass()) { 14323 default: 14324 break; 14325 case Stmt::CStyleCastExprClass: 14326 case Stmt::CXXStaticCastExprClass: 14327 case Stmt::ImplicitCastExprClass: { 14328 auto *CE = cast<CastExpr>(E); 14329 const Expr *From = CE->getSubExpr(); 14330 switch (CE->getCastKind()) { 14331 default: 14332 break; 14333 case CK_NoOp: 14334 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14335 case CK_ArrayToPointerDecay: 14336 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14337 case CK_UncheckedDerivedToBase: 14338 case CK_DerivedToBase: { 14339 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14340 if (!P) 14341 break; 14342 return getDerivedToBaseAlignmentAndOffset( 14343 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14344 } 14345 } 14346 break; 14347 } 14348 case Stmt::CXXThisExprClass: { 14349 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14350 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14351 return std::make_pair(Alignment, CharUnits::Zero()); 14352 } 14353 case Stmt::UnaryOperatorClass: { 14354 auto *UO = cast<UnaryOperator>(E); 14355 if (UO->getOpcode() == UO_AddrOf) 14356 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14357 break; 14358 } 14359 case Stmt::BinaryOperatorClass: { 14360 auto *BO = cast<BinaryOperator>(E); 14361 auto Opcode = BO->getOpcode(); 14362 switch (Opcode) { 14363 default: 14364 break; 14365 case BO_Add: 14366 case BO_Sub: { 14367 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14368 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14369 std::swap(LHS, RHS); 14370 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14371 Ctx); 14372 } 14373 case BO_Comma: 14374 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14375 } 14376 break; 14377 } 14378 } 14379 return llvm::None; 14380 } 14381 14382 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14383 // See if we can compute the alignment of a VarDecl and an offset from it. 14384 Optional<std::pair<CharUnits, CharUnits>> P = 14385 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14386 14387 if (P) 14388 return P->first.alignmentAtOffset(P->second); 14389 14390 // If that failed, return the type's alignment. 14391 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14392 } 14393 14394 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14395 /// pointer cast increases the alignment requirements. 14396 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14397 // This is actually a lot of work to potentially be doing on every 14398 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14399 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14400 return; 14401 14402 // Ignore dependent types. 14403 if (T->isDependentType() || Op->getType()->isDependentType()) 14404 return; 14405 14406 // Require that the destination be a pointer type. 14407 const PointerType *DestPtr = T->getAs<PointerType>(); 14408 if (!DestPtr) return; 14409 14410 // If the destination has alignment 1, we're done. 14411 QualType DestPointee = DestPtr->getPointeeType(); 14412 if (DestPointee->isIncompleteType()) return; 14413 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14414 if (DestAlign.isOne()) return; 14415 14416 // Require that the source be a pointer type. 14417 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14418 if (!SrcPtr) return; 14419 QualType SrcPointee = SrcPtr->getPointeeType(); 14420 14421 // Explicitly allow casts from cv void*. We already implicitly 14422 // allowed casts to cv void*, since they have alignment 1. 14423 // Also allow casts involving incomplete types, which implicitly 14424 // includes 'void'. 14425 if (SrcPointee->isIncompleteType()) return; 14426 14427 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14428 14429 if (SrcAlign >= DestAlign) return; 14430 14431 Diag(TRange.getBegin(), diag::warn_cast_align) 14432 << Op->getType() << T 14433 << static_cast<unsigned>(SrcAlign.getQuantity()) 14434 << static_cast<unsigned>(DestAlign.getQuantity()) 14435 << TRange << Op->getSourceRange(); 14436 } 14437 14438 /// Check whether this array fits the idiom of a size-one tail padded 14439 /// array member of a struct. 14440 /// 14441 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14442 /// commonly used to emulate flexible arrays in C89 code. 14443 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14444 const NamedDecl *ND) { 14445 if (Size != 1 || !ND) return false; 14446 14447 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14448 if (!FD) return false; 14449 14450 // Don't consider sizes resulting from macro expansions or template argument 14451 // substitution to form C89 tail-padded arrays. 14452 14453 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14454 while (TInfo) { 14455 TypeLoc TL = TInfo->getTypeLoc(); 14456 // Look through typedefs. 14457 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14458 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14459 TInfo = TDL->getTypeSourceInfo(); 14460 continue; 14461 } 14462 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14463 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14464 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14465 return false; 14466 } 14467 break; 14468 } 14469 14470 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14471 if (!RD) return false; 14472 if (RD->isUnion()) return false; 14473 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14474 if (!CRD->isStandardLayout()) return false; 14475 } 14476 14477 // See if this is the last field decl in the record. 14478 const Decl *D = FD; 14479 while ((D = D->getNextDeclInContext())) 14480 if (isa<FieldDecl>(D)) 14481 return false; 14482 return true; 14483 } 14484 14485 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14486 const ArraySubscriptExpr *ASE, 14487 bool AllowOnePastEnd, bool IndexNegated) { 14488 // Already diagnosed by the constant evaluator. 14489 if (isConstantEvaluated()) 14490 return; 14491 14492 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14493 if (IndexExpr->isValueDependent()) 14494 return; 14495 14496 const Type *EffectiveType = 14497 BaseExpr->getType()->getPointeeOrArrayElementType(); 14498 BaseExpr = BaseExpr->IgnoreParenCasts(); 14499 const ConstantArrayType *ArrayTy = 14500 Context.getAsConstantArrayType(BaseExpr->getType()); 14501 14502 if (!ArrayTy) 14503 return; 14504 14505 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 14506 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 14507 return; 14508 14509 Expr::EvalResult Result; 14510 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 14511 return; 14512 14513 llvm::APSInt index = Result.Val.getInt(); 14514 if (IndexNegated) 14515 index = -index; 14516 14517 const NamedDecl *ND = nullptr; 14518 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14519 ND = DRE->getDecl(); 14520 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14521 ND = ME->getMemberDecl(); 14522 14523 if (index.isUnsigned() || !index.isNegative()) { 14524 // It is possible that the type of the base expression after 14525 // IgnoreParenCasts is incomplete, even though the type of the base 14526 // expression before IgnoreParenCasts is complete (see PR39746 for an 14527 // example). In this case we have no information about whether the array 14528 // access exceeds the array bounds. However we can still diagnose an array 14529 // access which precedes the array bounds. 14530 if (BaseType->isIncompleteType()) 14531 return; 14532 14533 llvm::APInt size = ArrayTy->getSize(); 14534 if (!size.isStrictlyPositive()) 14535 return; 14536 14537 if (BaseType != EffectiveType) { 14538 // Make sure we're comparing apples to apples when comparing index to size 14539 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 14540 uint64_t array_typesize = Context.getTypeSize(BaseType); 14541 // Handle ptrarith_typesize being zero, such as when casting to void* 14542 if (!ptrarith_typesize) ptrarith_typesize = 1; 14543 if (ptrarith_typesize != array_typesize) { 14544 // There's a cast to a different size type involved 14545 uint64_t ratio = array_typesize / ptrarith_typesize; 14546 // TODO: Be smarter about handling cases where array_typesize is not a 14547 // multiple of ptrarith_typesize 14548 if (ptrarith_typesize * ratio == array_typesize) 14549 size *= llvm::APInt(size.getBitWidth(), ratio); 14550 } 14551 } 14552 14553 if (size.getBitWidth() > index.getBitWidth()) 14554 index = index.zext(size.getBitWidth()); 14555 else if (size.getBitWidth() < index.getBitWidth()) 14556 size = size.zext(index.getBitWidth()); 14557 14558 // For array subscripting the index must be less than size, but for pointer 14559 // arithmetic also allow the index (offset) to be equal to size since 14560 // computing the next address after the end of the array is legal and 14561 // commonly done e.g. in C++ iterators and range-based for loops. 14562 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 14563 return; 14564 14565 // Also don't warn for arrays of size 1 which are members of some 14566 // structure. These are often used to approximate flexible arrays in C89 14567 // code. 14568 if (IsTailPaddedMemberArray(*this, size, ND)) 14569 return; 14570 14571 // Suppress the warning if the subscript expression (as identified by the 14572 // ']' location) and the index expression are both from macro expansions 14573 // within a system header. 14574 if (ASE) { 14575 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 14576 ASE->getRBracketLoc()); 14577 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 14578 SourceLocation IndexLoc = 14579 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 14580 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 14581 return; 14582 } 14583 } 14584 14585 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 14586 if (ASE) 14587 DiagID = diag::warn_array_index_exceeds_bounds; 14588 14589 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14590 PDiag(DiagID) << index.toString(10, true) 14591 << size.toString(10, true) 14592 << (unsigned)size.getLimitedValue(~0U) 14593 << IndexExpr->getSourceRange()); 14594 } else { 14595 unsigned DiagID = diag::warn_array_index_precedes_bounds; 14596 if (!ASE) { 14597 DiagID = diag::warn_ptr_arith_precedes_bounds; 14598 if (index.isNegative()) index = -index; 14599 } 14600 14601 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 14602 PDiag(DiagID) << index.toString(10, true) 14603 << IndexExpr->getSourceRange()); 14604 } 14605 14606 if (!ND) { 14607 // Try harder to find a NamedDecl to point at in the note. 14608 while (const ArraySubscriptExpr *ASE = 14609 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 14610 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 14611 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 14612 ND = DRE->getDecl(); 14613 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 14614 ND = ME->getMemberDecl(); 14615 } 14616 14617 if (ND) 14618 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 14619 PDiag(diag::note_array_declared_here) << ND); 14620 } 14621 14622 void Sema::CheckArrayAccess(const Expr *expr) { 14623 int AllowOnePastEnd = 0; 14624 while (expr) { 14625 expr = expr->IgnoreParenImpCasts(); 14626 switch (expr->getStmtClass()) { 14627 case Stmt::ArraySubscriptExprClass: { 14628 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 14629 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 14630 AllowOnePastEnd > 0); 14631 expr = ASE->getBase(); 14632 break; 14633 } 14634 case Stmt::MemberExprClass: { 14635 expr = cast<MemberExpr>(expr)->getBase(); 14636 break; 14637 } 14638 case Stmt::OMPArraySectionExprClass: { 14639 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 14640 if (ASE->getLowerBound()) 14641 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 14642 /*ASE=*/nullptr, AllowOnePastEnd > 0); 14643 return; 14644 } 14645 case Stmt::UnaryOperatorClass: { 14646 // Only unwrap the * and & unary operators 14647 const UnaryOperator *UO = cast<UnaryOperator>(expr); 14648 expr = UO->getSubExpr(); 14649 switch (UO->getOpcode()) { 14650 case UO_AddrOf: 14651 AllowOnePastEnd++; 14652 break; 14653 case UO_Deref: 14654 AllowOnePastEnd--; 14655 break; 14656 default: 14657 return; 14658 } 14659 break; 14660 } 14661 case Stmt::ConditionalOperatorClass: { 14662 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14663 if (const Expr *lhs = cond->getLHS()) 14664 CheckArrayAccess(lhs); 14665 if (const Expr *rhs = cond->getRHS()) 14666 CheckArrayAccess(rhs); 14667 return; 14668 } 14669 case Stmt::CXXOperatorCallExprClass: { 14670 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14671 for (const auto *Arg : OCE->arguments()) 14672 CheckArrayAccess(Arg); 14673 return; 14674 } 14675 default: 14676 return; 14677 } 14678 } 14679 } 14680 14681 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14682 14683 namespace { 14684 14685 struct RetainCycleOwner { 14686 VarDecl *Variable = nullptr; 14687 SourceRange Range; 14688 SourceLocation Loc; 14689 bool Indirect = false; 14690 14691 RetainCycleOwner() = default; 14692 14693 void setLocsFrom(Expr *e) { 14694 Loc = e->getExprLoc(); 14695 Range = e->getSourceRange(); 14696 } 14697 }; 14698 14699 } // namespace 14700 14701 /// Consider whether capturing the given variable can possibly lead to 14702 /// a retain cycle. 14703 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14704 // In ARC, it's captured strongly iff the variable has __strong 14705 // lifetime. In MRR, it's captured strongly if the variable is 14706 // __block and has an appropriate type. 14707 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14708 return false; 14709 14710 owner.Variable = var; 14711 if (ref) 14712 owner.setLocsFrom(ref); 14713 return true; 14714 } 14715 14716 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14717 while (true) { 14718 e = e->IgnoreParens(); 14719 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14720 switch (cast->getCastKind()) { 14721 case CK_BitCast: 14722 case CK_LValueBitCast: 14723 case CK_LValueToRValue: 14724 case CK_ARCReclaimReturnedObject: 14725 e = cast->getSubExpr(); 14726 continue; 14727 14728 default: 14729 return false; 14730 } 14731 } 14732 14733 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14734 ObjCIvarDecl *ivar = ref->getDecl(); 14735 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14736 return false; 14737 14738 // Try to find a retain cycle in the base. 14739 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14740 return false; 14741 14742 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14743 owner.Indirect = true; 14744 return true; 14745 } 14746 14747 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14748 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14749 if (!var) return false; 14750 return considerVariable(var, ref, owner); 14751 } 14752 14753 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14754 if (member->isArrow()) return false; 14755 14756 // Don't count this as an indirect ownership. 14757 e = member->getBase(); 14758 continue; 14759 } 14760 14761 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14762 // Only pay attention to pseudo-objects on property references. 14763 ObjCPropertyRefExpr *pre 14764 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14765 ->IgnoreParens()); 14766 if (!pre) return false; 14767 if (pre->isImplicitProperty()) return false; 14768 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14769 if (!property->isRetaining() && 14770 !(property->getPropertyIvarDecl() && 14771 property->getPropertyIvarDecl()->getType() 14772 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14773 return false; 14774 14775 owner.Indirect = true; 14776 if (pre->isSuperReceiver()) { 14777 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14778 if (!owner.Variable) 14779 return false; 14780 owner.Loc = pre->getLocation(); 14781 owner.Range = pre->getSourceRange(); 14782 return true; 14783 } 14784 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14785 ->getSourceExpr()); 14786 continue; 14787 } 14788 14789 // Array ivars? 14790 14791 return false; 14792 } 14793 } 14794 14795 namespace { 14796 14797 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14798 ASTContext &Context; 14799 VarDecl *Variable; 14800 Expr *Capturer = nullptr; 14801 bool VarWillBeReased = false; 14802 14803 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14804 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14805 Context(Context), Variable(variable) {} 14806 14807 void VisitDeclRefExpr(DeclRefExpr *ref) { 14808 if (ref->getDecl() == Variable && !Capturer) 14809 Capturer = ref; 14810 } 14811 14812 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14813 if (Capturer) return; 14814 Visit(ref->getBase()); 14815 if (Capturer && ref->isFreeIvar()) 14816 Capturer = ref; 14817 } 14818 14819 void VisitBlockExpr(BlockExpr *block) { 14820 // Look inside nested blocks 14821 if (block->getBlockDecl()->capturesVariable(Variable)) 14822 Visit(block->getBlockDecl()->getBody()); 14823 } 14824 14825 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14826 if (Capturer) return; 14827 if (OVE->getSourceExpr()) 14828 Visit(OVE->getSourceExpr()); 14829 } 14830 14831 void VisitBinaryOperator(BinaryOperator *BinOp) { 14832 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14833 return; 14834 Expr *LHS = BinOp->getLHS(); 14835 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14836 if (DRE->getDecl() != Variable) 14837 return; 14838 if (Expr *RHS = BinOp->getRHS()) { 14839 RHS = RHS->IgnoreParenCasts(); 14840 Optional<llvm::APSInt> Value; 14841 VarWillBeReased = 14842 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14843 *Value == 0); 14844 } 14845 } 14846 } 14847 }; 14848 14849 } // namespace 14850 14851 /// Check whether the given argument is a block which captures a 14852 /// variable. 14853 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14854 assert(owner.Variable && owner.Loc.isValid()); 14855 14856 e = e->IgnoreParenCasts(); 14857 14858 // Look through [^{...} copy] and Block_copy(^{...}). 14859 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14860 Selector Cmd = ME->getSelector(); 14861 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14862 e = ME->getInstanceReceiver(); 14863 if (!e) 14864 return nullptr; 14865 e = e->IgnoreParenCasts(); 14866 } 14867 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14868 if (CE->getNumArgs() == 1) { 14869 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14870 if (Fn) { 14871 const IdentifierInfo *FnI = Fn->getIdentifier(); 14872 if (FnI && FnI->isStr("_Block_copy")) { 14873 e = CE->getArg(0)->IgnoreParenCasts(); 14874 } 14875 } 14876 } 14877 } 14878 14879 BlockExpr *block = dyn_cast<BlockExpr>(e); 14880 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14881 return nullptr; 14882 14883 FindCaptureVisitor visitor(S.Context, owner.Variable); 14884 visitor.Visit(block->getBlockDecl()->getBody()); 14885 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14886 } 14887 14888 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14889 RetainCycleOwner &owner) { 14890 assert(capturer); 14891 assert(owner.Variable && owner.Loc.isValid()); 14892 14893 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14894 << owner.Variable << capturer->getSourceRange(); 14895 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14896 << owner.Indirect << owner.Range; 14897 } 14898 14899 /// Check for a keyword selector that starts with the word 'add' or 14900 /// 'set'. 14901 static bool isSetterLikeSelector(Selector sel) { 14902 if (sel.isUnarySelector()) return false; 14903 14904 StringRef str = sel.getNameForSlot(0); 14905 while (!str.empty() && str.front() == '_') str = str.substr(1); 14906 if (str.startswith("set")) 14907 str = str.substr(3); 14908 else if (str.startswith("add")) { 14909 // Specially allow 'addOperationWithBlock:'. 14910 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14911 return false; 14912 str = str.substr(3); 14913 } 14914 else 14915 return false; 14916 14917 if (str.empty()) return true; 14918 return !isLowercase(str.front()); 14919 } 14920 14921 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14922 ObjCMessageExpr *Message) { 14923 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14924 Message->getReceiverInterface(), 14925 NSAPI::ClassId_NSMutableArray); 14926 if (!IsMutableArray) { 14927 return None; 14928 } 14929 14930 Selector Sel = Message->getSelector(); 14931 14932 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14933 S.NSAPIObj->getNSArrayMethodKind(Sel); 14934 if (!MKOpt) { 14935 return None; 14936 } 14937 14938 NSAPI::NSArrayMethodKind MK = *MKOpt; 14939 14940 switch (MK) { 14941 case NSAPI::NSMutableArr_addObject: 14942 case NSAPI::NSMutableArr_insertObjectAtIndex: 14943 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14944 return 0; 14945 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14946 return 1; 14947 14948 default: 14949 return None; 14950 } 14951 14952 return None; 14953 } 14954 14955 static 14956 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14957 ObjCMessageExpr *Message) { 14958 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14959 Message->getReceiverInterface(), 14960 NSAPI::ClassId_NSMutableDictionary); 14961 if (!IsMutableDictionary) { 14962 return None; 14963 } 14964 14965 Selector Sel = Message->getSelector(); 14966 14967 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14968 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14969 if (!MKOpt) { 14970 return None; 14971 } 14972 14973 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14974 14975 switch (MK) { 14976 case NSAPI::NSMutableDict_setObjectForKey: 14977 case NSAPI::NSMutableDict_setValueForKey: 14978 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14979 return 0; 14980 14981 default: 14982 return None; 14983 } 14984 14985 return None; 14986 } 14987 14988 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14989 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14990 Message->getReceiverInterface(), 14991 NSAPI::ClassId_NSMutableSet); 14992 14993 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14994 Message->getReceiverInterface(), 14995 NSAPI::ClassId_NSMutableOrderedSet); 14996 if (!IsMutableSet && !IsMutableOrderedSet) { 14997 return None; 14998 } 14999 15000 Selector Sel = Message->getSelector(); 15001 15002 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15003 if (!MKOpt) { 15004 return None; 15005 } 15006 15007 NSAPI::NSSetMethodKind MK = *MKOpt; 15008 15009 switch (MK) { 15010 case NSAPI::NSMutableSet_addObject: 15011 case NSAPI::NSOrderedSet_setObjectAtIndex: 15012 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15013 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15014 return 0; 15015 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15016 return 1; 15017 } 15018 15019 return None; 15020 } 15021 15022 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15023 if (!Message->isInstanceMessage()) { 15024 return; 15025 } 15026 15027 Optional<int> ArgOpt; 15028 15029 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15030 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15031 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15032 return; 15033 } 15034 15035 int ArgIndex = *ArgOpt; 15036 15037 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15038 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15039 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15040 } 15041 15042 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15043 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15044 if (ArgRE->isObjCSelfExpr()) { 15045 Diag(Message->getSourceRange().getBegin(), 15046 diag::warn_objc_circular_container) 15047 << ArgRE->getDecl() << StringRef("'super'"); 15048 } 15049 } 15050 } else { 15051 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15052 15053 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15054 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15055 } 15056 15057 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15058 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15059 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15060 ValueDecl *Decl = ReceiverRE->getDecl(); 15061 Diag(Message->getSourceRange().getBegin(), 15062 diag::warn_objc_circular_container) 15063 << Decl << Decl; 15064 if (!ArgRE->isObjCSelfExpr()) { 15065 Diag(Decl->getLocation(), 15066 diag::note_objc_circular_container_declared_here) 15067 << Decl; 15068 } 15069 } 15070 } 15071 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15072 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15073 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15074 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15075 Diag(Message->getSourceRange().getBegin(), 15076 diag::warn_objc_circular_container) 15077 << Decl << Decl; 15078 Diag(Decl->getLocation(), 15079 diag::note_objc_circular_container_declared_here) 15080 << Decl; 15081 } 15082 } 15083 } 15084 } 15085 } 15086 15087 /// Check a message send to see if it's likely to cause a retain cycle. 15088 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15089 // Only check instance methods whose selector looks like a setter. 15090 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15091 return; 15092 15093 // Try to find a variable that the receiver is strongly owned by. 15094 RetainCycleOwner owner; 15095 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15096 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15097 return; 15098 } else { 15099 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15100 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15101 owner.Loc = msg->getSuperLoc(); 15102 owner.Range = msg->getSuperLoc(); 15103 } 15104 15105 // Check whether the receiver is captured by any of the arguments. 15106 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15107 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15108 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15109 // noescape blocks should not be retained by the method. 15110 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15111 continue; 15112 return diagnoseRetainCycle(*this, capturer, owner); 15113 } 15114 } 15115 } 15116 15117 /// Check a property assign to see if it's likely to cause a retain cycle. 15118 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15119 RetainCycleOwner owner; 15120 if (!findRetainCycleOwner(*this, receiver, owner)) 15121 return; 15122 15123 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15124 diagnoseRetainCycle(*this, capturer, owner); 15125 } 15126 15127 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15128 RetainCycleOwner Owner; 15129 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15130 return; 15131 15132 // Because we don't have an expression for the variable, we have to set the 15133 // location explicitly here. 15134 Owner.Loc = Var->getLocation(); 15135 Owner.Range = Var->getSourceRange(); 15136 15137 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15138 diagnoseRetainCycle(*this, Capturer, Owner); 15139 } 15140 15141 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15142 Expr *RHS, bool isProperty) { 15143 // Check if RHS is an Objective-C object literal, which also can get 15144 // immediately zapped in a weak reference. Note that we explicitly 15145 // allow ObjCStringLiterals, since those are designed to never really die. 15146 RHS = RHS->IgnoreParenImpCasts(); 15147 15148 // This enum needs to match with the 'select' in 15149 // warn_objc_arc_literal_assign (off-by-1). 15150 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15151 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15152 return false; 15153 15154 S.Diag(Loc, diag::warn_arc_literal_assign) 15155 << (unsigned) Kind 15156 << (isProperty ? 0 : 1) 15157 << RHS->getSourceRange(); 15158 15159 return true; 15160 } 15161 15162 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15163 Qualifiers::ObjCLifetime LT, 15164 Expr *RHS, bool isProperty) { 15165 // Strip off any implicit cast added to get to the one ARC-specific. 15166 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15167 if (cast->getCastKind() == CK_ARCConsumeObject) { 15168 S.Diag(Loc, diag::warn_arc_retained_assign) 15169 << (LT == Qualifiers::OCL_ExplicitNone) 15170 << (isProperty ? 0 : 1) 15171 << RHS->getSourceRange(); 15172 return true; 15173 } 15174 RHS = cast->getSubExpr(); 15175 } 15176 15177 if (LT == Qualifiers::OCL_Weak && 15178 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15179 return true; 15180 15181 return false; 15182 } 15183 15184 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15185 QualType LHS, Expr *RHS) { 15186 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15187 15188 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15189 return false; 15190 15191 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15192 return true; 15193 15194 return false; 15195 } 15196 15197 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15198 Expr *LHS, Expr *RHS) { 15199 QualType LHSType; 15200 // PropertyRef on LHS type need be directly obtained from 15201 // its declaration as it has a PseudoType. 15202 ObjCPropertyRefExpr *PRE 15203 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15204 if (PRE && !PRE->isImplicitProperty()) { 15205 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15206 if (PD) 15207 LHSType = PD->getType(); 15208 } 15209 15210 if (LHSType.isNull()) 15211 LHSType = LHS->getType(); 15212 15213 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15214 15215 if (LT == Qualifiers::OCL_Weak) { 15216 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15217 getCurFunction()->markSafeWeakUse(LHS); 15218 } 15219 15220 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15221 return; 15222 15223 // FIXME. Check for other life times. 15224 if (LT != Qualifiers::OCL_None) 15225 return; 15226 15227 if (PRE) { 15228 if (PRE->isImplicitProperty()) 15229 return; 15230 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15231 if (!PD) 15232 return; 15233 15234 unsigned Attributes = PD->getPropertyAttributes(); 15235 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15236 // when 'assign' attribute was not explicitly specified 15237 // by user, ignore it and rely on property type itself 15238 // for lifetime info. 15239 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15240 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15241 LHSType->isObjCRetainableType()) 15242 return; 15243 15244 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15245 if (cast->getCastKind() == CK_ARCConsumeObject) { 15246 Diag(Loc, diag::warn_arc_retained_property_assign) 15247 << RHS->getSourceRange(); 15248 return; 15249 } 15250 RHS = cast->getSubExpr(); 15251 } 15252 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15253 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15254 return; 15255 } 15256 } 15257 } 15258 15259 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15260 15261 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15262 SourceLocation StmtLoc, 15263 const NullStmt *Body) { 15264 // Do not warn if the body is a macro that expands to nothing, e.g: 15265 // 15266 // #define CALL(x) 15267 // if (condition) 15268 // CALL(0); 15269 if (Body->hasLeadingEmptyMacro()) 15270 return false; 15271 15272 // Get line numbers of statement and body. 15273 bool StmtLineInvalid; 15274 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15275 &StmtLineInvalid); 15276 if (StmtLineInvalid) 15277 return false; 15278 15279 bool BodyLineInvalid; 15280 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15281 &BodyLineInvalid); 15282 if (BodyLineInvalid) 15283 return false; 15284 15285 // Warn if null statement and body are on the same line. 15286 if (StmtLine != BodyLine) 15287 return false; 15288 15289 return true; 15290 } 15291 15292 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15293 const Stmt *Body, 15294 unsigned DiagID) { 15295 // Since this is a syntactic check, don't emit diagnostic for template 15296 // instantiations, this just adds noise. 15297 if (CurrentInstantiationScope) 15298 return; 15299 15300 // The body should be a null statement. 15301 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15302 if (!NBody) 15303 return; 15304 15305 // Do the usual checks. 15306 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15307 return; 15308 15309 Diag(NBody->getSemiLoc(), DiagID); 15310 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15311 } 15312 15313 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15314 const Stmt *PossibleBody) { 15315 assert(!CurrentInstantiationScope); // Ensured by caller 15316 15317 SourceLocation StmtLoc; 15318 const Stmt *Body; 15319 unsigned DiagID; 15320 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15321 StmtLoc = FS->getRParenLoc(); 15322 Body = FS->getBody(); 15323 DiagID = diag::warn_empty_for_body; 15324 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15325 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15326 Body = WS->getBody(); 15327 DiagID = diag::warn_empty_while_body; 15328 } else 15329 return; // Neither `for' nor `while'. 15330 15331 // The body should be a null statement. 15332 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15333 if (!NBody) 15334 return; 15335 15336 // Skip expensive checks if diagnostic is disabled. 15337 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15338 return; 15339 15340 // Do the usual checks. 15341 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15342 return; 15343 15344 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15345 // noise level low, emit diagnostics only if for/while is followed by a 15346 // CompoundStmt, e.g.: 15347 // for (int i = 0; i < n; i++); 15348 // { 15349 // a(i); 15350 // } 15351 // or if for/while is followed by a statement with more indentation 15352 // than for/while itself: 15353 // for (int i = 0; i < n; i++); 15354 // a(i); 15355 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15356 if (!ProbableTypo) { 15357 bool BodyColInvalid; 15358 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15359 PossibleBody->getBeginLoc(), &BodyColInvalid); 15360 if (BodyColInvalid) 15361 return; 15362 15363 bool StmtColInvalid; 15364 unsigned StmtCol = 15365 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15366 if (StmtColInvalid) 15367 return; 15368 15369 if (BodyCol > StmtCol) 15370 ProbableTypo = true; 15371 } 15372 15373 if (ProbableTypo) { 15374 Diag(NBody->getSemiLoc(), DiagID); 15375 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15376 } 15377 } 15378 15379 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15380 15381 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15382 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15383 SourceLocation OpLoc) { 15384 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15385 return; 15386 15387 if (inTemplateInstantiation()) 15388 return; 15389 15390 // Strip parens and casts away. 15391 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15392 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15393 15394 // Check for a call expression 15395 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15396 if (!CE || CE->getNumArgs() != 1) 15397 return; 15398 15399 // Check for a call to std::move 15400 if (!CE->isCallToStdMove()) 15401 return; 15402 15403 // Get argument from std::move 15404 RHSExpr = CE->getArg(0); 15405 15406 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15407 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15408 15409 // Two DeclRefExpr's, check that the decls are the same. 15410 if (LHSDeclRef && RHSDeclRef) { 15411 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15412 return; 15413 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15414 RHSDeclRef->getDecl()->getCanonicalDecl()) 15415 return; 15416 15417 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15418 << LHSExpr->getSourceRange() 15419 << RHSExpr->getSourceRange(); 15420 return; 15421 } 15422 15423 // Member variables require a different approach to check for self moves. 15424 // MemberExpr's are the same if every nested MemberExpr refers to the same 15425 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15426 // the base Expr's are CXXThisExpr's. 15427 const Expr *LHSBase = LHSExpr; 15428 const Expr *RHSBase = RHSExpr; 15429 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15430 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15431 if (!LHSME || !RHSME) 15432 return; 15433 15434 while (LHSME && RHSME) { 15435 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15436 RHSME->getMemberDecl()->getCanonicalDecl()) 15437 return; 15438 15439 LHSBase = LHSME->getBase(); 15440 RHSBase = RHSME->getBase(); 15441 LHSME = dyn_cast<MemberExpr>(LHSBase); 15442 RHSME = dyn_cast<MemberExpr>(RHSBase); 15443 } 15444 15445 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 15446 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 15447 if (LHSDeclRef && RHSDeclRef) { 15448 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15449 return; 15450 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15451 RHSDeclRef->getDecl()->getCanonicalDecl()) 15452 return; 15453 15454 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15455 << LHSExpr->getSourceRange() 15456 << RHSExpr->getSourceRange(); 15457 return; 15458 } 15459 15460 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 15461 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15462 << LHSExpr->getSourceRange() 15463 << RHSExpr->getSourceRange(); 15464 } 15465 15466 //===--- Layout compatibility ----------------------------------------------// 15467 15468 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 15469 15470 /// Check if two enumeration types are layout-compatible. 15471 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 15472 // C++11 [dcl.enum] p8: 15473 // Two enumeration types are layout-compatible if they have the same 15474 // underlying type. 15475 return ED1->isComplete() && ED2->isComplete() && 15476 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 15477 } 15478 15479 /// Check if two fields are layout-compatible. 15480 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 15481 FieldDecl *Field2) { 15482 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 15483 return false; 15484 15485 if (Field1->isBitField() != Field2->isBitField()) 15486 return false; 15487 15488 if (Field1->isBitField()) { 15489 // Make sure that the bit-fields are the same length. 15490 unsigned Bits1 = Field1->getBitWidthValue(C); 15491 unsigned Bits2 = Field2->getBitWidthValue(C); 15492 15493 if (Bits1 != Bits2) 15494 return false; 15495 } 15496 15497 return true; 15498 } 15499 15500 /// Check if two standard-layout structs are layout-compatible. 15501 /// (C++11 [class.mem] p17) 15502 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 15503 RecordDecl *RD2) { 15504 // If both records are C++ classes, check that base classes match. 15505 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 15506 // If one of records is a CXXRecordDecl we are in C++ mode, 15507 // thus the other one is a CXXRecordDecl, too. 15508 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 15509 // Check number of base classes. 15510 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 15511 return false; 15512 15513 // Check the base classes. 15514 for (CXXRecordDecl::base_class_const_iterator 15515 Base1 = D1CXX->bases_begin(), 15516 BaseEnd1 = D1CXX->bases_end(), 15517 Base2 = D2CXX->bases_begin(); 15518 Base1 != BaseEnd1; 15519 ++Base1, ++Base2) { 15520 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 15521 return false; 15522 } 15523 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 15524 // If only RD2 is a C++ class, it should have zero base classes. 15525 if (D2CXX->getNumBases() > 0) 15526 return false; 15527 } 15528 15529 // Check the fields. 15530 RecordDecl::field_iterator Field2 = RD2->field_begin(), 15531 Field2End = RD2->field_end(), 15532 Field1 = RD1->field_begin(), 15533 Field1End = RD1->field_end(); 15534 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 15535 if (!isLayoutCompatible(C, *Field1, *Field2)) 15536 return false; 15537 } 15538 if (Field1 != Field1End || Field2 != Field2End) 15539 return false; 15540 15541 return true; 15542 } 15543 15544 /// Check if two standard-layout unions are layout-compatible. 15545 /// (C++11 [class.mem] p18) 15546 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 15547 RecordDecl *RD2) { 15548 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 15549 for (auto *Field2 : RD2->fields()) 15550 UnmatchedFields.insert(Field2); 15551 15552 for (auto *Field1 : RD1->fields()) { 15553 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 15554 I = UnmatchedFields.begin(), 15555 E = UnmatchedFields.end(); 15556 15557 for ( ; I != E; ++I) { 15558 if (isLayoutCompatible(C, Field1, *I)) { 15559 bool Result = UnmatchedFields.erase(*I); 15560 (void) Result; 15561 assert(Result); 15562 break; 15563 } 15564 } 15565 if (I == E) 15566 return false; 15567 } 15568 15569 return UnmatchedFields.empty(); 15570 } 15571 15572 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 15573 RecordDecl *RD2) { 15574 if (RD1->isUnion() != RD2->isUnion()) 15575 return false; 15576 15577 if (RD1->isUnion()) 15578 return isLayoutCompatibleUnion(C, RD1, RD2); 15579 else 15580 return isLayoutCompatibleStruct(C, RD1, RD2); 15581 } 15582 15583 /// Check if two types are layout-compatible in C++11 sense. 15584 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 15585 if (T1.isNull() || T2.isNull()) 15586 return false; 15587 15588 // C++11 [basic.types] p11: 15589 // If two types T1 and T2 are the same type, then T1 and T2 are 15590 // layout-compatible types. 15591 if (C.hasSameType(T1, T2)) 15592 return true; 15593 15594 T1 = T1.getCanonicalType().getUnqualifiedType(); 15595 T2 = T2.getCanonicalType().getUnqualifiedType(); 15596 15597 const Type::TypeClass TC1 = T1->getTypeClass(); 15598 const Type::TypeClass TC2 = T2->getTypeClass(); 15599 15600 if (TC1 != TC2) 15601 return false; 15602 15603 if (TC1 == Type::Enum) { 15604 return isLayoutCompatible(C, 15605 cast<EnumType>(T1)->getDecl(), 15606 cast<EnumType>(T2)->getDecl()); 15607 } else if (TC1 == Type::Record) { 15608 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 15609 return false; 15610 15611 return isLayoutCompatible(C, 15612 cast<RecordType>(T1)->getDecl(), 15613 cast<RecordType>(T2)->getDecl()); 15614 } 15615 15616 return false; 15617 } 15618 15619 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 15620 15621 /// Given a type tag expression find the type tag itself. 15622 /// 15623 /// \param TypeExpr Type tag expression, as it appears in user's code. 15624 /// 15625 /// \param VD Declaration of an identifier that appears in a type tag. 15626 /// 15627 /// \param MagicValue Type tag magic value. 15628 /// 15629 /// \param isConstantEvaluated wether the evalaution should be performed in 15630 15631 /// constant context. 15632 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 15633 const ValueDecl **VD, uint64_t *MagicValue, 15634 bool isConstantEvaluated) { 15635 while(true) { 15636 if (!TypeExpr) 15637 return false; 15638 15639 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 15640 15641 switch (TypeExpr->getStmtClass()) { 15642 case Stmt::UnaryOperatorClass: { 15643 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 15644 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 15645 TypeExpr = UO->getSubExpr(); 15646 continue; 15647 } 15648 return false; 15649 } 15650 15651 case Stmt::DeclRefExprClass: { 15652 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15653 *VD = DRE->getDecl(); 15654 return true; 15655 } 15656 15657 case Stmt::IntegerLiteralClass: { 15658 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15659 llvm::APInt MagicValueAPInt = IL->getValue(); 15660 if (MagicValueAPInt.getActiveBits() <= 64) { 15661 *MagicValue = MagicValueAPInt.getZExtValue(); 15662 return true; 15663 } else 15664 return false; 15665 } 15666 15667 case Stmt::BinaryConditionalOperatorClass: 15668 case Stmt::ConditionalOperatorClass: { 15669 const AbstractConditionalOperator *ACO = 15670 cast<AbstractConditionalOperator>(TypeExpr); 15671 bool Result; 15672 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15673 isConstantEvaluated)) { 15674 if (Result) 15675 TypeExpr = ACO->getTrueExpr(); 15676 else 15677 TypeExpr = ACO->getFalseExpr(); 15678 continue; 15679 } 15680 return false; 15681 } 15682 15683 case Stmt::BinaryOperatorClass: { 15684 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15685 if (BO->getOpcode() == BO_Comma) { 15686 TypeExpr = BO->getRHS(); 15687 continue; 15688 } 15689 return false; 15690 } 15691 15692 default: 15693 return false; 15694 } 15695 } 15696 } 15697 15698 /// Retrieve the C type corresponding to type tag TypeExpr. 15699 /// 15700 /// \param TypeExpr Expression that specifies a type tag. 15701 /// 15702 /// \param MagicValues Registered magic values. 15703 /// 15704 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15705 /// kind. 15706 /// 15707 /// \param TypeInfo Information about the corresponding C type. 15708 /// 15709 /// \param isConstantEvaluated wether the evalaution should be performed in 15710 /// constant context. 15711 /// 15712 /// \returns true if the corresponding C type was found. 15713 static bool GetMatchingCType( 15714 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15715 const ASTContext &Ctx, 15716 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15717 *MagicValues, 15718 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15719 bool isConstantEvaluated) { 15720 FoundWrongKind = false; 15721 15722 // Variable declaration that has type_tag_for_datatype attribute. 15723 const ValueDecl *VD = nullptr; 15724 15725 uint64_t MagicValue; 15726 15727 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15728 return false; 15729 15730 if (VD) { 15731 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15732 if (I->getArgumentKind() != ArgumentKind) { 15733 FoundWrongKind = true; 15734 return false; 15735 } 15736 TypeInfo.Type = I->getMatchingCType(); 15737 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15738 TypeInfo.MustBeNull = I->getMustBeNull(); 15739 return true; 15740 } 15741 return false; 15742 } 15743 15744 if (!MagicValues) 15745 return false; 15746 15747 llvm::DenseMap<Sema::TypeTagMagicValue, 15748 Sema::TypeTagData>::const_iterator I = 15749 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15750 if (I == MagicValues->end()) 15751 return false; 15752 15753 TypeInfo = I->second; 15754 return true; 15755 } 15756 15757 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15758 uint64_t MagicValue, QualType Type, 15759 bool LayoutCompatible, 15760 bool MustBeNull) { 15761 if (!TypeTagForDatatypeMagicValues) 15762 TypeTagForDatatypeMagicValues.reset( 15763 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15764 15765 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15766 (*TypeTagForDatatypeMagicValues)[Magic] = 15767 TypeTagData(Type, LayoutCompatible, MustBeNull); 15768 } 15769 15770 static bool IsSameCharType(QualType T1, QualType T2) { 15771 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15772 if (!BT1) 15773 return false; 15774 15775 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15776 if (!BT2) 15777 return false; 15778 15779 BuiltinType::Kind T1Kind = BT1->getKind(); 15780 BuiltinType::Kind T2Kind = BT2->getKind(); 15781 15782 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15783 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15784 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15785 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15786 } 15787 15788 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15789 const ArrayRef<const Expr *> ExprArgs, 15790 SourceLocation CallSiteLoc) { 15791 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15792 bool IsPointerAttr = Attr->getIsPointer(); 15793 15794 // Retrieve the argument representing the 'type_tag'. 15795 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15796 if (TypeTagIdxAST >= ExprArgs.size()) { 15797 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15798 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15799 return; 15800 } 15801 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15802 bool FoundWrongKind; 15803 TypeTagData TypeInfo; 15804 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15805 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15806 TypeInfo, isConstantEvaluated())) { 15807 if (FoundWrongKind) 15808 Diag(TypeTagExpr->getExprLoc(), 15809 diag::warn_type_tag_for_datatype_wrong_kind) 15810 << TypeTagExpr->getSourceRange(); 15811 return; 15812 } 15813 15814 // Retrieve the argument representing the 'arg_idx'. 15815 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15816 if (ArgumentIdxAST >= ExprArgs.size()) { 15817 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15818 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15819 return; 15820 } 15821 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15822 if (IsPointerAttr) { 15823 // Skip implicit cast of pointer to `void *' (as a function argument). 15824 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15825 if (ICE->getType()->isVoidPointerType() && 15826 ICE->getCastKind() == CK_BitCast) 15827 ArgumentExpr = ICE->getSubExpr(); 15828 } 15829 QualType ArgumentType = ArgumentExpr->getType(); 15830 15831 // Passing a `void*' pointer shouldn't trigger a warning. 15832 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15833 return; 15834 15835 if (TypeInfo.MustBeNull) { 15836 // Type tag with matching void type requires a null pointer. 15837 if (!ArgumentExpr->isNullPointerConstant(Context, 15838 Expr::NPC_ValueDependentIsNotNull)) { 15839 Diag(ArgumentExpr->getExprLoc(), 15840 diag::warn_type_safety_null_pointer_required) 15841 << ArgumentKind->getName() 15842 << ArgumentExpr->getSourceRange() 15843 << TypeTagExpr->getSourceRange(); 15844 } 15845 return; 15846 } 15847 15848 QualType RequiredType = TypeInfo.Type; 15849 if (IsPointerAttr) 15850 RequiredType = Context.getPointerType(RequiredType); 15851 15852 bool mismatch = false; 15853 if (!TypeInfo.LayoutCompatible) { 15854 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15855 15856 // C++11 [basic.fundamental] p1: 15857 // Plain char, signed char, and unsigned char are three distinct types. 15858 // 15859 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15860 // char' depending on the current char signedness mode. 15861 if (mismatch) 15862 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15863 RequiredType->getPointeeType())) || 15864 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15865 mismatch = false; 15866 } else 15867 if (IsPointerAttr) 15868 mismatch = !isLayoutCompatible(Context, 15869 ArgumentType->getPointeeType(), 15870 RequiredType->getPointeeType()); 15871 else 15872 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15873 15874 if (mismatch) 15875 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15876 << ArgumentType << ArgumentKind 15877 << TypeInfo.LayoutCompatible << RequiredType 15878 << ArgumentExpr->getSourceRange() 15879 << TypeTagExpr->getSourceRange(); 15880 } 15881 15882 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15883 CharUnits Alignment) { 15884 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15885 } 15886 15887 void Sema::DiagnoseMisalignedMembers() { 15888 for (MisalignedMember &m : MisalignedMembers) { 15889 const NamedDecl *ND = m.RD; 15890 if (ND->getName().empty()) { 15891 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15892 ND = TD; 15893 } 15894 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15895 << m.MD << ND << m.E->getSourceRange(); 15896 } 15897 MisalignedMembers.clear(); 15898 } 15899 15900 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15901 E = E->IgnoreParens(); 15902 if (!T->isPointerType() && !T->isIntegerType()) 15903 return; 15904 if (isa<UnaryOperator>(E) && 15905 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15906 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15907 if (isa<MemberExpr>(Op)) { 15908 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15909 if (MA != MisalignedMembers.end() && 15910 (T->isIntegerType() || 15911 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15912 Context.getTypeAlignInChars( 15913 T->getPointeeType()) <= MA->Alignment)))) 15914 MisalignedMembers.erase(MA); 15915 } 15916 } 15917 } 15918 15919 void Sema::RefersToMemberWithReducedAlignment( 15920 Expr *E, 15921 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15922 Action) { 15923 const auto *ME = dyn_cast<MemberExpr>(E); 15924 if (!ME) 15925 return; 15926 15927 // No need to check expressions with an __unaligned-qualified type. 15928 if (E->getType().getQualifiers().hasUnaligned()) 15929 return; 15930 15931 // For a chain of MemberExpr like "a.b.c.d" this list 15932 // will keep FieldDecl's like [d, c, b]. 15933 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15934 const MemberExpr *TopME = nullptr; 15935 bool AnyIsPacked = false; 15936 do { 15937 QualType BaseType = ME->getBase()->getType(); 15938 if (BaseType->isDependentType()) 15939 return; 15940 if (ME->isArrow()) 15941 BaseType = BaseType->getPointeeType(); 15942 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15943 if (RD->isInvalidDecl()) 15944 return; 15945 15946 ValueDecl *MD = ME->getMemberDecl(); 15947 auto *FD = dyn_cast<FieldDecl>(MD); 15948 // We do not care about non-data members. 15949 if (!FD || FD->isInvalidDecl()) 15950 return; 15951 15952 AnyIsPacked = 15953 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15954 ReverseMemberChain.push_back(FD); 15955 15956 TopME = ME; 15957 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15958 } while (ME); 15959 assert(TopME && "We did not compute a topmost MemberExpr!"); 15960 15961 // Not the scope of this diagnostic. 15962 if (!AnyIsPacked) 15963 return; 15964 15965 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15966 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15967 // TODO: The innermost base of the member expression may be too complicated. 15968 // For now, just disregard these cases. This is left for future 15969 // improvement. 15970 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15971 return; 15972 15973 // Alignment expected by the whole expression. 15974 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15975 15976 // No need to do anything else with this case. 15977 if (ExpectedAlignment.isOne()) 15978 return; 15979 15980 // Synthesize offset of the whole access. 15981 CharUnits Offset; 15982 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15983 I++) { 15984 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15985 } 15986 15987 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15988 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15989 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15990 15991 // The base expression of the innermost MemberExpr may give 15992 // stronger guarantees than the class containing the member. 15993 if (DRE && !TopME->isArrow()) { 15994 const ValueDecl *VD = DRE->getDecl(); 15995 if (!VD->getType()->isReferenceType()) 15996 CompleteObjectAlignment = 15997 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15998 } 15999 16000 // Check if the synthesized offset fulfills the alignment. 16001 if (Offset % ExpectedAlignment != 0 || 16002 // It may fulfill the offset it but the effective alignment may still be 16003 // lower than the expected expression alignment. 16004 CompleteObjectAlignment < ExpectedAlignment) { 16005 // If this happens, we want to determine a sensible culprit of this. 16006 // Intuitively, watching the chain of member expressions from right to 16007 // left, we start with the required alignment (as required by the field 16008 // type) but some packed attribute in that chain has reduced the alignment. 16009 // It may happen that another packed structure increases it again. But if 16010 // we are here such increase has not been enough. So pointing the first 16011 // FieldDecl that either is packed or else its RecordDecl is, 16012 // seems reasonable. 16013 FieldDecl *FD = nullptr; 16014 CharUnits Alignment; 16015 for (FieldDecl *FDI : ReverseMemberChain) { 16016 if (FDI->hasAttr<PackedAttr>() || 16017 FDI->getParent()->hasAttr<PackedAttr>()) { 16018 FD = FDI; 16019 Alignment = std::min( 16020 Context.getTypeAlignInChars(FD->getType()), 16021 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16022 break; 16023 } 16024 } 16025 assert(FD && "We did not find a packed FieldDecl!"); 16026 Action(E, FD->getParent(), FD, Alignment); 16027 } 16028 } 16029 16030 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16031 using namespace std::placeholders; 16032 16033 RefersToMemberWithReducedAlignment( 16034 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16035 _2, _3, _4)); 16036 } 16037 16038 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16039 ExprResult CallResult) { 16040 if (checkArgCount(*this, TheCall, 1)) 16041 return ExprError(); 16042 16043 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16044 if (MatrixArg.isInvalid()) 16045 return MatrixArg; 16046 Expr *Matrix = MatrixArg.get(); 16047 16048 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16049 if (!MType) { 16050 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 16051 return ExprError(); 16052 } 16053 16054 // Create returned matrix type by swapping rows and columns of the argument 16055 // matrix type. 16056 QualType ResultType = Context.getConstantMatrixType( 16057 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16058 16059 // Change the return type to the type of the returned matrix. 16060 TheCall->setType(ResultType); 16061 16062 // Update call argument to use the possibly converted matrix argument. 16063 TheCall->setArg(0, Matrix); 16064 return CallResult; 16065 } 16066 16067 // Get and verify the matrix dimensions. 16068 static llvm::Optional<unsigned> 16069 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16070 SourceLocation ErrorPos; 16071 Optional<llvm::APSInt> Value = 16072 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16073 if (!Value) { 16074 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16075 << Name; 16076 return {}; 16077 } 16078 uint64_t Dim = Value->getZExtValue(); 16079 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16080 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16081 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16082 return {}; 16083 } 16084 return Dim; 16085 } 16086 16087 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16088 ExprResult CallResult) { 16089 if (!getLangOpts().MatrixTypes) { 16090 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16091 return ExprError(); 16092 } 16093 16094 if (checkArgCount(*this, TheCall, 4)) 16095 return ExprError(); 16096 16097 unsigned PtrArgIdx = 0; 16098 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16099 Expr *RowsExpr = TheCall->getArg(1); 16100 Expr *ColumnsExpr = TheCall->getArg(2); 16101 Expr *StrideExpr = TheCall->getArg(3); 16102 16103 bool ArgError = false; 16104 16105 // Check pointer argument. 16106 { 16107 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16108 if (PtrConv.isInvalid()) 16109 return PtrConv; 16110 PtrExpr = PtrConv.get(); 16111 TheCall->setArg(0, PtrExpr); 16112 if (PtrExpr->isTypeDependent()) { 16113 TheCall->setType(Context.DependentTy); 16114 return TheCall; 16115 } 16116 } 16117 16118 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16119 QualType ElementTy; 16120 if (!PtrTy) { 16121 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16122 << PtrArgIdx + 1; 16123 ArgError = true; 16124 } else { 16125 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16126 16127 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16128 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16129 << PtrArgIdx + 1; 16130 ArgError = true; 16131 } 16132 } 16133 16134 // Apply default Lvalue conversions and convert the expression to size_t. 16135 auto ApplyArgumentConversions = [this](Expr *E) { 16136 ExprResult Conv = DefaultLvalueConversion(E); 16137 if (Conv.isInvalid()) 16138 return Conv; 16139 16140 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16141 }; 16142 16143 // Apply conversion to row and column expressions. 16144 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16145 if (!RowsConv.isInvalid()) { 16146 RowsExpr = RowsConv.get(); 16147 TheCall->setArg(1, RowsExpr); 16148 } else 16149 RowsExpr = nullptr; 16150 16151 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16152 if (!ColumnsConv.isInvalid()) { 16153 ColumnsExpr = ColumnsConv.get(); 16154 TheCall->setArg(2, ColumnsExpr); 16155 } else 16156 ColumnsExpr = nullptr; 16157 16158 // If any any part of the result matrix type is still pending, just use 16159 // Context.DependentTy, until all parts are resolved. 16160 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16161 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16162 TheCall->setType(Context.DependentTy); 16163 return CallResult; 16164 } 16165 16166 // Check row and column dimenions. 16167 llvm::Optional<unsigned> MaybeRows; 16168 if (RowsExpr) 16169 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16170 16171 llvm::Optional<unsigned> MaybeColumns; 16172 if (ColumnsExpr) 16173 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16174 16175 // Check stride argument. 16176 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16177 if (StrideConv.isInvalid()) 16178 return ExprError(); 16179 StrideExpr = StrideConv.get(); 16180 TheCall->setArg(3, StrideExpr); 16181 16182 if (MaybeRows) { 16183 if (Optional<llvm::APSInt> Value = 16184 StrideExpr->getIntegerConstantExpr(Context)) { 16185 uint64_t Stride = Value->getZExtValue(); 16186 if (Stride < *MaybeRows) { 16187 Diag(StrideExpr->getBeginLoc(), 16188 diag::err_builtin_matrix_stride_too_small); 16189 ArgError = true; 16190 } 16191 } 16192 } 16193 16194 if (ArgError || !MaybeRows || !MaybeColumns) 16195 return ExprError(); 16196 16197 TheCall->setType( 16198 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16199 return CallResult; 16200 } 16201 16202 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16203 ExprResult CallResult) { 16204 if (checkArgCount(*this, TheCall, 3)) 16205 return ExprError(); 16206 16207 unsigned PtrArgIdx = 1; 16208 Expr *MatrixExpr = TheCall->getArg(0); 16209 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16210 Expr *StrideExpr = TheCall->getArg(2); 16211 16212 bool ArgError = false; 16213 16214 { 16215 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16216 if (MatrixConv.isInvalid()) 16217 return MatrixConv; 16218 MatrixExpr = MatrixConv.get(); 16219 TheCall->setArg(0, MatrixExpr); 16220 } 16221 if (MatrixExpr->isTypeDependent()) { 16222 TheCall->setType(Context.DependentTy); 16223 return TheCall; 16224 } 16225 16226 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16227 if (!MatrixTy) { 16228 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16229 ArgError = true; 16230 } 16231 16232 { 16233 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16234 if (PtrConv.isInvalid()) 16235 return PtrConv; 16236 PtrExpr = PtrConv.get(); 16237 TheCall->setArg(1, PtrExpr); 16238 if (PtrExpr->isTypeDependent()) { 16239 TheCall->setType(Context.DependentTy); 16240 return TheCall; 16241 } 16242 } 16243 16244 // Check pointer argument. 16245 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16246 if (!PtrTy) { 16247 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16248 << PtrArgIdx + 1; 16249 ArgError = true; 16250 } else { 16251 QualType ElementTy = PtrTy->getPointeeType(); 16252 if (ElementTy.isConstQualified()) { 16253 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16254 ArgError = true; 16255 } 16256 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16257 if (MatrixTy && 16258 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16259 Diag(PtrExpr->getBeginLoc(), 16260 diag::err_builtin_matrix_pointer_arg_mismatch) 16261 << ElementTy << MatrixTy->getElementType(); 16262 ArgError = true; 16263 } 16264 } 16265 16266 // Apply default Lvalue conversions and convert the stride expression to 16267 // size_t. 16268 { 16269 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16270 if (StrideConv.isInvalid()) 16271 return StrideConv; 16272 16273 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16274 if (StrideConv.isInvalid()) 16275 return StrideConv; 16276 StrideExpr = StrideConv.get(); 16277 TheCall->setArg(2, StrideExpr); 16278 } 16279 16280 // Check stride argument. 16281 if (MatrixTy) { 16282 if (Optional<llvm::APSInt> Value = 16283 StrideExpr->getIntegerConstantExpr(Context)) { 16284 uint64_t Stride = Value->getZExtValue(); 16285 if (Stride < MatrixTy->getNumRows()) { 16286 Diag(StrideExpr->getBeginLoc(), 16287 diag::err_builtin_matrix_stride_too_small); 16288 ArgError = true; 16289 } 16290 } 16291 } 16292 16293 if (ArgError) 16294 return ExprError(); 16295 16296 return CallResult; 16297 } 16298 16299 /// \brief Enforce the bounds of a TCB 16300 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16301 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16302 /// and enforce_tcb_leaf attributes. 16303 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16304 const FunctionDecl *Callee) { 16305 const FunctionDecl *Caller = getCurFunctionDecl(); 16306 16307 // Calls to builtins are not enforced. 16308 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16309 Callee->getBuiltinID() != 0) 16310 return; 16311 16312 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16313 // all TCBs the callee is a part of. 16314 llvm::StringSet<> CalleeTCBs; 16315 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16316 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16317 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16318 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16319 16320 // Go through the TCBs the caller is a part of and emit warnings if Caller 16321 // is in a TCB that the Callee is not. 16322 for_each( 16323 Caller->specific_attrs<EnforceTCBAttr>(), 16324 [&](const auto *A) { 16325 StringRef CallerTCB = A->getTCBName(); 16326 if (CalleeTCBs.count(CallerTCB) == 0) { 16327 this->Diag(TheCall->getExprLoc(), 16328 diag::warn_tcb_enforcement_violation) << Callee 16329 << CallerTCB; 16330 } 16331 }); 16332 } 16333