Path: blob/main/contrib/llvm-project/clang/lib/Sema/SemaChecking.cpp
35234 views
//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements extra semantic analysis beyond what is enforced9// by the C type system.10//11//===----------------------------------------------------------------------===//1213#include "clang/AST/APValue.h"14#include "clang/AST/ASTContext.h"15#include "clang/AST/Attr.h"16#include "clang/AST/AttrIterator.h"17#include "clang/AST/CharUnits.h"18#include "clang/AST/Decl.h"19#include "clang/AST/DeclBase.h"20#include "clang/AST/DeclCXX.h"21#include "clang/AST/DeclObjC.h"22#include "clang/AST/DeclarationName.h"23#include "clang/AST/EvaluatedExprVisitor.h"24#include "clang/AST/Expr.h"25#include "clang/AST/ExprCXX.h"26#include "clang/AST/ExprObjC.h"27#include "clang/AST/ExprOpenMP.h"28#include "clang/AST/FormatString.h"29#include "clang/AST/IgnoreExpr.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/SemaAMDGPU.h"64#include "clang/Sema/SemaARM.h"65#include "clang/Sema/SemaBPF.h"66#include "clang/Sema/SemaHLSL.h"67#include "clang/Sema/SemaHexagon.h"68#include "clang/Sema/SemaInternal.h"69#include "clang/Sema/SemaLoongArch.h"70#include "clang/Sema/SemaMIPS.h"71#include "clang/Sema/SemaNVPTX.h"72#include "clang/Sema/SemaObjC.h"73#include "clang/Sema/SemaOpenCL.h"74#include "clang/Sema/SemaPPC.h"75#include "clang/Sema/SemaRISCV.h"76#include "clang/Sema/SemaSystemZ.h"77#include "clang/Sema/SemaWasm.h"78#include "clang/Sema/SemaX86.h"79#include "llvm/ADT/APFloat.h"80#include "llvm/ADT/APInt.h"81#include "llvm/ADT/APSInt.h"82#include "llvm/ADT/ArrayRef.h"83#include "llvm/ADT/DenseMap.h"84#include "llvm/ADT/FoldingSet.h"85#include "llvm/ADT/STLExtras.h"86#include "llvm/ADT/SmallBitVector.h"87#include "llvm/ADT/SmallPtrSet.h"88#include "llvm/ADT/SmallString.h"89#include "llvm/ADT/SmallVector.h"90#include "llvm/ADT/StringExtras.h"91#include "llvm/ADT/StringRef.h"92#include "llvm/ADT/StringSet.h"93#include "llvm/ADT/StringSwitch.h"94#include "llvm/Support/AtomicOrdering.h"95#include "llvm/Support/Casting.h"96#include "llvm/Support/Compiler.h"97#include "llvm/Support/ConvertUTF.h"98#include "llvm/Support/ErrorHandling.h"99#include "llvm/Support/Format.h"100#include "llvm/Support/Locale.h"101#include "llvm/Support/MathExtras.h"102#include "llvm/Support/SaveAndRestore.h"103#include "llvm/Support/raw_ostream.h"104#include "llvm/TargetParser/RISCVTargetParser.h"105#include "llvm/TargetParser/Triple.h"106#include <algorithm>107#include <bitset>108#include <cassert>109#include <cctype>110#include <cstddef>111#include <cstdint>112#include <functional>113#include <limits>114#include <optional>115#include <string>116#include <tuple>117#include <utility>118119using namespace clang;120using namespace sema;121122SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,123unsigned ByteNo) const {124return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,125Context.getTargetInfo());126}127128static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,129Sema::FormatArgumentPassingKind B) {130return (A << 8) | B;131}132133bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {134unsigned ArgCount = Call->getNumArgs();135if (ArgCount >= MinArgCount)136return false;137138return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)139<< 0 /*function call*/ << MinArgCount << ArgCount140<< /*is non object*/ 0 << Call->getSourceRange();141}142143bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {144unsigned ArgCount = Call->getNumArgs();145if (ArgCount <= MaxArgCount)146return false;147return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)148<< 0 /*function call*/ << MaxArgCount << ArgCount149<< /*is non object*/ 0 << Call->getSourceRange();150}151152bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,153unsigned MaxArgCount) {154return checkArgCountAtLeast(Call, MinArgCount) ||155checkArgCountAtMost(Call, MaxArgCount);156}157158bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {159unsigned ArgCount = Call->getNumArgs();160if (ArgCount == DesiredArgCount)161return false;162163if (checkArgCountAtLeast(Call, DesiredArgCount))164return true;165assert(ArgCount > DesiredArgCount && "should have diagnosed this");166167// Highlight all the excess arguments.168SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),169Call->getArg(ArgCount - 1)->getEndLoc());170171return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)172<< 0 /*function call*/ << DesiredArgCount << ArgCount173<< /*is non object*/ 0 << Call->getArg(1)->getSourceRange();174}175176static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S) {177bool HasError = false;178179for (unsigned I = 0; I < Call->getNumArgs(); ++I) {180Expr *Arg = Call->getArg(I);181182if (Arg->isValueDependent())183continue;184185std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);186int DiagMsgKind = -1;187// Arguments must be pointers to constant strings and cannot use '$'.188if (!ArgString.has_value())189DiagMsgKind = 0;190else if (ArgString->find('$') != std::string::npos)191DiagMsgKind = 1;192193if (DiagMsgKind >= 0) {194S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)195<< DiagMsgKind << Arg->getSourceRange();196HasError = true;197}198}199200return !HasError;201}202203static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty) {204if (Value->isTypeDependent())205return false;206207InitializedEntity Entity =208InitializedEntity::InitializeParameter(S.Context, Ty, false);209ExprResult Result =210S.PerformCopyInitialization(Entity, SourceLocation(), Value);211if (Result.isInvalid())212return true;213Value = Result.get();214return false;215}216217/// Check that the first argument to __builtin_annotation is an integer218/// and the second argument is a non-wide string literal.219static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {220if (S.checkArgCount(TheCall, 2))221return true;222223// First argument should be an integer.224Expr *ValArg = TheCall->getArg(0);225QualType Ty = ValArg->getType();226if (!Ty->isIntegerType()) {227S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)228<< ValArg->getSourceRange();229return true;230}231232// Second argument should be a constant string.233Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();234StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);235if (!Literal || !Literal->isOrdinary()) {236S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)237<< StrArg->getSourceRange();238return true;239}240241TheCall->setType(Ty);242return false;243}244245static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {246// We need at least one argument.247if (TheCall->getNumArgs() < 1) {248S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)249<< 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0250<< TheCall->getCallee()->getSourceRange();251return true;252}253254// All arguments should be wide string literals.255for (Expr *Arg : TheCall->arguments()) {256auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());257if (!Literal || !Literal->isWide()) {258S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)259<< Arg->getSourceRange();260return true;261}262}263264return false;265}266267/// Check that the argument to __builtin_addressof is a glvalue, and set the268/// result type to the corresponding pointer type.269static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {270if (S.checkArgCount(TheCall, 1))271return true;272273ExprResult Arg(TheCall->getArg(0));274QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());275if (ResultType.isNull())276return true;277278TheCall->setArg(0, Arg.get());279TheCall->setType(ResultType);280return false;281}282283/// Check that the argument to __builtin_function_start is a function.284static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {285if (S.checkArgCount(TheCall, 1))286return true;287288ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));289if (Arg.isInvalid())290return true;291292TheCall->setArg(0, Arg.get());293const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(294Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext()));295296if (!FD) {297S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)298<< TheCall->getSourceRange();299return true;300}301302return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,303TheCall->getBeginLoc());304}305306/// Check the number of arguments and set the result type to307/// the argument type.308static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {309if (S.checkArgCount(TheCall, 1))310return true;311312TheCall->setType(TheCall->getArg(0)->getType());313return false;314}315316/// Check that the value argument for __builtin_is_aligned(value, alignment) and317/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer318/// type (but not a function pointer) and that the alignment is a power-of-two.319static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {320if (S.checkArgCount(TheCall, 2))321return true;322323clang::Expr *Source = TheCall->getArg(0);324bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;325326auto IsValidIntegerType = [](QualType Ty) {327return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();328};329QualType SrcTy = Source->getType();330// We should also be able to use it with arrays (but not functions!).331if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {332SrcTy = S.Context.getDecayedType(SrcTy);333}334if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||335SrcTy->isFunctionPointerType()) {336// FIXME: this is not quite the right error message since we don't allow337// floating point types, or member pointers.338S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)339<< SrcTy;340return true;341}342343clang::Expr *AlignOp = TheCall->getArg(1);344if (!IsValidIntegerType(AlignOp->getType())) {345S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)346<< AlignOp->getType();347return true;348}349Expr::EvalResult AlignResult;350unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;351// We can't check validity of alignment if it is value dependent.352if (!AlignOp->isValueDependent() &&353AlignOp->EvaluateAsInt(AlignResult, S.Context,354Expr::SE_AllowSideEffects)) {355llvm::APSInt AlignValue = AlignResult.Val.getInt();356llvm::APSInt MaxValue(357llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));358if (AlignValue < 1) {359S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;360return true;361}362if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {363S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)364<< toString(MaxValue, 10);365return true;366}367if (!AlignValue.isPowerOf2()) {368S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);369return true;370}371if (AlignValue == 1) {372S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)373<< IsBooleanAlignBuiltin;374}375}376377ExprResult SrcArg = S.PerformCopyInitialization(378InitializedEntity::InitializeParameter(S.Context, SrcTy, false),379SourceLocation(), Source);380if (SrcArg.isInvalid())381return true;382TheCall->setArg(0, SrcArg.get());383ExprResult AlignArg =384S.PerformCopyInitialization(InitializedEntity::InitializeParameter(385S.Context, AlignOp->getType(), false),386SourceLocation(), AlignOp);387if (AlignArg.isInvalid())388return true;389TheCall->setArg(1, AlignArg.get());390// For align_up/align_down, the return type is the same as the (potentially391// decayed) argument type including qualifiers. For is_aligned(), the result392// is always bool.393TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);394return false;395}396397static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {398if (S.checkArgCount(TheCall, 3))399return true;400401std::pair<unsigned, const char *> Builtins[] = {402{ Builtin::BI__builtin_add_overflow, "ckd_add" },403{ Builtin::BI__builtin_sub_overflow, "ckd_sub" },404{ Builtin::BI__builtin_mul_overflow, "ckd_mul" },405};406407bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,408const char *> &P) {409return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&410Lexer::getImmediateMacroName(TheCall->getExprLoc(),411S.getSourceManager(), S.getLangOpts()) == P.second;412});413414auto ValidCkdIntType = [](QualType QT) {415// A valid checked integer type is an integer type other than a plain char,416// bool, a bit-precise type, or an enumeration type.417if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())418return (BT->getKind() >= BuiltinType::Short &&419BT->getKind() <= BuiltinType::Int128) || (420BT->getKind() >= BuiltinType::UShort &&421BT->getKind() <= BuiltinType::UInt128) ||422BT->getKind() == BuiltinType::UChar ||423BT->getKind() == BuiltinType::SChar;424return false;425};426427// First two arguments should be integers.428for (unsigned I = 0; I < 2; ++I) {429ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));430if (Arg.isInvalid()) return true;431TheCall->setArg(I, Arg.get());432433QualType Ty = Arg.get()->getType();434bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();435if (!IsValid) {436S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)437<< CkdOperation << Ty << Arg.get()->getSourceRange();438return true;439}440}441442// Third argument should be a pointer to a non-const integer.443// IRGen correctly handles volatile, restrict, and address spaces, and444// the other qualifiers aren't possible.445{446ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));447if (Arg.isInvalid()) return true;448TheCall->setArg(2, Arg.get());449450QualType Ty = Arg.get()->getType();451const auto *PtrTy = Ty->getAs<PointerType>();452if (!PtrTy ||453!PtrTy->getPointeeType()->isIntegerType() ||454(!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||455PtrTy->getPointeeType().isConstQualified()) {456S.Diag(Arg.get()->getBeginLoc(),457diag::err_overflow_builtin_must_be_ptr_int)458<< CkdOperation << Ty << Arg.get()->getSourceRange();459return true;460}461}462463// Disallow signed bit-precise integer args larger than 128 bits to mul464// function until we improve backend support.465if (BuiltinID == Builtin::BI__builtin_mul_overflow) {466for (unsigned I = 0; I < 3; ++I) {467const auto Arg = TheCall->getArg(I);468// Third argument will be a pointer.469auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();470if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&471S.getASTContext().getIntWidth(Ty) > 128)472return S.Diag(Arg->getBeginLoc(),473diag::err_overflow_builtin_bit_int_max_size)474<< 128;475}476}477478return false;479}480481namespace {482struct BuiltinDumpStructGenerator {483Sema &S;484CallExpr *TheCall;485SourceLocation Loc = TheCall->getBeginLoc();486SmallVector<Expr *, 32> Actions;487DiagnosticErrorTrap ErrorTracker;488PrintingPolicy Policy;489490BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)491: S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),492Policy(S.Context.getPrintingPolicy()) {493Policy.AnonymousTagLocations = false;494}495496Expr *makeOpaqueValueExpr(Expr *Inner) {497auto *OVE = new (S.Context)498OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),499Inner->getObjectKind(), Inner);500Actions.push_back(OVE);501return OVE;502}503504Expr *getStringLiteral(llvm::StringRef Str) {505Expr *Lit = S.Context.getPredefinedStringLiteralFromCache(Str);506// Wrap the literal in parentheses to attach a source location.507return new (S.Context) ParenExpr(Loc, Loc, Lit);508}509510bool callPrintFunction(llvm::StringRef Format,511llvm::ArrayRef<Expr *> Exprs = {}) {512SmallVector<Expr *, 8> Args;513assert(TheCall->getNumArgs() >= 2);514Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());515Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());516Args.push_back(getStringLiteral(Format));517Args.insert(Args.end(), Exprs.begin(), Exprs.end());518519// Register a note to explain why we're performing the call.520Sema::CodeSynthesisContext Ctx;521Ctx.Kind = Sema::CodeSynthesisContext::BuildingBuiltinDumpStructCall;522Ctx.PointOfInstantiation = Loc;523Ctx.CallArgs = Args.data();524Ctx.NumCallArgs = Args.size();525S.pushCodeSynthesisContext(Ctx);526527ExprResult RealCall =528S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),529TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());530531S.popCodeSynthesisContext();532if (!RealCall.isInvalid())533Actions.push_back(RealCall.get());534// Bail out if we've hit any errors, even if we managed to build the535// call. We don't want to produce more than one error.536return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();537}538539Expr *getIndentString(unsigned Depth) {540if (!Depth)541return nullptr;542543llvm::SmallString<32> Indent;544Indent.resize(Depth * Policy.Indentation, ' ');545return getStringLiteral(Indent);546}547548Expr *getTypeString(QualType T) {549return getStringLiteral(T.getAsString(Policy));550}551552bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {553llvm::raw_svector_ostream OS(Str);554555// Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather556// than trying to print a single character.557if (auto *BT = T->getAs<BuiltinType>()) {558switch (BT->getKind()) {559case BuiltinType::Bool:560OS << "%d";561return true;562case BuiltinType::Char_U:563case BuiltinType::UChar:564OS << "%hhu";565return true;566case BuiltinType::Char_S:567case BuiltinType::SChar:568OS << "%hhd";569return true;570default:571break;572}573}574575analyze_printf::PrintfSpecifier Specifier;576if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {577// We were able to guess how to format this.578if (Specifier.getConversionSpecifier().getKind() ==579analyze_printf::PrintfConversionSpecifier::sArg) {580// Wrap double-quotes around a '%s' specifier and limit its maximum581// length. Ideally we'd also somehow escape special characters in the582// contents but printf doesn't support that.583// FIXME: '%s' formatting is not safe in general.584OS << '"';585Specifier.setPrecision(analyze_printf::OptionalAmount(32u));586Specifier.toString(OS);587OS << '"';588// FIXME: It would be nice to include a '...' if the string doesn't fit589// in the length limit.590} else {591Specifier.toString(OS);592}593return true;594}595596if (T->isPointerType()) {597// Format all pointers with '%p'.598OS << "%p";599return true;600}601602return false;603}604605bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {606Expr *IndentLit = getIndentString(Depth);607Expr *TypeLit = getTypeString(S.Context.getRecordType(RD));608if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})609: callPrintFunction("%s", {TypeLit}))610return true;611612return dumpRecordValue(RD, E, IndentLit, Depth);613}614615// Dump a record value. E should be a pointer or lvalue referring to an RD.616bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,617unsigned Depth) {618// FIXME: Decide what to do if RD is a union. At least we should probably619// turn off printing `const char*` members with `%s`, because that is very620// likely to crash if that's not the active member. Whatever we decide, we621// should document it.622623// Build an OpaqueValueExpr so we can refer to E more than once without624// triggering re-evaluation.625Expr *RecordArg = makeOpaqueValueExpr(E);626bool RecordArgIsPtr = RecordArg->getType()->isPointerType();627628if (callPrintFunction(" {\n"))629return true;630631// Dump each base class, regardless of whether they're aggregates.632if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {633for (const auto &Base : CXXRD->bases()) {634QualType BaseType =635RecordArgIsPtr ? S.Context.getPointerType(Base.getType())636: S.Context.getLValueReferenceType(Base.getType());637ExprResult BasePtr = S.BuildCStyleCastExpr(638Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,639RecordArg);640if (BasePtr.isInvalid() ||641dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),642Depth + 1))643return true;644}645}646647Expr *FieldIndentArg = getIndentString(Depth + 1);648649// Dump each field.650for (auto *D : RD->decls()) {651auto *IFD = dyn_cast<IndirectFieldDecl>(D);652auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);653if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())654continue;655656llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");657llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,658getTypeString(FD->getType()),659getStringLiteral(FD->getName())};660661if (FD->isBitField()) {662Format += ": %zu ";663QualType SizeT = S.Context.getSizeType();664llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),665FD->getBitWidthValue(S.Context));666Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));667}668669Format += "=";670671ExprResult Field =672IFD ? S.BuildAnonymousStructUnionMemberReference(673CXXScopeSpec(), Loc, IFD,674DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)675: S.BuildFieldReferenceExpr(676RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,677DeclAccessPair::make(FD, AS_public),678DeclarationNameInfo(FD->getDeclName(), Loc));679if (Field.isInvalid())680return true;681682auto *InnerRD = FD->getType()->getAsRecordDecl();683auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);684if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {685// Recursively print the values of members of aggregate record type.686if (callPrintFunction(Format, Args) ||687dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))688return true;689} else {690Format += " ";691if (appendFormatSpecifier(FD->getType(), Format)) {692// We know how to print this field.693Args.push_back(Field.get());694} else {695// We don't know how to print this field. Print out its address696// with a format specifier that a smart tool will be able to697// recognize and treat specially.698Format += "*%p";699ExprResult FieldAddr =700S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());701if (FieldAddr.isInvalid())702return true;703Args.push_back(FieldAddr.get());704}705Format += "\n";706if (callPrintFunction(Format, Args))707return true;708}709}710711return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)712: callPrintFunction("}\n");713}714715Expr *buildWrapper() {716auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,717PseudoObjectExpr::NoResult);718TheCall->setType(Wrapper->getType());719TheCall->setValueKind(Wrapper->getValueKind());720return Wrapper;721}722};723} // namespace724725static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall) {726if (S.checkArgCountAtLeast(TheCall, 2))727return ExprError();728729ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));730if (PtrArgResult.isInvalid())731return ExprError();732TheCall->setArg(0, PtrArgResult.get());733734// First argument should be a pointer to a struct.735QualType PtrArgType = PtrArgResult.get()->getType();736if (!PtrArgType->isPointerType() ||737!PtrArgType->getPointeeType()->isRecordType()) {738S.Diag(PtrArgResult.get()->getBeginLoc(),739diag::err_expected_struct_pointer_argument)740<< 1 << TheCall->getDirectCallee() << PtrArgType;741return ExprError();742}743QualType Pointee = PtrArgType->getPointeeType();744const RecordDecl *RD = Pointee->getAsRecordDecl();745// Try to instantiate the class template as appropriate; otherwise, access to746// its data() may lead to a crash.747if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,748diag::err_incomplete_type))749return ExprError();750// Second argument is a callable, but we can't fully validate it until we try751// calling it.752QualType FnArgType = TheCall->getArg(1)->getType();753if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&754!FnArgType->isBlockPointerType() &&755!(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {756auto *BT = FnArgType->getAs<BuiltinType>();757switch (BT ? BT->getKind() : BuiltinType::Void) {758case BuiltinType::Dependent:759case BuiltinType::Overload:760case BuiltinType::BoundMember:761case BuiltinType::PseudoObject:762case BuiltinType::UnknownAny:763case BuiltinType::BuiltinFn:764// This might be a callable.765break;766767default:768S.Diag(TheCall->getArg(1)->getBeginLoc(),769diag::err_expected_callable_argument)770<< 2 << TheCall->getDirectCallee() << FnArgType;771return ExprError();772}773}774775BuiltinDumpStructGenerator Generator(S, TheCall);776777// Wrap parentheses around the given pointer. This is not necessary for778// correct code generation, but it means that when we pretty-print the call779// arguments in our diagnostics we will produce '(&s)->n' instead of the780// incorrect '&s->n'.781Expr *PtrArg = PtrArgResult.get();782PtrArg = new (S.Context)783ParenExpr(PtrArg->getBeginLoc(),784S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);785if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))786return ExprError();787788return Generator.buildWrapper();789}790791static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {792if (S.checkArgCount(BuiltinCall, 2))793return true;794795SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();796Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();797Expr *Call = BuiltinCall->getArg(0);798Expr *Chain = BuiltinCall->getArg(1);799800if (Call->getStmtClass() != Stmt::CallExprClass) {801S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)802<< Call->getSourceRange();803return true;804}805806auto CE = cast<CallExpr>(Call);807if (CE->getCallee()->getType()->isBlockPointerType()) {808S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)809<< Call->getSourceRange();810return true;811}812813const Decl *TargetDecl = CE->getCalleeDecl();814if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))815if (FD->getBuiltinID()) {816S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)817<< Call->getSourceRange();818return true;819}820821if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {822S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)823<< Call->getSourceRange();824return true;825}826827ExprResult ChainResult = S.UsualUnaryConversions(Chain);828if (ChainResult.isInvalid())829return true;830if (!ChainResult.get()->getType()->isPointerType()) {831S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)832<< Chain->getSourceRange();833return true;834}835836QualType ReturnTy = CE->getCallReturnType(S.Context);837QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };838QualType BuiltinTy = S.Context.getFunctionType(839ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());840QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);841842Builtin =843S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();844845BuiltinCall->setType(CE->getType());846BuiltinCall->setValueKind(CE->getValueKind());847BuiltinCall->setObjectKind(CE->getObjectKind());848BuiltinCall->setCallee(Builtin);849BuiltinCall->setArg(1, ChainResult.get());850851return false;852}853854namespace {855856class ScanfDiagnosticFormatHandler857: public analyze_format_string::FormatStringHandler {858// Accepts the argument index (relative to the first destination index) of the859// argument whose size we want.860using ComputeSizeFunction =861llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;862863// Accepts the argument index (relative to the first destination index), the864// destination size, and the source size).865using DiagnoseFunction =866llvm::function_ref<void(unsigned, unsigned, unsigned)>;867868ComputeSizeFunction ComputeSizeArgument;869DiagnoseFunction Diagnose;870871public:872ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,873DiagnoseFunction Diagnose)874: ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}875876bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,877const char *StartSpecifier,878unsigned specifierLen) override {879if (!FS.consumesDataArgument())880return true;881882unsigned NulByte = 0;883switch ((FS.getConversionSpecifier().getKind())) {884default:885return true;886case analyze_format_string::ConversionSpecifier::sArg:887case analyze_format_string::ConversionSpecifier::ScanListArg:888NulByte = 1;889break;890case analyze_format_string::ConversionSpecifier::cArg:891break;892}893894analyze_format_string::OptionalAmount FW = FS.getFieldWidth();895if (FW.getHowSpecified() !=896analyze_format_string::OptionalAmount::HowSpecified::Constant)897return true;898899unsigned SourceSize = FW.getConstantAmount() + NulByte;900901std::optional<llvm::APSInt> DestSizeAPS =902ComputeSizeArgument(FS.getArgIndex());903if (!DestSizeAPS)904return true;905906unsigned DestSize = DestSizeAPS->getZExtValue();907908if (DestSize < SourceSize)909Diagnose(FS.getArgIndex(), DestSize, SourceSize);910911return true;912}913};914915class EstimateSizeFormatHandler916: public analyze_format_string::FormatStringHandler {917size_t Size;918/// Whether the format string contains Linux kernel's format specifier919/// extension.920bool IsKernelCompatible = true;921922public:923EstimateSizeFormatHandler(StringRef Format)924: Size(std::min(Format.find(0), Format.size()) +9251 /* null byte always written by sprintf */) {}926927bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,928const char *, unsigned SpecifierLen,929const TargetInfo &) override {930931const size_t FieldWidth = computeFieldWidth(FS);932const size_t Precision = computePrecision(FS);933934// The actual format.935switch (FS.getConversionSpecifier().getKind()) {936// Just a char.937case analyze_format_string::ConversionSpecifier::cArg:938case analyze_format_string::ConversionSpecifier::CArg:939Size += std::max(FieldWidth, (size_t)1);940break;941// Just an integer.942case analyze_format_string::ConversionSpecifier::dArg:943case analyze_format_string::ConversionSpecifier::DArg:944case analyze_format_string::ConversionSpecifier::iArg:945case analyze_format_string::ConversionSpecifier::oArg:946case analyze_format_string::ConversionSpecifier::OArg:947case analyze_format_string::ConversionSpecifier::uArg:948case analyze_format_string::ConversionSpecifier::UArg:949case analyze_format_string::ConversionSpecifier::xArg:950case analyze_format_string::ConversionSpecifier::XArg:951Size += std::max(FieldWidth, Precision);952break;953954// %g style conversion switches between %f or %e style dynamically.955// %g removes trailing zeros, and does not print decimal point if there are956// no digits that follow it. Thus %g can print a single digit.957// FIXME: If it is alternative form:958// For g and G conversions, trailing zeros are not removed from the result.959case analyze_format_string::ConversionSpecifier::gArg:960case analyze_format_string::ConversionSpecifier::GArg:961Size += 1;962break;963964// Floating point number in the form '[+]ddd.ddd'.965case analyze_format_string::ConversionSpecifier::fArg:966case analyze_format_string::ConversionSpecifier::FArg:967Size += std::max(FieldWidth, 1 /* integer part */ +968(Precision ? 1 + Precision969: 0) /* period + decimal */);970break;971972// Floating point number in the form '[-]d.ddde[+-]dd'.973case analyze_format_string::ConversionSpecifier::eArg:974case analyze_format_string::ConversionSpecifier::EArg:975Size +=976std::max(FieldWidth,9771 /* integer part */ +978(Precision ? 1 + Precision : 0) /* period + decimal */ +9791 /* e or E letter */ + 2 /* exponent */);980break;981982// Floating point number in the form '[-]0xh.hhhhp±dd'.983case analyze_format_string::ConversionSpecifier::aArg:984case analyze_format_string::ConversionSpecifier::AArg:985Size +=986std::max(FieldWidth,9872 /* 0x */ + 1 /* integer part */ +988(Precision ? 1 + Precision : 0) /* period + decimal */ +9891 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);990break;991992// Just a string.993case analyze_format_string::ConversionSpecifier::sArg:994case analyze_format_string::ConversionSpecifier::SArg:995Size += FieldWidth;996break;997998// Just a pointer in the form '0xddd'.999case analyze_format_string::ConversionSpecifier::pArg:1000// Linux kernel has its own extesion for `%p` specifier.1001// Kernel Document:1002// https://docs.kernel.org/core-api/printk-formats.html#pointer-types1003IsKernelCompatible = false;1004Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);1005break;10061007// A plain percent.1008case analyze_format_string::ConversionSpecifier::PercentArg:1009Size += 1;1010break;10111012default:1013break;1014}10151016Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();10171018if (FS.hasAlternativeForm()) {1019switch (FS.getConversionSpecifier().getKind()) {1020// For o conversion, it increases the precision, if and only if necessary,1021// to force the first digit of the result to be a zero1022// (if the value and precision are both 0, a single 0 is printed)1023case analyze_format_string::ConversionSpecifier::oArg:1024// For b conversion, a nonzero result has 0b prefixed to it.1025case analyze_format_string::ConversionSpecifier::bArg:1026// For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to1027// it.1028case analyze_format_string::ConversionSpecifier::xArg:1029case analyze_format_string::ConversionSpecifier::XArg:1030// Note: even when the prefix is added, if1031// (prefix_width <= FieldWidth - formatted_length) holds,1032// the prefix does not increase the format1033// size. e.g.(("%#3x", 0xf) is "0xf")10341035// If the result is zero, o, b, x, X adds nothing.1036break;1037// For a, A, e, E, f, F, g, and G conversions,1038// the result of converting a floating-point number always contains a1039// decimal-point1040case analyze_format_string::ConversionSpecifier::aArg:1041case analyze_format_string::ConversionSpecifier::AArg:1042case analyze_format_string::ConversionSpecifier::eArg:1043case analyze_format_string::ConversionSpecifier::EArg:1044case analyze_format_string::ConversionSpecifier::fArg:1045case analyze_format_string::ConversionSpecifier::FArg:1046case analyze_format_string::ConversionSpecifier::gArg:1047case analyze_format_string::ConversionSpecifier::GArg:1048Size += (Precision ? 0 : 1);1049break;1050// For other conversions, the behavior is undefined.1051default:1052break;1053}1054}1055assert(SpecifierLen <= Size && "no underflow");1056Size -= SpecifierLen;1057return true;1058}10591060size_t getSizeLowerBound() const { return Size; }1061bool isKernelCompatible() const { return IsKernelCompatible; }10621063private:1064static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {1065const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();1066size_t FieldWidth = 0;1067if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)1068FieldWidth = FW.getConstantAmount();1069return FieldWidth;1070}10711072static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {1073const analyze_format_string::OptionalAmount &FW = FS.getPrecision();1074size_t Precision = 0;10751076// See man 3 printf for default precision value based on the specifier.1077switch (FW.getHowSpecified()) {1078case analyze_format_string::OptionalAmount::NotSpecified:1079switch (FS.getConversionSpecifier().getKind()) {1080default:1081break;1082case analyze_format_string::ConversionSpecifier::dArg: // %d1083case analyze_format_string::ConversionSpecifier::DArg: // %D1084case analyze_format_string::ConversionSpecifier::iArg: // %i1085Precision = 1;1086break;1087case analyze_format_string::ConversionSpecifier::oArg: // %d1088case analyze_format_string::ConversionSpecifier::OArg: // %D1089case analyze_format_string::ConversionSpecifier::uArg: // %d1090case analyze_format_string::ConversionSpecifier::UArg: // %D1091case analyze_format_string::ConversionSpecifier::xArg: // %d1092case analyze_format_string::ConversionSpecifier::XArg: // %D1093Precision = 1;1094break;1095case analyze_format_string::ConversionSpecifier::fArg: // %f1096case analyze_format_string::ConversionSpecifier::FArg: // %F1097case analyze_format_string::ConversionSpecifier::eArg: // %e1098case analyze_format_string::ConversionSpecifier::EArg: // %E1099case analyze_format_string::ConversionSpecifier::gArg: // %g1100case analyze_format_string::ConversionSpecifier::GArg: // %G1101Precision = 6;1102break;1103case analyze_format_string::ConversionSpecifier::pArg: // %d1104Precision = 1;1105break;1106}1107break;1108case analyze_format_string::OptionalAmount::Constant:1109Precision = FW.getConstantAmount();1110break;1111default:1112break;1113}1114return Precision;1115}1116};11171118} // namespace11191120static bool ProcessFormatStringLiteral(const Expr *FormatExpr,1121StringRef &FormatStrRef, size_t &StrLen,1122ASTContext &Context) {1123if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);1124Format && (Format->isOrdinary() || Format->isUTF8())) {1125FormatStrRef = Format->getString();1126const ConstantArrayType *T =1127Context.getAsConstantArrayType(Format->getType());1128assert(T && "String literal not of constant array type!");1129size_t TypeSize = T->getZExtSize();1130// In case there's a null byte somewhere.1131StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));1132return true;1133}1134return false;1135}11361137void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,1138CallExpr *TheCall) {1139if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||1140isConstantEvaluatedContext())1141return;11421143bool UseDABAttr = false;1144const FunctionDecl *UseDecl = FD;11451146const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();1147if (DABAttr) {1148UseDecl = DABAttr->getFunction();1149assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");1150UseDABAttr = true;1151}11521153unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);11541155if (!BuiltinID)1156return;11571158const TargetInfo &TI = getASTContext().getTargetInfo();1159unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());11601161auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {1162// If we refer to a diagnose_as_builtin attribute, we need to change the1163// argument index to refer to the arguments of the called function. Unless1164// the index is out of bounds, which presumably means it's a variadic1165// function.1166if (!UseDABAttr)1167return Index;1168unsigned DABIndices = DABAttr->argIndices_size();1169unsigned NewIndex = Index < DABIndices1170? DABAttr->argIndices_begin()[Index]1171: Index - DABIndices + FD->getNumParams();1172if (NewIndex >= TheCall->getNumArgs())1173return std::nullopt;1174return NewIndex;1175};11761177auto ComputeExplicitObjectSizeArgument =1178[&](unsigned Index) -> std::optional<llvm::APSInt> {1179std::optional<unsigned> IndexOptional = TranslateIndex(Index);1180if (!IndexOptional)1181return std::nullopt;1182unsigned NewIndex = *IndexOptional;1183Expr::EvalResult Result;1184Expr *SizeArg = TheCall->getArg(NewIndex);1185if (!SizeArg->EvaluateAsInt(Result, getASTContext()))1186return std::nullopt;1187llvm::APSInt Integer = Result.Val.getInt();1188Integer.setIsUnsigned(true);1189return Integer;1190};11911192auto ComputeSizeArgument =1193[&](unsigned Index) -> std::optional<llvm::APSInt> {1194// If the parameter has a pass_object_size attribute, then we should use its1195// (potentially) more strict checking mode. Otherwise, conservatively assume1196// type 0.1197int BOSType = 0;1198// This check can fail for variadic functions.1199if (Index < FD->getNumParams()) {1200if (const auto *POS =1201FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())1202BOSType = POS->getType();1203}12041205std::optional<unsigned> IndexOptional = TranslateIndex(Index);1206if (!IndexOptional)1207return std::nullopt;1208unsigned NewIndex = *IndexOptional;12091210if (NewIndex >= TheCall->getNumArgs())1211return std::nullopt;12121213const Expr *ObjArg = TheCall->getArg(NewIndex);1214uint64_t Result;1215if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))1216return std::nullopt;12171218// Get the object size in the target's size_t width.1219return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);1220};12211222auto ComputeStrLenArgument =1223[&](unsigned Index) -> std::optional<llvm::APSInt> {1224std::optional<unsigned> IndexOptional = TranslateIndex(Index);1225if (!IndexOptional)1226return std::nullopt;1227unsigned NewIndex = *IndexOptional;12281229const Expr *ObjArg = TheCall->getArg(NewIndex);1230uint64_t Result;1231if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))1232return std::nullopt;1233// Add 1 for null byte.1234return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);1235};12361237std::optional<llvm::APSInt> SourceSize;1238std::optional<llvm::APSInt> DestinationSize;1239unsigned DiagID = 0;1240bool IsChkVariant = false;12411242auto GetFunctionName = [&]() {1243StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);1244// Skim off the details of whichever builtin was called to produce a better1245// diagnostic, as it's unlikely that the user wrote the __builtin1246// explicitly.1247if (IsChkVariant) {1248FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));1249FunctionName = FunctionName.drop_back(std::strlen("_chk"));1250} else {1251FunctionName.consume_front("__builtin_");1252}1253return FunctionName;1254};12551256switch (BuiltinID) {1257default:1258return;1259case Builtin::BI__builtin_strcpy:1260case Builtin::BIstrcpy: {1261DiagID = diag::warn_fortify_strlen_overflow;1262SourceSize = ComputeStrLenArgument(1);1263DestinationSize = ComputeSizeArgument(0);1264break;1265}12661267case Builtin::BI__builtin___strcpy_chk: {1268DiagID = diag::warn_fortify_strlen_overflow;1269SourceSize = ComputeStrLenArgument(1);1270DestinationSize = ComputeExplicitObjectSizeArgument(2);1271IsChkVariant = true;1272break;1273}12741275case Builtin::BIscanf:1276case Builtin::BIfscanf:1277case Builtin::BIsscanf: {1278unsigned FormatIndex = 1;1279unsigned DataIndex = 2;1280if (BuiltinID == Builtin::BIscanf) {1281FormatIndex = 0;1282DataIndex = 1;1283}12841285const auto *FormatExpr =1286TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();12871288StringRef FormatStrRef;1289size_t StrLen;1290if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))1291return;12921293auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,1294unsigned SourceSize) {1295DiagID = diag::warn_fortify_scanf_overflow;1296unsigned Index = ArgIndex + DataIndex;1297StringRef FunctionName = GetFunctionName();1298DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,1299PDiag(DiagID) << FunctionName << (Index + 1)1300<< DestSize << SourceSize);1301};13021303auto ShiftedComputeSizeArgument = [&](unsigned Index) {1304return ComputeSizeArgument(Index + DataIndex);1305};1306ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);1307const char *FormatBytes = FormatStrRef.data();1308analyze_format_string::ParseScanfString(H, FormatBytes,1309FormatBytes + StrLen, getLangOpts(),1310Context.getTargetInfo());13111312// Unlike the other cases, in this one we have already issued the diagnostic1313// here, so no need to continue (because unlike the other cases, here the1314// diagnostic refers to the argument number).1315return;1316}13171318case Builtin::BIsprintf:1319case Builtin::BI__builtin___sprintf_chk: {1320size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;1321auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();13221323StringRef FormatStrRef;1324size_t StrLen;1325if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {1326EstimateSizeFormatHandler H(FormatStrRef);1327const char *FormatBytes = FormatStrRef.data();1328if (!analyze_format_string::ParsePrintfString(1329H, FormatBytes, FormatBytes + StrLen, getLangOpts(),1330Context.getTargetInfo(), false)) {1331DiagID = H.isKernelCompatible()1332? diag::warn_format_overflow1333: diag::warn_format_overflow_non_kprintf;1334SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())1335.extOrTrunc(SizeTypeWidth);1336if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {1337DestinationSize = ComputeExplicitObjectSizeArgument(2);1338IsChkVariant = true;1339} else {1340DestinationSize = ComputeSizeArgument(0);1341}1342break;1343}1344}1345return;1346}1347case Builtin::BI__builtin___memcpy_chk:1348case Builtin::BI__builtin___memmove_chk:1349case Builtin::BI__builtin___memset_chk:1350case Builtin::BI__builtin___strlcat_chk:1351case Builtin::BI__builtin___strlcpy_chk:1352case Builtin::BI__builtin___strncat_chk:1353case Builtin::BI__builtin___strncpy_chk:1354case Builtin::BI__builtin___stpncpy_chk:1355case Builtin::BI__builtin___memccpy_chk:1356case Builtin::BI__builtin___mempcpy_chk: {1357DiagID = diag::warn_builtin_chk_overflow;1358SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);1359DestinationSize =1360ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);1361IsChkVariant = true;1362break;1363}13641365case Builtin::BI__builtin___snprintf_chk:1366case Builtin::BI__builtin___vsnprintf_chk: {1367DiagID = diag::warn_builtin_chk_overflow;1368SourceSize = ComputeExplicitObjectSizeArgument(1);1369DestinationSize = ComputeExplicitObjectSizeArgument(3);1370IsChkVariant = true;1371break;1372}13731374case Builtin::BIstrncat:1375case Builtin::BI__builtin_strncat:1376case Builtin::BIstrncpy:1377case Builtin::BI__builtin_strncpy:1378case Builtin::BIstpncpy:1379case Builtin::BI__builtin_stpncpy: {1380// Whether these functions overflow depends on the runtime strlen of the1381// string, not just the buffer size, so emitting the "always overflow"1382// diagnostic isn't quite right. We should still diagnose passing a buffer1383// size larger than the destination buffer though; this is a runtime abort1384// in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.1385DiagID = diag::warn_fortify_source_size_mismatch;1386SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);1387DestinationSize = ComputeSizeArgument(0);1388break;1389}13901391case Builtin::BImemcpy:1392case Builtin::BI__builtin_memcpy:1393case Builtin::BImemmove:1394case Builtin::BI__builtin_memmove:1395case Builtin::BImemset:1396case Builtin::BI__builtin_memset:1397case Builtin::BImempcpy:1398case Builtin::BI__builtin_mempcpy: {1399DiagID = diag::warn_fortify_source_overflow;1400SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);1401DestinationSize = ComputeSizeArgument(0);1402break;1403}1404case Builtin::BIsnprintf:1405case Builtin::BI__builtin_snprintf:1406case Builtin::BIvsnprintf:1407case Builtin::BI__builtin_vsnprintf: {1408DiagID = diag::warn_fortify_source_size_mismatch;1409SourceSize = ComputeExplicitObjectSizeArgument(1);1410const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();1411StringRef FormatStrRef;1412size_t StrLen;1413if (SourceSize &&1414ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {1415EstimateSizeFormatHandler H(FormatStrRef);1416const char *FormatBytes = FormatStrRef.data();1417if (!analyze_format_string::ParsePrintfString(1418H, FormatBytes, FormatBytes + StrLen, getLangOpts(),1419Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {1420llvm::APSInt FormatSize =1421llvm::APSInt::getUnsigned(H.getSizeLowerBound())1422.extOrTrunc(SizeTypeWidth);1423if (FormatSize > *SourceSize && *SourceSize != 0) {1424unsigned TruncationDiagID =1425H.isKernelCompatible() ? diag::warn_format_truncation1426: diag::warn_format_truncation_non_kprintf;1427SmallString<16> SpecifiedSizeStr;1428SmallString<16> FormatSizeStr;1429SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);1430FormatSize.toString(FormatSizeStr, /*Radix=*/10);1431DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,1432PDiag(TruncationDiagID)1433<< GetFunctionName() << SpecifiedSizeStr1434<< FormatSizeStr);1435}1436}1437}1438DestinationSize = ComputeSizeArgument(0);1439}1440}14411442if (!SourceSize || !DestinationSize ||1443llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)1444return;14451446StringRef FunctionName = GetFunctionName();14471448SmallString<16> DestinationStr;1449SmallString<16> SourceStr;1450DestinationSize->toString(DestinationStr, /*Radix=*/10);1451SourceSize->toString(SourceStr, /*Radix=*/10);1452DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,1453PDiag(DiagID)1454<< FunctionName << DestinationStr << SourceStr);1455}14561457static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,1458Scope::ScopeFlags NeededScopeFlags,1459unsigned DiagID) {1460// Scopes aren't available during instantiation. Fortunately, builtin1461// functions cannot be template args so they cannot be formed through template1462// instantiation. Therefore checking once during the parse is sufficient.1463if (SemaRef.inTemplateInstantiation())1464return false;14651466Scope *S = SemaRef.getCurScope();1467while (S && !S->isSEHExceptScope())1468S = S->getParent();1469if (!S || !(S->getFlags() & NeededScopeFlags)) {1470auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());1471SemaRef.Diag(TheCall->getExprLoc(), DiagID)1472<< DRE->getDecl()->getIdentifier();1473return true;1474}14751476return false;1477}14781479namespace {1480enum PointerAuthOpKind {1481PAO_Strip,1482PAO_Sign,1483PAO_Auth,1484PAO_SignGeneric,1485PAO_Discriminator,1486PAO_BlendPointer,1487PAO_BlendInteger1488};1489}14901491bool Sema::checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range) {1492if (getLangOpts().PointerAuthIntrinsics)1493return false;14941495Diag(Loc, diag::err_ptrauth_disabled) << Range;1496return true;1497}14981499static bool checkPointerAuthEnabled(Sema &S, Expr *E) {1500return S.checkPointerAuthEnabled(E->getExprLoc(), E->getSourceRange());1501}15021503static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {1504// Convert it to type 'int'.1505if (convertArgumentToType(S, Arg, S.Context.IntTy))1506return true;15071508// Value-dependent expressions are okay; wait for template instantiation.1509if (Arg->isValueDependent())1510return false;15111512unsigned KeyValue;1513return S.checkConstantPointerAuthKey(Arg, KeyValue);1514}15151516bool Sema::checkConstantPointerAuthKey(Expr *Arg, unsigned &Result) {1517// Attempt to constant-evaluate the expression.1518std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);1519if (!KeyValue) {1520Diag(Arg->getExprLoc(), diag::err_expr_not_ice)1521<< 0 << Arg->getSourceRange();1522return true;1523}15241525// Ask the target to validate the key parameter.1526if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {1527llvm::SmallString<32> Value;1528{1529llvm::raw_svector_ostream Str(Value);1530Str << *KeyValue;1531}15321533Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)1534<< Value << Arg->getSourceRange();1535return true;1536}15371538Result = KeyValue->getZExtValue();1539return false;1540}15411542static std::pair<const ValueDecl *, CharUnits>1543findConstantBaseAndOffset(Sema &S, Expr *E) {1544// Must evaluate as a pointer.1545Expr::EvalResult Result;1546if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())1547return {nullptr, CharUnits()};15481549const auto *BaseDecl =1550Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();1551if (!BaseDecl)1552return {nullptr, CharUnits()};15531554return {BaseDecl, Result.Val.getLValueOffset()};1555}15561557static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,1558bool RequireConstant = false) {1559if (Arg->hasPlaceholderType()) {1560ExprResult R = S.CheckPlaceholderExpr(Arg);1561if (R.isInvalid())1562return true;1563Arg = R.get();1564}15651566auto AllowsPointer = [](PointerAuthOpKind OpKind) {1567return OpKind != PAO_BlendInteger;1568};1569auto AllowsInteger = [](PointerAuthOpKind OpKind) {1570return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||1571OpKind == PAO_SignGeneric;1572};15731574// Require the value to have the right range of type.1575QualType ExpectedTy;1576if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {1577ExpectedTy = Arg->getType().getUnqualifiedType();1578} else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {1579ExpectedTy = S.Context.VoidPtrTy;1580} else if (AllowsInteger(OpKind) &&1581Arg->getType()->isIntegralOrUnscopedEnumerationType()) {1582ExpectedTy = S.Context.getUIntPtrType();15831584} else {1585// Diagnose the failures.1586S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)1587<< unsigned(OpKind == PAO_Discriminator ? 11588: OpKind == PAO_BlendPointer ? 21589: OpKind == PAO_BlendInteger ? 31590: 0)1591<< unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)1592<< Arg->getType() << Arg->getSourceRange();1593return true;1594}15951596// Convert to that type. This should just be an lvalue-to-rvalue1597// conversion.1598if (convertArgumentToType(S, Arg, ExpectedTy))1599return true;16001601if (!RequireConstant) {1602// Warn about null pointers for non-generic sign and auth operations.1603if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&1604Arg->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull)) {1605S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign1606? diag::warn_ptrauth_sign_null_pointer1607: diag::warn_ptrauth_auth_null_pointer)1608<< Arg->getSourceRange();1609}16101611return false;1612}16131614// Perform special checking on the arguments to ptrauth_sign_constant.16151616// The main argument.1617if (OpKind == PAO_Sign) {1618// Require the value we're signing to have a special form.1619auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);1620bool Invalid;16211622// Must be rooted in a declaration reference.1623if (!BaseDecl)1624Invalid = true;16251626// If it's a function declaration, we can't have an offset.1627else if (isa<FunctionDecl>(BaseDecl))1628Invalid = !Offset.isZero();16291630// Otherwise we're fine.1631else1632Invalid = false;16331634if (Invalid)1635S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);1636return Invalid;1637}16381639// The discriminator argument.1640assert(OpKind == PAO_Discriminator);16411642// Must be a pointer or integer or blend thereof.1643Expr *Pointer = nullptr;1644Expr *Integer = nullptr;1645if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {1646if (Call->getBuiltinCallee() ==1647Builtin::BI__builtin_ptrauth_blend_discriminator) {1648Pointer = Call->getArg(0);1649Integer = Call->getArg(1);1650}1651}1652if (!Pointer && !Integer) {1653if (Arg->getType()->isPointerType())1654Pointer = Arg;1655else1656Integer = Arg;1657}16581659// Check the pointer.1660bool Invalid = false;1661if (Pointer) {1662assert(Pointer->getType()->isPointerType());16631664// TODO: if we're initializing a global, check that the address is1665// somehow related to what we're initializing. This probably will1666// never really be feasible and we'll have to catch it at link-time.1667auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);1668if (!BaseDecl || !isa<VarDecl>(BaseDecl))1669Invalid = true;1670}16711672// Check the integer.1673if (Integer) {1674assert(Integer->getType()->isIntegerType());1675if (!Integer->isEvaluatable(S.Context))1676Invalid = true;1677}16781679if (Invalid)1680S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);1681return Invalid;1682}16831684static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call) {1685if (S.checkArgCount(Call, 2))1686return ExprError();1687if (checkPointerAuthEnabled(S, Call))1688return ExprError();1689if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||1690checkPointerAuthKey(S, Call->getArgs()[1]))1691return ExprError();16921693Call->setType(Call->getArgs()[0]->getType());1694return Call;1695}16961697static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call) {1698if (S.checkArgCount(Call, 2))1699return ExprError();1700if (checkPointerAuthEnabled(S, Call))1701return ExprError();1702if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||1703checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))1704return ExprError();17051706Call->setType(S.Context.getUIntPtrType());1707return Call;1708}17091710static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call) {1711if (S.checkArgCount(Call, 2))1712return ExprError();1713if (checkPointerAuthEnabled(S, Call))1714return ExprError();1715if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||1716checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))1717return ExprError();17181719Call->setType(S.Context.getUIntPtrType());1720return Call;1721}17221723static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call,1724PointerAuthOpKind OpKind,1725bool RequireConstant) {1726if (S.checkArgCount(Call, 3))1727return ExprError();1728if (checkPointerAuthEnabled(S, Call))1729return ExprError();1730if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||1731checkPointerAuthKey(S, Call->getArgs()[1]) ||1732checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,1733RequireConstant))1734return ExprError();17351736Call->setType(Call->getArgs()[0]->getType());1737return Call;1738}17391740static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call) {1741if (S.checkArgCount(Call, 5))1742return ExprError();1743if (checkPointerAuthEnabled(S, Call))1744return ExprError();1745if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||1746checkPointerAuthKey(S, Call->getArgs()[1]) ||1747checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||1748checkPointerAuthKey(S, Call->getArgs()[3]) ||1749checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))1750return ExprError();17511752Call->setType(Call->getArgs()[0]->getType());1753return Call;1754}17551756static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call) {1757if (checkPointerAuthEnabled(S, Call))1758return ExprError();17591760// We've already performed normal call type-checking.1761const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();17621763// Operand must be an ordinary or UTF-8 string literal.1764const auto *Literal = dyn_cast<StringLiteral>(Arg);1765if (!Literal || Literal->getCharByteWidth() != 1) {1766S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)1767<< (Literal ? 1 : 0) << Arg->getSourceRange();1768return ExprError();1769}17701771return Call;1772}17731774static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) {1775if (S.checkArgCount(TheCall, 1))1776return ExprError();17771778// Compute __builtin_launder's parameter type from the argument.1779// The parameter type is:1780// * The type of the argument if it's not an array or function type,1781// Otherwise,1782// * The decayed argument type.1783QualType ParamTy = [&]() {1784QualType ArgTy = TheCall->getArg(0)->getType();1785if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())1786return S.Context.getPointerType(Ty->getElementType());1787if (ArgTy->isFunctionType()) {1788return S.Context.getPointerType(ArgTy);1789}1790return ArgTy;1791}();17921793TheCall->setType(ParamTy);17941795auto DiagSelect = [&]() -> std::optional<unsigned> {1796if (!ParamTy->isPointerType())1797return 0;1798if (ParamTy->isFunctionPointerType())1799return 1;1800if (ParamTy->isVoidPointerType())1801return 2;1802return std::optional<unsigned>{};1803}();1804if (DiagSelect) {1805S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)1806<< *DiagSelect << TheCall->getSourceRange();1807return ExprError();1808}18091810// We either have an incomplete class type, or we have a class template1811// whose instantiation has not been forced. Example:1812//1813// template <class T> struct Foo { T value; };1814// Foo<int> *p = nullptr;1815// auto *d = __builtin_launder(p);1816if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),1817diag::err_incomplete_type))1818return ExprError();18191820assert(ParamTy->getPointeeType()->isObjectType() &&1821"Unhandled non-object pointer case");18221823InitializedEntity Entity =1824InitializedEntity::InitializeParameter(S.Context, ParamTy, false);1825ExprResult Arg =1826S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));1827if (Arg.isInvalid())1828return ExprError();1829TheCall->setArg(0, Arg.get());18301831return TheCall;1832}18331834// Emit an error and return true if the current object format type is in the1835// list of unsupported types.1836static bool CheckBuiltinTargetNotInUnsupported(1837Sema &S, unsigned BuiltinID, CallExpr *TheCall,1838ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {1839llvm::Triple::ObjectFormatType CurObjFormat =1840S.getASTContext().getTargetInfo().getTriple().getObjectFormat();1841if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {1842S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)1843<< TheCall->getSourceRange();1844return true;1845}1846return false;1847}18481849// Emit an error and return true if the current architecture is not in the list1850// of supported architectures.1851static bool1852CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,1853ArrayRef<llvm::Triple::ArchType> SupportedArchs) {1854llvm::Triple::ArchType CurArch =1855S.getASTContext().getTargetInfo().getTriple().getArch();1856if (llvm::is_contained(SupportedArchs, CurArch))1857return false;1858S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)1859<< TheCall->getSourceRange();1860return true;1861}18621863static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,1864SourceLocation CallSiteLoc);18651866bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,1867CallExpr *TheCall) {1868switch (TI.getTriple().getArch()) {1869default:1870// Some builtins don't require additional checking, so just consider these1871// acceptable.1872return false;1873case llvm::Triple::arm:1874case llvm::Triple::armeb:1875case llvm::Triple::thumb:1876case llvm::Triple::thumbeb:1877return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);1878case llvm::Triple::aarch64:1879case llvm::Triple::aarch64_32:1880case llvm::Triple::aarch64_be:1881return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);1882case llvm::Triple::bpfeb:1883case llvm::Triple::bpfel:1884return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);1885case llvm::Triple::hexagon:1886return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);1887case llvm::Triple::mips:1888case llvm::Triple::mipsel:1889case llvm::Triple::mips64:1890case llvm::Triple::mips64el:1891return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);1892case llvm::Triple::systemz:1893return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);1894case llvm::Triple::x86:1895case llvm::Triple::x86_64:1896return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);1897case llvm::Triple::ppc:1898case llvm::Triple::ppcle:1899case llvm::Triple::ppc64:1900case llvm::Triple::ppc64le:1901return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);1902case llvm::Triple::amdgcn:1903return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);1904case llvm::Triple::riscv32:1905case llvm::Triple::riscv64:1906return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);1907case llvm::Triple::loongarch32:1908case llvm::Triple::loongarch64:1909return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,1910TheCall);1911case llvm::Triple::wasm32:1912case llvm::Triple::wasm64:1913return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);1914case llvm::Triple::nvptx:1915case llvm::Triple::nvptx64:1916return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);1917}1918}19191920// Check if \p Ty is a valid type for the elementwise math builtins. If it is1921// not a valid type, emit an error message and return true. Otherwise return1922// false.1923static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,1924QualType ArgTy, int ArgIndex) {1925if (!ArgTy->getAs<VectorType>() &&1926!ConstantMatrixType::isValidElementType(ArgTy)) {1927return S.Diag(Loc, diag::err_builtin_invalid_arg_type)1928<< ArgIndex << /* vector, integer or float ty*/ 0 << ArgTy;1929}19301931return false;1932}19331934static bool checkFPMathBuiltinElementType(Sema &S, SourceLocation Loc,1935QualType ArgTy, int ArgIndex) {1936QualType EltTy = ArgTy;1937if (auto *VecTy = EltTy->getAs<VectorType>())1938EltTy = VecTy->getElementType();19391940if (!EltTy->isRealFloatingType()) {1941return S.Diag(Loc, diag::err_builtin_invalid_arg_type)1942<< ArgIndex << /* vector or float ty*/ 5 << ArgTy;1943}19441945return false;1946}19471948/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).1949/// This checks that the target supports the builtin and that the string1950/// argument is constant and valid.1951static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,1952const TargetInfo *AuxTI, unsigned BuiltinID) {1953assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||1954BuiltinID == Builtin::BI__builtin_cpu_is) &&1955"Expecting __builtin_cpu_...");19561957bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;1958const TargetInfo *TheTI = &TI;1959auto SupportsBI = [=](const TargetInfo *TInfo) {1960return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||1961(!IsCPUSupports && TInfo->supportsCpuIs()));1962};1963if (!SupportsBI(&TI) && SupportsBI(AuxTI))1964TheTI = AuxTI;19651966if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||1967(IsCPUSupports && !TheTI->supportsCpuSupports()))1968return S.Diag(TheCall->getBeginLoc(),1969TI.getTriple().isOSAIX()1970? diag::err_builtin_aix_os_unsupported1971: diag::err_builtin_target_unsupported)1972<< SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());19731974Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();1975// Check if the argument is a string literal.1976if (!isa<StringLiteral>(Arg))1977return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)1978<< Arg->getSourceRange();19791980// Check the contents of the string.1981StringRef Feature = cast<StringLiteral>(Arg)->getString();1982if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {1983S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)1984<< Arg->getSourceRange();1985return false;1986}1987if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))1988return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)1989<< Arg->getSourceRange();1990return false;1991}19921993/// Checks that __builtin_popcountg was called with a single argument, which is1994/// an unsigned integer.1995static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {1996if (S.checkArgCount(TheCall, 1))1997return true;19981999ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));2000if (ArgRes.isInvalid())2001return true;20022003Expr *Arg = ArgRes.get();2004TheCall->setArg(0, Arg);20052006QualType ArgTy = Arg->getType();20072008if (!ArgTy->isUnsignedIntegerType()) {2009S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)2010<< 1 << /*unsigned integer ty*/ 7 << ArgTy;2011return true;2012}2013return false;2014}20152016/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is2017/// an unsigned integer, and an optional second argument, which is promoted to2018/// an 'int'.2019static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {2020if (S.checkArgCountRange(TheCall, 1, 2))2021return true;20222023ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));2024if (Arg0Res.isInvalid())2025return true;20262027Expr *Arg0 = Arg0Res.get();2028TheCall->setArg(0, Arg0);20292030QualType Arg0Ty = Arg0->getType();20312032if (!Arg0Ty->isUnsignedIntegerType()) {2033S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)2034<< 1 << /*unsigned integer ty*/ 7 << Arg0Ty;2035return true;2036}20372038if (TheCall->getNumArgs() > 1) {2039ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));2040if (Arg1Res.isInvalid())2041return true;20422043Expr *Arg1 = Arg1Res.get();2044TheCall->setArg(1, Arg1);20452046QualType Arg1Ty = Arg1->getType();20472048if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {2049S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)2050<< 2 << /*'int' ty*/ 8 << Arg1Ty;2051return true;2052}2053}20542055return false;2056}20572058ExprResult2059Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,2060CallExpr *TheCall) {2061ExprResult TheCallResult(TheCall);20622063// Find out if any arguments are required to be integer constant expressions.2064unsigned ICEArguments = 0;2065ASTContext::GetBuiltinTypeError Error;2066Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);2067if (Error != ASTContext::GE_None)2068ICEArguments = 0; // Don't diagnose previously diagnosed errors.20692070// If any arguments are required to be ICE's, check and diagnose.2071for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {2072// Skip arguments not required to be ICE's.2073if ((ICEArguments & (1 << ArgNo)) == 0) continue;20742075llvm::APSInt Result;2076// If we don't have enough arguments, continue so we can issue better2077// diagnostic in checkArgCount(...)2078if (ArgNo < TheCall->getNumArgs() &&2079BuiltinConstantArg(TheCall, ArgNo, Result))2080return true;2081ICEArguments &= ~(1 << ArgNo);2082}20832084FPOptions FPO;2085switch (BuiltinID) {2086case Builtin::BI__builtin_cpu_supports:2087case Builtin::BI__builtin_cpu_is:2088if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,2089Context.getAuxTargetInfo(), BuiltinID))2090return ExprError();2091break;2092case Builtin::BI__builtin_cpu_init:2093if (!Context.getTargetInfo().supportsCpuInit()) {2094Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)2095<< SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());2096return ExprError();2097}2098break;2099case Builtin::BI__builtin___CFStringMakeConstantString:2100// CFStringMakeConstantString is currently not implemented for GOFF (i.e.,2101// on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported2102if (CheckBuiltinTargetNotInUnsupported(2103*this, BuiltinID, TheCall,2104{llvm::Triple::GOFF, llvm::Triple::XCOFF}))2105return ExprError();2106assert(TheCall->getNumArgs() == 1 &&2107"Wrong # arguments to builtin CFStringMakeConstantString");2108if (ObjC().CheckObjCString(TheCall->getArg(0)))2109return ExprError();2110break;2111case Builtin::BI__builtin_ms_va_start:2112case Builtin::BI__builtin_stdarg_start:2113case Builtin::BI__builtin_va_start:2114if (BuiltinVAStart(BuiltinID, TheCall))2115return ExprError();2116break;2117case Builtin::BI__va_start: {2118switch (Context.getTargetInfo().getTriple().getArch()) {2119case llvm::Triple::aarch64:2120case llvm::Triple::arm:2121case llvm::Triple::thumb:2122if (BuiltinVAStartARMMicrosoft(TheCall))2123return ExprError();2124break;2125default:2126if (BuiltinVAStart(BuiltinID, TheCall))2127return ExprError();2128break;2129}2130break;2131}21322133// The acquire, release, and no fence variants are ARM and AArch64 only.2134case Builtin::BI_interlockedbittestandset_acq:2135case Builtin::BI_interlockedbittestandset_rel:2136case Builtin::BI_interlockedbittestandset_nf:2137case Builtin::BI_interlockedbittestandreset_acq:2138case Builtin::BI_interlockedbittestandreset_rel:2139case Builtin::BI_interlockedbittestandreset_nf:2140if (CheckBuiltinTargetInSupported(2141*this, BuiltinID, TheCall,2142{llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))2143return ExprError();2144break;21452146// The 64-bit bittest variants are x64, ARM, and AArch64 only.2147case Builtin::BI_bittest64:2148case Builtin::BI_bittestandcomplement64:2149case Builtin::BI_bittestandreset64:2150case Builtin::BI_bittestandset64:2151case Builtin::BI_interlockedbittestandreset64:2152case Builtin::BI_interlockedbittestandset64:2153if (CheckBuiltinTargetInSupported(2154*this, BuiltinID, TheCall,2155{llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,2156llvm::Triple::aarch64, llvm::Triple::amdgcn}))2157return ExprError();2158break;21592160case Builtin::BI__builtin_set_flt_rounds:2161if (CheckBuiltinTargetInSupported(2162*this, BuiltinID, TheCall,2163{llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,2164llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn}))2165return ExprError();2166break;21672168case Builtin::BI__builtin_isgreater:2169case Builtin::BI__builtin_isgreaterequal:2170case Builtin::BI__builtin_isless:2171case Builtin::BI__builtin_islessequal:2172case Builtin::BI__builtin_islessgreater:2173case Builtin::BI__builtin_isunordered:2174if (BuiltinUnorderedCompare(TheCall, BuiltinID))2175return ExprError();2176break;2177case Builtin::BI__builtin_fpclassify:2178if (BuiltinFPClassification(TheCall, 6, BuiltinID))2179return ExprError();2180break;2181case Builtin::BI__builtin_isfpclass:2182if (BuiltinFPClassification(TheCall, 2, BuiltinID))2183return ExprError();2184break;2185case Builtin::BI__builtin_isfinite:2186case Builtin::BI__builtin_isinf:2187case Builtin::BI__builtin_isinf_sign:2188case Builtin::BI__builtin_isnan:2189case Builtin::BI__builtin_issignaling:2190case Builtin::BI__builtin_isnormal:2191case Builtin::BI__builtin_issubnormal:2192case Builtin::BI__builtin_iszero:2193case Builtin::BI__builtin_signbit:2194case Builtin::BI__builtin_signbitf:2195case Builtin::BI__builtin_signbitl:2196if (BuiltinFPClassification(TheCall, 1, BuiltinID))2197return ExprError();2198break;2199case Builtin::BI__builtin_shufflevector:2200return BuiltinShuffleVector(TheCall);2201// TheCall will be freed by the smart pointer here, but that's fine, since2202// BuiltinShuffleVector guts it, but then doesn't release it.2203case Builtin::BI__builtin_prefetch:2204if (BuiltinPrefetch(TheCall))2205return ExprError();2206break;2207case Builtin::BI__builtin_alloca_with_align:2208case Builtin::BI__builtin_alloca_with_align_uninitialized:2209if (BuiltinAllocaWithAlign(TheCall))2210return ExprError();2211[[fallthrough]];2212case Builtin::BI__builtin_alloca:2213case Builtin::BI__builtin_alloca_uninitialized:2214Diag(TheCall->getBeginLoc(), diag::warn_alloca)2215<< TheCall->getDirectCallee();2216break;2217case Builtin::BI__arithmetic_fence:2218if (BuiltinArithmeticFence(TheCall))2219return ExprError();2220break;2221case Builtin::BI__assume:2222case Builtin::BI__builtin_assume:2223if (BuiltinAssume(TheCall))2224return ExprError();2225break;2226case Builtin::BI__builtin_assume_aligned:2227if (BuiltinAssumeAligned(TheCall))2228return ExprError();2229break;2230case Builtin::BI__builtin_dynamic_object_size:2231case Builtin::BI__builtin_object_size:2232if (BuiltinConstantArgRange(TheCall, 1, 0, 3))2233return ExprError();2234break;2235case Builtin::BI__builtin_longjmp:2236if (BuiltinLongjmp(TheCall))2237return ExprError();2238break;2239case Builtin::BI__builtin_setjmp:2240if (BuiltinSetjmp(TheCall))2241return ExprError();2242break;2243case Builtin::BI__builtin_classify_type:2244if (checkArgCount(TheCall, 1))2245return true;2246TheCall->setType(Context.IntTy);2247break;2248case Builtin::BI__builtin_complex:2249if (BuiltinComplex(TheCall))2250return ExprError();2251break;2252case Builtin::BI__builtin_constant_p: {2253if (checkArgCount(TheCall, 1))2254return true;2255ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));2256if (Arg.isInvalid()) return true;2257TheCall->setArg(0, Arg.get());2258TheCall->setType(Context.IntTy);2259break;2260}2261case Builtin::BI__builtin_launder:2262return BuiltinLaunder(*this, TheCall);2263case Builtin::BI__sync_fetch_and_add:2264case Builtin::BI__sync_fetch_and_add_1:2265case Builtin::BI__sync_fetch_and_add_2:2266case Builtin::BI__sync_fetch_and_add_4:2267case Builtin::BI__sync_fetch_and_add_8:2268case Builtin::BI__sync_fetch_and_add_16:2269case Builtin::BI__sync_fetch_and_sub:2270case Builtin::BI__sync_fetch_and_sub_1:2271case Builtin::BI__sync_fetch_and_sub_2:2272case Builtin::BI__sync_fetch_and_sub_4:2273case Builtin::BI__sync_fetch_and_sub_8:2274case Builtin::BI__sync_fetch_and_sub_16:2275case Builtin::BI__sync_fetch_and_or:2276case Builtin::BI__sync_fetch_and_or_1:2277case Builtin::BI__sync_fetch_and_or_2:2278case Builtin::BI__sync_fetch_and_or_4:2279case Builtin::BI__sync_fetch_and_or_8:2280case Builtin::BI__sync_fetch_and_or_16:2281case Builtin::BI__sync_fetch_and_and:2282case Builtin::BI__sync_fetch_and_and_1:2283case Builtin::BI__sync_fetch_and_and_2:2284case Builtin::BI__sync_fetch_and_and_4:2285case Builtin::BI__sync_fetch_and_and_8:2286case Builtin::BI__sync_fetch_and_and_16:2287case Builtin::BI__sync_fetch_and_xor:2288case Builtin::BI__sync_fetch_and_xor_1:2289case Builtin::BI__sync_fetch_and_xor_2:2290case Builtin::BI__sync_fetch_and_xor_4:2291case Builtin::BI__sync_fetch_and_xor_8:2292case Builtin::BI__sync_fetch_and_xor_16:2293case Builtin::BI__sync_fetch_and_nand:2294case Builtin::BI__sync_fetch_and_nand_1:2295case Builtin::BI__sync_fetch_and_nand_2:2296case Builtin::BI__sync_fetch_and_nand_4:2297case Builtin::BI__sync_fetch_and_nand_8:2298case Builtin::BI__sync_fetch_and_nand_16:2299case Builtin::BI__sync_add_and_fetch:2300case Builtin::BI__sync_add_and_fetch_1:2301case Builtin::BI__sync_add_and_fetch_2:2302case Builtin::BI__sync_add_and_fetch_4:2303case Builtin::BI__sync_add_and_fetch_8:2304case Builtin::BI__sync_add_and_fetch_16:2305case Builtin::BI__sync_sub_and_fetch:2306case Builtin::BI__sync_sub_and_fetch_1:2307case Builtin::BI__sync_sub_and_fetch_2:2308case Builtin::BI__sync_sub_and_fetch_4:2309case Builtin::BI__sync_sub_and_fetch_8:2310case Builtin::BI__sync_sub_and_fetch_16:2311case Builtin::BI__sync_and_and_fetch:2312case Builtin::BI__sync_and_and_fetch_1:2313case Builtin::BI__sync_and_and_fetch_2:2314case Builtin::BI__sync_and_and_fetch_4:2315case Builtin::BI__sync_and_and_fetch_8:2316case Builtin::BI__sync_and_and_fetch_16:2317case Builtin::BI__sync_or_and_fetch:2318case Builtin::BI__sync_or_and_fetch_1:2319case Builtin::BI__sync_or_and_fetch_2:2320case Builtin::BI__sync_or_and_fetch_4:2321case Builtin::BI__sync_or_and_fetch_8:2322case Builtin::BI__sync_or_and_fetch_16:2323case Builtin::BI__sync_xor_and_fetch:2324case Builtin::BI__sync_xor_and_fetch_1:2325case Builtin::BI__sync_xor_and_fetch_2:2326case Builtin::BI__sync_xor_and_fetch_4:2327case Builtin::BI__sync_xor_and_fetch_8:2328case Builtin::BI__sync_xor_and_fetch_16:2329case Builtin::BI__sync_nand_and_fetch:2330case Builtin::BI__sync_nand_and_fetch_1:2331case Builtin::BI__sync_nand_and_fetch_2:2332case Builtin::BI__sync_nand_and_fetch_4:2333case Builtin::BI__sync_nand_and_fetch_8:2334case Builtin::BI__sync_nand_and_fetch_16:2335case Builtin::BI__sync_val_compare_and_swap:2336case Builtin::BI__sync_val_compare_and_swap_1:2337case Builtin::BI__sync_val_compare_and_swap_2:2338case Builtin::BI__sync_val_compare_and_swap_4:2339case Builtin::BI__sync_val_compare_and_swap_8:2340case Builtin::BI__sync_val_compare_and_swap_16:2341case Builtin::BI__sync_bool_compare_and_swap:2342case Builtin::BI__sync_bool_compare_and_swap_1:2343case Builtin::BI__sync_bool_compare_and_swap_2:2344case Builtin::BI__sync_bool_compare_and_swap_4:2345case Builtin::BI__sync_bool_compare_and_swap_8:2346case Builtin::BI__sync_bool_compare_and_swap_16:2347case Builtin::BI__sync_lock_test_and_set:2348case Builtin::BI__sync_lock_test_and_set_1:2349case Builtin::BI__sync_lock_test_and_set_2:2350case Builtin::BI__sync_lock_test_and_set_4:2351case Builtin::BI__sync_lock_test_and_set_8:2352case Builtin::BI__sync_lock_test_and_set_16:2353case Builtin::BI__sync_lock_release:2354case Builtin::BI__sync_lock_release_1:2355case Builtin::BI__sync_lock_release_2:2356case Builtin::BI__sync_lock_release_4:2357case Builtin::BI__sync_lock_release_8:2358case Builtin::BI__sync_lock_release_16:2359case Builtin::BI__sync_swap:2360case Builtin::BI__sync_swap_1:2361case Builtin::BI__sync_swap_2:2362case Builtin::BI__sync_swap_4:2363case Builtin::BI__sync_swap_8:2364case Builtin::BI__sync_swap_16:2365return BuiltinAtomicOverloaded(TheCallResult);2366case Builtin::BI__sync_synchronize:2367Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)2368<< TheCall->getCallee()->getSourceRange();2369break;2370case Builtin::BI__builtin_nontemporal_load:2371case Builtin::BI__builtin_nontemporal_store:2372return BuiltinNontemporalOverloaded(TheCallResult);2373case Builtin::BI__builtin_memcpy_inline: {2374clang::Expr *SizeOp = TheCall->getArg(2);2375// We warn about copying to or from `nullptr` pointers when `size` is2376// greater than 0. When `size` is value dependent we cannot evaluate its2377// value so we bail out.2378if (SizeOp->isValueDependent())2379break;2380if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {2381CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());2382CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());2383}2384break;2385}2386case Builtin::BI__builtin_memset_inline: {2387clang::Expr *SizeOp = TheCall->getArg(2);2388// We warn about filling to `nullptr` pointers when `size` is greater than2389// 0. When `size` is value dependent we cannot evaluate its value so we bail2390// out.2391if (SizeOp->isValueDependent())2392break;2393if (!SizeOp->EvaluateKnownConstInt(Context).isZero())2394CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());2395break;2396}2397#define BUILTIN(ID, TYPE, ATTRS)2398#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \2399case Builtin::BI##ID: \2400return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);2401#include "clang/Basic/Builtins.inc"2402case Builtin::BI__annotation:2403if (BuiltinMSVCAnnotation(*this, TheCall))2404return ExprError();2405break;2406case Builtin::BI__builtin_annotation:2407if (BuiltinAnnotation(*this, TheCall))2408return ExprError();2409break;2410case Builtin::BI__builtin_addressof:2411if (BuiltinAddressof(*this, TheCall))2412return ExprError();2413break;2414case Builtin::BI__builtin_function_start:2415if (BuiltinFunctionStart(*this, TheCall))2416return ExprError();2417break;2418case Builtin::BI__builtin_is_aligned:2419case Builtin::BI__builtin_align_up:2420case Builtin::BI__builtin_align_down:2421if (BuiltinAlignment(*this, TheCall, BuiltinID))2422return ExprError();2423break;2424case Builtin::BI__builtin_add_overflow:2425case Builtin::BI__builtin_sub_overflow:2426case Builtin::BI__builtin_mul_overflow:2427if (BuiltinOverflow(*this, TheCall, BuiltinID))2428return ExprError();2429break;2430case Builtin::BI__builtin_operator_new:2431case Builtin::BI__builtin_operator_delete: {2432bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;2433ExprResult Res =2434BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);2435if (Res.isInvalid())2436CorrectDelayedTyposInExpr(TheCallResult.get());2437return Res;2438}2439case Builtin::BI__builtin_dump_struct:2440return BuiltinDumpStruct(*this, TheCall);2441case Builtin::BI__builtin_expect_with_probability: {2442// We first want to ensure we are called with 3 arguments2443if (checkArgCount(TheCall, 3))2444return ExprError();2445// then check probability is constant float in range [0.0, 1.0]2446const Expr *ProbArg = TheCall->getArg(2);2447SmallVector<PartialDiagnosticAt, 8> Notes;2448Expr::EvalResult Eval;2449Eval.Diag = &Notes;2450if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||2451!Eval.Val.isFloat()) {2452Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)2453<< ProbArg->getSourceRange();2454for (const PartialDiagnosticAt &PDiag : Notes)2455Diag(PDiag.first, PDiag.second);2456return ExprError();2457}2458llvm::APFloat Probability = Eval.Val.getFloat();2459bool LoseInfo = false;2460Probability.convert(llvm::APFloat::IEEEdouble(),2461llvm::RoundingMode::Dynamic, &LoseInfo);2462if (!(Probability >= llvm::APFloat(0.0) &&2463Probability <= llvm::APFloat(1.0))) {2464Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)2465<< ProbArg->getSourceRange();2466return ExprError();2467}2468break;2469}2470case Builtin::BI__builtin_preserve_access_index:2471if (BuiltinPreserveAI(*this, TheCall))2472return ExprError();2473break;2474case Builtin::BI__builtin_call_with_static_chain:2475if (BuiltinCallWithStaticChain(*this, TheCall))2476return ExprError();2477break;2478case Builtin::BI__exception_code:2479case Builtin::BI_exception_code:2480if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,2481diag::err_seh___except_block))2482return ExprError();2483break;2484case Builtin::BI__exception_info:2485case Builtin::BI_exception_info:2486if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,2487diag::err_seh___except_filter))2488return ExprError();2489break;2490case Builtin::BI__GetExceptionInfo:2491if (checkArgCount(TheCall, 1))2492return ExprError();24932494if (CheckCXXThrowOperand(2495TheCall->getBeginLoc(),2496Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),2497TheCall))2498return ExprError();24992500TheCall->setType(Context.VoidPtrTy);2501break;2502case Builtin::BIaddressof:2503case Builtin::BI__addressof:2504case Builtin::BIforward:2505case Builtin::BIforward_like:2506case Builtin::BImove:2507case Builtin::BImove_if_noexcept:2508case Builtin::BIas_const: {2509// These are all expected to be of the form2510// T &/&&/* f(U &/&&)2511// where T and U only differ in qualification.2512if (checkArgCount(TheCall, 1))2513return ExprError();2514QualType Param = FDecl->getParamDecl(0)->getType();2515QualType Result = FDecl->getReturnType();2516bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||2517BuiltinID == Builtin::BI__addressof;2518if (!(Param->isReferenceType() &&2519(ReturnsPointer ? Result->isAnyPointerType()2520: Result->isReferenceType()) &&2521Context.hasSameUnqualifiedType(Param->getPointeeType(),2522Result->getPointeeType()))) {2523Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)2524<< FDecl;2525return ExprError();2526}2527break;2528}2529case Builtin::BI__builtin_ptrauth_strip:2530return PointerAuthStrip(*this, TheCall);2531case Builtin::BI__builtin_ptrauth_blend_discriminator:2532return PointerAuthBlendDiscriminator(*this, TheCall);2533case Builtin::BI__builtin_ptrauth_sign_constant:2534return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,2535/*RequireConstant=*/true);2536case Builtin::BI__builtin_ptrauth_sign_unauthenticated:2537return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,2538/*RequireConstant=*/false);2539case Builtin::BI__builtin_ptrauth_auth:2540return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,2541/*RequireConstant=*/false);2542case Builtin::BI__builtin_ptrauth_sign_generic_data:2543return PointerAuthSignGenericData(*this, TheCall);2544case Builtin::BI__builtin_ptrauth_auth_and_resign:2545return PointerAuthAuthAndResign(*this, TheCall);2546case Builtin::BI__builtin_ptrauth_string_discriminator:2547return PointerAuthStringDiscriminator(*this, TheCall);2548// OpenCL v2.0, s6.13.16 - Pipe functions2549case Builtin::BIread_pipe:2550case Builtin::BIwrite_pipe:2551// Since those two functions are declared with var args, we need a semantic2552// check for the argument.2553if (OpenCL().checkBuiltinRWPipe(TheCall))2554return ExprError();2555break;2556case Builtin::BIreserve_read_pipe:2557case Builtin::BIreserve_write_pipe:2558case Builtin::BIwork_group_reserve_read_pipe:2559case Builtin::BIwork_group_reserve_write_pipe:2560if (OpenCL().checkBuiltinReserveRWPipe(TheCall))2561return ExprError();2562break;2563case Builtin::BIsub_group_reserve_read_pipe:2564case Builtin::BIsub_group_reserve_write_pipe:2565if (OpenCL().checkSubgroupExt(TheCall) ||2566OpenCL().checkBuiltinReserveRWPipe(TheCall))2567return ExprError();2568break;2569case Builtin::BIcommit_read_pipe:2570case Builtin::BIcommit_write_pipe:2571case Builtin::BIwork_group_commit_read_pipe:2572case Builtin::BIwork_group_commit_write_pipe:2573if (OpenCL().checkBuiltinCommitRWPipe(TheCall))2574return ExprError();2575break;2576case Builtin::BIsub_group_commit_read_pipe:2577case Builtin::BIsub_group_commit_write_pipe:2578if (OpenCL().checkSubgroupExt(TheCall) ||2579OpenCL().checkBuiltinCommitRWPipe(TheCall))2580return ExprError();2581break;2582case Builtin::BIget_pipe_num_packets:2583case Builtin::BIget_pipe_max_packets:2584if (OpenCL().checkBuiltinPipePackets(TheCall))2585return ExprError();2586break;2587case Builtin::BIto_global:2588case Builtin::BIto_local:2589case Builtin::BIto_private:2590if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))2591return ExprError();2592break;2593// OpenCL v2.0, s6.13.17 - Enqueue kernel functions.2594case Builtin::BIenqueue_kernel:2595if (OpenCL().checkBuiltinEnqueueKernel(TheCall))2596return ExprError();2597break;2598case Builtin::BIget_kernel_work_group_size:2599case Builtin::BIget_kernel_preferred_work_group_size_multiple:2600if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))2601return ExprError();2602break;2603case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:2604case Builtin::BIget_kernel_sub_group_count_for_ndrange:2605if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))2606return ExprError();2607break;2608case Builtin::BI__builtin_os_log_format:2609Cleanup.setExprNeedsCleanups(true);2610[[fallthrough]];2611case Builtin::BI__builtin_os_log_format_buffer_size:2612if (BuiltinOSLogFormat(TheCall))2613return ExprError();2614break;2615case Builtin::BI__builtin_frame_address:2616case Builtin::BI__builtin_return_address: {2617if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))2618return ExprError();26192620// -Wframe-address warning if non-zero passed to builtin2621// return/frame address.2622Expr::EvalResult Result;2623if (!TheCall->getArg(0)->isValueDependent() &&2624TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&2625Result.Val.getInt() != 0)2626Diag(TheCall->getBeginLoc(), diag::warn_frame_address)2627<< ((BuiltinID == Builtin::BI__builtin_return_address)2628? "__builtin_return_address"2629: "__builtin_frame_address")2630<< TheCall->getSourceRange();2631break;2632}26332634case Builtin::BI__builtin_nondeterministic_value: {2635if (BuiltinNonDeterministicValue(TheCall))2636return ExprError();2637break;2638}26392640// __builtin_elementwise_abs restricts the element type to signed integers or2641// floating point types only.2642case Builtin::BI__builtin_elementwise_abs: {2643if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))2644return ExprError();26452646QualType ArgTy = TheCall->getArg(0)->getType();2647QualType EltTy = ArgTy;26482649if (auto *VecTy = EltTy->getAs<VectorType>())2650EltTy = VecTy->getElementType();2651if (EltTy->isUnsignedIntegerType()) {2652Diag(TheCall->getArg(0)->getBeginLoc(),2653diag::err_builtin_invalid_arg_type)2654<< 1 << /* signed integer or float ty*/ 3 << ArgTy;2655return ExprError();2656}2657break;2658}26592660// These builtins restrict the element type to floating point2661// types only.2662case Builtin::BI__builtin_elementwise_acos:2663case Builtin::BI__builtin_elementwise_asin:2664case Builtin::BI__builtin_elementwise_atan:2665case Builtin::BI__builtin_elementwise_ceil:2666case Builtin::BI__builtin_elementwise_cos:2667case Builtin::BI__builtin_elementwise_cosh:2668case Builtin::BI__builtin_elementwise_exp:2669case Builtin::BI__builtin_elementwise_exp2:2670case Builtin::BI__builtin_elementwise_floor:2671case Builtin::BI__builtin_elementwise_log:2672case Builtin::BI__builtin_elementwise_log2:2673case Builtin::BI__builtin_elementwise_log10:2674case Builtin::BI__builtin_elementwise_roundeven:2675case Builtin::BI__builtin_elementwise_round:2676case Builtin::BI__builtin_elementwise_rint:2677case Builtin::BI__builtin_elementwise_nearbyint:2678case Builtin::BI__builtin_elementwise_sin:2679case Builtin::BI__builtin_elementwise_sinh:2680case Builtin::BI__builtin_elementwise_sqrt:2681case Builtin::BI__builtin_elementwise_tan:2682case Builtin::BI__builtin_elementwise_tanh:2683case Builtin::BI__builtin_elementwise_trunc:2684case Builtin::BI__builtin_elementwise_canonicalize: {2685if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))2686return ExprError();26872688QualType ArgTy = TheCall->getArg(0)->getType();2689if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),2690ArgTy, 1))2691return ExprError();2692break;2693}2694case Builtin::BI__builtin_elementwise_fma: {2695if (BuiltinElementwiseTernaryMath(TheCall))2696return ExprError();2697break;2698}26992700// These builtins restrict the element type to floating point2701// types only, and take in two arguments.2702case Builtin::BI__builtin_elementwise_pow: {2703if (BuiltinElementwiseMath(TheCall))2704return ExprError();27052706QualType ArgTy = TheCall->getArg(0)->getType();2707if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),2708ArgTy, 1) ||2709checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),2710ArgTy, 2))2711return ExprError();2712break;2713}27142715// These builtins restrict the element type to integer2716// types only.2717case Builtin::BI__builtin_elementwise_add_sat:2718case Builtin::BI__builtin_elementwise_sub_sat: {2719if (BuiltinElementwiseMath(TheCall))2720return ExprError();27212722const Expr *Arg = TheCall->getArg(0);2723QualType ArgTy = Arg->getType();2724QualType EltTy = ArgTy;27252726if (auto *VecTy = EltTy->getAs<VectorType>())2727EltTy = VecTy->getElementType();27282729if (!EltTy->isIntegerType()) {2730Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)2731<< 1 << /* integer ty */ 6 << ArgTy;2732return ExprError();2733}2734break;2735}27362737case Builtin::BI__builtin_elementwise_min:2738case Builtin::BI__builtin_elementwise_max:2739if (BuiltinElementwiseMath(TheCall))2740return ExprError();2741break;27422743case Builtin::BI__builtin_elementwise_bitreverse: {2744if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))2745return ExprError();27462747const Expr *Arg = TheCall->getArg(0);2748QualType ArgTy = Arg->getType();2749QualType EltTy = ArgTy;27502751if (auto *VecTy = EltTy->getAs<VectorType>())2752EltTy = VecTy->getElementType();27532754if (!EltTy->isIntegerType()) {2755Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)2756<< 1 << /* integer ty */ 6 << ArgTy;2757return ExprError();2758}2759break;2760}27612762case Builtin::BI__builtin_elementwise_copysign: {2763if (checkArgCount(TheCall, 2))2764return ExprError();27652766ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));2767ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));2768if (Magnitude.isInvalid() || Sign.isInvalid())2769return ExprError();27702771QualType MagnitudeTy = Magnitude.get()->getType();2772QualType SignTy = Sign.get()->getType();2773if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),2774MagnitudeTy, 1) ||2775checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),2776SignTy, 2)) {2777return ExprError();2778}27792780if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {2781return Diag(Sign.get()->getBeginLoc(),2782diag::err_typecheck_call_different_arg_types)2783<< MagnitudeTy << SignTy;2784}27852786TheCall->setArg(0, Magnitude.get());2787TheCall->setArg(1, Sign.get());2788TheCall->setType(Magnitude.get()->getType());2789break;2790}2791case Builtin::BI__builtin_reduce_max:2792case Builtin::BI__builtin_reduce_min: {2793if (PrepareBuiltinReduceMathOneArgCall(TheCall))2794return ExprError();27952796const Expr *Arg = TheCall->getArg(0);2797const auto *TyA = Arg->getType()->getAs<VectorType>();27982799QualType ElTy;2800if (TyA)2801ElTy = TyA->getElementType();2802else if (Arg->getType()->isSizelessVectorType())2803ElTy = Arg->getType()->getSizelessVectorEltType(Context);28042805if (ElTy.isNull()) {2806Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)2807<< 1 << /* vector ty*/ 4 << Arg->getType();2808return ExprError();2809}28102811TheCall->setType(ElTy);2812break;2813}28142815// These builtins support vectors of integers only.2816// TODO: ADD/MUL should support floating-point types.2817case Builtin::BI__builtin_reduce_add:2818case Builtin::BI__builtin_reduce_mul:2819case Builtin::BI__builtin_reduce_xor:2820case Builtin::BI__builtin_reduce_or:2821case Builtin::BI__builtin_reduce_and: {2822if (PrepareBuiltinReduceMathOneArgCall(TheCall))2823return ExprError();28242825const Expr *Arg = TheCall->getArg(0);2826const auto *TyA = Arg->getType()->getAs<VectorType>();28272828QualType ElTy;2829if (TyA)2830ElTy = TyA->getElementType();2831else if (Arg->getType()->isSizelessVectorType())2832ElTy = Arg->getType()->getSizelessVectorEltType(Context);28332834if (ElTy.isNull() || !ElTy->isIntegerType()) {2835Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)2836<< 1 << /* vector of integers */ 6 << Arg->getType();2837return ExprError();2838}28392840TheCall->setType(ElTy);2841break;2842}28432844case Builtin::BI__builtin_matrix_transpose:2845return BuiltinMatrixTranspose(TheCall, TheCallResult);28462847case Builtin::BI__builtin_matrix_column_major_load:2848return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);28492850case Builtin::BI__builtin_matrix_column_major_store:2851return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);28522853case Builtin::BI__builtin_verbose_trap:2854if (!checkBuiltinVerboseTrap(TheCall, *this))2855return ExprError();2856break;28572858case Builtin::BI__builtin_get_device_side_mangled_name: {2859auto Check = [](CallExpr *TheCall) {2860if (TheCall->getNumArgs() != 1)2861return false;2862auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());2863if (!DRE)2864return false;2865auto *D = DRE->getDecl();2866if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))2867return false;2868return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||2869D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();2870};2871if (!Check(TheCall)) {2872Diag(TheCall->getBeginLoc(),2873diag::err_hip_invalid_args_builtin_mangled_name);2874return ExprError();2875}2876break;2877}2878case Builtin::BI__builtin_popcountg:2879if (BuiltinPopcountg(*this, TheCall))2880return ExprError();2881break;2882case Builtin::BI__builtin_clzg:2883case Builtin::BI__builtin_ctzg:2884if (BuiltinCountZeroBitsGeneric(*this, TheCall))2885return ExprError();2886break;28872888case Builtin::BI__builtin_allow_runtime_check: {2889Expr *Arg = TheCall->getArg(0);2890// Check if the argument is a string literal.2891if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) {2892Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)2893<< Arg->getSourceRange();2894return ExprError();2895}2896break;2897}2898}28992900if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))2901return ExprError();29022903// Since the target specific builtins for each arch overlap, only check those2904// of the arch we are compiling for.2905if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {2906if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {2907assert(Context.getAuxTargetInfo() &&2908"Aux Target Builtin, but not an aux target?");29092910if (CheckTSBuiltinFunctionCall(2911*Context.getAuxTargetInfo(),2912Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))2913return ExprError();2914} else {2915if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,2916TheCall))2917return ExprError();2918}2919}29202921return TheCallResult;2922}29232924bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {2925llvm::APSInt Result;2926// We can't check the value of a dependent argument.2927Expr *Arg = TheCall->getArg(ArgNum);2928if (Arg->isTypeDependent() || Arg->isValueDependent())2929return false;29302931// Check constant-ness first.2932if (BuiltinConstantArg(TheCall, ArgNum, Result))2933return true;29342935// Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.2936if (Result.isShiftedMask() || (~Result).isShiftedMask())2937return false;29382939return Diag(TheCall->getBeginLoc(),2940diag::err_argument_not_contiguous_bit_field)2941<< ArgNum << Arg->getSourceRange();2942}29432944bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,2945bool IsVariadic, FormatStringInfo *FSI) {2946if (Format->getFirstArg() == 0)2947FSI->ArgPassingKind = FAPK_VAList;2948else if (IsVariadic)2949FSI->ArgPassingKind = FAPK_Variadic;2950else2951FSI->ArgPassingKind = FAPK_Fixed;2952FSI->FormatIdx = Format->getFormatIdx() - 1;2953FSI->FirstDataArg =2954FSI->ArgPassingKind == FAPK_VAList ? 0 : Format->getFirstArg() - 1;29552956// The way the format attribute works in GCC, the implicit this argument2957// of member functions is counted. However, it doesn't appear in our own2958// lists, so decrement format_idx in that case.2959if (IsCXXMember) {2960if(FSI->FormatIdx == 0)2961return false;2962--FSI->FormatIdx;2963if (FSI->FirstDataArg != 0)2964--FSI->FirstDataArg;2965}2966return true;2967}29682969/// Checks if a the given expression evaluates to null.2970///2971/// Returns true if the value evaluates to null.2972static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {2973// Treat (smart) pointers constructed from nullptr as null, whether we can2974// const-evaluate them or not.2975// This must happen first: the smart pointer expr might have _Nonnull type!2976if (isa<CXXNullPtrLiteralExpr>(2977IgnoreExprNodes(Expr, IgnoreImplicitAsWrittenSingleStep,2978IgnoreElidableImplicitConstructorSingleStep)))2979return true;29802981// If the expression has non-null type, it doesn't evaluate to null.2982if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {2983if (*nullability == NullabilityKind::NonNull)2984return false;2985}29862987// As a special case, transparent unions initialized with zero are2988// considered null for the purposes of the nonnull attribute.2989if (const RecordType *UT = Expr->getType()->getAsUnionType();2990UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {2991if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))2992if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))2993Expr = ILE->getInit(0);2994}29952996bool Result;2997return (!Expr->isValueDependent() &&2998Expr->EvaluateAsBooleanCondition(Result, S.Context) &&2999!Result);3000}30013002static void CheckNonNullArgument(Sema &S,3003const Expr *ArgExpr,3004SourceLocation CallSiteLoc) {3005if (CheckNonNullExpr(S, ArgExpr))3006S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,3007S.PDiag(diag::warn_null_arg)3008<< ArgExpr->getSourceRange());3009}30103011/// Determine whether the given type has a non-null nullability annotation.3012static bool isNonNullType(QualType type) {3013if (auto nullability = type->getNullability())3014return *nullability == NullabilityKind::NonNull;30153016return false;3017}30183019static void CheckNonNullArguments(Sema &S,3020const NamedDecl *FDecl,3021const FunctionProtoType *Proto,3022ArrayRef<const Expr *> Args,3023SourceLocation CallSiteLoc) {3024assert((FDecl || Proto) && "Need a function declaration or prototype");30253026// Already checked by constant evaluator.3027if (S.isConstantEvaluatedContext())3028return;3029// Check the attributes attached to the method/function itself.3030llvm::SmallBitVector NonNullArgs;3031if (FDecl) {3032// Handle the nonnull attribute on the function/method declaration itself.3033for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {3034if (!NonNull->args_size()) {3035// Easy case: all pointer arguments are nonnull.3036for (const auto *Arg : Args)3037if (S.isValidPointerAttrType(Arg->getType()))3038CheckNonNullArgument(S, Arg, CallSiteLoc);3039return;3040}30413042for (const ParamIdx &Idx : NonNull->args()) {3043unsigned IdxAST = Idx.getASTIndex();3044if (IdxAST >= Args.size())3045continue;3046if (NonNullArgs.empty())3047NonNullArgs.resize(Args.size());3048NonNullArgs.set(IdxAST);3049}3050}3051}30523053if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {3054// Handle the nonnull attribute on the parameters of the3055// function/method.3056ArrayRef<ParmVarDecl*> parms;3057if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))3058parms = FD->parameters();3059else3060parms = cast<ObjCMethodDecl>(FDecl)->parameters();30613062unsigned ParamIndex = 0;3063for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();3064I != E; ++I, ++ParamIndex) {3065const ParmVarDecl *PVD = *I;3066if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {3067if (NonNullArgs.empty())3068NonNullArgs.resize(Args.size());30693070NonNullArgs.set(ParamIndex);3071}3072}3073} else {3074// If we have a non-function, non-method declaration but no3075// function prototype, try to dig out the function prototype.3076if (!Proto) {3077if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {3078QualType type = VD->getType().getNonReferenceType();3079if (auto pointerType = type->getAs<PointerType>())3080type = pointerType->getPointeeType();3081else if (auto blockType = type->getAs<BlockPointerType>())3082type = blockType->getPointeeType();3083// FIXME: data member pointers?30843085// Dig out the function prototype, if there is one.3086Proto = type->getAs<FunctionProtoType>();3087}3088}30893090// Fill in non-null argument information from the nullability3091// information on the parameter types (if we have them).3092if (Proto) {3093unsigned Index = 0;3094for (auto paramType : Proto->getParamTypes()) {3095if (isNonNullType(paramType)) {3096if (NonNullArgs.empty())3097NonNullArgs.resize(Args.size());30983099NonNullArgs.set(Index);3100}31013102++Index;3103}3104}3105}31063107// Check for non-null arguments.3108for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();3109ArgIndex != ArgIndexEnd; ++ArgIndex) {3110if (NonNullArgs[ArgIndex])3111CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());3112}3113}31143115void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,3116StringRef ParamName, QualType ArgTy,3117QualType ParamTy) {31183119// If a function accepts a pointer or reference type3120if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())3121return;31223123// If the parameter is a pointer type, get the pointee type for the3124// argument too. If the parameter is a reference type, don't try to get3125// the pointee type for the argument.3126if (ParamTy->isPointerType())3127ArgTy = ArgTy->getPointeeType();31283129// Remove reference or pointer3130ParamTy = ParamTy->getPointeeType();31313132// Find expected alignment, and the actual alignment of the passed object.3133// getTypeAlignInChars requires complete types3134if (ArgTy.isNull() || ParamTy->isDependentType() ||3135ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||3136ParamTy->isUndeducedType() || ArgTy->isUndeducedType())3137return;31383139CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);3140CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);31413142// If the argument is less aligned than the parameter, there is a3143// potential alignment issue.3144if (ArgAlign < ParamAlign)3145Diag(Loc, diag::warn_param_mismatched_alignment)3146<< (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()3147<< ParamName << (FDecl != nullptr) << FDecl;3148}31493150void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,3151const Expr *ThisArg, ArrayRef<const Expr *> Args,3152bool IsMemberFunction, SourceLocation Loc,3153SourceRange Range, VariadicCallType CallType) {3154// FIXME: We should check as much as we can in the template definition.3155if (CurContext->isDependentContext())3156return;31573158// Printf and scanf checking.3159llvm::SmallBitVector CheckedVarArgs;3160if (FDecl) {3161for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {3162// Only create vector if there are format attributes.3163CheckedVarArgs.resize(Args.size());31643165CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,3166CheckedVarArgs);3167}3168}31693170// Refuse POD arguments that weren't caught by the format string3171// checks above.3172auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);3173if (CallType != VariadicDoesNotApply &&3174(!FD || FD->getBuiltinID() != Builtin::BI__noop)) {3175unsigned NumParams = Proto ? Proto->getNumParams()3176: isa_and_nonnull<FunctionDecl>(FDecl)3177? cast<FunctionDecl>(FDecl)->getNumParams()3178: isa_and_nonnull<ObjCMethodDecl>(FDecl)3179? cast<ObjCMethodDecl>(FDecl)->param_size()3180: 0;31813182for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {3183// Args[ArgIdx] can be null in malformed code.3184if (const Expr *Arg = Args[ArgIdx]) {3185if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])3186checkVariadicArgument(Arg, CallType);3187}3188}3189}31903191if (FDecl || Proto) {3192CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);31933194// Type safety checking.3195if (FDecl) {3196for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())3197CheckArgumentWithTypeTag(I, Args, Loc);3198}3199}32003201// Check that passed arguments match the alignment of original arguments.3202// Try to get the missing prototype from the declaration.3203if (!Proto && FDecl) {3204const auto *FT = FDecl->getFunctionType();3205if (isa_and_nonnull<FunctionProtoType>(FT))3206Proto = cast<FunctionProtoType>(FDecl->getFunctionType());3207}3208if (Proto) {3209// For variadic functions, we may have more args than parameters.3210// For some K&R functions, we may have less args than parameters.3211const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());3212bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();3213bool IsScalableArg = false;3214for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {3215// Args[ArgIdx] can be null in malformed code.3216if (const Expr *Arg = Args[ArgIdx]) {3217if (Arg->containsErrors())3218continue;32193220if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&3221FDecl->hasLinkage() &&3222FDecl->getFormalLinkage() != Linkage::Internal &&3223CallType == VariadicDoesNotApply)3224PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);32253226QualType ParamTy = Proto->getParamType(ArgIdx);3227if (ParamTy->isSizelessVectorType())3228IsScalableArg = true;3229QualType ArgTy = Arg->getType();3230CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),3231ArgTy, ParamTy);3232}3233}32343235// If the callee has an AArch64 SME attribute to indicate that it is an3236// __arm_streaming function, then the caller requires SME to be available.3237FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();3238if (ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask) {3239if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {3240llvm::StringMap<bool> CallerFeatureMap;3241Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);3242if (!CallerFeatureMap.contains("sme"))3243Diag(Loc, diag::err_sme_call_in_non_sme_target);3244} else if (!Context.getTargetInfo().hasFeature("sme")) {3245Diag(Loc, diag::err_sme_call_in_non_sme_target);3246}3247}32483249// If the call requires a streaming-mode change and has scalable vector3250// arguments or return values, then warn the user that the streaming and3251// non-streaming vector lengths may be different.3252const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);3253if (CallerFD && (!FD || !FD->getBuiltinID()) &&3254(IsScalableArg || IsScalableRet)) {3255bool IsCalleeStreaming =3256ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;3257bool IsCalleeStreamingCompatible =3258ExtInfo.AArch64SMEAttributes &3259FunctionType::SME_PStateSMCompatibleMask;3260SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);3261if (!IsCalleeStreamingCompatible &&3262(CallerFnType == SemaARM::ArmStreamingCompatible ||3263((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {3264if (IsScalableArg)3265Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)3266<< /*IsArg=*/true;3267if (IsScalableRet)3268Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)3269<< /*IsArg=*/false;3270}3271}32723273FunctionType::ArmStateValue CalleeArmZAState =3274FunctionType::getArmZAState(ExtInfo.AArch64SMEAttributes);3275FunctionType::ArmStateValue CalleeArmZT0State =3276FunctionType::getArmZT0State(ExtInfo.AArch64SMEAttributes);3277if (CalleeArmZAState != FunctionType::ARM_None ||3278CalleeArmZT0State != FunctionType::ARM_None) {3279bool CallerHasZAState = false;3280bool CallerHasZT0State = false;3281if (CallerFD) {3282auto *Attr = CallerFD->getAttr<ArmNewAttr>();3283if (Attr && Attr->isNewZA())3284CallerHasZAState = true;3285if (Attr && Attr->isNewZT0())3286CallerHasZT0State = true;3287if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {3288CallerHasZAState |=3289FunctionType::getArmZAState(3290FPT->getExtProtoInfo().AArch64SMEAttributes) !=3291FunctionType::ARM_None;3292CallerHasZT0State |=3293FunctionType::getArmZT0State(3294FPT->getExtProtoInfo().AArch64SMEAttributes) !=3295FunctionType::ARM_None;3296}3297}32983299if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)3300Diag(Loc, diag::err_sme_za_call_no_za_state);33013302if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)3303Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);33043305if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&3306CalleeArmZT0State != FunctionType::ARM_None) {3307Diag(Loc, diag::err_sme_unimplemented_za_save_restore);3308Diag(Loc, diag::note_sme_use_preserves_za);3309}3310}3311}33123313if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {3314auto *AA = FDecl->getAttr<AllocAlignAttr>();3315const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];3316if (!Arg->isValueDependent()) {3317Expr::EvalResult Align;3318if (Arg->EvaluateAsInt(Align, Context)) {3319const llvm::APSInt &I = Align.Val.getInt();3320if (!I.isPowerOf2())3321Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)3322<< Arg->getSourceRange();33233324if (I > Sema::MaximumAlignment)3325Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)3326<< Arg->getSourceRange() << Sema::MaximumAlignment;3327}3328}3329}33303331if (FD)3332diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);3333}33343335void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {3336if (ConceptDecl *Decl = AutoT->getTypeConstraintConcept()) {3337DiagnoseUseOfDecl(Decl, Loc);3338}3339}33403341void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,3342ArrayRef<const Expr *> Args,3343const FunctionProtoType *Proto,3344SourceLocation Loc) {3345VariadicCallType CallType =3346Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;33473348auto *Ctor = cast<CXXConstructorDecl>(FDecl);3349CheckArgAlignment(3350Loc, FDecl, "'this'", Context.getPointerType(ThisType),3351Context.getPointerType(Ctor->getFunctionObjectParameterType()));33523353checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,3354Loc, SourceRange(), CallType);3355}33563357bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,3358const FunctionProtoType *Proto) {3359bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&3360isa<CXXMethodDecl>(FDecl);3361bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||3362IsMemberOperatorCall;3363VariadicCallType CallType = getVariadicCallType(FDecl, Proto,3364TheCall->getCallee());3365Expr** Args = TheCall->getArgs();3366unsigned NumArgs = TheCall->getNumArgs();33673368Expr *ImplicitThis = nullptr;3369if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {3370// If this is a call to a member operator, hide the first3371// argument from checkCall.3372// FIXME: Our choice of AST representation here is less than ideal.3373ImplicitThis = Args[0];3374++Args;3375--NumArgs;3376} else if (IsMemberFunction && !FDecl->isStatic() &&3377!FDecl->hasCXXExplicitFunctionObjectParameter())3378ImplicitThis =3379cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();33803381if (ImplicitThis) {3382// ImplicitThis may or may not be a pointer, depending on whether . or -> is3383// used.3384QualType ThisType = ImplicitThis->getType();3385if (!ThisType->isPointerType()) {3386assert(!ThisType->isReferenceType());3387ThisType = Context.getPointerType(ThisType);3388}33893390QualType ThisTypeFromDecl = Context.getPointerType(3391cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());33923393CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,3394ThisTypeFromDecl);3395}33963397checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),3398IsMemberFunction, TheCall->getRParenLoc(),3399TheCall->getCallee()->getSourceRange(), CallType);34003401IdentifierInfo *FnInfo = FDecl->getIdentifier();3402// None of the checks below are needed for functions that don't have3403// simple names (e.g., C++ conversion functions).3404if (!FnInfo)3405return false;34063407// Enforce TCB except for builtin calls, which are always allowed.3408if (FDecl->getBuiltinID() == 0)3409CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);34103411CheckAbsoluteValueFunction(TheCall, FDecl);3412CheckMaxUnsignedZero(TheCall, FDecl);3413CheckInfNaNFunction(TheCall, FDecl);34143415if (getLangOpts().ObjC)3416ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);34173418unsigned CMId = FDecl->getMemoryFunctionKind();34193420// Handle memory setting and copying functions.3421switch (CMId) {3422case 0:3423return false;3424case Builtin::BIstrlcpy: // fallthrough3425case Builtin::BIstrlcat:3426CheckStrlcpycatArguments(TheCall, FnInfo);3427break;3428case Builtin::BIstrncat:3429CheckStrncatArguments(TheCall, FnInfo);3430break;3431case Builtin::BIfree:3432CheckFreeArguments(TheCall);3433break;3434default:3435CheckMemaccessArguments(TheCall, CMId, FnInfo);3436}34373438return false;3439}34403441bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,3442const FunctionProtoType *Proto) {3443QualType Ty;3444if (const auto *V = dyn_cast<VarDecl>(NDecl))3445Ty = V->getType().getNonReferenceType();3446else if (const auto *F = dyn_cast<FieldDecl>(NDecl))3447Ty = F->getType().getNonReferenceType();3448else3449return false;34503451if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&3452!Ty->isFunctionProtoType())3453return false;34543455VariadicCallType CallType;3456if (!Proto || !Proto->isVariadic()) {3457CallType = VariadicDoesNotApply;3458} else if (Ty->isBlockPointerType()) {3459CallType = VariadicBlock;3460} else { // Ty->isFunctionPointerType()3461CallType = VariadicFunction;3462}34633464checkCall(NDecl, Proto, /*ThisArg=*/nullptr,3465llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),3466/*IsMemberFunction=*/false, TheCall->getRParenLoc(),3467TheCall->getCallee()->getSourceRange(), CallType);34683469return false;3470}34713472bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {3473VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,3474TheCall->getCallee());3475checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,3476llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),3477/*IsMemberFunction=*/false, TheCall->getRParenLoc(),3478TheCall->getCallee()->getSourceRange(), CallType);34793480return false;3481}34823483static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {3484if (!llvm::isValidAtomicOrderingCABI(Ordering))3485return false;34863487auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;3488switch (Op) {3489case AtomicExpr::AO__c11_atomic_init:3490case AtomicExpr::AO__opencl_atomic_init:3491llvm_unreachable("There is no ordering argument for an init");34923493case AtomicExpr::AO__c11_atomic_load:3494case AtomicExpr::AO__opencl_atomic_load:3495case AtomicExpr::AO__hip_atomic_load:3496case AtomicExpr::AO__atomic_load_n:3497case AtomicExpr::AO__atomic_load:3498case AtomicExpr::AO__scoped_atomic_load_n:3499case AtomicExpr::AO__scoped_atomic_load:3500return OrderingCABI != llvm::AtomicOrderingCABI::release &&3501OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;35023503case AtomicExpr::AO__c11_atomic_store:3504case AtomicExpr::AO__opencl_atomic_store:3505case AtomicExpr::AO__hip_atomic_store:3506case AtomicExpr::AO__atomic_store:3507case AtomicExpr::AO__atomic_store_n:3508case AtomicExpr::AO__scoped_atomic_store:3509case AtomicExpr::AO__scoped_atomic_store_n:3510return OrderingCABI != llvm::AtomicOrderingCABI::consume &&3511OrderingCABI != llvm::AtomicOrderingCABI::acquire &&3512OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;35133514default:3515return true;3516}3517}35183519ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,3520AtomicExpr::AtomicOp Op) {3521CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());3522DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());3523MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};3524return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},3525DRE->getSourceRange(), TheCall->getRParenLoc(), Args,3526Op);3527}35283529ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,3530SourceLocation RParenLoc, MultiExprArg Args,3531AtomicExpr::AtomicOp Op,3532AtomicArgumentOrder ArgOrder) {3533// All the non-OpenCL operations take one of the following forms.3534// The OpenCL operations take the __c11 forms with one extra argument for3535// synchronization scope.3536enum {3537// C __c11_atomic_init(A *, C)3538Init,35393540// C __c11_atomic_load(A *, int)3541Load,35423543// void __atomic_load(A *, CP, int)3544LoadCopy,35453546// void __atomic_store(A *, CP, int)3547Copy,35483549// C __c11_atomic_add(A *, M, int)3550Arithmetic,35513552// C __atomic_exchange_n(A *, CP, int)3553Xchg,35543555// void __atomic_exchange(A *, C *, CP, int)3556GNUXchg,35573558// bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)3559C11CmpXchg,35603561// bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)3562GNUCmpXchg3563} Form = Init;35643565const unsigned NumForm = GNUCmpXchg + 1;3566const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };3567const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };3568// where:3569// C is an appropriate type,3570// A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,3571// CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,3572// M is C if C is an integer, and ptrdiff_t if C is a pointer, and3573// the int parameters are for orderings.35743575static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm3576&& sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,3577"need to update code for modified forms");3578static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&3579AtomicExpr::AO__atomic_xor_fetch + 1 ==3580AtomicExpr::AO__c11_atomic_compare_exchange_strong,3581"need to update code for modified C11 atomics");3582bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&3583Op <= AtomicExpr::AO__opencl_atomic_store;3584bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&3585Op <= AtomicExpr::AO__hip_atomic_store;3586bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&3587Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;3588bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&3589Op <= AtomicExpr::AO__c11_atomic_store) ||3590IsOpenCL;3591bool IsN = Op == AtomicExpr::AO__atomic_load_n ||3592Op == AtomicExpr::AO__atomic_store_n ||3593Op == AtomicExpr::AO__atomic_exchange_n ||3594Op == AtomicExpr::AO__atomic_compare_exchange_n ||3595Op == AtomicExpr::AO__scoped_atomic_load_n ||3596Op == AtomicExpr::AO__scoped_atomic_store_n ||3597Op == AtomicExpr::AO__scoped_atomic_exchange_n ||3598Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;3599// Bit mask for extra allowed value types other than integers for atomic3600// arithmetic operations. Add/sub allow pointer and floating point. Min/max3601// allow floating point.3602enum ArithOpExtraValueType {3603AOEVT_None = 0,3604AOEVT_Pointer = 1,3605AOEVT_FP = 2,3606};3607unsigned ArithAllows = AOEVT_None;36083609switch (Op) {3610case AtomicExpr::AO__c11_atomic_init:3611case AtomicExpr::AO__opencl_atomic_init:3612Form = Init;3613break;36143615case AtomicExpr::AO__c11_atomic_load:3616case AtomicExpr::AO__opencl_atomic_load:3617case AtomicExpr::AO__hip_atomic_load:3618case AtomicExpr::AO__atomic_load_n:3619case AtomicExpr::AO__scoped_atomic_load_n:3620Form = Load;3621break;36223623case AtomicExpr::AO__atomic_load:3624case AtomicExpr::AO__scoped_atomic_load:3625Form = LoadCopy;3626break;36273628case AtomicExpr::AO__c11_atomic_store:3629case AtomicExpr::AO__opencl_atomic_store:3630case AtomicExpr::AO__hip_atomic_store:3631case AtomicExpr::AO__atomic_store:3632case AtomicExpr::AO__atomic_store_n:3633case AtomicExpr::AO__scoped_atomic_store:3634case AtomicExpr::AO__scoped_atomic_store_n:3635Form = Copy;3636break;3637case AtomicExpr::AO__atomic_fetch_add:3638case AtomicExpr::AO__atomic_fetch_sub:3639case AtomicExpr::AO__atomic_add_fetch:3640case AtomicExpr::AO__atomic_sub_fetch:3641case AtomicExpr::AO__scoped_atomic_fetch_add:3642case AtomicExpr::AO__scoped_atomic_fetch_sub:3643case AtomicExpr::AO__scoped_atomic_add_fetch:3644case AtomicExpr::AO__scoped_atomic_sub_fetch:3645case AtomicExpr::AO__c11_atomic_fetch_add:3646case AtomicExpr::AO__c11_atomic_fetch_sub:3647case AtomicExpr::AO__opencl_atomic_fetch_add:3648case AtomicExpr::AO__opencl_atomic_fetch_sub:3649case AtomicExpr::AO__hip_atomic_fetch_add:3650case AtomicExpr::AO__hip_atomic_fetch_sub:3651ArithAllows = AOEVT_Pointer | AOEVT_FP;3652Form = Arithmetic;3653break;3654case AtomicExpr::AO__atomic_fetch_max:3655case AtomicExpr::AO__atomic_fetch_min:3656case AtomicExpr::AO__atomic_max_fetch:3657case AtomicExpr::AO__atomic_min_fetch:3658case AtomicExpr::AO__scoped_atomic_fetch_max:3659case AtomicExpr::AO__scoped_atomic_fetch_min:3660case AtomicExpr::AO__scoped_atomic_max_fetch:3661case AtomicExpr::AO__scoped_atomic_min_fetch:3662case AtomicExpr::AO__c11_atomic_fetch_max:3663case AtomicExpr::AO__c11_atomic_fetch_min:3664case AtomicExpr::AO__opencl_atomic_fetch_max:3665case AtomicExpr::AO__opencl_atomic_fetch_min:3666case AtomicExpr::AO__hip_atomic_fetch_max:3667case AtomicExpr::AO__hip_atomic_fetch_min:3668ArithAllows = AOEVT_FP;3669Form = Arithmetic;3670break;3671case AtomicExpr::AO__c11_atomic_fetch_and:3672case AtomicExpr::AO__c11_atomic_fetch_or:3673case AtomicExpr::AO__c11_atomic_fetch_xor:3674case AtomicExpr::AO__hip_atomic_fetch_and:3675case AtomicExpr::AO__hip_atomic_fetch_or:3676case AtomicExpr::AO__hip_atomic_fetch_xor:3677case AtomicExpr::AO__c11_atomic_fetch_nand:3678case AtomicExpr::AO__opencl_atomic_fetch_and:3679case AtomicExpr::AO__opencl_atomic_fetch_or:3680case AtomicExpr::AO__opencl_atomic_fetch_xor:3681case AtomicExpr::AO__atomic_fetch_and:3682case AtomicExpr::AO__atomic_fetch_or:3683case AtomicExpr::AO__atomic_fetch_xor:3684case AtomicExpr::AO__atomic_fetch_nand:3685case AtomicExpr::AO__atomic_and_fetch:3686case AtomicExpr::AO__atomic_or_fetch:3687case AtomicExpr::AO__atomic_xor_fetch:3688case AtomicExpr::AO__atomic_nand_fetch:3689case AtomicExpr::AO__scoped_atomic_fetch_and:3690case AtomicExpr::AO__scoped_atomic_fetch_or:3691case AtomicExpr::AO__scoped_atomic_fetch_xor:3692case AtomicExpr::AO__scoped_atomic_fetch_nand:3693case AtomicExpr::AO__scoped_atomic_and_fetch:3694case AtomicExpr::AO__scoped_atomic_or_fetch:3695case AtomicExpr::AO__scoped_atomic_xor_fetch:3696case AtomicExpr::AO__scoped_atomic_nand_fetch:3697Form = Arithmetic;3698break;36993700case AtomicExpr::AO__c11_atomic_exchange:3701case AtomicExpr::AO__hip_atomic_exchange:3702case AtomicExpr::AO__opencl_atomic_exchange:3703case AtomicExpr::AO__atomic_exchange_n:3704case AtomicExpr::AO__scoped_atomic_exchange_n:3705Form = Xchg;3706break;37073708case AtomicExpr::AO__atomic_exchange:3709case AtomicExpr::AO__scoped_atomic_exchange:3710Form = GNUXchg;3711break;37123713case AtomicExpr::AO__c11_atomic_compare_exchange_strong:3714case AtomicExpr::AO__c11_atomic_compare_exchange_weak:3715case AtomicExpr::AO__hip_atomic_compare_exchange_strong:3716case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:3717case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:3718case AtomicExpr::AO__hip_atomic_compare_exchange_weak:3719Form = C11CmpXchg;3720break;37213722case AtomicExpr::AO__atomic_compare_exchange:3723case AtomicExpr::AO__atomic_compare_exchange_n:3724case AtomicExpr::AO__scoped_atomic_compare_exchange:3725case AtomicExpr::AO__scoped_atomic_compare_exchange_n:3726Form = GNUCmpXchg;3727break;3728}37293730unsigned AdjustedNumArgs = NumArgs[Form];3731if ((IsOpenCL || IsHIP || IsScoped) &&3732Op != AtomicExpr::AO__opencl_atomic_init)3733++AdjustedNumArgs;3734// Check we have the right number of arguments.3735if (Args.size() < AdjustedNumArgs) {3736Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)3737<< 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())3738<< /*is non object*/ 0 << ExprRange;3739return ExprError();3740} else if (Args.size() > AdjustedNumArgs) {3741Diag(Args[AdjustedNumArgs]->getBeginLoc(),3742diag::err_typecheck_call_too_many_args)3743<< 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())3744<< /*is non object*/ 0 << ExprRange;3745return ExprError();3746}37473748// Inspect the first argument of the atomic operation.3749Expr *Ptr = Args[0];3750ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);3751if (ConvertedPtr.isInvalid())3752return ExprError();37533754Ptr = ConvertedPtr.get();3755const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();3756if (!pointerType) {3757Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)3758<< Ptr->getType() << 0 << Ptr->getSourceRange();3759return ExprError();3760}37613762// For a __c11 builtin, this should be a pointer to an _Atomic type.3763QualType AtomTy = pointerType->getPointeeType(); // 'A'3764QualType ValType = AtomTy; // 'C'3765if (IsC11) {3766if (!AtomTy->isAtomicType()) {3767Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)3768<< Ptr->getType() << Ptr->getSourceRange();3769return ExprError();3770}3771if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||3772AtomTy.getAddressSpace() == LangAS::opencl_constant) {3773Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)3774<< (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()3775<< Ptr->getSourceRange();3776return ExprError();3777}3778ValType = AtomTy->castAs<AtomicType>()->getValueType();3779} else if (Form != Load && Form != LoadCopy) {3780if (ValType.isConstQualified()) {3781Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)3782<< Ptr->getType() << Ptr->getSourceRange();3783return ExprError();3784}3785}37863787// Pointer to object of size zero is not allowed.3788if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,3789diag::err_incomplete_type))3790return ExprError();3791if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {3792Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)3793<< Ptr->getType() << 1 << Ptr->getSourceRange();3794return ExprError();3795}37963797// For an arithmetic operation, the implied arithmetic must be well-formed.3798if (Form == Arithmetic) {3799// GCC does not enforce these rules for GNU atomics, but we do to help catch3800// trivial type errors.3801auto IsAllowedValueType = [&](QualType ValType,3802unsigned AllowedType) -> bool {3803if (ValType->isIntegerType())3804return true;3805if (ValType->isPointerType())3806return AllowedType & AOEVT_Pointer;3807if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))3808return false;3809// LLVM Parser does not allow atomicrmw with x86_fp80 type.3810if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&3811&Context.getTargetInfo().getLongDoubleFormat() ==3812&llvm::APFloat::x87DoubleExtended())3813return false;3814return true;3815};3816if (!IsAllowedValueType(ValType, ArithAllows)) {3817auto DID = ArithAllows & AOEVT_FP3818? (ArithAllows & AOEVT_Pointer3819? diag::err_atomic_op_needs_atomic_int_ptr_or_fp3820: diag::err_atomic_op_needs_atomic_int_or_fp)3821: diag::err_atomic_op_needs_atomic_int;3822Diag(ExprRange.getBegin(), DID)3823<< IsC11 << Ptr->getType() << Ptr->getSourceRange();3824return ExprError();3825}3826if (IsC11 && ValType->isPointerType() &&3827RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),3828diag::err_incomplete_type)) {3829return ExprError();3830}3831} else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {3832// For __atomic_*_n operations, the value type must be a scalar integral or3833// pointer type which is 1, 2, 4, 8 or 16 bytes in length.3834Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)3835<< IsC11 << Ptr->getType() << Ptr->getSourceRange();3836return ExprError();3837}38383839if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&3840!AtomTy->isScalarType()) {3841// For GNU atomics, require a trivially-copyable type. This is not part of3842// the GNU atomics specification but we enforce it for consistency with3843// other atomics which generally all require a trivially-copyable type. This3844// is because atomics just copy bits.3845Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)3846<< Ptr->getType() << Ptr->getSourceRange();3847return ExprError();3848}38493850switch (ValType.getObjCLifetime()) {3851case Qualifiers::OCL_None:3852case Qualifiers::OCL_ExplicitNone:3853// okay3854break;38553856case Qualifiers::OCL_Weak:3857case Qualifiers::OCL_Strong:3858case Qualifiers::OCL_Autoreleasing:3859// FIXME: Can this happen? By this point, ValType should be known3860// to be trivially copyable.3861Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)3862<< ValType << Ptr->getSourceRange();3863return ExprError();3864}38653866// All atomic operations have an overload which takes a pointer to a volatile3867// 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself3868// into the result or the other operands. Similarly atomic_load takes a3869// pointer to a const 'A'.3870ValType.removeLocalVolatile();3871ValType.removeLocalConst();3872QualType ResultType = ValType;3873if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||3874Form == Init)3875ResultType = Context.VoidTy;3876else if (Form == C11CmpXchg || Form == GNUCmpXchg)3877ResultType = Context.BoolTy;38783879// The type of a parameter passed 'by value'. In the GNU atomics, such3880// arguments are actually passed as pointers.3881QualType ByValType = ValType; // 'CP'3882bool IsPassedByAddress = false;3883if (!IsC11 && !IsHIP && !IsN) {3884ByValType = Ptr->getType();3885IsPassedByAddress = true;3886}38873888SmallVector<Expr *, 5> APIOrderedArgs;3889if (ArgOrder == Sema::AtomicArgumentOrder::AST) {3890APIOrderedArgs.push_back(Args[0]);3891switch (Form) {3892case Init:3893case Load:3894APIOrderedArgs.push_back(Args[1]); // Val1/Order3895break;3896case LoadCopy:3897case Copy:3898case Arithmetic:3899case Xchg:3900APIOrderedArgs.push_back(Args[2]); // Val13901APIOrderedArgs.push_back(Args[1]); // Order3902break;3903case GNUXchg:3904APIOrderedArgs.push_back(Args[2]); // Val13905APIOrderedArgs.push_back(Args[3]); // Val23906APIOrderedArgs.push_back(Args[1]); // Order3907break;3908case C11CmpXchg:3909APIOrderedArgs.push_back(Args[2]); // Val13910APIOrderedArgs.push_back(Args[4]); // Val23911APIOrderedArgs.push_back(Args[1]); // Order3912APIOrderedArgs.push_back(Args[3]); // OrderFail3913break;3914case GNUCmpXchg:3915APIOrderedArgs.push_back(Args[2]); // Val13916APIOrderedArgs.push_back(Args[4]); // Val23917APIOrderedArgs.push_back(Args[5]); // Weak3918APIOrderedArgs.push_back(Args[1]); // Order3919APIOrderedArgs.push_back(Args[3]); // OrderFail3920break;3921}3922} else3923APIOrderedArgs.append(Args.begin(), Args.end());39243925// The first argument's non-CV pointer type is used to deduce the type of3926// subsequent arguments, except for:3927// - weak flag (always converted to bool)3928// - memory order (always converted to int)3929// - scope (always converted to int)3930for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {3931QualType Ty;3932if (i < NumVals[Form] + 1) {3933switch (i) {3934case 0:3935// The first argument is always a pointer. It has a fixed type.3936// It is always dereferenced, a nullptr is undefined.3937CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());3938// Nothing else to do: we already know all we want about this pointer.3939continue;3940case 1:3941// The second argument is the non-atomic operand. For arithmetic, this3942// is always passed by value, and for a compare_exchange it is always3943// passed by address. For the rest, GNU uses by-address and C11 uses3944// by-value.3945assert(Form != Load);3946if (Form == Arithmetic && ValType->isPointerType())3947Ty = Context.getPointerDiffType();3948else if (Form == Init || Form == Arithmetic)3949Ty = ValType;3950else if (Form == Copy || Form == Xchg) {3951if (IsPassedByAddress) {3952// The value pointer is always dereferenced, a nullptr is undefined.3953CheckNonNullArgument(*this, APIOrderedArgs[i],3954ExprRange.getBegin());3955}3956Ty = ByValType;3957} else {3958Expr *ValArg = APIOrderedArgs[i];3959// The value pointer is always dereferenced, a nullptr is undefined.3960CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());3961LangAS AS = LangAS::Default;3962// Keep address space of non-atomic pointer type.3963if (const PointerType *PtrTy =3964ValArg->getType()->getAs<PointerType>()) {3965AS = PtrTy->getPointeeType().getAddressSpace();3966}3967Ty = Context.getPointerType(3968Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));3969}3970break;3971case 2:3972// The third argument to compare_exchange / GNU exchange is the desired3973// value, either by-value (for the C11 and *_n variant) or as a pointer.3974if (IsPassedByAddress)3975CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());3976Ty = ByValType;3977break;3978case 3:3979// The fourth argument to GNU compare_exchange is a 'weak' flag.3980Ty = Context.BoolTy;3981break;3982}3983} else {3984// The order(s) and scope are always converted to int.3985Ty = Context.IntTy;3986}39873988InitializedEntity Entity =3989InitializedEntity::InitializeParameter(Context, Ty, false);3990ExprResult Arg = APIOrderedArgs[i];3991Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);3992if (Arg.isInvalid())3993return true;3994APIOrderedArgs[i] = Arg.get();3995}39963997// Permute the arguments into a 'consistent' order.3998SmallVector<Expr*, 5> SubExprs;3999SubExprs.push_back(Ptr);4000switch (Form) {4001case Init:4002// Note, AtomicExpr::getVal1() has a special case for this atomic.4003SubExprs.push_back(APIOrderedArgs[1]); // Val14004break;4005case Load:4006SubExprs.push_back(APIOrderedArgs[1]); // Order4007break;4008case LoadCopy:4009case Copy:4010case Arithmetic:4011case Xchg:4012SubExprs.push_back(APIOrderedArgs[2]); // Order4013SubExprs.push_back(APIOrderedArgs[1]); // Val14014break;4015case GNUXchg:4016// Note, AtomicExpr::getVal2() has a special case for this atomic.4017SubExprs.push_back(APIOrderedArgs[3]); // Order4018SubExprs.push_back(APIOrderedArgs[1]); // Val14019SubExprs.push_back(APIOrderedArgs[2]); // Val24020break;4021case C11CmpXchg:4022SubExprs.push_back(APIOrderedArgs[3]); // Order4023SubExprs.push_back(APIOrderedArgs[1]); // Val14024SubExprs.push_back(APIOrderedArgs[4]); // OrderFail4025SubExprs.push_back(APIOrderedArgs[2]); // Val24026break;4027case GNUCmpXchg:4028SubExprs.push_back(APIOrderedArgs[4]); // Order4029SubExprs.push_back(APIOrderedArgs[1]); // Val14030SubExprs.push_back(APIOrderedArgs[5]); // OrderFail4031SubExprs.push_back(APIOrderedArgs[2]); // Val24032SubExprs.push_back(APIOrderedArgs[3]); // Weak4033break;4034}40354036// If the memory orders are constants, check they are valid.4037if (SubExprs.size() >= 2 && Form != Init) {4038std::optional<llvm::APSInt> Success =4039SubExprs[1]->getIntegerConstantExpr(Context);4040if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {4041Diag(SubExprs[1]->getBeginLoc(),4042diag::warn_atomic_op_has_invalid_memory_order)4043<< /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)4044<< SubExprs[1]->getSourceRange();4045}4046if (SubExprs.size() >= 5) {4047if (std::optional<llvm::APSInt> Failure =4048SubExprs[3]->getIntegerConstantExpr(Context)) {4049if (!llvm::is_contained(4050{llvm::AtomicOrderingCABI::relaxed,4051llvm::AtomicOrderingCABI::consume,4052llvm::AtomicOrderingCABI::acquire,4053llvm::AtomicOrderingCABI::seq_cst},4054(llvm::AtomicOrderingCABI)Failure->getSExtValue())) {4055Diag(SubExprs[3]->getBeginLoc(),4056diag::warn_atomic_op_has_invalid_memory_order)4057<< /*failure=*/2 << SubExprs[3]->getSourceRange();4058}4059}4060}4061}40624063if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {4064auto *Scope = Args[Args.size() - 1];4065if (std::optional<llvm::APSInt> Result =4066Scope->getIntegerConstantExpr(Context)) {4067if (!ScopeModel->isValid(Result->getZExtValue()))4068Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)4069<< Scope->getSourceRange();4070}4071SubExprs.push_back(Scope);4072}40734074AtomicExpr *AE = new (Context)4075AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);40764077if ((Op == AtomicExpr::AO__c11_atomic_load ||4078Op == AtomicExpr::AO__c11_atomic_store ||4079Op == AtomicExpr::AO__opencl_atomic_load ||4080Op == AtomicExpr::AO__hip_atomic_load ||4081Op == AtomicExpr::AO__opencl_atomic_store ||4082Op == AtomicExpr::AO__hip_atomic_store) &&4083Context.AtomicUsesUnsupportedLibcall(AE))4084Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)4085<< ((Op == AtomicExpr::AO__c11_atomic_load ||4086Op == AtomicExpr::AO__opencl_atomic_load ||4087Op == AtomicExpr::AO__hip_atomic_load)4088? 04089: 1);40904091if (ValType->isBitIntType()) {4092Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);4093return ExprError();4094}40954096return AE;4097}40984099/// checkBuiltinArgument - Given a call to a builtin function, perform4100/// normal type-checking on the given argument, updating the call in4101/// place. This is useful when a builtin function requires custom4102/// type-checking for some of its arguments but not necessarily all of4103/// them.4104///4105/// Returns true on error.4106static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {4107FunctionDecl *Fn = E->getDirectCallee();4108assert(Fn && "builtin call without direct callee!");41094110ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);4111InitializedEntity Entity =4112InitializedEntity::InitializeParameter(S.Context, Param);41134114ExprResult Arg = E->getArg(ArgIndex);4115Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);4116if (Arg.isInvalid())4117return true;41184119E->setArg(ArgIndex, Arg.get());4120return false;4121}41224123ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {4124CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());4125Expr *Callee = TheCall->getCallee();4126DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());4127FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());41284129// Ensure that we have at least one argument to do type inference from.4130if (TheCall->getNumArgs() < 1) {4131Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)4132<< 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 04133<< Callee->getSourceRange();4134return ExprError();4135}41364137// Inspect the first argument of the atomic builtin. This should always be4138// a pointer type, whose element is an integral scalar or pointer type.4139// Because it is a pointer type, we don't have to worry about any implicit4140// casts here.4141// FIXME: We don't allow floating point scalars as input.4142Expr *FirstArg = TheCall->getArg(0);4143ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);4144if (FirstArgResult.isInvalid())4145return ExprError();4146FirstArg = FirstArgResult.get();4147TheCall->setArg(0, FirstArg);41484149const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();4150if (!pointerType) {4151Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)4152<< FirstArg->getType() << 0 << FirstArg->getSourceRange();4153return ExprError();4154}41554156QualType ValType = pointerType->getPointeeType();4157if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&4158!ValType->isBlockPointerType()) {4159Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)4160<< FirstArg->getType() << 0 << FirstArg->getSourceRange();4161return ExprError();4162}41634164if (ValType.isConstQualified()) {4165Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)4166<< FirstArg->getType() << FirstArg->getSourceRange();4167return ExprError();4168}41694170switch (ValType.getObjCLifetime()) {4171case Qualifiers::OCL_None:4172case Qualifiers::OCL_ExplicitNone:4173// okay4174break;41754176case Qualifiers::OCL_Weak:4177case Qualifiers::OCL_Strong:4178case Qualifiers::OCL_Autoreleasing:4179Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)4180<< ValType << FirstArg->getSourceRange();4181return ExprError();4182}41834184// Strip any qualifiers off ValType.4185ValType = ValType.getUnqualifiedType();41864187// The majority of builtins return a value, but a few have special return4188// types, so allow them to override appropriately below.4189QualType ResultType = ValType;41904191// We need to figure out which concrete builtin this maps onto. For example,4192// __sync_fetch_and_add with a 2 byte object turns into4193// __sync_fetch_and_add_2.4194#define BUILTIN_ROW(x) \4195{ Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \4196Builtin::BI##x##_8, Builtin::BI##x##_16 }41974198static const unsigned BuiltinIndices[][5] = {4199BUILTIN_ROW(__sync_fetch_and_add),4200BUILTIN_ROW(__sync_fetch_and_sub),4201BUILTIN_ROW(__sync_fetch_and_or),4202BUILTIN_ROW(__sync_fetch_and_and),4203BUILTIN_ROW(__sync_fetch_and_xor),4204BUILTIN_ROW(__sync_fetch_and_nand),42054206BUILTIN_ROW(__sync_add_and_fetch),4207BUILTIN_ROW(__sync_sub_and_fetch),4208BUILTIN_ROW(__sync_and_and_fetch),4209BUILTIN_ROW(__sync_or_and_fetch),4210BUILTIN_ROW(__sync_xor_and_fetch),4211BUILTIN_ROW(__sync_nand_and_fetch),42124213BUILTIN_ROW(__sync_val_compare_and_swap),4214BUILTIN_ROW(__sync_bool_compare_and_swap),4215BUILTIN_ROW(__sync_lock_test_and_set),4216BUILTIN_ROW(__sync_lock_release),4217BUILTIN_ROW(__sync_swap)4218};4219#undef BUILTIN_ROW42204221// Determine the index of the size.4222unsigned SizeIndex;4223switch (Context.getTypeSizeInChars(ValType).getQuantity()) {4224case 1: SizeIndex = 0; break;4225case 2: SizeIndex = 1; break;4226case 4: SizeIndex = 2; break;4227case 8: SizeIndex = 3; break;4228case 16: SizeIndex = 4; break;4229default:4230Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)4231<< FirstArg->getType() << FirstArg->getSourceRange();4232return ExprError();4233}42344235// Each of these builtins has one pointer argument, followed by some number of4236// values (0, 1 or 2) followed by a potentially empty varags list of stuff4237// that we ignore. Find out which row of BuiltinIndices to read from as well4238// as the number of fixed args.4239unsigned BuiltinID = FDecl->getBuiltinID();4240unsigned BuiltinIndex, NumFixed = 1;4241bool WarnAboutSemanticsChange = false;4242switch (BuiltinID) {4243default: llvm_unreachable("Unknown overloaded atomic builtin!");4244case Builtin::BI__sync_fetch_and_add:4245case Builtin::BI__sync_fetch_and_add_1:4246case Builtin::BI__sync_fetch_and_add_2:4247case Builtin::BI__sync_fetch_and_add_4:4248case Builtin::BI__sync_fetch_and_add_8:4249case Builtin::BI__sync_fetch_and_add_16:4250BuiltinIndex = 0;4251break;42524253case Builtin::BI__sync_fetch_and_sub:4254case Builtin::BI__sync_fetch_and_sub_1:4255case Builtin::BI__sync_fetch_and_sub_2:4256case Builtin::BI__sync_fetch_and_sub_4:4257case Builtin::BI__sync_fetch_and_sub_8:4258case Builtin::BI__sync_fetch_and_sub_16:4259BuiltinIndex = 1;4260break;42614262case Builtin::BI__sync_fetch_and_or:4263case Builtin::BI__sync_fetch_and_or_1:4264case Builtin::BI__sync_fetch_and_or_2:4265case Builtin::BI__sync_fetch_and_or_4:4266case Builtin::BI__sync_fetch_and_or_8:4267case Builtin::BI__sync_fetch_and_or_16:4268BuiltinIndex = 2;4269break;42704271case Builtin::BI__sync_fetch_and_and:4272case Builtin::BI__sync_fetch_and_and_1:4273case Builtin::BI__sync_fetch_and_and_2:4274case Builtin::BI__sync_fetch_and_and_4:4275case Builtin::BI__sync_fetch_and_and_8:4276case Builtin::BI__sync_fetch_and_and_16:4277BuiltinIndex = 3;4278break;42794280case Builtin::BI__sync_fetch_and_xor:4281case Builtin::BI__sync_fetch_and_xor_1:4282case Builtin::BI__sync_fetch_and_xor_2:4283case Builtin::BI__sync_fetch_and_xor_4:4284case Builtin::BI__sync_fetch_and_xor_8:4285case Builtin::BI__sync_fetch_and_xor_16:4286BuiltinIndex = 4;4287break;42884289case Builtin::BI__sync_fetch_and_nand:4290case Builtin::BI__sync_fetch_and_nand_1:4291case Builtin::BI__sync_fetch_and_nand_2:4292case Builtin::BI__sync_fetch_and_nand_4:4293case Builtin::BI__sync_fetch_and_nand_8:4294case Builtin::BI__sync_fetch_and_nand_16:4295BuiltinIndex = 5;4296WarnAboutSemanticsChange = true;4297break;42984299case Builtin::BI__sync_add_and_fetch:4300case Builtin::BI__sync_add_and_fetch_1:4301case Builtin::BI__sync_add_and_fetch_2:4302case Builtin::BI__sync_add_and_fetch_4:4303case Builtin::BI__sync_add_and_fetch_8:4304case Builtin::BI__sync_add_and_fetch_16:4305BuiltinIndex = 6;4306break;43074308case Builtin::BI__sync_sub_and_fetch:4309case Builtin::BI__sync_sub_and_fetch_1:4310case Builtin::BI__sync_sub_and_fetch_2:4311case Builtin::BI__sync_sub_and_fetch_4:4312case Builtin::BI__sync_sub_and_fetch_8:4313case Builtin::BI__sync_sub_and_fetch_16:4314BuiltinIndex = 7;4315break;43164317case Builtin::BI__sync_and_and_fetch:4318case Builtin::BI__sync_and_and_fetch_1:4319case Builtin::BI__sync_and_and_fetch_2:4320case Builtin::BI__sync_and_and_fetch_4:4321case Builtin::BI__sync_and_and_fetch_8:4322case Builtin::BI__sync_and_and_fetch_16:4323BuiltinIndex = 8;4324break;43254326case Builtin::BI__sync_or_and_fetch:4327case Builtin::BI__sync_or_and_fetch_1:4328case Builtin::BI__sync_or_and_fetch_2:4329case Builtin::BI__sync_or_and_fetch_4:4330case Builtin::BI__sync_or_and_fetch_8:4331case Builtin::BI__sync_or_and_fetch_16:4332BuiltinIndex = 9;4333break;43344335case Builtin::BI__sync_xor_and_fetch:4336case Builtin::BI__sync_xor_and_fetch_1:4337case Builtin::BI__sync_xor_and_fetch_2:4338case Builtin::BI__sync_xor_and_fetch_4:4339case Builtin::BI__sync_xor_and_fetch_8:4340case Builtin::BI__sync_xor_and_fetch_16:4341BuiltinIndex = 10;4342break;43434344case Builtin::BI__sync_nand_and_fetch:4345case Builtin::BI__sync_nand_and_fetch_1:4346case Builtin::BI__sync_nand_and_fetch_2:4347case Builtin::BI__sync_nand_and_fetch_4:4348case Builtin::BI__sync_nand_and_fetch_8:4349case Builtin::BI__sync_nand_and_fetch_16:4350BuiltinIndex = 11;4351WarnAboutSemanticsChange = true;4352break;43534354case Builtin::BI__sync_val_compare_and_swap:4355case Builtin::BI__sync_val_compare_and_swap_1:4356case Builtin::BI__sync_val_compare_and_swap_2:4357case Builtin::BI__sync_val_compare_and_swap_4:4358case Builtin::BI__sync_val_compare_and_swap_8:4359case Builtin::BI__sync_val_compare_and_swap_16:4360BuiltinIndex = 12;4361NumFixed = 2;4362break;43634364case Builtin::BI__sync_bool_compare_and_swap:4365case Builtin::BI__sync_bool_compare_and_swap_1:4366case Builtin::BI__sync_bool_compare_and_swap_2:4367case Builtin::BI__sync_bool_compare_and_swap_4:4368case Builtin::BI__sync_bool_compare_and_swap_8:4369case Builtin::BI__sync_bool_compare_and_swap_16:4370BuiltinIndex = 13;4371NumFixed = 2;4372ResultType = Context.BoolTy;4373break;43744375case Builtin::BI__sync_lock_test_and_set:4376case Builtin::BI__sync_lock_test_and_set_1:4377case Builtin::BI__sync_lock_test_and_set_2:4378case Builtin::BI__sync_lock_test_and_set_4:4379case Builtin::BI__sync_lock_test_and_set_8:4380case Builtin::BI__sync_lock_test_and_set_16:4381BuiltinIndex = 14;4382break;43834384case Builtin::BI__sync_lock_release:4385case Builtin::BI__sync_lock_release_1:4386case Builtin::BI__sync_lock_release_2:4387case Builtin::BI__sync_lock_release_4:4388case Builtin::BI__sync_lock_release_8:4389case Builtin::BI__sync_lock_release_16:4390BuiltinIndex = 15;4391NumFixed = 0;4392ResultType = Context.VoidTy;4393break;43944395case Builtin::BI__sync_swap:4396case Builtin::BI__sync_swap_1:4397case Builtin::BI__sync_swap_2:4398case Builtin::BI__sync_swap_4:4399case Builtin::BI__sync_swap_8:4400case Builtin::BI__sync_swap_16:4401BuiltinIndex = 16;4402break;4403}44044405// Now that we know how many fixed arguments we expect, first check that we4406// have at least that many.4407if (TheCall->getNumArgs() < 1+NumFixed) {4408Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)4409<< 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 04410<< Callee->getSourceRange();4411return ExprError();4412}44134414Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)4415<< Callee->getSourceRange();44164417if (WarnAboutSemanticsChange) {4418Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)4419<< Callee->getSourceRange();4420}44214422// Get the decl for the concrete builtin from this, we can tell what the4423// concrete integer type we should convert to is.4424unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];4425StringRef NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);4426FunctionDecl *NewBuiltinDecl;4427if (NewBuiltinID == BuiltinID)4428NewBuiltinDecl = FDecl;4429else {4430// Perform builtin lookup to avoid redeclaring it.4431DeclarationName DN(&Context.Idents.get(NewBuiltinName));4432LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);4433LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);4434assert(Res.getFoundDecl());4435NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());4436if (!NewBuiltinDecl)4437return ExprError();4438}44394440// The first argument --- the pointer --- has a fixed type; we4441// deduce the types of the rest of the arguments accordingly. Walk4442// the remaining arguments, converting them to the deduced value type.4443for (unsigned i = 0; i != NumFixed; ++i) {4444ExprResult Arg = TheCall->getArg(i+1);44454446// GCC does an implicit conversion to the pointer or integer ValType. This4447// can fail in some cases (1i -> int**), check for this error case now.4448// Initialize the argument.4449InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,4450ValType, /*consume*/ false);4451Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);4452if (Arg.isInvalid())4453return ExprError();44544455// Okay, we have something that *can* be converted to the right type. Check4456// to see if there is a potentially weird extension going on here. This can4457// happen when you do an atomic operation on something like an char* and4458// pass in 42. The 42 gets converted to char. This is even more strange4459// for things like 45.123 -> char, etc.4460// FIXME: Do this check.4461TheCall->setArg(i+1, Arg.get());4462}44634464// Create a new DeclRefExpr to refer to the new decl.4465DeclRefExpr *NewDRE = DeclRefExpr::Create(4466Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,4467/*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,4468DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());44694470// Set the callee in the CallExpr.4471// FIXME: This loses syntactic information.4472QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());4473ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,4474CK_BuiltinFnToFnPtr);4475TheCall->setCallee(PromotedCall.get());44764477// Change the result type of the call to match the original value type. This4478// is arbitrary, but the codegen for these builtins ins design to handle it4479// gracefully.4480TheCall->setType(ResultType);44814482// Prohibit problematic uses of bit-precise integer types with atomic4483// builtins. The arguments would have already been converted to the first4484// argument's type, so only need to check the first argument.4485const auto *BitIntValType = ValType->getAs<BitIntType>();4486if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {4487Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);4488return ExprError();4489}44904491return TheCallResult;4492}44934494ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {4495CallExpr *TheCall = (CallExpr *)TheCallResult.get();4496DeclRefExpr *DRE =4497cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());4498FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());4499unsigned BuiltinID = FDecl->getBuiltinID();4500assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||4501BuiltinID == Builtin::BI__builtin_nontemporal_load) &&4502"Unexpected nontemporal load/store builtin!");4503bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;4504unsigned numArgs = isStore ? 2 : 1;45054506// Ensure that we have the proper number of arguments.4507if (checkArgCount(TheCall, numArgs))4508return ExprError();45094510// Inspect the last argument of the nontemporal builtin. This should always4511// be a pointer type, from which we imply the type of the memory access.4512// Because it is a pointer type, we don't have to worry about any implicit4513// casts here.4514Expr *PointerArg = TheCall->getArg(numArgs - 1);4515ExprResult PointerArgResult =4516DefaultFunctionArrayLvalueConversion(PointerArg);45174518if (PointerArgResult.isInvalid())4519return ExprError();4520PointerArg = PointerArgResult.get();4521TheCall->setArg(numArgs - 1, PointerArg);45224523const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();4524if (!pointerType) {4525Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)4526<< PointerArg->getType() << PointerArg->getSourceRange();4527return ExprError();4528}45294530QualType ValType = pointerType->getPointeeType();45314532// Strip any qualifiers off ValType.4533ValType = ValType.getUnqualifiedType();4534if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&4535!ValType->isBlockPointerType() && !ValType->isFloatingType() &&4536!ValType->isVectorType()) {4537Diag(DRE->getBeginLoc(),4538diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)4539<< PointerArg->getType() << PointerArg->getSourceRange();4540return ExprError();4541}45424543if (!isStore) {4544TheCall->setType(ValType);4545return TheCallResult;4546}45474548ExprResult ValArg = TheCall->getArg(0);4549InitializedEntity Entity = InitializedEntity::InitializeParameter(4550Context, ValType, /*consume*/ false);4551ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);4552if (ValArg.isInvalid())4553return ExprError();45544555TheCall->setArg(0, ValArg.get());4556TheCall->setType(Context.VoidTy);4557return TheCallResult;4558}45594560/// CheckObjCString - Checks that the format string argument to the os_log()4561/// and os_trace() functions is correct, and converts it to const char *.4562ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {4563Arg = Arg->IgnoreParenCasts();4564auto *Literal = dyn_cast<StringLiteral>(Arg);4565if (!Literal) {4566if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {4567Literal = ObjcLiteral->getString();4568}4569}45704571if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {4572return ExprError(4573Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)4574<< Arg->getSourceRange());4575}45764577ExprResult Result(Literal);4578QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());4579InitializedEntity Entity =4580InitializedEntity::InitializeParameter(Context, ResultTy, false);4581Result = PerformCopyInitialization(Entity, SourceLocation(), Result);4582return Result;4583}45844585/// Check that the user is calling the appropriate va_start builtin for the4586/// target and calling convention.4587static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {4588const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();4589bool IsX64 = TT.getArch() == llvm::Triple::x86_64;4590bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||4591TT.getArch() == llvm::Triple::aarch64_32);4592bool IsWindows = TT.isOSWindows();4593bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;4594if (IsX64 || IsAArch64) {4595CallingConv CC = CC_C;4596if (const FunctionDecl *FD = S.getCurFunctionDecl())4597CC = FD->getType()->castAs<FunctionType>()->getCallConv();4598if (IsMSVAStart) {4599// Don't allow this in System V ABI functions.4600if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))4601return S.Diag(Fn->getBeginLoc(),4602diag::err_ms_va_start_used_in_sysv_function);4603} else {4604// On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.4605// On x64 Windows, don't allow this in System V ABI functions.4606// (Yes, that means there's no corresponding way to support variadic4607// System V ABI functions on Windows.)4608if ((IsWindows && CC == CC_X86_64SysV) ||4609(!IsWindows && CC == CC_Win64))4610return S.Diag(Fn->getBeginLoc(),4611diag::err_va_start_used_in_wrong_abi_function)4612<< !IsWindows;4613}4614return false;4615}46164617if (IsMSVAStart)4618return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);4619return false;4620}46214622static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,4623ParmVarDecl **LastParam = nullptr) {4624// Determine whether the current function, block, or obj-c method is variadic4625// and get its parameter list.4626bool IsVariadic = false;4627ArrayRef<ParmVarDecl *> Params;4628DeclContext *Caller = S.CurContext;4629if (auto *Block = dyn_cast<BlockDecl>(Caller)) {4630IsVariadic = Block->isVariadic();4631Params = Block->parameters();4632} else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {4633IsVariadic = FD->isVariadic();4634Params = FD->parameters();4635} else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {4636IsVariadic = MD->isVariadic();4637// FIXME: This isn't correct for methods (results in bogus warning).4638Params = MD->parameters();4639} else if (isa<CapturedDecl>(Caller)) {4640// We don't support va_start in a CapturedDecl.4641S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);4642return true;4643} else {4644// This must be some other declcontext that parses exprs.4645S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);4646return true;4647}46484649if (!IsVariadic) {4650S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);4651return true;4652}46534654if (LastParam)4655*LastParam = Params.empty() ? nullptr : Params.back();46564657return false;4658}46594660bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {4661Expr *Fn = TheCall->getCallee();46624663if (checkVAStartABI(*this, BuiltinID, Fn))4664return true;46654666// In C23 mode, va_start only needs one argument. However, the builtin still4667// requires two arguments (which matches the behavior of the GCC builtin),4668// <stdarg.h> passes `0` as the second argument in C23 mode.4669if (checkArgCount(TheCall, 2))4670return true;46714672// Type-check the first argument normally.4673if (checkBuiltinArgument(*this, TheCall, 0))4674return true;46754676// Check that the current function is variadic, and get its last parameter.4677ParmVarDecl *LastParam;4678if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))4679return true;46804681// Verify that the second argument to the builtin is the last argument of the4682// current function or method. In C23 mode, if the second argument is an4683// integer constant expression with value 0, then we don't bother with this4684// check.4685bool SecondArgIsLastNamedArgument = false;4686const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();4687if (std::optional<llvm::APSInt> Val =4688TheCall->getArg(1)->getIntegerConstantExpr(Context);4689Val && LangOpts.C23 && *Val == 0)4690return false;46914692// These are valid if SecondArgIsLastNamedArgument is false after the next4693// block.4694QualType Type;4695SourceLocation ParamLoc;4696bool IsCRegister = false;46974698if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {4699if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {4700SecondArgIsLastNamedArgument = PV == LastParam;47014702Type = PV->getType();4703ParamLoc = PV->getLocation();4704IsCRegister =4705PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;4706}4707}47084709if (!SecondArgIsLastNamedArgument)4710Diag(TheCall->getArg(1)->getBeginLoc(),4711diag::warn_second_arg_of_va_start_not_last_named_param);4712else if (IsCRegister || Type->isReferenceType() ||4713Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {4714// Promotable integers are UB, but enumerations need a bit of4715// extra checking to see what their promotable type actually is.4716if (!Context.isPromotableIntegerType(Type))4717return false;4718if (!Type->isEnumeralType())4719return true;4720const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();4721return !(ED &&4722Context.typesAreCompatible(ED->getPromotionType(), Type));4723}()) {4724unsigned Reason = 0;4725if (Type->isReferenceType()) Reason = 1;4726else if (IsCRegister) Reason = 2;4727Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;4728Diag(ParamLoc, diag::note_parameter_type) << Type;4729}47304731return false;4732}47334734bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {4735auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {4736const LangOptions &LO = getLangOpts();47374738if (LO.CPlusPlus)4739return Arg->getType()4740.getCanonicalType()4741.getTypePtr()4742->getPointeeType()4743.withoutLocalFastQualifiers() == Context.CharTy;47444745// In C, allow aliasing through `char *`, this is required for AArch64 at4746// least.4747return true;4748};47494750// void __va_start(va_list *ap, const char *named_addr, size_t slot_size,4751// const char *named_addr);47524753Expr *Func = Call->getCallee();47544755if (Call->getNumArgs() < 3)4756return Diag(Call->getEndLoc(),4757diag::err_typecheck_call_too_few_args_at_least)4758<< 0 /*function call*/ << 3 << Call->getNumArgs()4759<< /*is non object*/ 0;47604761// Type-check the first argument normally.4762if (checkBuiltinArgument(*this, Call, 0))4763return true;47644765// Check that the current function is variadic.4766if (checkVAStartIsInVariadicFunction(*this, Func))4767return true;47684769// __va_start on Windows does not validate the parameter qualifiers47704771const Expr *Arg1 = Call->getArg(1)->IgnoreParens();4772const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();47734774const Expr *Arg2 = Call->getArg(2)->IgnoreParens();4775const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();47764777const QualType &ConstCharPtrTy =4778Context.getPointerType(Context.CharTy.withConst());4779if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))4780Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)4781<< Arg1->getType() << ConstCharPtrTy << 1 /* different class */4782<< 0 /* qualifier difference */4783<< 3 /* parameter mismatch */4784<< 2 << Arg1->getType() << ConstCharPtrTy;47854786const QualType SizeTy = Context.getSizeType();4787if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)4788Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)4789<< Arg2->getType() << SizeTy << 1 /* different class */4790<< 0 /* qualifier difference */4791<< 3 /* parameter mismatch */4792<< 3 << Arg2->getType() << SizeTy;47934794return false;4795}47964797bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {4798if (checkArgCount(TheCall, 2))4799return true;48004801if (BuiltinID == Builtin::BI__builtin_isunordered &&4802TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())4803Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)4804<< 1 << 0 << TheCall->getSourceRange();48054806ExprResult OrigArg0 = TheCall->getArg(0);4807ExprResult OrigArg1 = TheCall->getArg(1);48084809// Do standard promotions between the two arguments, returning their common4810// type.4811QualType Res = UsualArithmeticConversions(4812OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);4813if (OrigArg0.isInvalid() || OrigArg1.isInvalid())4814return true;48154816// Make sure any conversions are pushed back into the call; this is4817// type safe since unordered compare builtins are declared as "_Bool4818// foo(...)".4819TheCall->setArg(0, OrigArg0.get());4820TheCall->setArg(1, OrigArg1.get());48214822if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())4823return false;48244825// If the common type isn't a real floating type, then the arguments were4826// invalid for this operation.4827if (Res.isNull() || !Res->isRealFloatingType())4828return Diag(OrigArg0.get()->getBeginLoc(),4829diag::err_typecheck_call_invalid_ordered_compare)4830<< OrigArg0.get()->getType() << OrigArg1.get()->getType()4831<< SourceRange(OrigArg0.get()->getBeginLoc(),4832OrigArg1.get()->getEndLoc());48334834return false;4835}48364837bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,4838unsigned BuiltinID) {4839if (checkArgCount(TheCall, NumArgs))4840return true;48414842FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());4843if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||4844BuiltinID == Builtin::BI__builtin_isinf ||4845BuiltinID == Builtin::BI__builtin_isinf_sign))4846Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)4847<< 0 << 0 << TheCall->getSourceRange();48484849if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||4850BuiltinID == Builtin::BI__builtin_isunordered))4851Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)4852<< 1 << 0 << TheCall->getSourceRange();48534854bool IsFPClass = NumArgs == 2;48554856// Find out position of floating-point argument.4857unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;48584859// We can count on all parameters preceding the floating-point just being int.4860// Try all of those.4861for (unsigned i = 0; i < FPArgNo; ++i) {4862Expr *Arg = TheCall->getArg(i);48634864if (Arg->isTypeDependent())4865return false;48664867ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);48684869if (Res.isInvalid())4870return true;4871TheCall->setArg(i, Res.get());4872}48734874Expr *OrigArg = TheCall->getArg(FPArgNo);48754876if (OrigArg->isTypeDependent())4877return false;48784879// Usual Unary Conversions will convert half to float, which we want for4880// machines that use fp16 conversion intrinsics. Else, we wnat to leave the4881// type how it is, but do normal L->Rvalue conversions.4882if (Context.getTargetInfo().useFP16ConversionIntrinsics())4883OrigArg = UsualUnaryConversions(OrigArg).get();4884else4885OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();4886TheCall->setArg(FPArgNo, OrigArg);48874888QualType VectorResultTy;4889QualType ElementTy = OrigArg->getType();4890// TODO: When all classification function are implemented with is_fpclass,4891// vector argument can be supported in all of them.4892if (ElementTy->isVectorType() && IsFPClass) {4893VectorResultTy = GetSignedVectorType(ElementTy);4894ElementTy = ElementTy->castAs<VectorType>()->getElementType();4895}48964897// This operation requires a non-_Complex floating-point number.4898if (!ElementTy->isRealFloatingType())4899return Diag(OrigArg->getBeginLoc(),4900diag::err_typecheck_call_invalid_unary_fp)4901<< OrigArg->getType() << OrigArg->getSourceRange();49024903// __builtin_isfpclass has integer parameter that specify test mask. It is4904// passed in (...), so it should be analyzed completely here.4905if (IsFPClass)4906if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))4907return true;49084909// TODO: enable this code to all classification functions.4910if (IsFPClass) {4911QualType ResultTy;4912if (!VectorResultTy.isNull())4913ResultTy = VectorResultTy;4914else4915ResultTy = Context.IntTy;4916TheCall->setType(ResultTy);4917}49184919return false;4920}49214922bool Sema::BuiltinComplex(CallExpr *TheCall) {4923if (checkArgCount(TheCall, 2))4924return true;49254926bool Dependent = false;4927for (unsigned I = 0; I != 2; ++I) {4928Expr *Arg = TheCall->getArg(I);4929QualType T = Arg->getType();4930if (T->isDependentType()) {4931Dependent = true;4932continue;4933}49344935// Despite supporting _Complex int, GCC requires a real floating point type4936// for the operands of __builtin_complex.4937if (!T->isRealFloatingType()) {4938return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)4939<< Arg->getType() << Arg->getSourceRange();4940}49414942ExprResult Converted = DefaultLvalueConversion(Arg);4943if (Converted.isInvalid())4944return true;4945TheCall->setArg(I, Converted.get());4946}49474948if (Dependent) {4949TheCall->setType(Context.DependentTy);4950return false;4951}49524953Expr *Real = TheCall->getArg(0);4954Expr *Imag = TheCall->getArg(1);4955if (!Context.hasSameType(Real->getType(), Imag->getType())) {4956return Diag(Real->getBeginLoc(),4957diag::err_typecheck_call_different_arg_types)4958<< Real->getType() << Imag->getType()4959<< Real->getSourceRange() << Imag->getSourceRange();4960}49614962// We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;4963// don't allow this builtin to form those types either.4964// FIXME: Should we allow these types?4965if (Real->getType()->isFloat16Type())4966return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)4967<< "_Float16";4968if (Real->getType()->isHalfType())4969return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)4970<< "half";49714972TheCall->setType(Context.getComplexType(Real->getType()));4973return false;4974}49754976/// BuiltinShuffleVector - Handle __builtin_shufflevector.4977// This is declared to take (...), so we have to check everything.4978ExprResult Sema::BuiltinShuffleVector(CallExpr *TheCall) {4979if (TheCall->getNumArgs() < 2)4980return ExprError(Diag(TheCall->getEndLoc(),4981diag::err_typecheck_call_too_few_args_at_least)4982<< 0 /*function call*/ << 2 << TheCall->getNumArgs()4983<< /*is non object*/ 0 << TheCall->getSourceRange());49844985// Determine which of the following types of shufflevector we're checking:4986// 1) unary, vector mask: (lhs, mask)4987// 2) binary, scalar mask: (lhs, rhs, index, ..., index)4988QualType resType = TheCall->getArg(0)->getType();4989unsigned numElements = 0;49904991if (!TheCall->getArg(0)->isTypeDependent() &&4992!TheCall->getArg(1)->isTypeDependent()) {4993QualType LHSType = TheCall->getArg(0)->getType();4994QualType RHSType = TheCall->getArg(1)->getType();49954996if (!LHSType->isVectorType() || !RHSType->isVectorType())4997return ExprError(4998Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)4999<< TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false5000<< SourceRange(TheCall->getArg(0)->getBeginLoc(),5001TheCall->getArg(1)->getEndLoc()));50025003numElements = LHSType->castAs<VectorType>()->getNumElements();5004unsigned numResElements = TheCall->getNumArgs() - 2;50055006// Check to see if we have a call with 2 vector arguments, the unary shuffle5007// with mask. If so, verify that RHS is an integer vector type with the5008// same number of elts as lhs.5009if (TheCall->getNumArgs() == 2) {5010if (!RHSType->hasIntegerRepresentation() ||5011RHSType->castAs<VectorType>()->getNumElements() != numElements)5012return ExprError(Diag(TheCall->getBeginLoc(),5013diag::err_vec_builtin_incompatible_vector)5014<< TheCall->getDirectCallee()5015<< /*isMorethantwoArgs*/ false5016<< SourceRange(TheCall->getArg(1)->getBeginLoc(),5017TheCall->getArg(1)->getEndLoc()));5018} else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {5019return ExprError(Diag(TheCall->getBeginLoc(),5020diag::err_vec_builtin_incompatible_vector)5021<< TheCall->getDirectCallee()5022<< /*isMorethantwoArgs*/ false5023<< SourceRange(TheCall->getArg(0)->getBeginLoc(),5024TheCall->getArg(1)->getEndLoc()));5025} else if (numElements != numResElements) {5026QualType eltType = LHSType->castAs<VectorType>()->getElementType();5027resType =5028Context.getVectorType(eltType, numResElements, VectorKind::Generic);5029}5030}50315032for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {5033if (TheCall->getArg(i)->isTypeDependent() ||5034TheCall->getArg(i)->isValueDependent())5035continue;50365037std::optional<llvm::APSInt> Result;5038if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))5039return ExprError(Diag(TheCall->getBeginLoc(),5040diag::err_shufflevector_nonconstant_argument)5041<< TheCall->getArg(i)->getSourceRange());50425043// Allow -1 which will be translated to undef in the IR.5044if (Result->isSigned() && Result->isAllOnes())5045continue;50465047if (Result->getActiveBits() > 64 ||5048Result->getZExtValue() >= numElements * 2)5049return ExprError(Diag(TheCall->getBeginLoc(),5050diag::err_shufflevector_argument_too_large)5051<< TheCall->getArg(i)->getSourceRange());5052}50535054SmallVector<Expr*, 32> exprs;50555056for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {5057exprs.push_back(TheCall->getArg(i));5058TheCall->setArg(i, nullptr);5059}50605061return new (Context) ShuffleVectorExpr(Context, exprs, resType,5062TheCall->getCallee()->getBeginLoc(),5063TheCall->getRParenLoc());5064}50655066ExprResult Sema::ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,5067SourceLocation BuiltinLoc,5068SourceLocation RParenLoc) {5069ExprValueKind VK = VK_PRValue;5070ExprObjectKind OK = OK_Ordinary;5071QualType DstTy = TInfo->getType();5072QualType SrcTy = E->getType();50735074if (!SrcTy->isVectorType() && !SrcTy->isDependentType())5075return ExprError(Diag(BuiltinLoc,5076diag::err_convertvector_non_vector)5077<< E->getSourceRange());5078if (!DstTy->isVectorType() && !DstTy->isDependentType())5079return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)5080<< "second"5081<< "__builtin_convertvector");50825083if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {5084unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();5085unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();5086if (SrcElts != DstElts)5087return ExprError(Diag(BuiltinLoc,5088diag::err_convertvector_incompatible_vector)5089<< E->getSourceRange());5090}50915092return new (Context) class ConvertVectorExpr(E, TInfo, DstTy, VK, OK,5093BuiltinLoc, RParenLoc);5094}50955096bool Sema::BuiltinPrefetch(CallExpr *TheCall) {5097unsigned NumArgs = TheCall->getNumArgs();50985099if (NumArgs > 3)5100return Diag(TheCall->getEndLoc(),5101diag::err_typecheck_call_too_many_args_at_most)5102<< 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 05103<< TheCall->getSourceRange();51045105// Argument 0 is checked for us and the remaining arguments must be5106// constant integers.5107for (unsigned i = 1; i != NumArgs; ++i)5108if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))5109return true;51105111return false;5112}51135114bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {5115if (!Context.getTargetInfo().checkArithmeticFenceSupported())5116return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)5117<< SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());5118if (checkArgCount(TheCall, 1))5119return true;5120Expr *Arg = TheCall->getArg(0);5121if (Arg->isInstantiationDependent())5122return false;51235124QualType ArgTy = Arg->getType();5125if (!ArgTy->hasFloatingRepresentation())5126return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)5127<< ArgTy;5128if (Arg->isLValue()) {5129ExprResult FirstArg = DefaultLvalueConversion(Arg);5130TheCall->setArg(0, FirstArg.get());5131}5132TheCall->setType(TheCall->getArg(0)->getType());5133return false;5134}51355136bool Sema::BuiltinAssume(CallExpr *TheCall) {5137Expr *Arg = TheCall->getArg(0);5138if (Arg->isInstantiationDependent()) return false;51395140if (Arg->HasSideEffects(Context))5141Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)5142<< Arg->getSourceRange()5143<< cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();51445145return false;5146}51475148bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {5149// The alignment must be a constant integer.5150Expr *Arg = TheCall->getArg(1);51515152// We can't check the value of a dependent argument.5153if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {5154if (const auto *UE =5155dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))5156if (UE->getKind() == UETT_AlignOf ||5157UE->getKind() == UETT_PreferredAlignOf)5158Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)5159<< Arg->getSourceRange();51605161llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);51625163if (!Result.isPowerOf2())5164return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)5165<< Arg->getSourceRange();51665167if (Result < Context.getCharWidth())5168return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)5169<< (unsigned)Context.getCharWidth() << Arg->getSourceRange();51705171if (Result > std::numeric_limits<int32_t>::max())5172return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)5173<< std::numeric_limits<int32_t>::max() << Arg->getSourceRange();5174}51755176return false;5177}51785179bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {5180if (checkArgCountRange(TheCall, 2, 3))5181return true;51825183unsigned NumArgs = TheCall->getNumArgs();5184Expr *FirstArg = TheCall->getArg(0);51855186{5187ExprResult FirstArgResult =5188DefaultFunctionArrayLvalueConversion(FirstArg);5189if (checkBuiltinArgument(*this, TheCall, 0))5190return true;5191/// In-place updation of FirstArg by checkBuiltinArgument is ignored.5192TheCall->setArg(0, FirstArgResult.get());5193}51945195// The alignment must be a constant integer.5196Expr *SecondArg = TheCall->getArg(1);51975198// We can't check the value of a dependent argument.5199if (!SecondArg->isValueDependent()) {5200llvm::APSInt Result;5201if (BuiltinConstantArg(TheCall, 1, Result))5202return true;52035204if (!Result.isPowerOf2())5205return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)5206<< SecondArg->getSourceRange();52075208if (Result > Sema::MaximumAlignment)5209Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)5210<< SecondArg->getSourceRange() << Sema::MaximumAlignment;5211}52125213if (NumArgs > 2) {5214Expr *ThirdArg = TheCall->getArg(2);5215if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))5216return true;5217TheCall->setArg(2, ThirdArg);5218}52195220return false;5221}52225223bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {5224unsigned BuiltinID =5225cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();5226bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;52275228unsigned NumArgs = TheCall->getNumArgs();5229unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;5230if (NumArgs < NumRequiredArgs) {5231return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)5232<< 0 /* function call */ << NumRequiredArgs << NumArgs5233<< /*is non object*/ 0 << TheCall->getSourceRange();5234}5235if (NumArgs >= NumRequiredArgs + 0x100) {5236return Diag(TheCall->getEndLoc(),5237diag::err_typecheck_call_too_many_args_at_most)5238<< 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs5239<< /*is non object*/ 0 << TheCall->getSourceRange();5240}5241unsigned i = 0;52425243// For formatting call, check buffer arg.5244if (!IsSizeCall) {5245ExprResult Arg(TheCall->getArg(i));5246InitializedEntity Entity = InitializedEntity::InitializeParameter(5247Context, Context.VoidPtrTy, false);5248Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);5249if (Arg.isInvalid())5250return true;5251TheCall->setArg(i, Arg.get());5252i++;5253}52545255// Check string literal arg.5256unsigned FormatIdx = i;5257{5258ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));5259if (Arg.isInvalid())5260return true;5261TheCall->setArg(i, Arg.get());5262i++;5263}52645265// Make sure variadic args are scalar.5266unsigned FirstDataArg = i;5267while (i < NumArgs) {5268ExprResult Arg = DefaultVariadicArgumentPromotion(5269TheCall->getArg(i), VariadicFunction, nullptr);5270if (Arg.isInvalid())5271return true;5272CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());5273if (ArgSize.getQuantity() >= 0x100) {5274return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)5275<< i << (int)ArgSize.getQuantity() << 0xff5276<< TheCall->getSourceRange();5277}5278TheCall->setArg(i, Arg.get());5279i++;5280}52815282// Check formatting specifiers. NOTE: We're only doing this for the non-size5283// call to avoid duplicate diagnostics.5284if (!IsSizeCall) {5285llvm::SmallBitVector CheckedVarArgs(NumArgs, false);5286ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());5287bool Success = CheckFormatArguments(5288Args, FAPK_Variadic, FormatIdx, FirstDataArg, FST_OSLog,5289VariadicFunction, TheCall->getBeginLoc(), SourceRange(),5290CheckedVarArgs);5291if (!Success)5292return true;5293}52945295if (IsSizeCall) {5296TheCall->setType(Context.getSizeType());5297} else {5298TheCall->setType(Context.VoidPtrTy);5299}5300return false;5301}53025303bool Sema::BuiltinConstantArg(CallExpr *TheCall, int ArgNum,5304llvm::APSInt &Result) {5305Expr *Arg = TheCall->getArg(ArgNum);5306DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());5307FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());53085309if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;53105311std::optional<llvm::APSInt> R;5312if (!(R = Arg->getIntegerConstantExpr(Context)))5313return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)5314<< FDecl->getDeclName() << Arg->getSourceRange();5315Result = *R;5316return false;5317}53185319bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,5320int High, bool RangeIsError) {5321if (isConstantEvaluatedContext())5322return false;5323llvm::APSInt Result;53245325// We can't check the value of a dependent argument.5326Expr *Arg = TheCall->getArg(ArgNum);5327if (Arg->isTypeDependent() || Arg->isValueDependent())5328return false;53295330// Check constant-ness first.5331if (BuiltinConstantArg(TheCall, ArgNum, Result))5332return true;53335334if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {5335if (RangeIsError)5336return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)5337<< toString(Result, 10) << Low << High << Arg->getSourceRange();5338else5339// Defer the warning until we know if the code will be emitted so that5340// dead code can ignore this.5341DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,5342PDiag(diag::warn_argument_invalid_range)5343<< toString(Result, 10) << Low << High5344<< Arg->getSourceRange());5345}53465347return false;5348}53495350bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,5351unsigned Num) {5352llvm::APSInt Result;53535354// We can't check the value of a dependent argument.5355Expr *Arg = TheCall->getArg(ArgNum);5356if (Arg->isTypeDependent() || Arg->isValueDependent())5357return false;53585359// Check constant-ness first.5360if (BuiltinConstantArg(TheCall, ArgNum, Result))5361return true;53625363if (Result.getSExtValue() % Num != 0)5364return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)5365<< Num << Arg->getSourceRange();53665367return false;5368}53695370bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {5371llvm::APSInt Result;53725373// We can't check the value of a dependent argument.5374Expr *Arg = TheCall->getArg(ArgNum);5375if (Arg->isTypeDependent() || Arg->isValueDependent())5376return false;53775378// Check constant-ness first.5379if (BuiltinConstantArg(TheCall, ArgNum, Result))5380return true;53815382// Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if5383// and only if x is a power of 2.5384if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)5385return false;53865387return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)5388<< Arg->getSourceRange();5389}53905391static bool IsShiftedByte(llvm::APSInt Value) {5392if (Value.isNegative())5393return false;53945395// Check if it's a shifted byte, by shifting it down5396while (true) {5397// If the value fits in the bottom byte, the check passes.5398if (Value < 0x100)5399return true;54005401// Otherwise, if the value has _any_ bits in the bottom byte, the check5402// fails.5403if ((Value & 0xFF) != 0)5404return false;54055406// If the bottom 8 bits are all 0, but something above that is nonzero,5407// then shifting the value right by 8 bits won't affect whether it's a5408// shifted byte or not. So do that, and go round again.5409Value >>= 8;5410}5411}54125413bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,5414unsigned ArgBits) {5415llvm::APSInt Result;54165417// We can't check the value of a dependent argument.5418Expr *Arg = TheCall->getArg(ArgNum);5419if (Arg->isTypeDependent() || Arg->isValueDependent())5420return false;54215422// Check constant-ness first.5423if (BuiltinConstantArg(TheCall, ArgNum, Result))5424return true;54255426// Truncate to the given size.5427Result = Result.getLoBits(ArgBits);5428Result.setIsUnsigned(true);54295430if (IsShiftedByte(Result))5431return false;54325433return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)5434<< Arg->getSourceRange();5435}54365437bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,5438unsigned ArgBits) {5439llvm::APSInt Result;54405441// We can't check the value of a dependent argument.5442Expr *Arg = TheCall->getArg(ArgNum);5443if (Arg->isTypeDependent() || Arg->isValueDependent())5444return false;54455446// Check constant-ness first.5447if (BuiltinConstantArg(TheCall, ArgNum, Result))5448return true;54495450// Truncate to the given size.5451Result = Result.getLoBits(ArgBits);5452Result.setIsUnsigned(true);54535454// Check to see if it's in either of the required forms.5455if (IsShiftedByte(Result) ||5456(Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))5457return false;54585459return Diag(TheCall->getBeginLoc(),5460diag::err_argument_not_shifted_byte_or_xxff)5461<< Arg->getSourceRange();5462}54635464bool Sema::BuiltinLongjmp(CallExpr *TheCall) {5465if (!Context.getTargetInfo().hasSjLjLowering())5466return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)5467<< SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());54685469Expr *Arg = TheCall->getArg(1);5470llvm::APSInt Result;54715472// TODO: This is less than ideal. Overload this to take a value.5473if (BuiltinConstantArg(TheCall, 1, Result))5474return true;54755476if (Result != 1)5477return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)5478<< SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());54795480return false;5481}54825483bool Sema::BuiltinSetjmp(CallExpr *TheCall) {5484if (!Context.getTargetInfo().hasSjLjLowering())5485return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)5486<< SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());5487return false;5488}54895490namespace {54915492class UncoveredArgHandler {5493enum { Unknown = -1, AllCovered = -2 };54945495signed FirstUncoveredArg = Unknown;5496SmallVector<const Expr *, 4> DiagnosticExprs;54975498public:5499UncoveredArgHandler() = default;55005501bool hasUncoveredArg() const {5502return (FirstUncoveredArg >= 0);5503}55045505unsigned getUncoveredArg() const {5506assert(hasUncoveredArg() && "no uncovered argument");5507return FirstUncoveredArg;5508}55095510void setAllCovered() {5511// A string has been found with all arguments covered, so clear out5512// the diagnostics.5513DiagnosticExprs.clear();5514FirstUncoveredArg = AllCovered;5515}55165517void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {5518assert(NewFirstUncoveredArg >= 0 && "Outside range");55195520// Don't update if a previous string covers all arguments.5521if (FirstUncoveredArg == AllCovered)5522return;55235524// UncoveredArgHandler tracks the highest uncovered argument index5525// and with it all the strings that match this index.5526if (NewFirstUncoveredArg == FirstUncoveredArg)5527DiagnosticExprs.push_back(StrExpr);5528else if (NewFirstUncoveredArg > FirstUncoveredArg) {5529DiagnosticExprs.clear();5530DiagnosticExprs.push_back(StrExpr);5531FirstUncoveredArg = NewFirstUncoveredArg;5532}5533}55345535void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);5536};55375538enum StringLiteralCheckType {5539SLCT_NotALiteral,5540SLCT_UncheckedLiteral,5541SLCT_CheckedLiteral5542};55435544} // namespace55455546static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,5547BinaryOperatorKind BinOpKind,5548bool AddendIsRight) {5549unsigned BitWidth = Offset.getBitWidth();5550unsigned AddendBitWidth = Addend.getBitWidth();5551// There might be negative interim results.5552if (Addend.isUnsigned()) {5553Addend = Addend.zext(++AddendBitWidth);5554Addend.setIsSigned(true);5555}5556// Adjust the bit width of the APSInts.5557if (AddendBitWidth > BitWidth) {5558Offset = Offset.sext(AddendBitWidth);5559BitWidth = AddendBitWidth;5560} else if (BitWidth > AddendBitWidth) {5561Addend = Addend.sext(BitWidth);5562}55635564bool Ov = false;5565llvm::APSInt ResOffset = Offset;5566if (BinOpKind == BO_Add)5567ResOffset = Offset.sadd_ov(Addend, Ov);5568else {5569assert(AddendIsRight && BinOpKind == BO_Sub &&5570"operator must be add or sub with addend on the right");5571ResOffset = Offset.ssub_ov(Addend, Ov);5572}55735574// We add an offset to a pointer here so we should support an offset as big as5575// possible.5576if (Ov) {5577assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&5578"index (intermediate) result too big");5579Offset = Offset.sext(2 * BitWidth);5580sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);5581return;5582}55835584Offset = ResOffset;5585}55865587namespace {55885589// This is a wrapper class around StringLiteral to support offsetted string5590// literals as format strings. It takes the offset into account when returning5591// the string and its length or the source locations to display notes correctly.5592class FormatStringLiteral {5593const StringLiteral *FExpr;5594int64_t Offset;55955596public:5597FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)5598: FExpr(fexpr), Offset(Offset) {}55995600StringRef getString() const {5601return FExpr->getString().drop_front(Offset);5602}56035604unsigned getByteLength() const {5605return FExpr->getByteLength() - getCharByteWidth() * Offset;5606}56075608unsigned getLength() const { return FExpr->getLength() - Offset; }5609unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }56105611StringLiteralKind getKind() const { return FExpr->getKind(); }56125613QualType getType() const { return FExpr->getType(); }56145615bool isAscii() const { return FExpr->isOrdinary(); }5616bool isWide() const { return FExpr->isWide(); }5617bool isUTF8() const { return FExpr->isUTF8(); }5618bool isUTF16() const { return FExpr->isUTF16(); }5619bool isUTF32() const { return FExpr->isUTF32(); }5620bool isPascal() const { return FExpr->isPascal(); }56215622SourceLocation getLocationOfByte(5623unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,5624const TargetInfo &Target, unsigned *StartToken = nullptr,5625unsigned *StartTokenByteOffset = nullptr) const {5626return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,5627StartToken, StartTokenByteOffset);5628}56295630SourceLocation getBeginLoc() const LLVM_READONLY {5631return FExpr->getBeginLoc().getLocWithOffset(Offset);5632}56335634SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }5635};56365637} // namespace56385639static void CheckFormatString(5640Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,5641ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,5642unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,5643bool inFunctionCall, Sema::VariadicCallType CallType,5644llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,5645bool IgnoreStringsWithoutSpecifiers);56465647static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,5648const Expr *E);56495650// Determine if an expression is a string literal or constant string.5651// If this function returns false on the arguments to a function expecting a5652// format string, we will usually need to emit a warning.5653// True string literals are then checked by CheckFormatString.5654static StringLiteralCheckType5655checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,5656Sema::FormatArgumentPassingKind APK, unsigned format_idx,5657unsigned firstDataArg, Sema::FormatStringType Type,5658Sema::VariadicCallType CallType, bool InFunctionCall,5659llvm::SmallBitVector &CheckedVarArgs,5660UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,5661bool IgnoreStringsWithoutSpecifiers = false) {5662if (S.isConstantEvaluatedContext())5663return SLCT_NotALiteral;5664tryAgain:5665assert(Offset.isSigned() && "invalid offset");56665667if (E->isTypeDependent() || E->isValueDependent())5668return SLCT_NotALiteral;56695670E = E->IgnoreParenCasts();56715672if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))5673// Technically -Wformat-nonliteral does not warn about this case.5674// The behavior of printf and friends in this case is implementation5675// dependent. Ideally if the format string cannot be null then5676// it should have a 'nonnull' attribute in the function prototype.5677return SLCT_UncheckedLiteral;56785679switch (E->getStmtClass()) {5680case Stmt::InitListExprClass:5681// Handle expressions like {"foobar"}.5682if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {5683return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,5684Type, CallType, /*InFunctionCall*/ false,5685CheckedVarArgs, UncoveredArg, Offset,5686IgnoreStringsWithoutSpecifiers);5687}5688return SLCT_NotALiteral;5689case Stmt::BinaryConditionalOperatorClass:5690case Stmt::ConditionalOperatorClass: {5691// The expression is a literal if both sub-expressions were, and it was5692// completely checked only if both sub-expressions were checked.5693const AbstractConditionalOperator *C =5694cast<AbstractConditionalOperator>(E);56955696// Determine whether it is necessary to check both sub-expressions, for5697// example, because the condition expression is a constant that can be5698// evaluated at compile time.5699bool CheckLeft = true, CheckRight = true;57005701bool Cond;5702if (C->getCond()->EvaluateAsBooleanCondition(5703Cond, S.getASTContext(), S.isConstantEvaluatedContext())) {5704if (Cond)5705CheckRight = false;5706else5707CheckLeft = false;5708}57095710// We need to maintain the offsets for the right and the left hand side5711// separately to check if every possible indexed expression is a valid5712// string literal. They might have different offsets for different string5713// literals in the end.5714StringLiteralCheckType Left;5715if (!CheckLeft)5716Left = SLCT_UncheckedLiteral;5717else {5718Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, APK, format_idx,5719firstDataArg, Type, CallType, InFunctionCall,5720CheckedVarArgs, UncoveredArg, Offset,5721IgnoreStringsWithoutSpecifiers);5722if (Left == SLCT_NotALiteral || !CheckRight) {5723return Left;5724}5725}57265727StringLiteralCheckType Right = checkFormatStringExpr(5728S, C->getFalseExpr(), Args, APK, format_idx, firstDataArg, Type,5729CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,5730IgnoreStringsWithoutSpecifiers);57315732return (CheckLeft && Left < Right) ? Left : Right;5733}57345735case Stmt::ImplicitCastExprClass:5736E = cast<ImplicitCastExpr>(E)->getSubExpr();5737goto tryAgain;57385739case Stmt::OpaqueValueExprClass:5740if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {5741E = src;5742goto tryAgain;5743}5744return SLCT_NotALiteral;57455746case Stmt::PredefinedExprClass:5747// While __func__, etc., are technically not string literals, they5748// cannot contain format specifiers and thus are not a security5749// liability.5750return SLCT_UncheckedLiteral;57515752case Stmt::DeclRefExprClass: {5753const DeclRefExpr *DR = cast<DeclRefExpr>(E);57545755// As an exception, do not flag errors for variables binding to5756// const string literals.5757if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {5758bool isConstant = false;5759QualType T = DR->getType();57605761if (const ArrayType *AT = S.Context.getAsArrayType(T)) {5762isConstant = AT->getElementType().isConstant(S.Context);5763} else if (const PointerType *PT = T->getAs<PointerType>()) {5764isConstant = T.isConstant(S.Context) &&5765PT->getPointeeType().isConstant(S.Context);5766} else if (T->isObjCObjectPointerType()) {5767// In ObjC, there is usually no "const ObjectPointer" type,5768// so don't check if the pointee type is constant.5769isConstant = T.isConstant(S.Context);5770}57715772if (isConstant) {5773if (const Expr *Init = VD->getAnyInitializer()) {5774// Look through initializers like const char c[] = { "foo" }5775if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {5776if (InitList->isStringLiteralInit())5777Init = InitList->getInit(0)->IgnoreParenImpCasts();5778}5779return checkFormatStringExpr(5780S, Init, Args, APK, format_idx, firstDataArg, Type, CallType,5781/*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);5782}5783}57845785// When the format argument is an argument of this function, and this5786// function also has the format attribute, there are several interactions5787// for which there shouldn't be a warning. For instance, when calling5788// v*printf from a function that has the printf format attribute, we5789// should not emit a warning about using `fmt`, even though it's not5790// constant, because the arguments have already been checked for the5791// caller of `logmessage`:5792//5793// __attribute__((format(printf, 1, 2)))5794// void logmessage(char const *fmt, ...) {5795// va_list ap;5796// va_start(ap, fmt);5797// vprintf(fmt, ap); /* do not emit a warning about "fmt" */5798// ...5799// }5800//5801// Another interaction that we need to support is calling a variadic5802// format function from a format function that has fixed arguments. For5803// instance:5804//5805// __attribute__((format(printf, 1, 2)))5806// void logstring(char const *fmt, char const *str) {5807// printf(fmt, str); /* do not emit a warning about "fmt" */5808// }5809//5810// Same (and perhaps more relatably) for the variadic template case:5811//5812// template<typename... Args>5813// __attribute__((format(printf, 1, 2)))5814// void log(const char *fmt, Args&&... args) {5815// printf(fmt, forward<Args>(args)...);5816// /* do not emit a warning about "fmt" */5817// }5818//5819// Due to implementation difficulty, we only check the format, not the5820// format arguments, in all cases.5821//5822if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {5823if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {5824for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {5825bool IsCXXMember = false;5826if (const auto *MD = dyn_cast<CXXMethodDecl>(D))5827IsCXXMember = MD->isInstance();58285829bool IsVariadic = false;5830if (const FunctionType *FnTy = D->getFunctionType())5831IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();5832else if (const auto *BD = dyn_cast<BlockDecl>(D))5833IsVariadic = BD->isVariadic();5834else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))5835IsVariadic = OMD->isVariadic();58365837Sema::FormatStringInfo CallerFSI;5838if (Sema::getFormatStringInfo(PVFormat, IsCXXMember, IsVariadic,5839&CallerFSI)) {5840// We also check if the formats are compatible.5841// We can't pass a 'scanf' string to a 'printf' function.5842if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx &&5843Type == S.GetFormatStringType(PVFormat)) {5844// Lastly, check that argument passing kinds transition in a5845// way that makes sense:5846// from a caller with FAPK_VAList, allow FAPK_VAList5847// from a caller with FAPK_Fixed, allow FAPK_Fixed5848// from a caller with FAPK_Fixed, allow FAPK_Variadic5849// from a caller with FAPK_Variadic, allow FAPK_VAList5850switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {5851case combineFAPK(Sema::FAPK_VAList, Sema::FAPK_VAList):5852case combineFAPK(Sema::FAPK_Fixed, Sema::FAPK_Fixed):5853case combineFAPK(Sema::FAPK_Fixed, Sema::FAPK_Variadic):5854case combineFAPK(Sema::FAPK_Variadic, Sema::FAPK_VAList):5855return SLCT_UncheckedLiteral;5856}5857}5858}5859}5860}5861}5862}58635864return SLCT_NotALiteral;5865}58665867case Stmt::CallExprClass:5868case Stmt::CXXMemberCallExprClass: {5869const CallExpr *CE = cast<CallExpr>(E);5870if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {5871bool IsFirst = true;5872StringLiteralCheckType CommonResult;5873for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {5874const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());5875StringLiteralCheckType Result = checkFormatStringExpr(5876S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,5877InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,5878IgnoreStringsWithoutSpecifiers);5879if (IsFirst) {5880CommonResult = Result;5881IsFirst = false;5882}5883}5884if (!IsFirst)5885return CommonResult;58865887if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {5888unsigned BuiltinID = FD->getBuiltinID();5889if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||5890BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {5891const Expr *Arg = CE->getArg(0);5892return checkFormatStringExpr(5893S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,5894InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,5895IgnoreStringsWithoutSpecifiers);5896}5897}5898}5899if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))5900return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,5901Type, CallType, /*InFunctionCall*/ false,5902CheckedVarArgs, UncoveredArg, Offset,5903IgnoreStringsWithoutSpecifiers);5904return SLCT_NotALiteral;5905}5906case Stmt::ObjCMessageExprClass: {5907const auto *ME = cast<ObjCMessageExpr>(E);5908if (const auto *MD = ME->getMethodDecl()) {5909if (const auto *FA = MD->getAttr<FormatArgAttr>()) {5910// As a special case heuristic, if we're using the method -[NSBundle5911// localizedStringForKey:value:table:], ignore any key strings that lack5912// format specifiers. The idea is that if the key doesn't have any5913// format specifiers then its probably just a key to map to the5914// localized strings. If it does have format specifiers though, then its5915// likely that the text of the key is the format string in the5916// programmer's language, and should be checked.5917const ObjCInterfaceDecl *IFace;5918if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&5919IFace->getIdentifier()->isStr("NSBundle") &&5920MD->getSelector().isKeywordSelector(5921{"localizedStringForKey", "value", "table"})) {5922IgnoreStringsWithoutSpecifiers = true;5923}59245925const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());5926return checkFormatStringExpr(5927S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,5928InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,5929IgnoreStringsWithoutSpecifiers);5930}5931}59325933return SLCT_NotALiteral;5934}5935case Stmt::ObjCStringLiteralClass:5936case Stmt::StringLiteralClass: {5937const StringLiteral *StrE = nullptr;59385939if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))5940StrE = ObjCFExpr->getString();5941else5942StrE = cast<StringLiteral>(E);59435944if (StrE) {5945if (Offset.isNegative() || Offset > StrE->getLength()) {5946// TODO: It would be better to have an explicit warning for out of5947// bounds literals.5948return SLCT_NotALiteral;5949}5950FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());5951CheckFormatString(S, &FStr, E, Args, APK, format_idx, firstDataArg, Type,5952InFunctionCall, CallType, CheckedVarArgs, UncoveredArg,5953IgnoreStringsWithoutSpecifiers);5954return SLCT_CheckedLiteral;5955}59565957return SLCT_NotALiteral;5958}5959case Stmt::BinaryOperatorClass: {5960const BinaryOperator *BinOp = cast<BinaryOperator>(E);59615962// A string literal + an int offset is still a string literal.5963if (BinOp->isAdditiveOp()) {5964Expr::EvalResult LResult, RResult;59655966bool LIsInt = BinOp->getLHS()->EvaluateAsInt(5967LResult, S.Context, Expr::SE_NoSideEffects,5968S.isConstantEvaluatedContext());5969bool RIsInt = BinOp->getRHS()->EvaluateAsInt(5970RResult, S.Context, Expr::SE_NoSideEffects,5971S.isConstantEvaluatedContext());59725973if (LIsInt != RIsInt) {5974BinaryOperatorKind BinOpKind = BinOp->getOpcode();59755976if (LIsInt) {5977if (BinOpKind == BO_Add) {5978sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);5979E = BinOp->getRHS();5980goto tryAgain;5981}5982} else {5983sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);5984E = BinOp->getLHS();5985goto tryAgain;5986}5987}5988}59895990return SLCT_NotALiteral;5991}5992case Stmt::UnaryOperatorClass: {5993const UnaryOperator *UnaOp = cast<UnaryOperator>(E);5994auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());5995if (UnaOp->getOpcode() == UO_AddrOf && ASE) {5996Expr::EvalResult IndexResult;5997if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,5998Expr::SE_NoSideEffects,5999S.isConstantEvaluatedContext())) {6000sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,6001/*RHS is int*/ true);6002E = ASE->getBase();6003goto tryAgain;6004}6005}60066007return SLCT_NotALiteral;6008}60096010default:6011return SLCT_NotALiteral;6012}6013}60146015// If this expression can be evaluated at compile-time,6016// check if the result is a StringLiteral and return it6017// otherwise return nullptr6018static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,6019const Expr *E) {6020Expr::EvalResult Result;6021if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {6022const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();6023if (isa_and_nonnull<StringLiteral>(LVE))6024return LVE;6025}6026return nullptr;6027}60286029Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {6030return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())6031.Case("scanf", FST_Scanf)6032.Cases("printf", "printf0", FST_Printf)6033.Cases("NSString", "CFString", FST_NSString)6034.Case("strftime", FST_Strftime)6035.Case("strfmon", FST_Strfmon)6036.Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)6037.Case("freebsd_kprintf", FST_FreeBSDKPrintf)6038.Case("os_trace", FST_OSLog)6039.Case("os_log", FST_OSLog)6040.Default(FST_Unknown);6041}60426043bool Sema::CheckFormatArguments(const FormatAttr *Format,6044ArrayRef<const Expr *> Args, bool IsCXXMember,6045VariadicCallType CallType, SourceLocation Loc,6046SourceRange Range,6047llvm::SmallBitVector &CheckedVarArgs) {6048FormatStringInfo FSI;6049if (getFormatStringInfo(Format, IsCXXMember, CallType != VariadicDoesNotApply,6050&FSI))6051return CheckFormatArguments(Args, FSI.ArgPassingKind, FSI.FormatIdx,6052FSI.FirstDataArg, GetFormatStringType(Format),6053CallType, Loc, Range, CheckedVarArgs);6054return false;6055}60566057bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,6058Sema::FormatArgumentPassingKind APK,6059unsigned format_idx, unsigned firstDataArg,6060FormatStringType Type,6061VariadicCallType CallType, SourceLocation Loc,6062SourceRange Range,6063llvm::SmallBitVector &CheckedVarArgs) {6064// CHECK: printf/scanf-like function is called with no format string.6065if (format_idx >= Args.size()) {6066Diag(Loc, diag::warn_missing_format_string) << Range;6067return false;6068}60696070const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();60716072// CHECK: format string is not a string literal.6073//6074// Dynamically generated format strings are difficult to6075// automatically vet at compile time. Requiring that format strings6076// are string literals: (1) permits the checking of format strings by6077// the compiler and thereby (2) can practically remove the source of6078// many format string exploits.60796080// Format string can be either ObjC string (e.g. @"%d") or6081// C string (e.g. "%d")6082// ObjC string uses the same format specifiers as C string, so we can use6083// the same format string checking logic for both ObjC and C strings.6084UncoveredArgHandler UncoveredArg;6085StringLiteralCheckType CT = checkFormatStringExpr(6086*this, OrigFormatExpr, Args, APK, format_idx, firstDataArg, Type,6087CallType,6088/*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,6089/*no string offset*/ llvm::APSInt(64, false) = 0);60906091// Generate a diagnostic where an uncovered argument is detected.6092if (UncoveredArg.hasUncoveredArg()) {6093unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;6094assert(ArgIdx < Args.size() && "ArgIdx outside bounds");6095UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);6096}60976098if (CT != SLCT_NotALiteral)6099// Literal format string found, check done!6100return CT == SLCT_CheckedLiteral;61016102// Strftime is particular as it always uses a single 'time' argument,6103// so it is safe to pass a non-literal string.6104if (Type == FST_Strftime)6105return false;61066107// Do not emit diag when the string param is a macro expansion and the6108// format is either NSString or CFString. This is a hack to prevent6109// diag when using the NSLocalizedString and CFCopyLocalizedString macros6110// which are usually used in place of NS and CF string literals.6111SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();6112if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))6113return false;61146115// If there are no arguments specified, warn with -Wformat-security, otherwise6116// warn only with -Wformat-nonliteral.6117if (Args.size() == firstDataArg) {6118Diag(FormatLoc, diag::warn_format_nonliteral_noargs)6119<< OrigFormatExpr->getSourceRange();6120switch (Type) {6121default:6122break;6123case FST_Kprintf:6124case FST_FreeBSDKPrintf:6125case FST_Printf:6126Diag(FormatLoc, diag::note_format_security_fixit)6127<< FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");6128break;6129case FST_NSString:6130Diag(FormatLoc, diag::note_format_security_fixit)6131<< FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");6132break;6133}6134} else {6135Diag(FormatLoc, diag::warn_format_nonliteral)6136<< OrigFormatExpr->getSourceRange();6137}6138return false;6139}61406141namespace {61426143class CheckFormatHandler : public analyze_format_string::FormatStringHandler {6144protected:6145Sema &S;6146const FormatStringLiteral *FExpr;6147const Expr *OrigFormatExpr;6148const Sema::FormatStringType FSType;6149const unsigned FirstDataArg;6150const unsigned NumDataArgs;6151const char *Beg; // Start of format string.6152const Sema::FormatArgumentPassingKind ArgPassingKind;6153ArrayRef<const Expr *> Args;6154unsigned FormatIdx;6155llvm::SmallBitVector CoveredArgs;6156bool usesPositionalArgs = false;6157bool atFirstArg = true;6158bool inFunctionCall;6159Sema::VariadicCallType CallType;6160llvm::SmallBitVector &CheckedVarArgs;6161UncoveredArgHandler &UncoveredArg;61626163public:6164CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,6165const Expr *origFormatExpr,6166const Sema::FormatStringType type, unsigned firstDataArg,6167unsigned numDataArgs, const char *beg,6168Sema::FormatArgumentPassingKind APK,6169ArrayRef<const Expr *> Args, unsigned formatIdx,6170bool inFunctionCall, Sema::VariadicCallType callType,6171llvm::SmallBitVector &CheckedVarArgs,6172UncoveredArgHandler &UncoveredArg)6173: S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),6174FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),6175ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),6176inFunctionCall(inFunctionCall), CallType(callType),6177CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {6178CoveredArgs.resize(numDataArgs);6179CoveredArgs.reset();6180}61816182void DoneProcessing();61836184void HandleIncompleteSpecifier(const char *startSpecifier,6185unsigned specifierLen) override;61866187void HandleInvalidLengthModifier(6188const analyze_format_string::FormatSpecifier &FS,6189const analyze_format_string::ConversionSpecifier &CS,6190const char *startSpecifier, unsigned specifierLen,6191unsigned DiagID);61926193void HandleNonStandardLengthModifier(6194const analyze_format_string::FormatSpecifier &FS,6195const char *startSpecifier, unsigned specifierLen);61966197void HandleNonStandardConversionSpecifier(6198const analyze_format_string::ConversionSpecifier &CS,6199const char *startSpecifier, unsigned specifierLen);62006201void HandlePosition(const char *startPos, unsigned posLen) override;62026203void HandleInvalidPosition(const char *startSpecifier,6204unsigned specifierLen,6205analyze_format_string::PositionContext p) override;62066207void HandleZeroPosition(const char *startPos, unsigned posLen) override;62086209void HandleNullChar(const char *nullCharacter) override;62106211template <typename Range>6212static void6213EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,6214const PartialDiagnostic &PDiag, SourceLocation StringLoc,6215bool IsStringLocation, Range StringRange,6216ArrayRef<FixItHint> Fixit = std::nullopt);62176218protected:6219bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,6220const char *startSpec,6221unsigned specifierLen,6222const char *csStart, unsigned csLen);62236224void HandlePositionalNonpositionalArgs(SourceLocation Loc,6225const char *startSpec,6226unsigned specifierLen);62276228SourceRange getFormatStringRange();6229CharSourceRange getSpecifierRange(const char *startSpecifier,6230unsigned specifierLen);6231SourceLocation getLocationOfByte(const char *x);62326233const Expr *getDataArg(unsigned i) const;62346235bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,6236const analyze_format_string::ConversionSpecifier &CS,6237const char *startSpecifier, unsigned specifierLen,6238unsigned argIndex);62396240template <typename Range>6241void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,6242bool IsStringLocation, Range StringRange,6243ArrayRef<FixItHint> Fixit = std::nullopt);6244};62456246} // namespace62476248SourceRange CheckFormatHandler::getFormatStringRange() {6249return OrigFormatExpr->getSourceRange();6250}62516252CharSourceRange CheckFormatHandler::6253getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {6254SourceLocation Start = getLocationOfByte(startSpecifier);6255SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);62566257// Advance the end SourceLocation by one due to half-open ranges.6258End = End.getLocWithOffset(1);62596260return CharSourceRange::getCharRange(Start, End);6261}62626263SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {6264return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),6265S.getLangOpts(), S.Context.getTargetInfo());6266}62676268void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,6269unsigned specifierLen){6270EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),6271getLocationOfByte(startSpecifier),6272/*IsStringLocation*/true,6273getSpecifierRange(startSpecifier, specifierLen));6274}62756276void CheckFormatHandler::HandleInvalidLengthModifier(6277const analyze_format_string::FormatSpecifier &FS,6278const analyze_format_string::ConversionSpecifier &CS,6279const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {6280using namespace analyze_format_string;62816282const LengthModifier &LM = FS.getLengthModifier();6283CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());62846285// See if we know how to fix this length modifier.6286std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();6287if (FixedLM) {6288EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),6289getLocationOfByte(LM.getStart()),6290/*IsStringLocation*/true,6291getSpecifierRange(startSpecifier, specifierLen));62926293S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)6294<< FixedLM->toString()6295<< FixItHint::CreateReplacement(LMRange, FixedLM->toString());62966297} else {6298FixItHint Hint;6299if (DiagID == diag::warn_format_nonsensical_length)6300Hint = FixItHint::CreateRemoval(LMRange);63016302EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),6303getLocationOfByte(LM.getStart()),6304/*IsStringLocation*/true,6305getSpecifierRange(startSpecifier, specifierLen),6306Hint);6307}6308}63096310void CheckFormatHandler::HandleNonStandardLengthModifier(6311const analyze_format_string::FormatSpecifier &FS,6312const char *startSpecifier, unsigned specifierLen) {6313using namespace analyze_format_string;63146315const LengthModifier &LM = FS.getLengthModifier();6316CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());63176318// See if we know how to fix this length modifier.6319std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();6320if (FixedLM) {6321EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)6322<< LM.toString() << 0,6323getLocationOfByte(LM.getStart()),6324/*IsStringLocation*/true,6325getSpecifierRange(startSpecifier, specifierLen));63266327S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)6328<< FixedLM->toString()6329<< FixItHint::CreateReplacement(LMRange, FixedLM->toString());63306331} else {6332EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)6333<< LM.toString() << 0,6334getLocationOfByte(LM.getStart()),6335/*IsStringLocation*/true,6336getSpecifierRange(startSpecifier, specifierLen));6337}6338}63396340void CheckFormatHandler::HandleNonStandardConversionSpecifier(6341const analyze_format_string::ConversionSpecifier &CS,6342const char *startSpecifier, unsigned specifierLen) {6343using namespace analyze_format_string;63446345// See if we know how to fix this conversion specifier.6346std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();6347if (FixedCS) {6348EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)6349<< CS.toString() << /*conversion specifier*/1,6350getLocationOfByte(CS.getStart()),6351/*IsStringLocation*/true,6352getSpecifierRange(startSpecifier, specifierLen));63536354CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());6355S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)6356<< FixedCS->toString()6357<< FixItHint::CreateReplacement(CSRange, FixedCS->toString());6358} else {6359EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)6360<< CS.toString() << /*conversion specifier*/1,6361getLocationOfByte(CS.getStart()),6362/*IsStringLocation*/true,6363getSpecifierRange(startSpecifier, specifierLen));6364}6365}63666367void CheckFormatHandler::HandlePosition(const char *startPos,6368unsigned posLen) {6369EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),6370getLocationOfByte(startPos),6371/*IsStringLocation*/true,6372getSpecifierRange(startPos, posLen));6373}63746375void CheckFormatHandler::HandleInvalidPosition(6376const char *startSpecifier, unsigned specifierLen,6377analyze_format_string::PositionContext p) {6378EmitFormatDiagnostic(6379S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,6380getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,6381getSpecifierRange(startSpecifier, specifierLen));6382}63836384void CheckFormatHandler::HandleZeroPosition(const char *startPos,6385unsigned posLen) {6386EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),6387getLocationOfByte(startPos),6388/*IsStringLocation*/true,6389getSpecifierRange(startPos, posLen));6390}63916392void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {6393if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {6394// The presence of a null character is likely an error.6395EmitFormatDiagnostic(6396S.PDiag(diag::warn_printf_format_string_contains_null_char),6397getLocationOfByte(nullCharacter), /*IsStringLocation*/true,6398getFormatStringRange());6399}6400}64016402// Note that this may return NULL if there was an error parsing or building6403// one of the argument expressions.6404const Expr *CheckFormatHandler::getDataArg(unsigned i) const {6405return Args[FirstDataArg + i];6406}64076408void CheckFormatHandler::DoneProcessing() {6409// Does the number of data arguments exceed the number of6410// format conversions in the format string?6411if (ArgPassingKind != Sema::FAPK_VAList) {6412// Find any arguments that weren't covered.6413CoveredArgs.flip();6414signed notCoveredArg = CoveredArgs.find_first();6415if (notCoveredArg >= 0) {6416assert((unsigned)notCoveredArg < NumDataArgs);6417UncoveredArg.Update(notCoveredArg, OrigFormatExpr);6418} else {6419UncoveredArg.setAllCovered();6420}6421}6422}64236424void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,6425const Expr *ArgExpr) {6426assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&6427"Invalid state");64286429if (!ArgExpr)6430return;64316432SourceLocation Loc = ArgExpr->getBeginLoc();64336434if (S.getSourceManager().isInSystemMacro(Loc))6435return;64366437PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);6438for (auto E : DiagnosticExprs)6439PDiag << E->getSourceRange();64406441CheckFormatHandler::EmitFormatDiagnostic(6442S, IsFunctionCall, DiagnosticExprs[0],6443PDiag, Loc, /*IsStringLocation*/false,6444DiagnosticExprs[0]->getSourceRange());6445}64466447bool6448CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,6449SourceLocation Loc,6450const char *startSpec,6451unsigned specifierLen,6452const char *csStart,6453unsigned csLen) {6454bool keepGoing = true;6455if (argIndex < NumDataArgs) {6456// Consider the argument coverered, even though the specifier doesn't6457// make sense.6458CoveredArgs.set(argIndex);6459}6460else {6461// If argIndex exceeds the number of data arguments we6462// don't issue a warning because that is just a cascade of warnings (and6463// they may have intended '%%' anyway). We don't want to continue processing6464// the format string after this point, however, as we will like just get6465// gibberish when trying to match arguments.6466keepGoing = false;6467}64686469StringRef Specifier(csStart, csLen);64706471// If the specifier in non-printable, it could be the first byte of a UTF-86472// sequence. In that case, print the UTF-8 code point. If not, print the byte6473// hex value.6474std::string CodePointStr;6475if (!llvm::sys::locale::isPrint(*csStart)) {6476llvm::UTF32 CodePoint;6477const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);6478const llvm::UTF8 *E =6479reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);6480llvm::ConversionResult Result =6481llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);64826483if (Result != llvm::conversionOK) {6484unsigned char FirstChar = *csStart;6485CodePoint = (llvm::UTF32)FirstChar;6486}64876488llvm::raw_string_ostream OS(CodePointStr);6489if (CodePoint < 256)6490OS << "\\x" << llvm::format("%02x", CodePoint);6491else if (CodePoint <= 0xFFFF)6492OS << "\\u" << llvm::format("%04x", CodePoint);6493else6494OS << "\\U" << llvm::format("%08x", CodePoint);6495OS.flush();6496Specifier = CodePointStr;6497}64986499EmitFormatDiagnostic(6500S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,6501/*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));65026503return keepGoing;6504}65056506void6507CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,6508const char *startSpec,6509unsigned specifierLen) {6510EmitFormatDiagnostic(6511S.PDiag(diag::warn_format_mix_positional_nonpositional_args),6512Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));6513}65146515bool6516CheckFormatHandler::CheckNumArgs(6517const analyze_format_string::FormatSpecifier &FS,6518const analyze_format_string::ConversionSpecifier &CS,6519const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {65206521if (argIndex >= NumDataArgs) {6522PartialDiagnostic PDiag = FS.usesPositionalArg()6523? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)6524<< (argIndex+1) << NumDataArgs)6525: S.PDiag(diag::warn_printf_insufficient_data_args);6526EmitFormatDiagnostic(6527PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,6528getSpecifierRange(startSpecifier, specifierLen));65296530// Since more arguments than conversion tokens are given, by extension6531// all arguments are covered, so mark this as so.6532UncoveredArg.setAllCovered();6533return false;6534}6535return true;6536}65376538template<typename Range>6539void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,6540SourceLocation Loc,6541bool IsStringLocation,6542Range StringRange,6543ArrayRef<FixItHint> FixIt) {6544EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,6545Loc, IsStringLocation, StringRange, FixIt);6546}65476548/// If the format string is not within the function call, emit a note6549/// so that the function call and string are in diagnostic messages.6550///6551/// \param InFunctionCall if true, the format string is within the function6552/// call and only one diagnostic message will be produced. Otherwise, an6553/// extra note will be emitted pointing to location of the format string.6554///6555/// \param ArgumentExpr the expression that is passed as the format string6556/// argument in the function call. Used for getting locations when two6557/// diagnostics are emitted.6558///6559/// \param PDiag the callee should already have provided any strings for the6560/// diagnostic message. This function only adds locations and fixits6561/// to diagnostics.6562///6563/// \param Loc primary location for diagnostic. If two diagnostics are6564/// required, one will be at Loc and a new SourceLocation will be created for6565/// the other one.6566///6567/// \param IsStringLocation if true, Loc points to the format string should be6568/// used for the note. Otherwise, Loc points to the argument list and will6569/// be used with PDiag.6570///6571/// \param StringRange some or all of the string to highlight. This is6572/// templated so it can accept either a CharSourceRange or a SourceRange.6573///6574/// \param FixIt optional fix it hint for the format string.6575template <typename Range>6576void CheckFormatHandler::EmitFormatDiagnostic(6577Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,6578const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,6579Range StringRange, ArrayRef<FixItHint> FixIt) {6580if (InFunctionCall) {6581const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);6582D << StringRange;6583D << FixIt;6584} else {6585S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)6586<< ArgumentExpr->getSourceRange();65876588const Sema::SemaDiagnosticBuilder &Note =6589S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),6590diag::note_format_string_defined);65916592Note << StringRange;6593Note << FixIt;6594}6595}65966597//===--- CHECK: Printf format string checking -----------------------------===//65986599namespace {66006601class CheckPrintfHandler : public CheckFormatHandler {6602public:6603CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,6604const Expr *origFormatExpr,6605const Sema::FormatStringType type, unsigned firstDataArg,6606unsigned numDataArgs, bool isObjC, const char *beg,6607Sema::FormatArgumentPassingKind APK,6608ArrayRef<const Expr *> Args, unsigned formatIdx,6609bool inFunctionCall, Sema::VariadicCallType CallType,6610llvm::SmallBitVector &CheckedVarArgs,6611UncoveredArgHandler &UncoveredArg)6612: CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,6613numDataArgs, beg, APK, Args, formatIdx,6614inFunctionCall, CallType, CheckedVarArgs,6615UncoveredArg) {}66166617bool isObjCContext() const { return FSType == Sema::FST_NSString; }66186619/// Returns true if '%@' specifiers are allowed in the format string.6620bool allowsObjCArg() const {6621return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||6622FSType == Sema::FST_OSTrace;6623}66246625bool HandleInvalidPrintfConversionSpecifier(6626const analyze_printf::PrintfSpecifier &FS,6627const char *startSpecifier,6628unsigned specifierLen) override;66296630void handleInvalidMaskType(StringRef MaskType) override;66316632bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,6633const char *startSpecifier, unsigned specifierLen,6634const TargetInfo &Target) override;6635bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,6636const char *StartSpecifier,6637unsigned SpecifierLen,6638const Expr *E);66396640bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,6641const char *startSpecifier, unsigned specifierLen);6642void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,6643const analyze_printf::OptionalAmount &Amt,6644unsigned type,6645const char *startSpecifier, unsigned specifierLen);6646void HandleFlag(const analyze_printf::PrintfSpecifier &FS,6647const analyze_printf::OptionalFlag &flag,6648const char *startSpecifier, unsigned specifierLen);6649void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,6650const analyze_printf::OptionalFlag &ignoredFlag,6651const analyze_printf::OptionalFlag &flag,6652const char *startSpecifier, unsigned specifierLen);6653bool checkForCStrMembers(const analyze_printf::ArgType &AT,6654const Expr *E);66556656void HandleEmptyObjCModifierFlag(const char *startFlag,6657unsigned flagLen) override;66586659void HandleInvalidObjCModifierFlag(const char *startFlag,6660unsigned flagLen) override;66616662void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,6663const char *flagsEnd,6664const char *conversionPosition)6665override;6666};66676668} // namespace66696670bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(6671const analyze_printf::PrintfSpecifier &FS,6672const char *startSpecifier,6673unsigned specifierLen) {6674const analyze_printf::PrintfConversionSpecifier &CS =6675FS.getConversionSpecifier();66766677return HandleInvalidConversionSpecifier(FS.getArgIndex(),6678getLocationOfByte(CS.getStart()),6679startSpecifier, specifierLen,6680CS.getStart(), CS.getLength());6681}66826683void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {6684S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);6685}66866687bool CheckPrintfHandler::HandleAmount(6688const analyze_format_string::OptionalAmount &Amt, unsigned k,6689const char *startSpecifier, unsigned specifierLen) {6690if (Amt.hasDataArgument()) {6691if (ArgPassingKind != Sema::FAPK_VAList) {6692unsigned argIndex = Amt.getArgIndex();6693if (argIndex >= NumDataArgs) {6694EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)6695<< k,6696getLocationOfByte(Amt.getStart()),6697/*IsStringLocation*/ true,6698getSpecifierRange(startSpecifier, specifierLen));6699// Don't do any more checking. We will just emit6700// spurious errors.6701return false;6702}67036704// Type check the data argument. It should be an 'int'.6705// Although not in conformance with C99, we also allow the argument to be6706// an 'unsigned int' as that is a reasonably safe case. GCC also6707// doesn't emit a warning for that case.6708CoveredArgs.set(argIndex);6709const Expr *Arg = getDataArg(argIndex);6710if (!Arg)6711return false;67126713QualType T = Arg->getType();67146715const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);6716assert(AT.isValid());67176718if (!AT.matchesType(S.Context, T)) {6719EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)6720<< k << AT.getRepresentativeTypeName(S.Context)6721<< T << Arg->getSourceRange(),6722getLocationOfByte(Amt.getStart()),6723/*IsStringLocation*/true,6724getSpecifierRange(startSpecifier, specifierLen));6725// Don't do any more checking. We will just emit6726// spurious errors.6727return false;6728}6729}6730}6731return true;6732}67336734void CheckPrintfHandler::HandleInvalidAmount(6735const analyze_printf::PrintfSpecifier &FS,6736const analyze_printf::OptionalAmount &Amt,6737unsigned type,6738const char *startSpecifier,6739unsigned specifierLen) {6740const analyze_printf::PrintfConversionSpecifier &CS =6741FS.getConversionSpecifier();67426743FixItHint fixit =6744Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant6745? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),6746Amt.getConstantLength()))6747: FixItHint();67486749EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)6750<< type << CS.toString(),6751getLocationOfByte(Amt.getStart()),6752/*IsStringLocation*/true,6753getSpecifierRange(startSpecifier, specifierLen),6754fixit);6755}67566757void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,6758const analyze_printf::OptionalFlag &flag,6759const char *startSpecifier,6760unsigned specifierLen) {6761// Warn about pointless flag with a fixit removal.6762const analyze_printf::PrintfConversionSpecifier &CS =6763FS.getConversionSpecifier();6764EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)6765<< flag.toString() << CS.toString(),6766getLocationOfByte(flag.getPosition()),6767/*IsStringLocation*/true,6768getSpecifierRange(startSpecifier, specifierLen),6769FixItHint::CreateRemoval(6770getSpecifierRange(flag.getPosition(), 1)));6771}67726773void CheckPrintfHandler::HandleIgnoredFlag(6774const analyze_printf::PrintfSpecifier &FS,6775const analyze_printf::OptionalFlag &ignoredFlag,6776const analyze_printf::OptionalFlag &flag,6777const char *startSpecifier,6778unsigned specifierLen) {6779// Warn about ignored flag with a fixit removal.6780EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)6781<< ignoredFlag.toString() << flag.toString(),6782getLocationOfByte(ignoredFlag.getPosition()),6783/*IsStringLocation*/true,6784getSpecifierRange(startSpecifier, specifierLen),6785FixItHint::CreateRemoval(6786getSpecifierRange(ignoredFlag.getPosition(), 1)));6787}67886789void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,6790unsigned flagLen) {6791// Warn about an empty flag.6792EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),6793getLocationOfByte(startFlag),6794/*IsStringLocation*/true,6795getSpecifierRange(startFlag, flagLen));6796}67976798void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,6799unsigned flagLen) {6800// Warn about an invalid flag.6801auto Range = getSpecifierRange(startFlag, flagLen);6802StringRef flag(startFlag, flagLen);6803EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,6804getLocationOfByte(startFlag),6805/*IsStringLocation*/true,6806Range, FixItHint::CreateRemoval(Range));6807}68086809void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(6810const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {6811// Warn about using '[...]' without a '@' conversion.6812auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);6813auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;6814EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),6815getLocationOfByte(conversionPosition),6816/*IsStringLocation*/true,6817Range, FixItHint::CreateRemoval(Range));6818}68196820// Determines if the specified is a C++ class or struct containing6821// a member with the specified name and kind (e.g. a CXXMethodDecl named6822// "c_str()").6823template<typename MemberKind>6824static llvm::SmallPtrSet<MemberKind*, 1>6825CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {6826const RecordType *RT = Ty->getAs<RecordType>();6827llvm::SmallPtrSet<MemberKind*, 1> Results;68286829if (!RT)6830return Results;6831const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());6832if (!RD || !RD->getDefinition())6833return Results;68346835LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),6836Sema::LookupMemberName);6837R.suppressDiagnostics();68386839// We just need to include all members of the right kind turned up by the6840// filter, at this point.6841if (S.LookupQualifiedName(R, RT->getDecl()))6842for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {6843NamedDecl *decl = (*I)->getUnderlyingDecl();6844if (MemberKind *FK = dyn_cast<MemberKind>(decl))6845Results.insert(FK);6846}6847return Results;6848}68496850/// Check if we could call '.c_str()' on an object.6851///6852/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't6853/// allow the call, or if it would be ambiguous).6854bool Sema::hasCStrMethod(const Expr *E) {6855using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;68566857MethodSet Results =6858CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());6859for (MethodSet::iterator MI = Results.begin(), ME = Results.end();6860MI != ME; ++MI)6861if ((*MI)->getMinRequiredArguments() == 0)6862return true;6863return false;6864}68656866// Check if a (w)string was passed when a (w)char* was needed, and offer a6867// better diagnostic if so. AT is assumed to be valid.6868// Returns true when a c_str() conversion method is found.6869bool CheckPrintfHandler::checkForCStrMembers(6870const analyze_printf::ArgType &AT, const Expr *E) {6871using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;68726873MethodSet Results =6874CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());68756876for (MethodSet::iterator MI = Results.begin(), ME = Results.end();6877MI != ME; ++MI) {6878const CXXMethodDecl *Method = *MI;6879if (Method->getMinRequiredArguments() == 0 &&6880AT.matchesType(S.Context, Method->getReturnType())) {6881// FIXME: Suggest parens if the expression needs them.6882SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());6883S.Diag(E->getBeginLoc(), diag::note_printf_c_str)6884<< "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");6885return true;6886}6887}68886889return false;6890}68916892bool CheckPrintfHandler::HandlePrintfSpecifier(6893const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,6894unsigned specifierLen, const TargetInfo &Target) {6895using namespace analyze_format_string;6896using namespace analyze_printf;68976898const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();68996900if (FS.consumesDataArgument()) {6901if (atFirstArg) {6902atFirstArg = false;6903usesPositionalArgs = FS.usesPositionalArg();6904}6905else if (usesPositionalArgs != FS.usesPositionalArg()) {6906HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),6907startSpecifier, specifierLen);6908return false;6909}6910}69116912// First check if the field width, precision, and conversion specifier6913// have matching data arguments.6914if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,6915startSpecifier, specifierLen)) {6916return false;6917}69186919if (!HandleAmount(FS.getPrecision(), /* precision */ 1,6920startSpecifier, specifierLen)) {6921return false;6922}69236924if (!CS.consumesDataArgument()) {6925// FIXME: Technically specifying a precision or field width here6926// makes no sense. Worth issuing a warning at some point.6927return true;6928}69296930// Consume the argument.6931unsigned argIndex = FS.getArgIndex();6932if (argIndex < NumDataArgs) {6933// The check to see if the argIndex is valid will come later.6934// We set the bit here because we may exit early from this6935// function if we encounter some other error.6936CoveredArgs.set(argIndex);6937}69386939// FreeBSD kernel extensions.6940if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||6941CS.getKind() == ConversionSpecifier::FreeBSDDArg) {6942// We need at least two arguments.6943if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))6944return false;69456946// Claim the second argument.6947CoveredArgs.set(argIndex + 1);69486949// Type check the first argument (int for %b, pointer for %D)6950const Expr *Ex = getDataArg(argIndex);6951const analyze_printf::ArgType &AT =6952(CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?6953ArgType(S.Context.IntTy) : ArgType::CPointerTy;6954if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))6955EmitFormatDiagnostic(6956S.PDiag(diag::warn_format_conversion_argument_type_mismatch)6957<< AT.getRepresentativeTypeName(S.Context) << Ex->getType()6958<< false << Ex->getSourceRange(),6959Ex->getBeginLoc(), /*IsStringLocation*/ false,6960getSpecifierRange(startSpecifier, specifierLen));69616962// Type check the second argument (char * for both %b and %D)6963Ex = getDataArg(argIndex + 1);6964const analyze_printf::ArgType &AT2 = ArgType::CStrTy;6965if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))6966EmitFormatDiagnostic(6967S.PDiag(diag::warn_format_conversion_argument_type_mismatch)6968<< AT2.getRepresentativeTypeName(S.Context) << Ex->getType()6969<< false << Ex->getSourceRange(),6970Ex->getBeginLoc(), /*IsStringLocation*/ false,6971getSpecifierRange(startSpecifier, specifierLen));69726973return true;6974}69756976// Check for using an Objective-C specific conversion specifier6977// in a non-ObjC literal.6978if (!allowsObjCArg() && CS.isObjCArg()) {6979return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,6980specifierLen);6981}69826983// %P can only be used with os_log.6984if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {6985return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,6986specifierLen);6987}69886989// %n is not allowed with os_log.6990if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {6991EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),6992getLocationOfByte(CS.getStart()),6993/*IsStringLocation*/ false,6994getSpecifierRange(startSpecifier, specifierLen));69956996return true;6997}69986999// Only scalars are allowed for os_trace.7000if (FSType == Sema::FST_OSTrace &&7001(CS.getKind() == ConversionSpecifier::PArg ||7002CS.getKind() == ConversionSpecifier::sArg ||7003CS.getKind() == ConversionSpecifier::ObjCObjArg)) {7004return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,7005specifierLen);7006}70077008// Check for use of public/private annotation outside of os_log().7009if (FSType != Sema::FST_OSLog) {7010if (FS.isPublic().isSet()) {7011EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)7012<< "public",7013getLocationOfByte(FS.isPublic().getPosition()),7014/*IsStringLocation*/ false,7015getSpecifierRange(startSpecifier, specifierLen));7016}7017if (FS.isPrivate().isSet()) {7018EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)7019<< "private",7020getLocationOfByte(FS.isPrivate().getPosition()),7021/*IsStringLocation*/ false,7022getSpecifierRange(startSpecifier, specifierLen));7023}7024}70257026const llvm::Triple &Triple = Target.getTriple();7027if (CS.getKind() == ConversionSpecifier::nArg &&7028(Triple.isAndroid() || Triple.isOSFuchsia())) {7029EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),7030getLocationOfByte(CS.getStart()),7031/*IsStringLocation*/ false,7032getSpecifierRange(startSpecifier, specifierLen));7033}70347035// Check for invalid use of field width7036if (!FS.hasValidFieldWidth()) {7037HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,7038startSpecifier, specifierLen);7039}70407041// Check for invalid use of precision7042if (!FS.hasValidPrecision()) {7043HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,7044startSpecifier, specifierLen);7045}70467047// Precision is mandatory for %P specifier.7048if (CS.getKind() == ConversionSpecifier::PArg &&7049FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {7050EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),7051getLocationOfByte(startSpecifier),7052/*IsStringLocation*/ false,7053getSpecifierRange(startSpecifier, specifierLen));7054}70557056// Check each flag does not conflict with any other component.7057if (!FS.hasValidThousandsGroupingPrefix())7058HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);7059if (!FS.hasValidLeadingZeros())7060HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);7061if (!FS.hasValidPlusPrefix())7062HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);7063if (!FS.hasValidSpacePrefix())7064HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);7065if (!FS.hasValidAlternativeForm())7066HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);7067if (!FS.hasValidLeftJustified())7068HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);70697070// Check that flags are not ignored by another flag7071if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'7072HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),7073startSpecifier, specifierLen);7074if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'7075HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),7076startSpecifier, specifierLen);70777078// Check the length modifier is valid with the given conversion specifier.7079if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),7080S.getLangOpts()))7081HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,7082diag::warn_format_nonsensical_length);7083else if (!FS.hasStandardLengthModifier())7084HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);7085else if (!FS.hasStandardLengthConversionCombination())7086HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,7087diag::warn_format_non_standard_conversion_spec);70887089if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))7090HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);70917092// The remaining checks depend on the data arguments.7093if (ArgPassingKind == Sema::FAPK_VAList)7094return true;70957096if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))7097return false;70987099const Expr *Arg = getDataArg(argIndex);7100if (!Arg)7101return true;71027103return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);7104}71057106static bool requiresParensToAddCast(const Expr *E) {7107// FIXME: We should have a general way to reason about operator7108// precedence and whether parens are actually needed here.7109// Take care of a few common cases where they aren't.7110const Expr *Inside = E->IgnoreImpCasts();7111if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))7112Inside = POE->getSyntacticForm()->IgnoreImpCasts();71137114switch (Inside->getStmtClass()) {7115case Stmt::ArraySubscriptExprClass:7116case Stmt::CallExprClass:7117case Stmt::CharacterLiteralClass:7118case Stmt::CXXBoolLiteralExprClass:7119case Stmt::DeclRefExprClass:7120case Stmt::FloatingLiteralClass:7121case Stmt::IntegerLiteralClass:7122case Stmt::MemberExprClass:7123case Stmt::ObjCArrayLiteralClass:7124case Stmt::ObjCBoolLiteralExprClass:7125case Stmt::ObjCBoxedExprClass:7126case Stmt::ObjCDictionaryLiteralClass:7127case Stmt::ObjCEncodeExprClass:7128case Stmt::ObjCIvarRefExprClass:7129case Stmt::ObjCMessageExprClass:7130case Stmt::ObjCPropertyRefExprClass:7131case Stmt::ObjCStringLiteralClass:7132case Stmt::ObjCSubscriptRefExprClass:7133case Stmt::ParenExprClass:7134case Stmt::StringLiteralClass:7135case Stmt::UnaryOperatorClass:7136return false;7137default:7138return true;7139}7140}71417142static std::pair<QualType, StringRef>7143shouldNotPrintDirectly(const ASTContext &Context,7144QualType IntendedTy,7145const Expr *E) {7146// Use a 'while' to peel off layers of typedefs.7147QualType TyTy = IntendedTy;7148while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {7149StringRef Name = UserTy->getDecl()->getName();7150QualType CastTy = llvm::StringSwitch<QualType>(Name)7151.Case("CFIndex", Context.getNSIntegerType())7152.Case("NSInteger", Context.getNSIntegerType())7153.Case("NSUInteger", Context.getNSUIntegerType())7154.Case("SInt32", Context.IntTy)7155.Case("UInt32", Context.UnsignedIntTy)7156.Default(QualType());71577158if (!CastTy.isNull())7159return std::make_pair(CastTy, Name);71607161TyTy = UserTy->desugar();7162}71637164// Strip parens if necessary.7165if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))7166return shouldNotPrintDirectly(Context,7167PE->getSubExpr()->getType(),7168PE->getSubExpr());71697170// If this is a conditional expression, then its result type is constructed7171// via usual arithmetic conversions and thus there might be no necessary7172// typedef sugar there. Recurse to operands to check for NSInteger &7173// Co. usage condition.7174if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {7175QualType TrueTy, FalseTy;7176StringRef TrueName, FalseName;71777178std::tie(TrueTy, TrueName) =7179shouldNotPrintDirectly(Context,7180CO->getTrueExpr()->getType(),7181CO->getTrueExpr());7182std::tie(FalseTy, FalseName) =7183shouldNotPrintDirectly(Context,7184CO->getFalseExpr()->getType(),7185CO->getFalseExpr());71867187if (TrueTy == FalseTy)7188return std::make_pair(TrueTy, TrueName);7189else if (TrueTy.isNull())7190return std::make_pair(FalseTy, FalseName);7191else if (FalseTy.isNull())7192return std::make_pair(TrueTy, TrueName);7193}71947195return std::make_pair(QualType(), StringRef());7196}71977198/// Return true if \p ICE is an implicit argument promotion of an arithmetic7199/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked7200/// type do not count.7201static bool7202isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {7203QualType From = ICE->getSubExpr()->getType();7204QualType To = ICE->getType();7205// It's an integer promotion if the destination type is the promoted7206// source type.7207if (ICE->getCastKind() == CK_IntegralCast &&7208S.Context.isPromotableIntegerType(From) &&7209S.Context.getPromotedIntegerType(From) == To)7210return true;7211// Look through vector types, since we do default argument promotion for7212// those in OpenCL.7213if (const auto *VecTy = From->getAs<ExtVectorType>())7214From = VecTy->getElementType();7215if (const auto *VecTy = To->getAs<ExtVectorType>())7216To = VecTy->getElementType();7217// It's a floating promotion if the source type is a lower rank.7218return ICE->getCastKind() == CK_FloatingCast &&7219S.Context.getFloatingTypeOrder(From, To) < 0;7220}72217222static analyze_format_string::ArgType::MatchKind7223handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match,7224DiagnosticsEngine &Diags, SourceLocation Loc) {7225if (Match == analyze_format_string::ArgType::NoMatchSignedness) {7226Match =7227Diags.isIgnored(7228diag::warn_format_conversion_argument_type_mismatch_signedness, Loc)7229? analyze_format_string::ArgType::Match7230: analyze_format_string::ArgType::NoMatch;7231}7232return Match;7233}72347235bool7236CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,7237const char *StartSpecifier,7238unsigned SpecifierLen,7239const Expr *E) {7240using namespace analyze_format_string;7241using namespace analyze_printf;72427243// Now type check the data expression that matches the7244// format specifier.7245const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());7246if (!AT.isValid())7247return true;72487249QualType ExprTy = E->getType();7250while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {7251ExprTy = TET->getUnderlyingExpr()->getType();7252}72537254// When using the format attribute in C++, you can receive a function or an7255// array that will necessarily decay to a pointer when passed to the final7256// format consumer. Apply decay before type comparison.7257if (ExprTy->canDecayToPointerType())7258ExprTy = S.Context.getDecayedType(ExprTy);72597260// Diagnose attempts to print a boolean value as a character. Unlike other7261// -Wformat diagnostics, this is fine from a type perspective, but it still7262// doesn't make sense.7263if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&7264E->isKnownToHaveBooleanValue()) {7265const CharSourceRange &CSR =7266getSpecifierRange(StartSpecifier, SpecifierLen);7267SmallString<4> FSString;7268llvm::raw_svector_ostream os(FSString);7269FS.toString(os);7270EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)7271<< FSString,7272E->getExprLoc(), false, CSR);7273return true;7274}72757276// Diagnose attempts to use '%P' with ObjC object types, which will result in7277// dumping raw class data (like is-a pointer), not actual data.7278if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&7279ExprTy->isObjCObjectPointerType()) {7280const CharSourceRange &CSR =7281getSpecifierRange(StartSpecifier, SpecifierLen);7282EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),7283E->getExprLoc(), false, CSR);7284return true;7285}72867287ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;7288ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);7289ArgType::MatchKind OrigMatch = Match;72907291Match = handleFormatSignedness(Match, S.getDiagnostics(), E->getExprLoc());7292if (Match == ArgType::Match)7293return true;72947295// NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr7296assert(Match != ArgType::NoMatchPromotionTypeConfusion);72977298// Look through argument promotions for our error message's reported type.7299// This includes the integral and floating promotions, but excludes array7300// and function pointer decay (seeing that an argument intended to be a7301// string has type 'char [6]' is probably more confusing than 'char *') and7302// certain bitfield promotions (bitfields can be 'demoted' to a lesser type).7303if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {7304if (isArithmeticArgumentPromotion(S, ICE)) {7305E = ICE->getSubExpr();7306ExprTy = E->getType();73077308// Check if we didn't match because of an implicit cast from a 'char'7309// or 'short' to an 'int'. This is done because printf is a varargs7310// function.7311if (ICE->getType() == S.Context.IntTy ||7312ICE->getType() == S.Context.UnsignedIntTy) {7313// All further checking is done on the subexpression7314ImplicitMatch = AT.matchesType(S.Context, ExprTy);7315if (OrigMatch == ArgType::NoMatchSignedness &&7316ImplicitMatch != ArgType::NoMatchSignedness)7317// If the original match was a signedness match this match on the7318// implicit cast type also need to be signedness match otherwise we7319// might introduce new unexpected warnings from -Wformat-signedness.7320return true;7321ImplicitMatch = handleFormatSignedness(7322ImplicitMatch, S.getDiagnostics(), E->getExprLoc());7323if (ImplicitMatch == ArgType::Match)7324return true;7325}7326}7327} else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {7328// Special case for 'a', which has type 'int' in C.7329// Note, however, that we do /not/ want to treat multibyte constants like7330// 'MooV' as characters! This form is deprecated but still exists. In7331// addition, don't treat expressions as of type 'char' if one byte length7332// modifier is provided.7333if (ExprTy == S.Context.IntTy &&7334FS.getLengthModifier().getKind() != LengthModifier::AsChar)7335if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {7336ExprTy = S.Context.CharTy;7337// To improve check results, we consider a character literal in C7338// to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is7339// more likely a type confusion situation, so we will suggest to7340// use '%hhd' instead by discarding the MatchPromotion.7341if (Match == ArgType::MatchPromotion)7342Match = ArgType::NoMatch;7343}7344}7345if (Match == ArgType::MatchPromotion) {7346// WG14 N2562 only clarified promotions in *printf7347// For NSLog in ObjC, just preserve -Wformat behavior7348if (!S.getLangOpts().ObjC &&7349ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&7350ImplicitMatch != ArgType::NoMatchTypeConfusion)7351return true;7352Match = ArgType::NoMatch;7353}7354if (ImplicitMatch == ArgType::NoMatchPedantic ||7355ImplicitMatch == ArgType::NoMatchTypeConfusion)7356Match = ImplicitMatch;7357assert(Match != ArgType::MatchPromotion);73587359// Look through unscoped enums to their underlying type.7360bool IsEnum = false;7361bool IsScopedEnum = false;7362QualType IntendedTy = ExprTy;7363if (auto EnumTy = ExprTy->getAs<EnumType>()) {7364IntendedTy = EnumTy->getDecl()->getIntegerType();7365if (EnumTy->isUnscopedEnumerationType()) {7366ExprTy = IntendedTy;7367// This controls whether we're talking about the underlying type or not,7368// which we only want to do when it's an unscoped enum.7369IsEnum = true;7370} else {7371IsScopedEnum = true;7372}7373}73747375// %C in an Objective-C context prints a unichar, not a wchar_t.7376// If the argument is an integer of some kind, believe the %C and suggest7377// a cast instead of changing the conversion specifier.7378if (isObjCContext() &&7379FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {7380if (ExprTy->isIntegralOrUnscopedEnumerationType() &&7381!ExprTy->isCharType()) {7382// 'unichar' is defined as a typedef of unsigned short, but we should7383// prefer using the typedef if it is visible.7384IntendedTy = S.Context.UnsignedShortTy;73857386// While we are here, check if the value is an IntegerLiteral that happens7387// to be within the valid range.7388if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {7389const llvm::APInt &V = IL->getValue();7390if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))7391return true;7392}73937394LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),7395Sema::LookupOrdinaryName);7396if (S.LookupName(Result, S.getCurScope())) {7397NamedDecl *ND = Result.getFoundDecl();7398if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))7399if (TD->getUnderlyingType() == IntendedTy)7400IntendedTy = S.Context.getTypedefType(TD);7401}7402}7403}74047405// Special-case some of Darwin's platform-independence types by suggesting7406// casts to primitive types that are known to be large enough.7407bool ShouldNotPrintDirectly = false; StringRef CastTyName;7408if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {7409QualType CastTy;7410std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);7411if (!CastTy.isNull()) {7412// %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int7413// (long in ASTContext). Only complain to pedants or when they're the7414// underlying type of a scoped enum (which always needs a cast).7415if (!IsScopedEnum &&7416(CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&7417(AT.isSizeT() || AT.isPtrdiffT()) &&7418AT.matchesType(S.Context, CastTy))7419Match = ArgType::NoMatchPedantic;7420IntendedTy = CastTy;7421ShouldNotPrintDirectly = true;7422}7423}74247425// We may be able to offer a FixItHint if it is a supported type.7426PrintfSpecifier fixedFS = FS;7427bool Success =7428fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());74297430if (Success) {7431// Get the fix string from the fixed format specifier7432SmallString<16> buf;7433llvm::raw_svector_ostream os(buf);7434fixedFS.toString(os);74357436CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);74377438if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {7439unsigned Diag;7440switch (Match) {7441case ArgType::Match:7442case ArgType::MatchPromotion:7443case ArgType::NoMatchPromotionTypeConfusion:7444case ArgType::NoMatchSignedness:7445llvm_unreachable("expected non-matching");7446case ArgType::NoMatchPedantic:7447Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;7448break;7449case ArgType::NoMatchTypeConfusion:7450Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;7451break;7452case ArgType::NoMatch:7453Diag = diag::warn_format_conversion_argument_type_mismatch;7454break;7455}74567457// In this case, the specifier is wrong and should be changed to match7458// the argument.7459EmitFormatDiagnostic(S.PDiag(Diag)7460<< AT.getRepresentativeTypeName(S.Context)7461<< IntendedTy << IsEnum << E->getSourceRange(),7462E->getBeginLoc(),7463/*IsStringLocation*/ false, SpecRange,7464FixItHint::CreateReplacement(SpecRange, os.str()));7465} else {7466// The canonical type for formatting this value is different from the7467// actual type of the expression. (This occurs, for example, with Darwin's7468// NSInteger on 32-bit platforms, where it is typedef'd as 'int', but7469// should be printed as 'long' for 64-bit compatibility.)7470// Rather than emitting a normal format/argument mismatch, we want to7471// add a cast to the recommended type (and correct the format string7472// if necessary). We should also do so for scoped enumerations.7473SmallString<16> CastBuf;7474llvm::raw_svector_ostream CastFix(CastBuf);7475CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");7476IntendedTy.print(CastFix, S.Context.getPrintingPolicy());7477CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");74787479SmallVector<FixItHint,4> Hints;7480ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);7481IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),7482E->getExprLoc());7483if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)7484Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));74857486if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {7487// If there's already a cast present, just replace it.7488SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());7489Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));74907491} else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {7492// If the expression has high enough precedence,7493// just write the C-style cast.7494Hints.push_back(7495FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));7496} else {7497// Otherwise, add parens around the expression as well as the cast.7498CastFix << "(";7499Hints.push_back(7500FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));75017502// We don't use getLocForEndOfToken because it returns invalid source7503// locations for macro expansions (by design).7504SourceLocation EndLoc = S.SourceMgr.getSpellingLoc(E->getEndLoc());7505SourceLocation After = EndLoc.getLocWithOffset(7506Lexer::MeasureTokenLength(EndLoc, S.SourceMgr, S.LangOpts));7507Hints.push_back(FixItHint::CreateInsertion(After, ")"));7508}75097510if (ShouldNotPrintDirectly && !IsScopedEnum) {7511// The expression has a type that should not be printed directly.7512// We extract the name from the typedef because we don't want to show7513// the underlying type in the diagnostic.7514StringRef Name;7515if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())7516Name = TypedefTy->getDecl()->getName();7517else7518Name = CastTyName;7519unsigned Diag = Match == ArgType::NoMatchPedantic7520? diag::warn_format_argument_needs_cast_pedantic7521: diag::warn_format_argument_needs_cast;7522EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum7523<< E->getSourceRange(),7524E->getBeginLoc(), /*IsStringLocation=*/false,7525SpecRange, Hints);7526} else {7527// In this case, the expression could be printed using a different7528// specifier, but we've decided that the specifier is probably correct7529// and we should cast instead. Just use the normal warning message.75307531unsigned Diag =7532IsScopedEnum7533? diag::warn_format_conversion_argument_type_mismatch_pedantic7534: diag::warn_format_conversion_argument_type_mismatch;75357536EmitFormatDiagnostic(7537S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy7538<< IsEnum << E->getSourceRange(),7539E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);7540}7541}7542} else {7543const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,7544SpecifierLen);7545// Since the warning for passing non-POD types to variadic functions7546// was deferred until now, we emit a warning for non-POD7547// arguments here.7548bool EmitTypeMismatch = false;7549switch (S.isValidVarArgType(ExprTy)) {7550case Sema::VAK_Valid:7551case Sema::VAK_ValidInCXX11: {7552unsigned Diag;7553switch (Match) {7554case ArgType::Match:7555case ArgType::MatchPromotion:7556case ArgType::NoMatchPromotionTypeConfusion:7557case ArgType::NoMatchSignedness:7558llvm_unreachable("expected non-matching");7559case ArgType::NoMatchPedantic:7560Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;7561break;7562case ArgType::NoMatchTypeConfusion:7563Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;7564break;7565case ArgType::NoMatch:7566Diag = diag::warn_format_conversion_argument_type_mismatch;7567break;7568}75697570EmitFormatDiagnostic(7571S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy7572<< IsEnum << CSR << E->getSourceRange(),7573E->getBeginLoc(), /*IsStringLocation*/ false, CSR);7574break;7575}7576case Sema::VAK_Undefined:7577case Sema::VAK_MSVCUndefined:7578if (CallType == Sema::VariadicDoesNotApply) {7579EmitTypeMismatch = true;7580} else {7581EmitFormatDiagnostic(7582S.PDiag(diag::warn_non_pod_vararg_with_format_string)7583<< S.getLangOpts().CPlusPlus11 << ExprTy << CallType7584<< AT.getRepresentativeTypeName(S.Context) << CSR7585<< E->getSourceRange(),7586E->getBeginLoc(), /*IsStringLocation*/ false, CSR);7587checkForCStrMembers(AT, E);7588}7589break;75907591case Sema::VAK_Invalid:7592if (CallType == Sema::VariadicDoesNotApply)7593EmitTypeMismatch = true;7594else if (ExprTy->isObjCObjectType())7595EmitFormatDiagnostic(7596S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)7597<< S.getLangOpts().CPlusPlus11 << ExprTy << CallType7598<< AT.getRepresentativeTypeName(S.Context) << CSR7599<< E->getSourceRange(),7600E->getBeginLoc(), /*IsStringLocation*/ false, CSR);7601else7602// FIXME: If this is an initializer list, suggest removing the braces7603// or inserting a cast to the target type.7604S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)7605<< isa<InitListExpr>(E) << ExprTy << CallType7606<< AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();7607break;7608}76097610if (EmitTypeMismatch) {7611// The function is not variadic, so we do not generate warnings about7612// being allowed to pass that object as a variadic argument. Instead,7613// since there are inherently no printf specifiers for types which cannot7614// be passed as variadic arguments, emit a plain old specifier mismatch7615// argument.7616EmitFormatDiagnostic(7617S.PDiag(diag::warn_format_conversion_argument_type_mismatch)7618<< AT.getRepresentativeTypeName(S.Context) << ExprTy << false7619<< E->getSourceRange(),7620E->getBeginLoc(), false, CSR);7621}76227623assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&7624"format string specifier index out of range");7625CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;7626}76277628return true;7629}76307631//===--- CHECK: Scanf format string checking ------------------------------===//76327633namespace {76347635class CheckScanfHandler : public CheckFormatHandler {7636public:7637CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,7638const Expr *origFormatExpr, Sema::FormatStringType type,7639unsigned firstDataArg, unsigned numDataArgs,7640const char *beg, Sema::FormatArgumentPassingKind APK,7641ArrayRef<const Expr *> Args, unsigned formatIdx,7642bool inFunctionCall, Sema::VariadicCallType CallType,7643llvm::SmallBitVector &CheckedVarArgs,7644UncoveredArgHandler &UncoveredArg)7645: CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,7646numDataArgs, beg, APK, Args, formatIdx,7647inFunctionCall, CallType, CheckedVarArgs,7648UncoveredArg) {}76497650bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,7651const char *startSpecifier,7652unsigned specifierLen) override;76537654bool HandleInvalidScanfConversionSpecifier(7655const analyze_scanf::ScanfSpecifier &FS,7656const char *startSpecifier,7657unsigned specifierLen) override;76587659void HandleIncompleteScanList(const char *start, const char *end) override;7660};76617662} // namespace76637664void CheckScanfHandler::HandleIncompleteScanList(const char *start,7665const char *end) {7666EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),7667getLocationOfByte(end), /*IsStringLocation*/true,7668getSpecifierRange(start, end - start));7669}76707671bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(7672const analyze_scanf::ScanfSpecifier &FS,7673const char *startSpecifier,7674unsigned specifierLen) {7675const analyze_scanf::ScanfConversionSpecifier &CS =7676FS.getConversionSpecifier();76777678return HandleInvalidConversionSpecifier(FS.getArgIndex(),7679getLocationOfByte(CS.getStart()),7680startSpecifier, specifierLen,7681CS.getStart(), CS.getLength());7682}76837684bool CheckScanfHandler::HandleScanfSpecifier(7685const analyze_scanf::ScanfSpecifier &FS,7686const char *startSpecifier,7687unsigned specifierLen) {7688using namespace analyze_scanf;7689using namespace analyze_format_string;76907691const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();76927693// Handle case where '%' and '*' don't consume an argument. These shouldn't7694// be used to decide if we are using positional arguments consistently.7695if (FS.consumesDataArgument()) {7696if (atFirstArg) {7697atFirstArg = false;7698usesPositionalArgs = FS.usesPositionalArg();7699}7700else if (usesPositionalArgs != FS.usesPositionalArg()) {7701HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),7702startSpecifier, specifierLen);7703return false;7704}7705}77067707// Check if the field with is non-zero.7708const OptionalAmount &Amt = FS.getFieldWidth();7709if (Amt.getHowSpecified() == OptionalAmount::Constant) {7710if (Amt.getConstantAmount() == 0) {7711const CharSourceRange &R = getSpecifierRange(Amt.getStart(),7712Amt.getConstantLength());7713EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),7714getLocationOfByte(Amt.getStart()),7715/*IsStringLocation*/true, R,7716FixItHint::CreateRemoval(R));7717}7718}77197720if (!FS.consumesDataArgument()) {7721// FIXME: Technically specifying a precision or field width here7722// makes no sense. Worth issuing a warning at some point.7723return true;7724}77257726// Consume the argument.7727unsigned argIndex = FS.getArgIndex();7728if (argIndex < NumDataArgs) {7729// The check to see if the argIndex is valid will come later.7730// We set the bit here because we may exit early from this7731// function if we encounter some other error.7732CoveredArgs.set(argIndex);7733}77347735// Check the length modifier is valid with the given conversion specifier.7736if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),7737S.getLangOpts()))7738HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,7739diag::warn_format_nonsensical_length);7740else if (!FS.hasStandardLengthModifier())7741HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);7742else if (!FS.hasStandardLengthConversionCombination())7743HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,7744diag::warn_format_non_standard_conversion_spec);77457746if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))7747HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);77487749// The remaining checks depend on the data arguments.7750if (ArgPassingKind == Sema::FAPK_VAList)7751return true;77527753if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))7754return false;77557756// Check that the argument type matches the format specifier.7757const Expr *Ex = getDataArg(argIndex);7758if (!Ex)7759return true;77607761const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);77627763if (!AT.isValid()) {7764return true;7765}77667767analyze_format_string::ArgType::MatchKind Match =7768AT.matchesType(S.Context, Ex->getType());7769Match = handleFormatSignedness(Match, S.getDiagnostics(), Ex->getExprLoc());7770bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;7771if (Match == analyze_format_string::ArgType::Match)7772return true;77737774ScanfSpecifier fixedFS = FS;7775bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),7776S.getLangOpts(), S.Context);77777778unsigned Diag =7779Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic7780: diag::warn_format_conversion_argument_type_mismatch;77817782if (Success) {7783// Get the fix string from the fixed format specifier.7784SmallString<128> buf;7785llvm::raw_svector_ostream os(buf);7786fixedFS.toString(os);77877788EmitFormatDiagnostic(7789S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)7790<< Ex->getType() << false << Ex->getSourceRange(),7791Ex->getBeginLoc(),7792/*IsStringLocation*/ false,7793getSpecifierRange(startSpecifier, specifierLen),7794FixItHint::CreateReplacement(7795getSpecifierRange(startSpecifier, specifierLen), os.str()));7796} else {7797EmitFormatDiagnostic(S.PDiag(Diag)7798<< AT.getRepresentativeTypeName(S.Context)7799<< Ex->getType() << false << Ex->getSourceRange(),7800Ex->getBeginLoc(),7801/*IsStringLocation*/ false,7802getSpecifierRange(startSpecifier, specifierLen));7803}78047805return true;7806}78077808static void CheckFormatString(7809Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,7810ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,7811unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,7812bool inFunctionCall, Sema::VariadicCallType CallType,7813llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,7814bool IgnoreStringsWithoutSpecifiers) {7815// CHECK: is the format string a wide literal?7816if (!FExpr->isAscii() && !FExpr->isUTF8()) {7817CheckFormatHandler::EmitFormatDiagnostic(7818S, inFunctionCall, Args[format_idx],7819S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),7820/*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());7821return;7822}78237824// Str - The format string. NOTE: this is NOT null-terminated!7825StringRef StrRef = FExpr->getString();7826const char *Str = StrRef.data();7827// Account for cases where the string literal is truncated in a declaration.7828const ConstantArrayType *T =7829S.Context.getAsConstantArrayType(FExpr->getType());7830assert(T && "String literal not of constant array type!");7831size_t TypeSize = T->getZExtSize();7832size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());7833const unsigned numDataArgs = Args.size() - firstDataArg;78347835if (IgnoreStringsWithoutSpecifiers &&7836!analyze_format_string::parseFormatStringHasFormattingSpecifiers(7837Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))7838return;78397840// Emit a warning if the string literal is truncated and does not contain an7841// embedded null character.7842if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {7843CheckFormatHandler::EmitFormatDiagnostic(7844S, inFunctionCall, Args[format_idx],7845S.PDiag(diag::warn_printf_format_string_not_null_terminated),7846FExpr->getBeginLoc(),7847/*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());7848return;7849}78507851// CHECK: empty format string?7852if (StrLen == 0 && numDataArgs > 0) {7853CheckFormatHandler::EmitFormatDiagnostic(7854S, inFunctionCall, Args[format_idx],7855S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),7856/*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());7857return;7858}78597860if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||7861Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||7862Type == Sema::FST_OSTrace) {7863CheckPrintfHandler H(7864S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,7865(Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, APK,7866Args, format_idx, inFunctionCall, CallType, CheckedVarArgs,7867UncoveredArg);78687869if (!analyze_format_string::ParsePrintfString(7870H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),7871Type == Sema::FST_FreeBSDKPrintf))7872H.DoneProcessing();7873} else if (Type == Sema::FST_Scanf) {7874CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,7875numDataArgs, Str, APK, Args, format_idx, inFunctionCall,7876CallType, CheckedVarArgs, UncoveredArg);78777878if (!analyze_format_string::ParseScanfString(7879H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))7880H.DoneProcessing();7881} // TODO: handle other formats7882}78837884bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {7885// Str - The format string. NOTE: this is NOT null-terminated!7886StringRef StrRef = FExpr->getString();7887const char *Str = StrRef.data();7888// Account for cases where the string literal is truncated in a declaration.7889const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());7890assert(T && "String literal not of constant array type!");7891size_t TypeSize = T->getZExtSize();7892size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());7893return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,7894getLangOpts(),7895Context.getTargetInfo());7896}78977898//===--- CHECK: Warn on use of wrong absolute value function. -------------===//78997900// Returns the related absolute value function that is larger, of 0 if one7901// does not exist.7902static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {7903switch (AbsFunction) {7904default:7905return 0;79067907case Builtin::BI__builtin_abs:7908return Builtin::BI__builtin_labs;7909case Builtin::BI__builtin_labs:7910return Builtin::BI__builtin_llabs;7911case Builtin::BI__builtin_llabs:7912return 0;79137914case Builtin::BI__builtin_fabsf:7915return Builtin::BI__builtin_fabs;7916case Builtin::BI__builtin_fabs:7917return Builtin::BI__builtin_fabsl;7918case Builtin::BI__builtin_fabsl:7919return 0;79207921case Builtin::BI__builtin_cabsf:7922return Builtin::BI__builtin_cabs;7923case Builtin::BI__builtin_cabs:7924return Builtin::BI__builtin_cabsl;7925case Builtin::BI__builtin_cabsl:7926return 0;79277928case Builtin::BIabs:7929return Builtin::BIlabs;7930case Builtin::BIlabs:7931return Builtin::BIllabs;7932case Builtin::BIllabs:7933return 0;79347935case Builtin::BIfabsf:7936return Builtin::BIfabs;7937case Builtin::BIfabs:7938return Builtin::BIfabsl;7939case Builtin::BIfabsl:7940return 0;79417942case Builtin::BIcabsf:7943return Builtin::BIcabs;7944case Builtin::BIcabs:7945return Builtin::BIcabsl;7946case Builtin::BIcabsl:7947return 0;7948}7949}79507951// Returns the argument type of the absolute value function.7952static QualType getAbsoluteValueArgumentType(ASTContext &Context,7953unsigned AbsType) {7954if (AbsType == 0)7955return QualType();79567957ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;7958QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);7959if (Error != ASTContext::GE_None)7960return QualType();79617962const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();7963if (!FT)7964return QualType();79657966if (FT->getNumParams() != 1)7967return QualType();79687969return FT->getParamType(0);7970}79717972// Returns the best absolute value function, or zero, based on type and7973// current absolute value function.7974static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,7975unsigned AbsFunctionKind) {7976unsigned BestKind = 0;7977uint64_t ArgSize = Context.getTypeSize(ArgType);7978for (unsigned Kind = AbsFunctionKind; Kind != 0;7979Kind = getLargerAbsoluteValueFunction(Kind)) {7980QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);7981if (Context.getTypeSize(ParamType) >= ArgSize) {7982if (BestKind == 0)7983BestKind = Kind;7984else if (Context.hasSameType(ParamType, ArgType)) {7985BestKind = Kind;7986break;7987}7988}7989}7990return BestKind;7991}79927993enum AbsoluteValueKind {7994AVK_Integer,7995AVK_Floating,7996AVK_Complex7997};79987999static AbsoluteValueKind getAbsoluteValueKind(QualType T) {8000if (T->isIntegralOrEnumerationType())8001return AVK_Integer;8002if (T->isRealFloatingType())8003return AVK_Floating;8004if (T->isAnyComplexType())8005return AVK_Complex;80068007llvm_unreachable("Type not integer, floating, or complex");8008}80098010// Changes the absolute value function to a different type. Preserves whether8011// the function is a builtin.8012static unsigned changeAbsFunction(unsigned AbsKind,8013AbsoluteValueKind ValueKind) {8014switch (ValueKind) {8015case AVK_Integer:8016switch (AbsKind) {8017default:8018return 0;8019case Builtin::BI__builtin_fabsf:8020case Builtin::BI__builtin_fabs:8021case Builtin::BI__builtin_fabsl:8022case Builtin::BI__builtin_cabsf:8023case Builtin::BI__builtin_cabs:8024case Builtin::BI__builtin_cabsl:8025return Builtin::BI__builtin_abs;8026case Builtin::BIfabsf:8027case Builtin::BIfabs:8028case Builtin::BIfabsl:8029case Builtin::BIcabsf:8030case Builtin::BIcabs:8031case Builtin::BIcabsl:8032return Builtin::BIabs;8033}8034case AVK_Floating:8035switch (AbsKind) {8036default:8037return 0;8038case Builtin::BI__builtin_abs:8039case Builtin::BI__builtin_labs:8040case Builtin::BI__builtin_llabs:8041case Builtin::BI__builtin_cabsf:8042case Builtin::BI__builtin_cabs:8043case Builtin::BI__builtin_cabsl:8044return Builtin::BI__builtin_fabsf;8045case Builtin::BIabs:8046case Builtin::BIlabs:8047case Builtin::BIllabs:8048case Builtin::BIcabsf:8049case Builtin::BIcabs:8050case Builtin::BIcabsl:8051return Builtin::BIfabsf;8052}8053case AVK_Complex:8054switch (AbsKind) {8055default:8056return 0;8057case Builtin::BI__builtin_abs:8058case Builtin::BI__builtin_labs:8059case Builtin::BI__builtin_llabs:8060case Builtin::BI__builtin_fabsf:8061case Builtin::BI__builtin_fabs:8062case Builtin::BI__builtin_fabsl:8063return Builtin::BI__builtin_cabsf;8064case Builtin::BIabs:8065case Builtin::BIlabs:8066case Builtin::BIllabs:8067case Builtin::BIfabsf:8068case Builtin::BIfabs:8069case Builtin::BIfabsl:8070return Builtin::BIcabsf;8071}8072}8073llvm_unreachable("Unable to convert function");8074}80758076static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {8077const IdentifierInfo *FnInfo = FDecl->getIdentifier();8078if (!FnInfo)8079return 0;80808081switch (FDecl->getBuiltinID()) {8082default:8083return 0;8084case Builtin::BI__builtin_abs:8085case Builtin::BI__builtin_fabs:8086case Builtin::BI__builtin_fabsf:8087case Builtin::BI__builtin_fabsl:8088case Builtin::BI__builtin_labs:8089case Builtin::BI__builtin_llabs:8090case Builtin::BI__builtin_cabs:8091case Builtin::BI__builtin_cabsf:8092case Builtin::BI__builtin_cabsl:8093case Builtin::BIabs:8094case Builtin::BIlabs:8095case Builtin::BIllabs:8096case Builtin::BIfabs:8097case Builtin::BIfabsf:8098case Builtin::BIfabsl:8099case Builtin::BIcabs:8100case Builtin::BIcabsf:8101case Builtin::BIcabsl:8102return FDecl->getBuiltinID();8103}8104llvm_unreachable("Unknown Builtin type");8105}81068107// If the replacement is valid, emit a note with replacement function.8108// Additionally, suggest including the proper header if not already included.8109static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,8110unsigned AbsKind, QualType ArgType) {8111bool EmitHeaderHint = true;8112const char *HeaderName = nullptr;8113StringRef FunctionName;8114if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {8115FunctionName = "std::abs";8116if (ArgType->isIntegralOrEnumerationType()) {8117HeaderName = "cstdlib";8118} else if (ArgType->isRealFloatingType()) {8119HeaderName = "cmath";8120} else {8121llvm_unreachable("Invalid Type");8122}81238124// Lookup all std::abs8125if (NamespaceDecl *Std = S.getStdNamespace()) {8126LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);8127R.suppressDiagnostics();8128S.LookupQualifiedName(R, Std);81298130for (const auto *I : R) {8131const FunctionDecl *FDecl = nullptr;8132if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {8133FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());8134} else {8135FDecl = dyn_cast<FunctionDecl>(I);8136}8137if (!FDecl)8138continue;81398140// Found std::abs(), check that they are the right ones.8141if (FDecl->getNumParams() != 1)8142continue;81438144// Check that the parameter type can handle the argument.8145QualType ParamType = FDecl->getParamDecl(0)->getType();8146if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&8147S.Context.getTypeSize(ArgType) <=8148S.Context.getTypeSize(ParamType)) {8149// Found a function, don't need the header hint.8150EmitHeaderHint = false;8151break;8152}8153}8154}8155} else {8156FunctionName = S.Context.BuiltinInfo.getName(AbsKind);8157HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);81588159if (HeaderName) {8160DeclarationName DN(&S.Context.Idents.get(FunctionName));8161LookupResult R(S, DN, Loc, Sema::LookupAnyName);8162R.suppressDiagnostics();8163S.LookupName(R, S.getCurScope());81648165if (R.isSingleResult()) {8166FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());8167if (FD && FD->getBuiltinID() == AbsKind) {8168EmitHeaderHint = false;8169} else {8170return;8171}8172} else if (!R.empty()) {8173return;8174}8175}8176}81778178S.Diag(Loc, diag::note_replace_abs_function)8179<< FunctionName << FixItHint::CreateReplacement(Range, FunctionName);81808181if (!HeaderName)8182return;81838184if (!EmitHeaderHint)8185return;81868187S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName8188<< FunctionName;8189}81908191template <std::size_t StrLen>8192static bool IsStdFunction(const FunctionDecl *FDecl,8193const char (&Str)[StrLen]) {8194if (!FDecl)8195return false;8196if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))8197return false;8198if (!FDecl->isInStdNamespace())8199return false;82008201return true;8202}82038204void Sema::CheckInfNaNFunction(const CallExpr *Call,8205const FunctionDecl *FDecl) {8206FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());8207if ((IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||8208(Call->getBuiltinCallee() == Builtin::BI__builtin_nanf)) &&8209FPO.getNoHonorNaNs())8210Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)8211<< 1 << 0 << Call->getSourceRange();8212else if ((IsStdFunction(FDecl, "isinf") ||8213(IsStdFunction(FDecl, "isfinite") ||8214(FDecl->getIdentifier() && FDecl->getName() == "infinity"))) &&8215FPO.getNoHonorInfs())8216Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)8217<< 0 << 0 << Call->getSourceRange();8218}82198220void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,8221const FunctionDecl *FDecl) {8222if (Call->getNumArgs() != 1)8223return;82248225unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);8226bool IsStdAbs = IsStdFunction(FDecl, "abs");8227if (AbsKind == 0 && !IsStdAbs)8228return;82298230QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();8231QualType ParamType = Call->getArg(0)->getType();82328233// Unsigned types cannot be negative. Suggest removing the absolute value8234// function call.8235if (ArgType->isUnsignedIntegerType()) {8236StringRef FunctionName =8237IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);8238Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;8239Diag(Call->getExprLoc(), diag::note_remove_abs)8240<< FunctionName8241<< FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());8242return;8243}82448245// Taking the absolute value of a pointer is very suspicious, they probably8246// wanted to index into an array, dereference a pointer, call a function, etc.8247if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {8248unsigned DiagType = 0;8249if (ArgType->isFunctionType())8250DiagType = 1;8251else if (ArgType->isArrayType())8252DiagType = 2;82538254Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;8255return;8256}82578258// std::abs has overloads which prevent most of the absolute value problems8259// from occurring.8260if (IsStdAbs)8261return;82628263AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);8264AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);82658266// The argument and parameter are the same kind. Check if they are the right8267// size.8268if (ArgValueKind == ParamValueKind) {8269if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))8270return;82718272unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);8273Diag(Call->getExprLoc(), diag::warn_abs_too_small)8274<< FDecl << ArgType << ParamType;82758276if (NewAbsKind == 0)8277return;82788279emitReplacement(*this, Call->getExprLoc(),8280Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);8281return;8282}82838284// ArgValueKind != ParamValueKind8285// The wrong type of absolute value function was used. Attempt to find the8286// proper one.8287unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);8288NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);8289if (NewAbsKind == 0)8290return;82918292Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)8293<< FDecl << ParamValueKind << ArgValueKind;82948295emitReplacement(*this, Call->getExprLoc(),8296Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);8297}82988299//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//8300void Sema::CheckMaxUnsignedZero(const CallExpr *Call,8301const FunctionDecl *FDecl) {8302if (!Call || !FDecl) return;83038304// Ignore template specializations and macros.8305if (inTemplateInstantiation()) return;8306if (Call->getExprLoc().isMacroID()) return;83078308// Only care about the one template argument, two function parameter std::max8309if (Call->getNumArgs() != 2) return;8310if (!IsStdFunction(FDecl, "max")) return;8311const auto * ArgList = FDecl->getTemplateSpecializationArgs();8312if (!ArgList) return;8313if (ArgList->size() != 1) return;83148315// Check that template type argument is unsigned integer.8316const auto& TA = ArgList->get(0);8317if (TA.getKind() != TemplateArgument::Type) return;8318QualType ArgType = TA.getAsType();8319if (!ArgType->isUnsignedIntegerType()) return;83208321// See if either argument is a literal zero.8322auto IsLiteralZeroArg = [](const Expr* E) -> bool {8323const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);8324if (!MTE) return false;8325const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());8326if (!Num) return false;8327if (Num->getValue() != 0) return false;8328return true;8329};83308331const Expr *FirstArg = Call->getArg(0);8332const Expr *SecondArg = Call->getArg(1);8333const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);8334const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);83358336// Only warn when exactly one argument is zero.8337if (IsFirstArgZero == IsSecondArgZero) return;83388339SourceRange FirstRange = FirstArg->getSourceRange();8340SourceRange SecondRange = SecondArg->getSourceRange();83418342SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;83438344Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)8345<< IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;83468347// Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".8348SourceRange RemovalRange;8349if (IsFirstArgZero) {8350RemovalRange = SourceRange(FirstRange.getBegin(),8351SecondRange.getBegin().getLocWithOffset(-1));8352} else {8353RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),8354SecondRange.getEnd());8355}83568357Diag(Call->getExprLoc(), diag::note_remove_max_call)8358<< FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())8359<< FixItHint::CreateRemoval(RemovalRange);8360}83618362//===--- CHECK: Standard memory functions ---------------------------------===//83638364/// Takes the expression passed to the size_t parameter of functions8365/// such as memcmp, strncat, etc and warns if it's a comparison.8366///8367/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.8368static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,8369IdentifierInfo *FnName,8370SourceLocation FnLoc,8371SourceLocation RParenLoc) {8372const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);8373if (!Size)8374return false;83758376// if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:8377if (!Size->isComparisonOp() && !Size->isLogicalOp())8378return false;83798380SourceRange SizeRange = Size->getSourceRange();8381S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)8382<< SizeRange << FnName;8383S.Diag(FnLoc, diag::note_memsize_comparison_paren)8384<< FnName8385<< FixItHint::CreateInsertion(8386S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")8387<< FixItHint::CreateRemoval(RParenLoc);8388S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)8389<< FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")8390<< FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),8391")");83928393return true;8394}83958396/// Determine whether the given type is or contains a dynamic class type8397/// (e.g., whether it has a vtable).8398static const CXXRecordDecl *getContainedDynamicClass(QualType T,8399bool &IsContained) {8400// Look through array types while ignoring qualifiers.8401const Type *Ty = T->getBaseElementTypeUnsafe();8402IsContained = false;84038404const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();8405RD = RD ? RD->getDefinition() : nullptr;8406if (!RD || RD->isInvalidDecl())8407return nullptr;84088409if (RD->isDynamicClass())8410return RD;84118412// Check all the fields. If any bases were dynamic, the class is dynamic.8413// It's impossible for a class to transitively contain itself by value, so8414// infinite recursion is impossible.8415for (auto *FD : RD->fields()) {8416bool SubContained;8417if (const CXXRecordDecl *ContainedRD =8418getContainedDynamicClass(FD->getType(), SubContained)) {8419IsContained = true;8420return ContainedRD;8421}8422}84238424return nullptr;8425}84268427static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {8428if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))8429if (Unary->getKind() == UETT_SizeOf)8430return Unary;8431return nullptr;8432}84338434/// If E is a sizeof expression, returns its argument expression,8435/// otherwise returns NULL.8436static const Expr *getSizeOfExprArg(const Expr *E) {8437if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))8438if (!SizeOf->isArgumentType())8439return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();8440return nullptr;8441}84428443/// If E is a sizeof expression, returns its argument type.8444static QualType getSizeOfArgType(const Expr *E) {8445if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))8446return SizeOf->getTypeOfArgument();8447return QualType();8448}84498450namespace {84518452struct SearchNonTrivialToInitializeField8453: DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {8454using Super =8455DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;84568457SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}84588459void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,8460SourceLocation SL) {8461if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {8462asDerived().visitArray(PDIK, AT, SL);8463return;8464}84658466Super::visitWithKind(PDIK, FT, SL);8467}84688469void visitARCStrong(QualType FT, SourceLocation SL) {8470S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);8471}8472void visitARCWeak(QualType FT, SourceLocation SL) {8473S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);8474}8475void visitStruct(QualType FT, SourceLocation SL) {8476for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())8477visit(FD->getType(), FD->getLocation());8478}8479void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,8480const ArrayType *AT, SourceLocation SL) {8481visit(getContext().getBaseElementType(AT), SL);8482}8483void visitTrivial(QualType FT, SourceLocation SL) {}84848485static void diag(QualType RT, const Expr *E, Sema &S) {8486SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());8487}84888489ASTContext &getContext() { return S.getASTContext(); }84908491const Expr *E;8492Sema &S;8493};84948495struct SearchNonTrivialToCopyField8496: CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {8497using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;84988499SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}85008501void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,8502SourceLocation SL) {8503if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {8504asDerived().visitArray(PCK, AT, SL);8505return;8506}85078508Super::visitWithKind(PCK, FT, SL);8509}85108511void visitARCStrong(QualType FT, SourceLocation SL) {8512S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);8513}8514void visitARCWeak(QualType FT, SourceLocation SL) {8515S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);8516}8517void visitStruct(QualType FT, SourceLocation SL) {8518for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())8519visit(FD->getType(), FD->getLocation());8520}8521void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,8522SourceLocation SL) {8523visit(getContext().getBaseElementType(AT), SL);8524}8525void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,8526SourceLocation SL) {}8527void visitTrivial(QualType FT, SourceLocation SL) {}8528void visitVolatileTrivial(QualType FT, SourceLocation SL) {}85298530static void diag(QualType RT, const Expr *E, Sema &S) {8531SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());8532}85338534ASTContext &getContext() { return S.getASTContext(); }85358536const Expr *E;8537Sema &S;8538};85398540}85418542/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.8543static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {8544SizeofExpr = SizeofExpr->IgnoreParenImpCasts();85458546if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {8547if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)8548return false;85498550return doesExprLikelyComputeSize(BO->getLHS()) ||8551doesExprLikelyComputeSize(BO->getRHS());8552}85538554return getAsSizeOfExpr(SizeofExpr) != nullptr;8555}85568557/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.8558///8559/// \code8560/// #define MACRO 08561/// foo(MACRO);8562/// foo(0);8563/// \endcode8564///8565/// This should return true for the first call to foo, but not for the second8566/// (regardless of whether foo is a macro or function).8567static bool isArgumentExpandedFromMacro(SourceManager &SM,8568SourceLocation CallLoc,8569SourceLocation ArgLoc) {8570if (!CallLoc.isMacroID())8571return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);85728573return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=8574SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));8575}85768577/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the8578/// last two arguments transposed.8579static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {8580if (BId != Builtin::BImemset && BId != Builtin::BIbzero)8581return;85828583const Expr *SizeArg =8584Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();85858586auto isLiteralZero = [](const Expr *E) {8587return (isa<IntegerLiteral>(E) &&8588cast<IntegerLiteral>(E)->getValue() == 0) ||8589(isa<CharacterLiteral>(E) &&8590cast<CharacterLiteral>(E)->getValue() == 0);8591};85928593// If we're memsetting or bzeroing 0 bytes, then this is likely an error.8594SourceLocation CallLoc = Call->getRParenLoc();8595SourceManager &SM = S.getSourceManager();8596if (isLiteralZero(SizeArg) &&8597!isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {85988599SourceLocation DiagLoc = SizeArg->getExprLoc();86008601// Some platforms #define bzero to __builtin_memset. See if this is the8602// case, and if so, emit a better diagnostic.8603if (BId == Builtin::BIbzero ||8604(CallLoc.isMacroID() && Lexer::getImmediateMacroName(8605CallLoc, SM, S.getLangOpts()) == "bzero")) {8606S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);8607S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);8608} else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {8609S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;8610S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;8611}8612return;8613}86148615// If the second argument to a memset is a sizeof expression and the third8616// isn't, this is also likely an error. This should catch8617// 'memset(buf, sizeof(buf), 0xff)'.8618if (BId == Builtin::BImemset &&8619doesExprLikelyComputeSize(Call->getArg(1)) &&8620!doesExprLikelyComputeSize(Call->getArg(2))) {8621SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();8622S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;8623S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;8624return;8625}8626}86278628void Sema::CheckMemaccessArguments(const CallExpr *Call,8629unsigned BId,8630IdentifierInfo *FnName) {8631assert(BId != 0);86328633// It is possible to have a non-standard definition of memset. Validate8634// we have enough arguments, and if not, abort further checking.8635unsigned ExpectedNumArgs =8636(BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);8637if (Call->getNumArgs() < ExpectedNumArgs)8638return;86398640unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||8641BId == Builtin::BIstrndup ? 1 : 2);8642unsigned LenArg =8643(BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);8644const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();86458646if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,8647Call->getBeginLoc(), Call->getRParenLoc()))8648return;86498650// Catch cases like 'memset(buf, sizeof(buf), 0)'.8651CheckMemaccessSize(*this, BId, Call);86528653// We have special checking when the length is a sizeof expression.8654QualType SizeOfArgTy = getSizeOfArgType(LenExpr);8655const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);8656llvm::FoldingSetNodeID SizeOfArgID;86578658// Although widely used, 'bzero' is not a standard function. Be more strict8659// with the argument types before allowing diagnostics and only allow the8660// form bzero(ptr, sizeof(...)).8661QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();8662if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())8663return;86648665for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {8666const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();8667SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();86688669QualType DestTy = Dest->getType();8670QualType PointeeTy;8671if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {8672PointeeTy = DestPtrTy->getPointeeType();86738674// Never warn about void type pointers. This can be used to suppress8675// false positives.8676if (PointeeTy->isVoidType())8677continue;86788679// Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by8680// actually comparing the expressions for equality. Because computing the8681// expression IDs can be expensive, we only do this if the diagnostic is8682// enabled.8683if (SizeOfArg &&8684!Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,8685SizeOfArg->getExprLoc())) {8686// We only compute IDs for expressions if the warning is enabled, and8687// cache the sizeof arg's ID.8688if (SizeOfArgID == llvm::FoldingSetNodeID())8689SizeOfArg->Profile(SizeOfArgID, Context, true);8690llvm::FoldingSetNodeID DestID;8691Dest->Profile(DestID, Context, true);8692if (DestID == SizeOfArgID) {8693// TODO: For strncpy() and friends, this could suggest sizeof(dst)8694// over sizeof(src) as well.8695unsigned ActionIdx = 0; // Default is to suggest dereferencing.8696StringRef ReadableName = FnName->getName();86978698if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))8699if (UnaryOp->getOpcode() == UO_AddrOf)8700ActionIdx = 1; // If its an address-of operator, just remove it.8701if (!PointeeTy->isIncompleteType() &&8702(Context.getTypeSize(PointeeTy) == Context.getCharWidth()))8703ActionIdx = 2; // If the pointee's size is sizeof(char),8704// suggest an explicit length.87058706// If the function is defined as a builtin macro, do not show macro8707// expansion.8708SourceLocation SL = SizeOfArg->getExprLoc();8709SourceRange DSR = Dest->getSourceRange();8710SourceRange SSR = SizeOfArg->getSourceRange();8711SourceManager &SM = getSourceManager();87128713if (SM.isMacroArgExpansion(SL)) {8714ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);8715SL = SM.getSpellingLoc(SL);8716DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),8717SM.getSpellingLoc(DSR.getEnd()));8718SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),8719SM.getSpellingLoc(SSR.getEnd()));8720}87218722DiagRuntimeBehavior(SL, SizeOfArg,8723PDiag(diag::warn_sizeof_pointer_expr_memaccess)8724<< ReadableName8725<< PointeeTy8726<< DestTy8727<< DSR8728<< SSR);8729DiagRuntimeBehavior(SL, SizeOfArg,8730PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)8731<< ActionIdx8732<< SSR);87338734break;8735}8736}87378738// Also check for cases where the sizeof argument is the exact same8739// type as the memory argument, and where it points to a user-defined8740// record type.8741if (SizeOfArgTy != QualType()) {8742if (PointeeTy->isRecordType() &&8743Context.typesAreCompatible(SizeOfArgTy, DestTy)) {8744DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,8745PDiag(diag::warn_sizeof_pointer_type_memaccess)8746<< FnName << SizeOfArgTy << ArgIdx8747<< PointeeTy << Dest->getSourceRange()8748<< LenExpr->getSourceRange());8749break;8750}8751}8752} else if (DestTy->isArrayType()) {8753PointeeTy = DestTy;8754}87558756if (PointeeTy == QualType())8757continue;87588759// Always complain about dynamic classes.8760bool IsContained;8761if (const CXXRecordDecl *ContainedRD =8762getContainedDynamicClass(PointeeTy, IsContained)) {87638764unsigned OperationType = 0;8765const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;8766// "overwritten" if we're warning about the destination for any call8767// but memcmp; otherwise a verb appropriate to the call.8768if (ArgIdx != 0 || IsCmp) {8769if (BId == Builtin::BImemcpy)8770OperationType = 1;8771else if(BId == Builtin::BImemmove)8772OperationType = 2;8773else if (IsCmp)8774OperationType = 3;8775}87768777DiagRuntimeBehavior(Dest->getExprLoc(), Dest,8778PDiag(diag::warn_dyn_class_memaccess)8779<< (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName8780<< IsContained << ContainedRD << OperationType8781<< Call->getCallee()->getSourceRange());8782} else if (PointeeTy.hasNonTrivialObjCLifetime() &&8783BId != Builtin::BImemset)8784DiagRuntimeBehavior(8785Dest->getExprLoc(), Dest,8786PDiag(diag::warn_arc_object_memaccess)8787<< ArgIdx << FnName << PointeeTy8788<< Call->getCallee()->getSourceRange());8789else if (const auto *RT = PointeeTy->getAs<RecordType>()) {8790if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&8791RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {8792DiagRuntimeBehavior(Dest->getExprLoc(), Dest,8793PDiag(diag::warn_cstruct_memaccess)8794<< ArgIdx << FnName << PointeeTy << 0);8795SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);8796} else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&8797RT->getDecl()->isNonTrivialToPrimitiveCopy()) {8798DiagRuntimeBehavior(Dest->getExprLoc(), Dest,8799PDiag(diag::warn_cstruct_memaccess)8800<< ArgIdx << FnName << PointeeTy << 1);8801SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);8802} else {8803continue;8804}8805} else8806continue;88078808DiagRuntimeBehavior(8809Dest->getExprLoc(), Dest,8810PDiag(diag::note_bad_memaccess_silence)8811<< FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));8812break;8813}8814}88158816// A little helper routine: ignore addition and subtraction of integer literals.8817// This intentionally does not ignore all integer constant expressions because8818// we don't want to remove sizeof().8819static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {8820Ex = Ex->IgnoreParenCasts();88218822while (true) {8823const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);8824if (!BO || !BO->isAdditiveOp())8825break;88268827const Expr *RHS = BO->getRHS()->IgnoreParenCasts();8828const Expr *LHS = BO->getLHS()->IgnoreParenCasts();88298830if (isa<IntegerLiteral>(RHS))8831Ex = LHS;8832else if (isa<IntegerLiteral>(LHS))8833Ex = RHS;8834else8835break;8836}88378838return Ex;8839}88408841static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,8842ASTContext &Context) {8843// Only handle constant-sized or VLAs, but not flexible members.8844if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {8845// Only issue the FIXIT for arrays of size > 1.8846if (CAT->getZExtSize() <= 1)8847return false;8848} else if (!Ty->isVariableArrayType()) {8849return false;8850}8851return true;8852}88538854void Sema::CheckStrlcpycatArguments(const CallExpr *Call,8855IdentifierInfo *FnName) {88568857// Don't crash if the user has the wrong number of arguments8858unsigned NumArgs = Call->getNumArgs();8859if ((NumArgs != 3) && (NumArgs != 4))8860return;88618862const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);8863const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);8864const Expr *CompareWithSrc = nullptr;88658866if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,8867Call->getBeginLoc(), Call->getRParenLoc()))8868return;88698870// Look for 'strlcpy(dst, x, sizeof(x))'8871if (const Expr *Ex = getSizeOfExprArg(SizeArg))8872CompareWithSrc = Ex;8873else {8874// Look for 'strlcpy(dst, x, strlen(x))'8875if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {8876if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&8877SizeCall->getNumArgs() == 1)8878CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);8879}8880}88818882if (!CompareWithSrc)8883return;88848885// Determine if the argument to sizeof/strlen is equal to the source8886// argument. In principle there's all kinds of things you could do8887// here, for instance creating an == expression and evaluating it with8888// EvaluateAsBooleanCondition, but this uses a more direct technique:8889const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);8890if (!SrcArgDRE)8891return;88928893const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);8894if (!CompareWithSrcDRE ||8895SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())8896return;88978898const Expr *OriginalSizeArg = Call->getArg(2);8899Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)8900<< OriginalSizeArg->getSourceRange() << FnName;89018902// Output a FIXIT hint if the destination is an array (rather than a8903// pointer to an array). This could be enhanced to handle some8904// pointers if we know the actual size, like if DstArg is 'array+2'8905// we could say 'sizeof(array)-2'.8906const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();8907if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))8908return;89098910SmallString<128> sizeString;8911llvm::raw_svector_ostream OS(sizeString);8912OS << "sizeof(";8913DstArg->printPretty(OS, nullptr, getPrintingPolicy());8914OS << ")";89158916Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)8917<< FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),8918OS.str());8919}89208921/// Check if two expressions refer to the same declaration.8922static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {8923if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))8924if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))8925return D1->getDecl() == D2->getDecl();8926return false;8927}89288929static const Expr *getStrlenExprArg(const Expr *E) {8930if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {8931const FunctionDecl *FD = CE->getDirectCallee();8932if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)8933return nullptr;8934return CE->getArg(0)->IgnoreParenCasts();8935}8936return nullptr;8937}89388939void Sema::CheckStrncatArguments(const CallExpr *CE,8940IdentifierInfo *FnName) {8941// Don't crash if the user has the wrong number of arguments.8942if (CE->getNumArgs() < 3)8943return;8944const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();8945const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();8946const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();89478948if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),8949CE->getRParenLoc()))8950return;89518952// Identify common expressions, which are wrongly used as the size argument8953// to strncat and may lead to buffer overflows.8954unsigned PatternType = 0;8955if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {8956// - sizeof(dst)8957if (referToTheSameDecl(SizeOfArg, DstArg))8958PatternType = 1;8959// - sizeof(src)8960else if (referToTheSameDecl(SizeOfArg, SrcArg))8961PatternType = 2;8962} else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {8963if (BE->getOpcode() == BO_Sub) {8964const Expr *L = BE->getLHS()->IgnoreParenCasts();8965const Expr *R = BE->getRHS()->IgnoreParenCasts();8966// - sizeof(dst) - strlen(dst)8967if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&8968referToTheSameDecl(DstArg, getStrlenExprArg(R)))8969PatternType = 1;8970// - sizeof(src) - (anything)8971else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))8972PatternType = 2;8973}8974}89758976if (PatternType == 0)8977return;89788979// Generate the diagnostic.8980SourceLocation SL = LenArg->getBeginLoc();8981SourceRange SR = LenArg->getSourceRange();8982SourceManager &SM = getSourceManager();89838984// If the function is defined as a builtin macro, do not show macro expansion.8985if (SM.isMacroArgExpansion(SL)) {8986SL = SM.getSpellingLoc(SL);8987SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),8988SM.getSpellingLoc(SR.getEnd()));8989}89908991// Check if the destination is an array (rather than a pointer to an array).8992QualType DstTy = DstArg->getType();8993bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,8994Context);8995if (!isKnownSizeArray) {8996if (PatternType == 1)8997Diag(SL, diag::warn_strncat_wrong_size) << SR;8998else8999Diag(SL, diag::warn_strncat_src_size) << SR;9000return;9001}90029003if (PatternType == 1)9004Diag(SL, diag::warn_strncat_large_size) << SR;9005else9006Diag(SL, diag::warn_strncat_src_size) << SR;90079008SmallString<128> sizeString;9009llvm::raw_svector_ostream OS(sizeString);9010OS << "sizeof(";9011DstArg->printPretty(OS, nullptr, getPrintingPolicy());9012OS << ") - ";9013OS << "strlen(";9014DstArg->printPretty(OS, nullptr, getPrintingPolicy());9015OS << ") - 1";90169017Diag(SL, diag::note_strncat_wrong_size)9018<< FixItHint::CreateReplacement(SR, OS.str());9019}90209021namespace {9022void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,9023const UnaryOperator *UnaryExpr, const Decl *D) {9024if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {9025S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)9026<< CalleeName << 0 /*object: */ << cast<NamedDecl>(D);9027return;9028}9029}90309031void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,9032const UnaryOperator *UnaryExpr) {9033if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {9034const Decl *D = Lvalue->getDecl();9035if (isa<DeclaratorDecl>(D))9036if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())9037return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);9038}90399040if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))9041return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,9042Lvalue->getMemberDecl());9043}90449045void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,9046const UnaryOperator *UnaryExpr) {9047const auto *Lambda = dyn_cast<LambdaExpr>(9048UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());9049if (!Lambda)9050return;90519052S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)9053<< CalleeName << 2 /*object: lambda expression*/;9054}90559056void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,9057const DeclRefExpr *Lvalue) {9058const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());9059if (Var == nullptr)9060return;90619062S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)9063<< CalleeName << 0 /*object: */ << Var;9064}90659066void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,9067const CastExpr *Cast) {9068SmallString<128> SizeString;9069llvm::raw_svector_ostream OS(SizeString);90709071clang::CastKind Kind = Cast->getCastKind();9072if (Kind == clang::CK_BitCast &&9073!Cast->getSubExpr()->getType()->isFunctionPointerType())9074return;9075if (Kind == clang::CK_IntegralToPointer &&9076!isa<IntegerLiteral>(9077Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))9078return;90799080switch (Cast->getCastKind()) {9081case clang::CK_BitCast:9082case clang::CK_IntegralToPointer:9083case clang::CK_FunctionToPointerDecay:9084OS << '\'';9085Cast->printPretty(OS, nullptr, S.getPrintingPolicy());9086OS << '\'';9087break;9088default:9089return;9090}90919092S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)9093<< CalleeName << 0 /*object: */ << OS.str();9094}9095} // namespace90969097void Sema::CheckFreeArguments(const CallExpr *E) {9098const std::string CalleeName =9099cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();91009101{ // Prefer something that doesn't involve a cast to make things simpler.9102const Expr *Arg = E->getArg(0)->IgnoreParenCasts();9103if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))9104switch (UnaryExpr->getOpcode()) {9105case UnaryOperator::Opcode::UO_AddrOf:9106return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);9107case UnaryOperator::Opcode::UO_Plus:9108return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);9109default:9110break;9111}91129113if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))9114if (Lvalue->getType()->isArrayType())9115return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);91169117if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {9118Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)9119<< CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();9120return;9121}91229123if (isa<BlockExpr>(Arg)) {9124Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)9125<< CalleeName << 1 /*object: block*/;9126return;9127}9128}9129// Maybe the cast was important, check after the other cases.9130if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))9131return CheckFreeArgumentsCast(*this, CalleeName, Cast);9132}91339134void9135Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,9136SourceLocation ReturnLoc,9137bool isObjCMethod,9138const AttrVec *Attrs,9139const FunctionDecl *FD) {9140// Check if the return value is null but should not be.9141if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||9142(!isObjCMethod && isNonNullType(lhsType))) &&9143CheckNonNullExpr(*this, RetValExp))9144Diag(ReturnLoc, diag::warn_null_ret)9145<< (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();91469147// C++11 [basic.stc.dynamic.allocation]p4:9148// If an allocation function declared with a non-throwing9149// exception-specification fails to allocate storage, it shall return9150// a null pointer. Any other allocation function that fails to allocate9151// storage shall indicate failure only by throwing an exception [...]9152if (FD) {9153OverloadedOperatorKind Op = FD->getOverloadedOperator();9154if (Op == OO_New || Op == OO_Array_New) {9155const FunctionProtoType *Proto9156= FD->getType()->castAs<FunctionProtoType>();9157if (!Proto->isNothrow(/*ResultIfDependent*/true) &&9158CheckNonNullExpr(*this, RetValExp))9159Diag(ReturnLoc, diag::warn_operator_new_returns_null)9160<< FD << getLangOpts().CPlusPlus11;9161}9162}91639164if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {9165Diag(ReturnLoc, diag::err_wasm_table_art) << 1;9166}91679168// PPC MMA non-pointer types are not allowed as return type. Checking the type9169// here prevent the user from using a PPC MMA type as trailing return type.9170if (Context.getTargetInfo().getTriple().isPPC64())9171PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);9172}91739174void Sema::CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,9175BinaryOperatorKind Opcode) {9176if (!BinaryOperator::isEqualityOp(Opcode))9177return;91789179// Match and capture subexpressions such as "(float) X == 0.1".9180FloatingLiteral *FPLiteral;9181CastExpr *FPCast;9182auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) {9183FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());9184FPCast = dyn_cast<CastExpr>(R->IgnoreParens());9185return FPLiteral && FPCast;9186};91879188if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {9189auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();9190auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();9191if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&9192TargetTy->isFloatingPoint()) {9193bool Lossy;9194llvm::APFloat TargetC = FPLiteral->getValue();9195TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),9196llvm::APFloat::rmNearestTiesToEven, &Lossy);9197if (Lossy) {9198// If the literal cannot be represented in the source type, then a9199// check for == is always false and check for != is always true.9200Diag(Loc, diag::warn_float_compare_literal)9201<< (Opcode == BO_EQ) << QualType(SourceTy, 0)9202<< LHS->getSourceRange() << RHS->getSourceRange();9203return;9204}9205}9206}92079208// Match a more general floating-point equality comparison (-Wfloat-equal).9209Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();9210Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();92119212// Special case: check for x == x (which is OK).9213// Do not emit warnings for such cases.9214if (auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))9215if (auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))9216if (DRL->getDecl() == DRR->getDecl())9217return;92189219// Special case: check for comparisons against literals that can be exactly9220// represented by APFloat. In such cases, do not emit a warning. This9221// is a heuristic: often comparison against such literals are used to9222// detect if a value in a variable has not changed. This clearly can9223// lead to false negatives.9224if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {9225if (FLL->isExact())9226return;9227} else9228if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))9229if (FLR->isExact())9230return;92319232// Check for comparisons with builtin types.9233if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))9234if (CL->getBuiltinCallee())9235return;92369237if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))9238if (CR->getBuiltinCallee())9239return;92409241// Emit the diagnostic.9242Diag(Loc, diag::warn_floatingpoint_eq)9243<< LHS->getSourceRange() << RHS->getSourceRange();9244}92459246//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//9247//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//92489249namespace {92509251/// Structure recording the 'active' range of an integer-valued9252/// expression.9253struct IntRange {9254/// The number of bits active in the int. Note that this includes exactly one9255/// sign bit if !NonNegative.9256unsigned Width;92579258/// True if the int is known not to have negative values. If so, all leading9259/// bits before Width are known zero, otherwise they are known to be the9260/// same as the MSB within Width.9261bool NonNegative;92629263IntRange(unsigned Width, bool NonNegative)9264: Width(Width), NonNegative(NonNegative) {}92659266/// Number of bits excluding the sign bit.9267unsigned valueBits() const {9268return NonNegative ? Width : Width - 1;9269}92709271/// Returns the range of the bool type.9272static IntRange forBoolType() {9273return IntRange(1, true);9274}92759276/// Returns the range of an opaque value of the given integral type.9277static IntRange forValueOfType(ASTContext &C, QualType T) {9278return forValueOfCanonicalType(C,9279T->getCanonicalTypeInternal().getTypePtr());9280}92819282/// Returns the range of an opaque value of a canonical integral type.9283static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {9284assert(T->isCanonicalUnqualified());92859286if (const VectorType *VT = dyn_cast<VectorType>(T))9287T = VT->getElementType().getTypePtr();9288if (const ComplexType *CT = dyn_cast<ComplexType>(T))9289T = CT->getElementType().getTypePtr();9290if (const AtomicType *AT = dyn_cast<AtomicType>(T))9291T = AT->getValueType().getTypePtr();92929293if (!C.getLangOpts().CPlusPlus) {9294// For enum types in C code, use the underlying datatype.9295if (const EnumType *ET = dyn_cast<EnumType>(T))9296T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();9297} else if (const EnumType *ET = dyn_cast<EnumType>(T)) {9298// For enum types in C++, use the known bit width of the enumerators.9299EnumDecl *Enum = ET->getDecl();9300// In C++11, enums can have a fixed underlying type. Use this type to9301// compute the range.9302if (Enum->isFixed()) {9303return IntRange(C.getIntWidth(QualType(T, 0)),9304!ET->isSignedIntegerOrEnumerationType());9305}93069307unsigned NumPositive = Enum->getNumPositiveBits();9308unsigned NumNegative = Enum->getNumNegativeBits();93099310if (NumNegative == 0)9311return IntRange(NumPositive, true/*NonNegative*/);9312else9313return IntRange(std::max(NumPositive + 1, NumNegative),9314false/*NonNegative*/);9315}93169317if (const auto *EIT = dyn_cast<BitIntType>(T))9318return IntRange(EIT->getNumBits(), EIT->isUnsigned());93199320const BuiltinType *BT = cast<BuiltinType>(T);9321assert(BT->isInteger());93229323return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());9324}93259326/// Returns the "target" range of a canonical integral type, i.e.9327/// the range of values expressible in the type.9328///9329/// This matches forValueOfCanonicalType except that enums have the9330/// full range of their type, not the range of their enumerators.9331static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {9332assert(T->isCanonicalUnqualified());93339334if (const VectorType *VT = dyn_cast<VectorType>(T))9335T = VT->getElementType().getTypePtr();9336if (const ComplexType *CT = dyn_cast<ComplexType>(T))9337T = CT->getElementType().getTypePtr();9338if (const AtomicType *AT = dyn_cast<AtomicType>(T))9339T = AT->getValueType().getTypePtr();9340if (const EnumType *ET = dyn_cast<EnumType>(T))9341T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();93429343if (const auto *EIT = dyn_cast<BitIntType>(T))9344return IntRange(EIT->getNumBits(), EIT->isUnsigned());93459346const BuiltinType *BT = cast<BuiltinType>(T);9347assert(BT->isInteger());93489349return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());9350}93519352/// Returns the supremum of two ranges: i.e. their conservative merge.9353static IntRange join(IntRange L, IntRange R) {9354bool Unsigned = L.NonNegative && R.NonNegative;9355return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,9356L.NonNegative && R.NonNegative);9357}93589359/// Return the range of a bitwise-AND of the two ranges.9360static IntRange bit_and(IntRange L, IntRange R) {9361unsigned Bits = std::max(L.Width, R.Width);9362bool NonNegative = false;9363if (L.NonNegative) {9364Bits = std::min(Bits, L.Width);9365NonNegative = true;9366}9367if (R.NonNegative) {9368Bits = std::min(Bits, R.Width);9369NonNegative = true;9370}9371return IntRange(Bits, NonNegative);9372}93739374/// Return the range of a sum of the two ranges.9375static IntRange sum(IntRange L, IntRange R) {9376bool Unsigned = L.NonNegative && R.NonNegative;9377return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,9378Unsigned);9379}93809381/// Return the range of a difference of the two ranges.9382static IntRange difference(IntRange L, IntRange R) {9383// We need a 1-bit-wider range if:9384// 1) LHS can be negative: least value can be reduced.9385// 2) RHS can be negative: greatest value can be increased.9386bool CanWiden = !L.NonNegative || !R.NonNegative;9387bool Unsigned = L.NonNegative && R.Width == 0;9388return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +9389!Unsigned,9390Unsigned);9391}93929393/// Return the range of a product of the two ranges.9394static IntRange product(IntRange L, IntRange R) {9395// If both LHS and RHS can be negative, we can form9396// -2^L * -2^R = 2^(L + R)9397// which requires L + R + 1 value bits to represent.9398bool CanWiden = !L.NonNegative && !R.NonNegative;9399bool Unsigned = L.NonNegative && R.NonNegative;9400return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,9401Unsigned);9402}94039404/// Return the range of a remainder operation between the two ranges.9405static IntRange rem(IntRange L, IntRange R) {9406// The result of a remainder can't be larger than the result of9407// either side. The sign of the result is the sign of the LHS.9408bool Unsigned = L.NonNegative;9409return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,9410Unsigned);9411}9412};94139414} // namespace94159416static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,9417unsigned MaxWidth) {9418if (value.isSigned() && value.isNegative())9419return IntRange(value.getSignificantBits(), false);94209421if (value.getBitWidth() > MaxWidth)9422value = value.trunc(MaxWidth);94239424// isNonNegative() just checks the sign bit without considering9425// signedness.9426return IntRange(value.getActiveBits(), true);9427}94289429static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,9430unsigned MaxWidth) {9431if (result.isInt())9432return GetValueRange(C, result.getInt(), MaxWidth);94339434if (result.isVector()) {9435IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);9436for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {9437IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);9438R = IntRange::join(R, El);9439}9440return R;9441}94429443if (result.isComplexInt()) {9444IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);9445IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);9446return IntRange::join(R, I);9447}94489449// This can happen with lossless casts to intptr_t of "based" lvalues.9450// Assume it might use arbitrary bits.9451// FIXME: The only reason we need to pass the type in here is to get9452// the sign right on this one case. It would be nice if APValue9453// preserved this.9454assert(result.isLValue() || result.isAddrLabelDiff());9455return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());9456}94579458static QualType GetExprType(const Expr *E) {9459QualType Ty = E->getType();9460if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())9461Ty = AtomicRHS->getValueType();9462return Ty;9463}94649465/// Pseudo-evaluate the given integer expression, estimating the9466/// range of values it might take.9467///9468/// \param MaxWidth The width to which the value will be truncated.9469/// \param Approximate If \c true, return a likely range for the result: in9470/// particular, assume that arithmetic on narrower types doesn't leave9471/// those types. If \c false, return a range including all possible9472/// result values.9473static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,9474bool InConstantContext, bool Approximate) {9475E = E->IgnoreParens();94769477// Try a full evaluation first.9478Expr::EvalResult result;9479if (E->EvaluateAsRValue(result, C, InConstantContext))9480return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);94819482// I think we only want to look through implicit casts here; if the9483// user has an explicit widening cast, we should treat the value as9484// being of the new, wider type.9485if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {9486if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)9487return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,9488Approximate);94899490IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));94919492bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||9493CE->getCastKind() == CK_BooleanToSignedIntegral;94949495// Assume that non-integer casts can span the full range of the type.9496if (!isIntegerCast)9497return OutputTypeRange;94989499IntRange SubRange = GetExprRange(C, CE->getSubExpr(),9500std::min(MaxWidth, OutputTypeRange.Width),9501InConstantContext, Approximate);95029503// Bail out if the subexpr's range is as wide as the cast type.9504if (SubRange.Width >= OutputTypeRange.Width)9505return OutputTypeRange;95069507// Otherwise, we take the smaller width, and we're non-negative if9508// either the output type or the subexpr is.9509return IntRange(SubRange.Width,9510SubRange.NonNegative || OutputTypeRange.NonNegative);9511}95129513if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {9514// If we can fold the condition, just take that operand.9515bool CondResult;9516if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))9517return GetExprRange(C,9518CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),9519MaxWidth, InConstantContext, Approximate);95209521// Otherwise, conservatively merge.9522// GetExprRange requires an integer expression, but a throw expression9523// results in a void type.9524Expr *E = CO->getTrueExpr();9525IntRange L = E->getType()->isVoidType()9526? IntRange{0, true}9527: GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);9528E = CO->getFalseExpr();9529IntRange R = E->getType()->isVoidType()9530? IntRange{0, true}9531: GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);9532return IntRange::join(L, R);9533}95349535if (const auto *BO = dyn_cast<BinaryOperator>(E)) {9536IntRange (*Combine)(IntRange, IntRange) = IntRange::join;95379538switch (BO->getOpcode()) {9539case BO_Cmp:9540llvm_unreachable("builtin <=> should have class type");95419542// Boolean-valued operations are single-bit and positive.9543case BO_LAnd:9544case BO_LOr:9545case BO_LT:9546case BO_GT:9547case BO_LE:9548case BO_GE:9549case BO_EQ:9550case BO_NE:9551return IntRange::forBoolType();95529553// The type of the assignments is the type of the LHS, so the RHS9554// is not necessarily the same type.9555case BO_MulAssign:9556case BO_DivAssign:9557case BO_RemAssign:9558case BO_AddAssign:9559case BO_SubAssign:9560case BO_XorAssign:9561case BO_OrAssign:9562// TODO: bitfields?9563return IntRange::forValueOfType(C, GetExprType(E));95649565// Simple assignments just pass through the RHS, which will have9566// been coerced to the LHS type.9567case BO_Assign:9568// TODO: bitfields?9569return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,9570Approximate);95719572// Operations with opaque sources are black-listed.9573case BO_PtrMemD:9574case BO_PtrMemI:9575return IntRange::forValueOfType(C, GetExprType(E));95769577// Bitwise-and uses the *infinum* of the two source ranges.9578case BO_And:9579case BO_AndAssign:9580Combine = IntRange::bit_and;9581break;95829583// Left shift gets black-listed based on a judgement call.9584case BO_Shl:9585// ...except that we want to treat '1 << (blah)' as logically9586// positive. It's an important idiom.9587if (IntegerLiteral *I9588= dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {9589if (I->getValue() == 1) {9590IntRange R = IntRange::forValueOfType(C, GetExprType(E));9591return IntRange(R.Width, /*NonNegative*/ true);9592}9593}9594[[fallthrough]];95959596case BO_ShlAssign:9597return IntRange::forValueOfType(C, GetExprType(E));95989599// Right shift by a constant can narrow its left argument.9600case BO_Shr:9601case BO_ShrAssign: {9602IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,9603Approximate);96049605// If the shift amount is a positive constant, drop the width by9606// that much.9607if (std::optional<llvm::APSInt> shift =9608BO->getRHS()->getIntegerConstantExpr(C)) {9609if (shift->isNonNegative()) {9610if (shift->uge(L.Width))9611L.Width = (L.NonNegative ? 0 : 1);9612else9613L.Width -= shift->getZExtValue();9614}9615}96169617return L;9618}96199620// Comma acts as its right operand.9621case BO_Comma:9622return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,9623Approximate);96249625case BO_Add:9626if (!Approximate)9627Combine = IntRange::sum;9628break;96299630case BO_Sub:9631if (BO->getLHS()->getType()->isPointerType())9632return IntRange::forValueOfType(C, GetExprType(E));9633if (!Approximate)9634Combine = IntRange::difference;9635break;96369637case BO_Mul:9638if (!Approximate)9639Combine = IntRange::product;9640break;96419642// The width of a division result is mostly determined by the size9643// of the LHS.9644case BO_Div: {9645// Don't 'pre-truncate' the operands.9646unsigned opWidth = C.getIntWidth(GetExprType(E));9647IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,9648Approximate);96499650// If the divisor is constant, use that.9651if (std::optional<llvm::APSInt> divisor =9652BO->getRHS()->getIntegerConstantExpr(C)) {9653unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))9654if (log2 >= L.Width)9655L.Width = (L.NonNegative ? 0 : 1);9656else9657L.Width = std::min(L.Width - log2, MaxWidth);9658return L;9659}96609661// Otherwise, just use the LHS's width.9662// FIXME: This is wrong if the LHS could be its minimal value and the RHS9663// could be -1.9664IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,9665Approximate);9666return IntRange(L.Width, L.NonNegative && R.NonNegative);9667}96689669case BO_Rem:9670Combine = IntRange::rem;9671break;96729673// The default behavior is okay for these.9674case BO_Xor:9675case BO_Or:9676break;9677}96789679// Combine the two ranges, but limit the result to the type in which we9680// performed the computation.9681QualType T = GetExprType(E);9682unsigned opWidth = C.getIntWidth(T);9683IntRange L =9684GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);9685IntRange R =9686GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);9687IntRange C = Combine(L, R);9688C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();9689C.Width = std::min(C.Width, MaxWidth);9690return C;9691}96929693if (const auto *UO = dyn_cast<UnaryOperator>(E)) {9694switch (UO->getOpcode()) {9695// Boolean-valued operations are white-listed.9696case UO_LNot:9697return IntRange::forBoolType();96989699// Operations with opaque sources are black-listed.9700case UO_Deref:9701case UO_AddrOf: // should be impossible9702return IntRange::forValueOfType(C, GetExprType(E));97039704default:9705return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,9706Approximate);9707}9708}97099710if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))9711return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,9712Approximate);97139714if (const auto *BitField = E->getSourceBitField())9715return IntRange(BitField->getBitWidthValue(C),9716BitField->getType()->isUnsignedIntegerOrEnumerationType());97179718return IntRange::forValueOfType(C, GetExprType(E));9719}97209721static IntRange GetExprRange(ASTContext &C, const Expr *E,9722bool InConstantContext, bool Approximate) {9723return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,9724Approximate);9725}97269727/// Checks whether the given value, which currently has the given9728/// source semantics, has the same value when coerced through the9729/// target semantics.9730static bool IsSameFloatAfterCast(const llvm::APFloat &value,9731const llvm::fltSemantics &Src,9732const llvm::fltSemantics &Tgt) {9733llvm::APFloat truncated = value;97349735bool ignored;9736truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);9737truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);97389739return truncated.bitwiseIsEqual(value);9740}97419742/// Checks whether the given value, which currently has the given9743/// source semantics, has the same value when coerced through the9744/// target semantics.9745///9746/// The value might be a vector of floats (or a complex number).9747static bool IsSameFloatAfterCast(const APValue &value,9748const llvm::fltSemantics &Src,9749const llvm::fltSemantics &Tgt) {9750if (value.isFloat())9751return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);97529753if (value.isVector()) {9754for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)9755if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))9756return false;9757return true;9758}97599760assert(value.isComplexFloat());9761return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&9762IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));9763}97649765static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,9766bool IsListInit = false);97679768static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {9769// Suppress cases where we are comparing against an enum constant.9770if (const DeclRefExpr *DR =9771dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))9772if (isa<EnumConstantDecl>(DR->getDecl()))9773return true;97749775// Suppress cases where the value is expanded from a macro, unless that macro9776// is how a language represents a boolean literal. This is the case in both C9777// and Objective-C.9778SourceLocation BeginLoc = E->getBeginLoc();9779if (BeginLoc.isMacroID()) {9780StringRef MacroName = Lexer::getImmediateMacroName(9781BeginLoc, S.getSourceManager(), S.getLangOpts());9782return MacroName != "YES" && MacroName != "NO" &&9783MacroName != "true" && MacroName != "false";9784}97859786return false;9787}97889789static bool isKnownToHaveUnsignedValue(Expr *E) {9790return E->getType()->isIntegerType() &&9791(!E->getType()->isSignedIntegerType() ||9792!E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());9793}97949795namespace {9796/// The promoted range of values of a type. In general this has the9797/// following structure:9798///9799/// |-----------| . . . |-----------|9800/// ^ ^ ^ ^9801/// Min HoleMin HoleMax Max9802///9803/// ... where there is only a hole if a signed type is promoted to unsigned9804/// (in which case Min and Max are the smallest and largest representable9805/// values).9806struct PromotedRange {9807// Min, or HoleMax if there is a hole.9808llvm::APSInt PromotedMin;9809// Max, or HoleMin if there is a hole.9810llvm::APSInt PromotedMax;98119812PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {9813if (R.Width == 0)9814PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);9815else if (R.Width >= BitWidth && !Unsigned) {9816// Promotion made the type *narrower*. This happens when promoting9817// a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.9818// Treat all values of 'signed int' as being in range for now.9819PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);9820PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);9821} else {9822PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)9823.extOrTrunc(BitWidth);9824PromotedMin.setIsUnsigned(Unsigned);98259826PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)9827.extOrTrunc(BitWidth);9828PromotedMax.setIsUnsigned(Unsigned);9829}9830}98319832// Determine whether this range is contiguous (has no hole).9833bool isContiguous() const { return PromotedMin <= PromotedMax; }98349835// Where a constant value is within the range.9836enum ComparisonResult {9837LT = 0x1,9838LE = 0x2,9839GT = 0x4,9840GE = 0x8,9841EQ = 0x10,9842NE = 0x20,9843InRangeFlag = 0x40,98449845Less = LE | LT | NE,9846Min = LE | InRangeFlag,9847InRange = InRangeFlag,9848Max = GE | InRangeFlag,9849Greater = GE | GT | NE,98509851OnlyValue = LE | GE | EQ | InRangeFlag,9852InHole = NE9853};98549855ComparisonResult compare(const llvm::APSInt &Value) const {9856assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&9857Value.isUnsigned() == PromotedMin.isUnsigned());9858if (!isContiguous()) {9859assert(Value.isUnsigned() && "discontiguous range for signed compare");9860if (Value.isMinValue()) return Min;9861if (Value.isMaxValue()) return Max;9862if (Value >= PromotedMin) return InRange;9863if (Value <= PromotedMax) return InRange;9864return InHole;9865}98669867switch (llvm::APSInt::compareValues(Value, PromotedMin)) {9868case -1: return Less;9869case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;9870case 1:9871switch (llvm::APSInt::compareValues(Value, PromotedMax)) {9872case -1: return InRange;9873case 0: return Max;9874case 1: return Greater;9875}9876}98779878llvm_unreachable("impossible compare result");9879}98809881static std::optional<StringRef>9882constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {9883if (Op == BO_Cmp) {9884ComparisonResult LTFlag = LT, GTFlag = GT;9885if (ConstantOnRHS) std::swap(LTFlag, GTFlag);98869887if (R & EQ) return StringRef("'std::strong_ordering::equal'");9888if (R & LTFlag) return StringRef("'std::strong_ordering::less'");9889if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");9890return std::nullopt;9891}98929893ComparisonResult TrueFlag, FalseFlag;9894if (Op == BO_EQ) {9895TrueFlag = EQ;9896FalseFlag = NE;9897} else if (Op == BO_NE) {9898TrueFlag = NE;9899FalseFlag = EQ;9900} else {9901if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {9902TrueFlag = LT;9903FalseFlag = GE;9904} else {9905TrueFlag = GT;9906FalseFlag = LE;9907}9908if (Op == BO_GE || Op == BO_LE)9909std::swap(TrueFlag, FalseFlag);9910}9911if (R & TrueFlag)9912return StringRef("true");9913if (R & FalseFlag)9914return StringRef("false");9915return std::nullopt;9916}9917};9918}99199920static bool HasEnumType(Expr *E) {9921// Strip off implicit integral promotions.9922while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {9923if (ICE->getCastKind() != CK_IntegralCast &&9924ICE->getCastKind() != CK_NoOp)9925break;9926E = ICE->getSubExpr();9927}99289929return E->getType()->isEnumeralType();9930}99319932static int classifyConstantValue(Expr *Constant) {9933// The values of this enumeration are used in the diagnostics9934// diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.9935enum ConstantValueKind {9936Miscellaneous = 0,9937LiteralTrue,9938LiteralFalse9939};9940if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))9941return BL->getValue() ? ConstantValueKind::LiteralTrue9942: ConstantValueKind::LiteralFalse;9943return ConstantValueKind::Miscellaneous;9944}99459946static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,9947Expr *Constant, Expr *Other,9948const llvm::APSInt &Value,9949bool RhsConstant) {9950if (S.inTemplateInstantiation())9951return false;99529953Expr *OriginalOther = Other;99549955Constant = Constant->IgnoreParenImpCasts();9956Other = Other->IgnoreParenImpCasts();99579958// Suppress warnings on tautological comparisons between values of the same9959// enumeration type. There are only two ways we could warn on this:9960// - If the constant is outside the range of representable values of9961// the enumeration. In such a case, we should warn about the cast9962// to enumeration type, not about the comparison.9963// - If the constant is the maximum / minimum in-range value. For an9964// enumeratin type, such comparisons can be meaningful and useful.9965if (Constant->getType()->isEnumeralType() &&9966S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))9967return false;99689969IntRange OtherValueRange = GetExprRange(9970S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);99719972QualType OtherT = Other->getType();9973if (const auto *AT = OtherT->getAs<AtomicType>())9974OtherT = AT->getValueType();9975IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);99769977// Special case for ObjC BOOL on targets where its a typedef for a signed char9978// (Namely, macOS). FIXME: IntRange::forValueOfType should do this.9979bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&9980S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&9981OtherT->isSpecificBuiltinType(BuiltinType::SChar);99829983// Whether we're treating Other as being a bool because of the form of9984// expression despite it having another type (typically 'int' in C).9985bool OtherIsBooleanDespiteType =9986!OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();9987if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)9988OtherTypeRange = OtherValueRange = IntRange::forBoolType();99899990// Check if all values in the range of possible values of this expression9991// lead to the same comparison outcome.9992PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),9993Value.isUnsigned());9994auto Cmp = OtherPromotedValueRange.compare(Value);9995auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);9996if (!Result)9997return false;99989999// Also consider the range determined by the type alone. This allows us to10000// classify the warning under the proper diagnostic group.10001bool TautologicalTypeCompare = false;10002{10003PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),10004Value.isUnsigned());10005auto TypeCmp = OtherPromotedTypeRange.compare(Value);10006if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,10007RhsConstant)) {10008TautologicalTypeCompare = true;10009Cmp = TypeCmp;10010Result = TypeResult;10011}10012}1001310014// Don't warn if the non-constant operand actually always evaluates to the10015// same value.10016if (!TautologicalTypeCompare && OtherValueRange.Width == 0)10017return false;1001810019// Suppress the diagnostic for an in-range comparison if the constant comes10020// from a macro or enumerator. We don't want to diagnose10021//10022// some_long_value <= INT_MAX10023//10024// when sizeof(int) == sizeof(long).10025bool InRange = Cmp & PromotedRange::InRangeFlag;10026if (InRange && IsEnumConstOrFromMacro(S, Constant))10027return false;1002810029// A comparison of an unsigned bit-field against 0 is really a type problem,10030// even though at the type level the bit-field might promote to 'signed int'.10031if (Other->refersToBitField() && InRange && Value == 0 &&10032Other->getType()->isUnsignedIntegerOrEnumerationType())10033TautologicalTypeCompare = true;1003410035// If this is a comparison to an enum constant, include that10036// constant in the diagnostic.10037const EnumConstantDecl *ED = nullptr;10038if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))10039ED = dyn_cast<EnumConstantDecl>(DR->getDecl());1004010041// Should be enough for uint128 (39 decimal digits)10042SmallString<64> PrettySourceValue;10043llvm::raw_svector_ostream OS(PrettySourceValue);10044if (ED) {10045OS << '\'' << *ED << "' (" << Value << ")";10046} else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(10047Constant->IgnoreParenImpCasts())) {10048OS << (BL->getValue() ? "YES" : "NO");10049} else {10050OS << Value;10051}1005210053if (!TautologicalTypeCompare) {10054S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)10055<< RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative10056<< E->getOpcodeStr() << OS.str() << *Result10057<< E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();10058return true;10059}1006010061if (IsObjCSignedCharBool) {10062S.DiagRuntimeBehavior(E->getOperatorLoc(), E,10063S.PDiag(diag::warn_tautological_compare_objc_bool)10064<< OS.str() << *Result);10065return true;10066}1006710068// FIXME: We use a somewhat different formatting for the in-range cases and10069// cases involving boolean values for historical reasons. We should pick a10070// consistent way of presenting these diagnostics.10071if (!InRange || Other->isKnownToHaveBooleanValue()) {1007210073S.DiagRuntimeBehavior(10074E->getOperatorLoc(), E,10075S.PDiag(!InRange ? diag::warn_out_of_range_compare10076: diag::warn_tautological_bool_compare)10077<< OS.str() << classifyConstantValue(Constant) << OtherT10078<< OtherIsBooleanDespiteType << *Result10079<< E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());10080} else {10081bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;10082unsigned Diag =10083(isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)10084? (HasEnumType(OriginalOther)10085? diag::warn_unsigned_enum_always_true_comparison10086: IsCharTy ? diag::warn_unsigned_char_always_true_comparison10087: diag::warn_unsigned_always_true_comparison)10088: diag::warn_tautological_constant_compare;1008910090S.Diag(E->getOperatorLoc(), Diag)10091<< RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result10092<< E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();10093}1009410095return true;10096}1009710098/// Analyze the operands of the given comparison. Implements the10099/// fallback case from AnalyzeComparison.10100static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {10101AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());10102AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());10103}1010410105/// Implements -Wsign-compare.10106///10107/// \param E the binary operator to check for warnings10108static void AnalyzeComparison(Sema &S, BinaryOperator *E) {10109// The type the comparison is being performed in.10110QualType T = E->getLHS()->getType();1011110112// Only analyze comparison operators where both sides have been converted to10113// the same type.10114if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))10115return AnalyzeImpConvsInComparison(S, E);1011610117// Don't analyze value-dependent comparisons directly.10118if (E->isValueDependent())10119return AnalyzeImpConvsInComparison(S, E);1012010121Expr *LHS = E->getLHS();10122Expr *RHS = E->getRHS();1012310124if (T->isIntegralType(S.Context)) {10125std::optional<llvm::APSInt> RHSValue =10126RHS->getIntegerConstantExpr(S.Context);10127std::optional<llvm::APSInt> LHSValue =10128LHS->getIntegerConstantExpr(S.Context);1012910130// We don't care about expressions whose result is a constant.10131if (RHSValue && LHSValue)10132return AnalyzeImpConvsInComparison(S, E);1013310134// We only care about expressions where just one side is literal10135if ((bool)RHSValue ^ (bool)LHSValue) {10136// Is the constant on the RHS or LHS?10137const bool RhsConstant = (bool)RHSValue;10138Expr *Const = RhsConstant ? RHS : LHS;10139Expr *Other = RhsConstant ? LHS : RHS;10140const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;1014110142// Check whether an integer constant comparison results in a value10143// of 'true' or 'false'.10144if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))10145return AnalyzeImpConvsInComparison(S, E);10146}10147}1014810149if (!T->hasUnsignedIntegerRepresentation()) {10150// We don't do anything special if this isn't an unsigned integral10151// comparison: we're only interested in integral comparisons, and10152// signed comparisons only happen in cases we don't care to warn about.10153return AnalyzeImpConvsInComparison(S, E);10154}1015510156LHS = LHS->IgnoreParenImpCasts();10157RHS = RHS->IgnoreParenImpCasts();1015810159if (!S.getLangOpts().CPlusPlus) {10160// Avoid warning about comparison of integers with different signs when10161// RHS/LHS has a `typeof(E)` type whose sign is different from the sign of10162// the type of `E`.10163if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))10164LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();10165if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))10166RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();10167}1016810169// Check to see if one of the (unmodified) operands is of different10170// signedness.10171Expr *signedOperand, *unsignedOperand;10172if (LHS->getType()->hasSignedIntegerRepresentation()) {10173assert(!RHS->getType()->hasSignedIntegerRepresentation() &&10174"unsigned comparison between two signed integer expressions?");10175signedOperand = LHS;10176unsignedOperand = RHS;10177} else if (RHS->getType()->hasSignedIntegerRepresentation()) {10178signedOperand = RHS;10179unsignedOperand = LHS;10180} else {10181return AnalyzeImpConvsInComparison(S, E);10182}1018310184// Otherwise, calculate the effective range of the signed operand.10185IntRange signedRange =10186GetExprRange(S.Context, signedOperand, S.isConstantEvaluatedContext(),10187/*Approximate=*/true);1018810189// Go ahead and analyze implicit conversions in the operands. Note10190// that we skip the implicit conversions on both sides.10191AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());10192AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());1019310194// If the signed range is non-negative, -Wsign-compare won't fire.10195if (signedRange.NonNegative)10196return;1019710198// For (in)equality comparisons, if the unsigned operand is a10199// constant which cannot collide with a overflowed signed operand,10200// then reinterpreting the signed operand as unsigned will not10201// change the result of the comparison.10202if (E->isEqualityOp()) {10203unsigned comparisonWidth = S.Context.getIntWidth(T);10204IntRange unsignedRange =10205GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluatedContext(),10206/*Approximate=*/true);1020710208// We should never be unable to prove that the unsigned operand is10209// non-negative.10210assert(unsignedRange.NonNegative && "unsigned range includes negative?");1021110212if (unsignedRange.Width < comparisonWidth)10213return;10214}1021510216S.DiagRuntimeBehavior(E->getOperatorLoc(), E,10217S.PDiag(diag::warn_mixed_sign_comparison)10218<< LHS->getType() << RHS->getType()10219<< LHS->getSourceRange() << RHS->getSourceRange());10220}1022110222/// Analyzes an attempt to assign the given value to a bitfield.10223///10224/// Returns true if there was something fishy about the attempt.10225static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,10226SourceLocation InitLoc) {10227assert(Bitfield->isBitField());10228if (Bitfield->isInvalidDecl())10229return false;1023010231// White-list bool bitfields.10232QualType BitfieldType = Bitfield->getType();10233if (BitfieldType->isBooleanType())10234return false;1023510236if (BitfieldType->isEnumeralType()) {10237EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();10238// If the underlying enum type was not explicitly specified as an unsigned10239// type and the enum contain only positive values, MSVC++ will cause an10240// inconsistency by storing this as a signed type.10241if (S.getLangOpts().CPlusPlus11 &&10242!BitfieldEnumDecl->getIntegerTypeSourceInfo() &&10243BitfieldEnumDecl->getNumPositiveBits() > 0 &&10244BitfieldEnumDecl->getNumNegativeBits() == 0) {10245S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)10246<< BitfieldEnumDecl;10247}10248}1024910250// Ignore value- or type-dependent expressions.10251if (Bitfield->getBitWidth()->isValueDependent() ||10252Bitfield->getBitWidth()->isTypeDependent() ||10253Init->isValueDependent() ||10254Init->isTypeDependent())10255return false;1025610257Expr *OriginalInit = Init->IgnoreParenImpCasts();10258unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);1025910260Expr::EvalResult Result;10261if (!OriginalInit->EvaluateAsInt(Result, S.Context,10262Expr::SE_AllowSideEffects)) {10263// The RHS is not constant. If the RHS has an enum type, make sure the10264// bitfield is wide enough to hold all the values of the enum without10265// truncation.10266if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {10267EnumDecl *ED = EnumTy->getDecl();10268bool SignedBitfield = BitfieldType->isSignedIntegerType();1026910270// Enum types are implicitly signed on Windows, so check if there are any10271// negative enumerators to see if the enum was intended to be signed or10272// not.10273bool SignedEnum = ED->getNumNegativeBits() > 0;1027410275// Check for surprising sign changes when assigning enum values to a10276// bitfield of different signedness. If the bitfield is signed and we10277// have exactly the right number of bits to store this unsigned enum,10278// suggest changing the enum to an unsigned type. This typically happens10279// on Windows where unfixed enums always use an underlying type of 'int'.10280unsigned DiagID = 0;10281if (SignedEnum && !SignedBitfield) {10282DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;10283} else if (SignedBitfield && !SignedEnum &&10284ED->getNumPositiveBits() == FieldWidth) {10285DiagID = diag::warn_signed_bitfield_enum_conversion;10286}1028710288if (DiagID) {10289S.Diag(InitLoc, DiagID) << Bitfield << ED;10290TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();10291SourceRange TypeRange =10292TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();10293S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)10294<< SignedEnum << TypeRange;10295}1029610297// Compute the required bitwidth. If the enum has negative values, we need10298// one more bit than the normal number of positive bits to represent the10299// sign bit.10300unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,10301ED->getNumNegativeBits())10302: ED->getNumPositiveBits();1030310304// Check the bitwidth.10305if (BitsNeeded > FieldWidth) {10306Expr *WidthExpr = Bitfield->getBitWidth();10307S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)10308<< Bitfield << ED;10309S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)10310<< BitsNeeded << ED << WidthExpr->getSourceRange();10311}10312}1031310314return false;10315}1031610317llvm::APSInt Value = Result.Val.getInt();1031810319unsigned OriginalWidth = Value.getBitWidth();1032010321// In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce10322// false positives where the user is demonstrating they intend to use the10323// bit-field as a Boolean, check to see if the value is 1 and we're assigning10324// to a one-bit bit-field to see if the value came from a macro named 'true'.10325bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;10326if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {10327SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();10328if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&10329S.findMacroSpelling(MaybeMacroLoc, "true"))10330return false;10331}1033210333if (!Value.isSigned() || Value.isNegative())10334if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))10335if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)10336OriginalWidth = Value.getSignificantBits();1033710338if (OriginalWidth <= FieldWidth)10339return false;1034010341// Compute the value which the bitfield will contain.10342llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);10343TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());1034410345// Check whether the stored value is equal to the original value.10346TruncatedValue = TruncatedValue.extend(OriginalWidth);10347if (llvm::APSInt::isSameValue(Value, TruncatedValue))10348return false;1034910350std::string PrettyValue = toString(Value, 10);10351std::string PrettyTrunc = toString(TruncatedValue, 10);1035210353S.Diag(InitLoc, OneAssignedToOneBitBitfield10354? diag::warn_impcast_single_bit_bitield_precision_constant10355: diag::warn_impcast_bitfield_precision_constant)10356<< PrettyValue << PrettyTrunc << OriginalInit->getType()10357<< Init->getSourceRange();1035810359return true;10360}1036110362/// Analyze the given simple or compound assignment for warning-worthy10363/// operations.10364static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {10365// Just recurse on the LHS.10366AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());1036710368// We want to recurse on the RHS as normal unless we're assigning to10369// a bitfield.10370if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {10371if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),10372E->getOperatorLoc())) {10373// Recurse, ignoring any implicit conversions on the RHS.10374return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),10375E->getOperatorLoc());10376}10377}1037810379AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());1038010381// Diagnose implicitly sequentially-consistent atomic assignment.10382if (E->getLHS()->getType()->isAtomicType())10383S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);10384}1038510386/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.10387static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,10388SourceLocation CContext, unsigned diag,10389bool pruneControlFlow = false) {10390if (pruneControlFlow) {10391S.DiagRuntimeBehavior(E->getExprLoc(), E,10392S.PDiag(diag)10393<< SourceType << T << E->getSourceRange()10394<< SourceRange(CContext));10395return;10396}10397S.Diag(E->getExprLoc(), diag)10398<< SourceType << T << E->getSourceRange() << SourceRange(CContext);10399}1040010401/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.10402static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,10403SourceLocation CContext,10404unsigned diag, bool pruneControlFlow = false) {10405DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);10406}1040710408/// Diagnose an implicit cast from a floating point value to an integer value.10409static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,10410SourceLocation CContext) {10411const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);10412const bool PruneWarnings = S.inTemplateInstantiation();1041310414Expr *InnerE = E->IgnoreParenImpCasts();10415// We also want to warn on, e.g., "int i = -1.234"10416if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))10417if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)10418InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();1041910420const bool IsLiteral =10421isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);1042210423llvm::APFloat Value(0.0);10424bool IsConstant =10425E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);10426if (!IsConstant) {10427if (S.ObjC().isSignedCharBool(T)) {10428return S.ObjC().adornBoolConversionDiagWithTernaryFixit(10429E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)10430<< E->getType());10431}1043210433return DiagnoseImpCast(S, E, T, CContext,10434diag::warn_impcast_float_integer, PruneWarnings);10435}1043610437bool isExact = false;1043810439llvm::APSInt IntegerValue(S.Context.getIntWidth(T),10440T->hasUnsignedIntegerRepresentation());10441llvm::APFloat::opStatus Result = Value.convertToInteger(10442IntegerValue, llvm::APFloat::rmTowardZero, &isExact);1044310444// FIXME: Force the precision of the source value down so we don't print10445// digits which are usually useless (we don't really care here if we10446// truncate a digit by accident in edge cases). Ideally, APFloat::toString10447// would automatically print the shortest representation, but it's a bit10448// tricky to implement.10449SmallString<16> PrettySourceValue;10450unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());10451precision = (precision * 59 + 195) / 196;10452Value.toString(PrettySourceValue, precision);1045310454if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {10455return S.ObjC().adornBoolConversionDiagWithTernaryFixit(10456E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)10457<< PrettySourceValue);10458}1045910460if (Result == llvm::APFloat::opOK && isExact) {10461if (IsLiteral) return;10462return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,10463PruneWarnings);10464}1046510466// Conversion of a floating-point value to a non-bool integer where the10467// integral part cannot be represented by the integer type is undefined.10468if (!IsBool && Result == llvm::APFloat::opInvalidOp)10469return DiagnoseImpCast(10470S, E, T, CContext,10471IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range10472: diag::warn_impcast_float_to_integer_out_of_range,10473PruneWarnings);1047410475unsigned DiagID = 0;10476if (IsLiteral) {10477// Warn on floating point literal to integer.10478DiagID = diag::warn_impcast_literal_float_to_integer;10479} else if (IntegerValue == 0) {10480if (Value.isZero()) { // Skip -0.0 to 0 conversion.10481return DiagnoseImpCast(S, E, T, CContext,10482diag::warn_impcast_float_integer, PruneWarnings);10483}10484// Warn on non-zero to zero conversion.10485DiagID = diag::warn_impcast_float_to_integer_zero;10486} else {10487if (IntegerValue.isUnsigned()) {10488if (!IntegerValue.isMaxValue()) {10489return DiagnoseImpCast(S, E, T, CContext,10490diag::warn_impcast_float_integer, PruneWarnings);10491}10492} else { // IntegerValue.isSigned()10493if (!IntegerValue.isMaxSignedValue() &&10494!IntegerValue.isMinSignedValue()) {10495return DiagnoseImpCast(S, E, T, CContext,10496diag::warn_impcast_float_integer, PruneWarnings);10497}10498}10499// Warn on evaluatable floating point expression to integer conversion.10500DiagID = diag::warn_impcast_float_to_integer;10501}1050210503SmallString<16> PrettyTargetValue;10504if (IsBool)10505PrettyTargetValue = Value.isZero() ? "false" : "true";10506else10507IntegerValue.toString(PrettyTargetValue);1050810509if (PruneWarnings) {10510S.DiagRuntimeBehavior(E->getExprLoc(), E,10511S.PDiag(DiagID)10512<< E->getType() << T.getUnqualifiedType()10513<< PrettySourceValue << PrettyTargetValue10514<< E->getSourceRange() << SourceRange(CContext));10515} else {10516S.Diag(E->getExprLoc(), DiagID)10517<< E->getType() << T.getUnqualifiedType() << PrettySourceValue10518<< PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);10519}10520}1052110522/// Analyze the given compound assignment for the possible losing of10523/// floating-point precision.10524static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {10525assert(isa<CompoundAssignOperator>(E) &&10526"Must be compound assignment operation");10527// Recurse on the LHS and RHS in here10528AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());10529AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());1053010531if (E->getLHS()->getType()->isAtomicType())10532S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);1053310534// Now check the outermost expression10535const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();10536const auto *RBT = cast<CompoundAssignOperator>(E)10537->getComputationResultType()10538->getAs<BuiltinType>();1053910540// The below checks assume source is floating point.10541if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;1054210543// If source is floating point but target is an integer.10544if (ResultBT->isInteger())10545return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),10546E->getExprLoc(), diag::warn_impcast_float_integer);1054710548if (!ResultBT->isFloatingPoint())10549return;1055010551// If both source and target are floating points, warn about losing precision.10552int Order = S.getASTContext().getFloatingTypeSemanticOrder(10553QualType(ResultBT, 0), QualType(RBT, 0));10554if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))10555// warn about dropping FP rank.10556DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),10557diag::warn_impcast_float_result_precision);10558}1055910560static std::string PrettyPrintInRange(const llvm::APSInt &Value,10561IntRange Range) {10562if (!Range.Width) return "0";1056310564llvm::APSInt ValueInRange = Value;10565ValueInRange.setIsSigned(!Range.NonNegative);10566ValueInRange = ValueInRange.trunc(Range.Width);10567return toString(ValueInRange, 10);10568}1056910570static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {10571if (!isa<ImplicitCastExpr>(Ex))10572return false;1057310574Expr *InnerE = Ex->IgnoreParenImpCasts();10575const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();10576const Type *Source =10577S.Context.getCanonicalType(InnerE->getType()).getTypePtr();10578if (Target->isDependentType())10579return false;1058010581const BuiltinType *FloatCandidateBT =10582dyn_cast<BuiltinType>(ToBool ? Source : Target);10583const Type *BoolCandidateType = ToBool ? Target : Source;1058410585return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&10586FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));10587}1058810589static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,10590SourceLocation CC) {10591unsigned NumArgs = TheCall->getNumArgs();10592for (unsigned i = 0; i < NumArgs; ++i) {10593Expr *CurrA = TheCall->getArg(i);10594if (!IsImplicitBoolFloatConversion(S, CurrA, true))10595continue;1059610597bool IsSwapped = ((i > 0) &&10598IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));10599IsSwapped |= ((i < (NumArgs - 1)) &&10600IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));10601if (IsSwapped) {10602// Warn on this floating-point to bool conversion.10603DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),10604CurrA->getType(), CC,10605diag::warn_impcast_floating_point_to_bool);10606}10607}10608}1060910610static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,10611SourceLocation CC) {10612if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,10613E->getExprLoc()))10614return;1061510616// Don't warn on functions which have return type nullptr_t.10617if (isa<CallExpr>(E))10618return;1061910620// Check for NULL (GNUNull) or nullptr (CXX11_nullptr).10621const Expr *NewE = E->IgnoreParenImpCasts();10622bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);10623bool HasNullPtrType = NewE->getType()->isNullPtrType();10624if (!IsGNUNullExpr && !HasNullPtrType)10625return;1062610627// Return if target type is a safe conversion.10628if (T->isAnyPointerType() || T->isBlockPointerType() ||10629T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())10630return;1063110632SourceLocation Loc = E->getSourceRange().getBegin();1063310634// Venture through the macro stacks to get to the source of macro arguments.10635// The new location is a better location than the complete location that was10636// passed in.10637Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);10638CC = S.SourceMgr.getTopMacroCallerLoc(CC);1063910640// __null is usually wrapped in a macro. Go up a macro if that is the case.10641if (IsGNUNullExpr && Loc.isMacroID()) {10642StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(10643Loc, S.SourceMgr, S.getLangOpts());10644if (MacroName == "NULL")10645Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();10646}1064710648// Only warn if the null and context location are in the same macro expansion.10649if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))10650return;1065110652S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)10653<< HasNullPtrType << T << SourceRange(CC)10654<< FixItHint::CreateReplacement(Loc,10655S.getFixItZeroLiteralForType(T, Loc));10656}1065710658// Helper function to filter out cases for constant width constant conversion.10659// Don't warn on char array initialization or for non-decimal values.10660static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,10661SourceLocation CC) {10662// If initializing from a constant, and the constant starts with '0',10663// then it is a binary, octal, or hexadecimal. Allow these constants10664// to fill all the bits, even if there is a sign change.10665if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {10666const char FirstLiteralCharacter =10667S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];10668if (FirstLiteralCharacter == '0')10669return false;10670}1067110672// If the CC location points to a '{', and the type is char, then assume10673// assume it is an array initialization.10674if (CC.isValid() && T->isCharType()) {10675const char FirstContextCharacter =10676S.getSourceManager().getCharacterData(CC)[0];10677if (FirstContextCharacter == '{')10678return false;10679}1068010681return true;10682}1068310684static const IntegerLiteral *getIntegerLiteral(Expr *E) {10685const auto *IL = dyn_cast<IntegerLiteral>(E);10686if (!IL) {10687if (auto *UO = dyn_cast<UnaryOperator>(E)) {10688if (UO->getOpcode() == UO_Minus)10689return dyn_cast<IntegerLiteral>(UO->getSubExpr());10690}10691}1069210693return IL;10694}1069510696static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {10697E = E->IgnoreParenImpCasts();10698SourceLocation ExprLoc = E->getExprLoc();1069910700if (const auto *BO = dyn_cast<BinaryOperator>(E)) {10701BinaryOperator::Opcode Opc = BO->getOpcode();10702Expr::EvalResult Result;10703// Do not diagnose unsigned shifts.10704if (Opc == BO_Shl) {10705const auto *LHS = getIntegerLiteral(BO->getLHS());10706const auto *RHS = getIntegerLiteral(BO->getRHS());10707if (LHS && LHS->getValue() == 0)10708S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;10709else if (!E->isValueDependent() && LHS && RHS &&10710RHS->getValue().isNonNegative() &&10711E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))10712S.Diag(ExprLoc, diag::warn_left_shift_always)10713<< (Result.Val.getInt() != 0);10714else if (E->getType()->isSignedIntegerType())10715S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;10716}10717}1071810719if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {10720const auto *LHS = getIntegerLiteral(CO->getTrueExpr());10721const auto *RHS = getIntegerLiteral(CO->getFalseExpr());10722if (!LHS || !RHS)10723return;10724if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&10725(RHS->getValue() == 0 || RHS->getValue() == 1))10726// Do not diagnose common idioms.10727return;10728if (LHS->getValue() != 0 && RHS->getValue() != 0)10729S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);10730}10731}1073210733void Sema::CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,10734bool *ICContext, bool IsListInit) {10735if (E->isTypeDependent() || E->isValueDependent()) return;1073610737const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();10738const Type *Target = Context.getCanonicalType(T).getTypePtr();10739if (Source == Target) return;10740if (Target->isDependentType()) return;1074110742// If the conversion context location is invalid don't complain. We also10743// don't want to emit a warning if the issue occurs from the expansion of10744// a system macro. The problem is that 'getSpellingLoc()' is slow, so we10745// delay this check as long as possible. Once we detect we are in that10746// scenario, we just return.10747if (CC.isInvalid())10748return;1074910750if (Source->isAtomicType())10751Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);1075210753// Diagnose implicit casts to bool.10754if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {10755if (isa<StringLiteral>(E))10756// Warn on string literal to bool. Checks for string literals in logical10757// and expressions, for instance, assert(0 && "error here"), are10758// prevented by a check in AnalyzeImplicitConversions().10759return DiagnoseImpCast(*this, E, T, CC,10760diag::warn_impcast_string_literal_to_bool);10761if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||10762isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {10763// This covers the literal expressions that evaluate to Objective-C10764// objects.10765return DiagnoseImpCast(*this, E, T, CC,10766diag::warn_impcast_objective_c_literal_to_bool);10767}10768if (Source->isPointerType() || Source->canDecayToPointerType()) {10769// Warn on pointer to bool conversion that is always true.10770DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,10771SourceRange(CC));10772}10773}1077410775// If the we're converting a constant to an ObjC BOOL on a platform where BOOL10776// is a typedef for signed char (macOS), then that constant value has to be 110777// or 0.10778if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {10779Expr::EvalResult Result;10780if (E->EvaluateAsInt(Result, getASTContext(), Expr::SE_AllowSideEffects)) {10781if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {10782ObjC().adornBoolConversionDiagWithTernaryFixit(10783E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)10784<< toString(Result.Val.getInt(), 10));10785}10786return;10787}10788}1078910790// Check implicit casts from Objective-C collection literals to specialized10791// collection types, e.g., NSArray<NSString *> *.10792if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))10793ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);10794else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))10795ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);1079610797// Strip vector types.10798if (isa<VectorType>(Source)) {10799if (Target->isSveVLSBuiltinType() &&10800(Context.areCompatibleSveTypes(QualType(Target, 0),10801QualType(Source, 0)) ||10802Context.areLaxCompatibleSveTypes(QualType(Target, 0),10803QualType(Source, 0))))10804return;1080510806if (Target->isRVVVLSBuiltinType() &&10807(Context.areCompatibleRVVTypes(QualType(Target, 0),10808QualType(Source, 0)) ||10809Context.areLaxCompatibleRVVTypes(QualType(Target, 0),10810QualType(Source, 0))))10811return;1081210813if (!isa<VectorType>(Target)) {10814if (SourceMgr.isInSystemMacro(CC))10815return;10816return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);10817} else if (getLangOpts().HLSL &&10818Target->castAs<VectorType>()->getNumElements() <10819Source->castAs<VectorType>()->getNumElements()) {10820// Diagnose vector truncation but don't return. We may also want to10821// diagnose an element conversion.10822DiagnoseImpCast(*this, E, T, CC,10823diag::warn_hlsl_impcast_vector_truncation);10824}1082510826// If the vector cast is cast between two vectors of the same size, it is10827// a bitcast, not a conversion, except under HLSL where it is a conversion.10828if (!getLangOpts().HLSL &&10829Context.getTypeSize(Source) == Context.getTypeSize(Target))10830return;1083110832Source = cast<VectorType>(Source)->getElementType().getTypePtr();10833Target = cast<VectorType>(Target)->getElementType().getTypePtr();10834}10835if (auto VecTy = dyn_cast<VectorType>(Target))10836Target = VecTy->getElementType().getTypePtr();1083710838// Strip complex types.10839if (isa<ComplexType>(Source)) {10840if (!isa<ComplexType>(Target)) {10841if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())10842return;1084310844return DiagnoseImpCast(*this, E, T, CC,10845getLangOpts().CPlusPlus10846? diag::err_impcast_complex_scalar10847: diag::warn_impcast_complex_scalar);10848}1084910850Source = cast<ComplexType>(Source)->getElementType().getTypePtr();10851Target = cast<ComplexType>(Target)->getElementType().getTypePtr();10852}1085310854const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);10855const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);1085610857// Strip SVE vector types10858if (SourceBT && SourceBT->isSveVLSBuiltinType()) {10859// Need the original target type for vector type checks10860const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();10861// Handle conversion from scalable to fixed when msve-vector-bits is10862// specified10863if (Context.areCompatibleSveTypes(QualType(OriginalTarget, 0),10864QualType(Source, 0)) ||10865Context.areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),10866QualType(Source, 0)))10867return;1086810869// If the vector cast is cast between two vectors of the same size, it is10870// a bitcast, not a conversion.10871if (Context.getTypeSize(Source) == Context.getTypeSize(Target))10872return;1087310874Source = SourceBT->getSveEltType(Context).getTypePtr();10875}1087610877if (TargetBT && TargetBT->isSveVLSBuiltinType())10878Target = TargetBT->getSveEltType(Context).getTypePtr();1087910880// If the source is floating point...10881if (SourceBT && SourceBT->isFloatingPoint()) {10882// ...and the target is floating point...10883if (TargetBT && TargetBT->isFloatingPoint()) {10884// ...then warn if we're dropping FP rank.1088510886int Order = getASTContext().getFloatingTypeSemanticOrder(10887QualType(SourceBT, 0), QualType(TargetBT, 0));10888if (Order > 0) {10889// Don't warn about float constants that are precisely10890// representable in the target type.10891Expr::EvalResult result;10892if (E->EvaluateAsRValue(result, Context)) {10893// Value might be a float, a float vector, or a float complex.10894if (IsSameFloatAfterCast(10895result.Val,10896Context.getFloatTypeSemantics(QualType(TargetBT, 0)),10897Context.getFloatTypeSemantics(QualType(SourceBT, 0))))10898return;10899}1090010901if (SourceMgr.isInSystemMacro(CC))10902return;1090310904DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);10905}10906// ... or possibly if we're increasing rank, too10907else if (Order < 0) {10908if (SourceMgr.isInSystemMacro(CC))10909return;1091010911DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);10912}10913return;10914}1091510916// If the target is integral, always warn.10917if (TargetBT && TargetBT->isInteger()) {10918if (SourceMgr.isInSystemMacro(CC))10919return;1092010921DiagnoseFloatingImpCast(*this, E, T, CC);10922}1092310924// Detect the case where a call result is converted from floating-point to10925// to bool, and the final argument to the call is converted from bool, to10926// discover this typo:10927//10928// bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"10929//10930// FIXME: This is an incredibly special case; is there some more general10931// way to detect this class of misplaced-parentheses bug?10932if (Target->isBooleanType() && isa<CallExpr>(E)) {10933// Check last argument of function call to see if it is an10934// implicit cast from a type matching the type the result10935// is being cast to.10936CallExpr *CEx = cast<CallExpr>(E);10937if (unsigned NumArgs = CEx->getNumArgs()) {10938Expr *LastA = CEx->getArg(NumArgs - 1);10939Expr *InnerE = LastA->IgnoreParenImpCasts();10940if (isa<ImplicitCastExpr>(LastA) &&10941InnerE->getType()->isBooleanType()) {10942// Warn on this floating-point to bool conversion10943DiagnoseImpCast(*this, E, T, CC,10944diag::warn_impcast_floating_point_to_bool);10945}10946}10947}10948return;10949}1095010951// Valid casts involving fixed point types should be accounted for here.10952if (Source->isFixedPointType()) {10953if (Target->isUnsaturatedFixedPointType()) {10954Expr::EvalResult Result;10955if (E->EvaluateAsFixedPoint(Result, Context, Expr::SE_AllowSideEffects,10956isConstantEvaluatedContext())) {10957llvm::APFixedPoint Value = Result.Val.getFixedPoint();10958llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);10959llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);10960if (Value > MaxVal || Value < MinVal) {10961DiagRuntimeBehavior(E->getExprLoc(), E,10962PDiag(diag::warn_impcast_fixed_point_range)10963<< Value.toString() << T10964<< E->getSourceRange()10965<< clang::SourceRange(CC));10966return;10967}10968}10969} else if (Target->isIntegerType()) {10970Expr::EvalResult Result;10971if (!isConstantEvaluatedContext() &&10972E->EvaluateAsFixedPoint(Result, Context, Expr::SE_AllowSideEffects)) {10973llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();1097410975bool Overflowed;10976llvm::APSInt IntResult = FXResult.convertToInt(10977Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),10978&Overflowed);1097910980if (Overflowed) {10981DiagRuntimeBehavior(E->getExprLoc(), E,10982PDiag(diag::warn_impcast_fixed_point_range)10983<< FXResult.toString() << T10984<< E->getSourceRange()10985<< clang::SourceRange(CC));10986return;10987}10988}10989}10990} else if (Target->isUnsaturatedFixedPointType()) {10991if (Source->isIntegerType()) {10992Expr::EvalResult Result;10993if (!isConstantEvaluatedContext() &&10994E->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) {10995llvm::APSInt Value = Result.Val.getInt();1099610997bool Overflowed;10998llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(10999Value, Context.getFixedPointSemantics(T), &Overflowed);1100011001if (Overflowed) {11002DiagRuntimeBehavior(E->getExprLoc(), E,11003PDiag(diag::warn_impcast_fixed_point_range)11004<< toString(Value, /*Radix=*/10) << T11005<< E->getSourceRange()11006<< clang::SourceRange(CC));11007return;11008}11009}11010}11011}1101211013// If we are casting an integer type to a floating point type without11014// initialization-list syntax, we might lose accuracy if the floating11015// point type has a narrower significand than the integer type.11016if (SourceBT && TargetBT && SourceBT->isIntegerType() &&11017TargetBT->isFloatingType() && !IsListInit) {11018// Determine the number of precision bits in the source integer type.11019IntRange SourceRange =11020GetExprRange(Context, E, isConstantEvaluatedContext(),11021/*Approximate=*/true);11022unsigned int SourcePrecision = SourceRange.Width;1102311024// Determine the number of precision bits in the11025// target floating point type.11026unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(11027Context.getFloatTypeSemantics(QualType(TargetBT, 0)));1102811029if (SourcePrecision > 0 && TargetPrecision > 0 &&11030SourcePrecision > TargetPrecision) {1103111032if (std::optional<llvm::APSInt> SourceInt =11033E->getIntegerConstantExpr(Context)) {11034// If the source integer is a constant, convert it to the target11035// floating point type. Issue a warning if the value changes11036// during the whole conversion.11037llvm::APFloat TargetFloatValue(11038Context.getFloatTypeSemantics(QualType(TargetBT, 0)));11039llvm::APFloat::opStatus ConversionStatus =11040TargetFloatValue.convertFromAPInt(11041*SourceInt, SourceBT->isSignedInteger(),11042llvm::APFloat::rmNearestTiesToEven);1104311044if (ConversionStatus != llvm::APFloat::opOK) {11045SmallString<32> PrettySourceValue;11046SourceInt->toString(PrettySourceValue, 10);11047SmallString<32> PrettyTargetValue;11048TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);1104911050DiagRuntimeBehavior(11051E->getExprLoc(), E,11052PDiag(diag::warn_impcast_integer_float_precision_constant)11053<< PrettySourceValue << PrettyTargetValue << E->getType() << T11054<< E->getSourceRange() << clang::SourceRange(CC));11055}11056} else {11057// Otherwise, the implicit conversion may lose precision.11058DiagnoseImpCast(*this, E, T, CC,11059diag::warn_impcast_integer_float_precision);11060}11061}11062}1106311064DiagnoseNullConversion(*this, E, T, CC);1106511066DiscardMisalignedMemberAddress(Target, E);1106711068if (Target->isBooleanType())11069DiagnoseIntInBoolContext(*this, E);1107011071if (!Source->isIntegerType() || !Target->isIntegerType())11072return;1107311074// TODO: remove this early return once the false positives for constant->bool11075// in templates, macros, etc, are reduced or removed.11076if (Target->isSpecificBuiltinType(BuiltinType::Bool))11077return;1107811079if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&11080!E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {11081return ObjC().adornBoolConversionDiagWithTernaryFixit(11082E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)11083<< E->getType());11084}1108511086IntRange SourceTypeRange =11087IntRange::forTargetOfCanonicalType(Context, Source);11088IntRange LikelySourceRange = GetExprRange(11089Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);11090IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);1109111092if (LikelySourceRange.Width > TargetRange.Width) {11093// If the source is a constant, use a default-on diagnostic.11094// TODO: this should happen for bitfield stores, too.11095Expr::EvalResult Result;11096if (E->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects,11097isConstantEvaluatedContext())) {11098llvm::APSInt Value(32);11099Value = Result.Val.getInt();1110011101if (SourceMgr.isInSystemMacro(CC))11102return;1110311104std::string PrettySourceValue = toString(Value, 10);11105std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);1110611107DiagRuntimeBehavior(E->getExprLoc(), E,11108PDiag(diag::warn_impcast_integer_precision_constant)11109<< PrettySourceValue << PrettyTargetValue11110<< E->getType() << T << E->getSourceRange()11111<< SourceRange(CC));11112return;11113}1111411115// People want to build with -Wshorten-64-to-32 and not -Wconversion.11116if (SourceMgr.isInSystemMacro(CC))11117return;1111811119if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)11120return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,11121/* pruneControlFlow */ true);11122return DiagnoseImpCast(*this, E, T, CC,11123diag::warn_impcast_integer_precision);11124}1112511126if (TargetRange.Width > SourceTypeRange.Width) {11127if (auto *UO = dyn_cast<UnaryOperator>(E))11128if (UO->getOpcode() == UO_Minus)11129if (Source->isUnsignedIntegerType()) {11130if (Target->isUnsignedIntegerType())11131return DiagnoseImpCast(*this, E, T, CC,11132diag::warn_impcast_high_order_zero_bits);11133if (Target->isSignedIntegerType())11134return DiagnoseImpCast(*this, E, T, CC,11135diag::warn_impcast_nonnegative_result);11136}11137}1113811139if (TargetRange.Width == LikelySourceRange.Width &&11140!TargetRange.NonNegative && LikelySourceRange.NonNegative &&11141Source->isSignedIntegerType()) {11142// Warn when doing a signed to signed conversion, warn if the positive11143// source value is exactly the width of the target type, which will11144// cause a negative value to be stored.1114511146Expr::EvalResult Result;11147if (E->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects) &&11148!SourceMgr.isInSystemMacro(CC)) {11149llvm::APSInt Value = Result.Val.getInt();11150if (isSameWidthConstantConversion(*this, E, T, CC)) {11151std::string PrettySourceValue = toString(Value, 10);11152std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);1115311154Diag(E->getExprLoc(),11155PDiag(diag::warn_impcast_integer_precision_constant)11156<< PrettySourceValue << PrettyTargetValue << E->getType() << T11157<< E->getSourceRange() << SourceRange(CC));11158return;11159}11160}1116111162// Fall through for non-constants to give a sign conversion warning.11163}1116411165if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&11166((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||11167(!TargetRange.NonNegative && LikelySourceRange.NonNegative &&11168LikelySourceRange.Width == TargetRange.Width))) {11169if (SourceMgr.isInSystemMacro(CC))11170return;1117111172if (SourceBT && SourceBT->isInteger() && TargetBT &&11173TargetBT->isInteger() &&11174Source->isSignedIntegerType() == Target->isSignedIntegerType()) {11175return;11176}1117711178unsigned DiagID = diag::warn_impcast_integer_sign;1117911180// Traditionally, gcc has warned about this under -Wsign-compare.11181// We also want to warn about it in -Wconversion.11182// So if -Wconversion is off, use a completely identical diagnostic11183// in the sign-compare group.11184// The conditional-checking code will11185if (ICContext) {11186DiagID = diag::warn_impcast_integer_sign_conditional;11187*ICContext = true;11188}1118911190return DiagnoseImpCast(*this, E, T, CC, DiagID);11191}1119211193// Diagnose conversions between different enumeration types.11194// In C, we pretend that the type of an EnumConstantDecl is its enumeration11195// type, to give us better diagnostics.11196QualType SourceType = E->getEnumCoercedType(Context);11197Source = Context.getCanonicalType(SourceType).getTypePtr();1119811199if (const EnumType *SourceEnum = Source->getAs<EnumType>())11200if (const EnumType *TargetEnum = Target->getAs<EnumType>())11201if (SourceEnum->getDecl()->hasNameForLinkage() &&11202TargetEnum->getDecl()->hasNameForLinkage() &&11203SourceEnum != TargetEnum) {11204if (SourceMgr.isInSystemMacro(CC))11205return;1120611207return DiagnoseImpCast(*this, E, SourceType, T, CC,11208diag::warn_impcast_different_enum_types);11209}11210}1121111212static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,11213SourceLocation CC, QualType T);1121411215static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,11216SourceLocation CC, bool &ICContext) {11217E = E->IgnoreParenImpCasts();11218// Diagnose incomplete type for second or third operand in C.11219if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())11220S.RequireCompleteExprType(E, diag::err_incomplete_type);1122111222if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))11223return CheckConditionalOperator(S, CO, CC, T);1122411225AnalyzeImplicitConversions(S, E, CC);11226if (E->getType() != T)11227return S.CheckImplicitConversion(E, T, CC, &ICContext);11228}1122911230static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,11231SourceLocation CC, QualType T) {11232AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());1123311234Expr *TrueExpr = E->getTrueExpr();11235if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))11236TrueExpr = BCO->getCommon();1123711238bool Suspicious = false;11239CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);11240CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);1124111242if (T->isBooleanType())11243DiagnoseIntInBoolContext(S, E);1124411245// If -Wconversion would have warned about either of the candidates11246// for a signedness conversion to the context type...11247if (!Suspicious) return;1124811249// ...but it's currently ignored...11250if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))11251return;1125211253// ...then check whether it would have warned about either of the11254// candidates for a signedness conversion to the condition type.11255if (E->getType() == T) return;1125611257Suspicious = false;11258S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,11259&Suspicious);11260if (!Suspicious)11261S.CheckImplicitConversion(E->getFalseExpr()->IgnoreParenImpCasts(),11262E->getType(), CC, &Suspicious);11263}1126411265/// Check conversion of given expression to boolean.11266/// Input argument E is a logical expression.11267static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {11268// Run the bool-like conversion checks only for C since there bools are11269// still not used as the return type from "boolean" operators or as the input11270// type for conditional operators.11271if (S.getLangOpts().CPlusPlus)11272return;11273if (E->IgnoreParenImpCasts()->getType()->isAtomicType())11274return;11275S.CheckImplicitConversion(E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);11276}1127711278namespace {11279struct AnalyzeImplicitConversionsWorkItem {11280Expr *E;11281SourceLocation CC;11282bool IsListInit;11283};11284}1128511286/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions11287/// that should be visited are added to WorkList.11288static void AnalyzeImplicitConversions(11289Sema &S, AnalyzeImplicitConversionsWorkItem Item,11290llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {11291Expr *OrigE = Item.E;11292SourceLocation CC = Item.CC;1129311294QualType T = OrigE->getType();11295Expr *E = OrigE->IgnoreParenImpCasts();1129611297// Propagate whether we are in a C++ list initialization expression.11298// If so, we do not issue warnings for implicit int-float conversion11299// precision loss, because C++11 narrowing already handles it.11300bool IsListInit = Item.IsListInit ||11301(isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);1130211303if (E->isTypeDependent() || E->isValueDependent())11304return;1130511306Expr *SourceExpr = E;11307// Examine, but don't traverse into the source expression of an11308// OpaqueValueExpr, since it may have multiple parents and we don't want to11309// emit duplicate diagnostics. Its fine to examine the form or attempt to11310// evaluate it in the context of checking the specific conversion to T though.11311if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))11312if (auto *Src = OVE->getSourceExpr())11313SourceExpr = Src;1131411315if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))11316if (UO->getOpcode() == UO_Not &&11317UO->getSubExpr()->isKnownToHaveBooleanValue())11318S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)11319<< OrigE->getSourceRange() << T->isBooleanType()11320<< FixItHint::CreateReplacement(UO->getBeginLoc(), "!");1132111322if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))11323if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&11324BO->getLHS()->isKnownToHaveBooleanValue() &&11325BO->getRHS()->isKnownToHaveBooleanValue() &&11326BO->getLHS()->HasSideEffects(S.Context) &&11327BO->getRHS()->HasSideEffects(S.Context)) {11328SourceManager &SM = S.getSourceManager();11329const LangOptions &LO = S.getLangOpts();11330SourceLocation BLoc = BO->getOperatorLoc();11331SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);11332StringRef SR = clang::Lexer::getSourceText(11333clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);11334// To reduce false positives, only issue the diagnostic if the operator11335// is explicitly spelled as a punctuator. This suppresses the diagnostic11336// when using 'bitand' or 'bitor' either as keywords in C++ or as macros11337// in C, along with other macro spellings the user might invent.11338if (SR.str() == "&" || SR.str() == "|") {1133911340S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)11341<< (BO->getOpcode() == BO_And ? "&" : "|")11342<< OrigE->getSourceRange()11343<< FixItHint::CreateReplacement(11344BO->getOperatorLoc(),11345(BO->getOpcode() == BO_And ? "&&" : "||"));11346S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);11347}11348}1134911350// For conditional operators, we analyze the arguments as if they11351// were being fed directly into the output.11352if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {11353CheckConditionalOperator(S, CO, CC, T);11354return;11355}1135611357// Check implicit argument conversions for function calls.11358if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))11359CheckImplicitArgumentConversions(S, Call, CC);1136011361// Go ahead and check any implicit conversions we might have skipped.11362// The non-canonical typecheck is just an optimization;11363// CheckImplicitConversion will filter out dead implicit conversions.11364if (SourceExpr->getType() != T)11365S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);1136611367// Now continue drilling into this expression.1136811369if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {11370// The bound subexpressions in a PseudoObjectExpr are not reachable11371// as transitive children.11372// FIXME: Use a more uniform representation for this.11373for (auto *SE : POE->semantics())11374if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))11375WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});11376}1137711378// Skip past explicit casts.11379if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {11380E = CE->getSubExpr()->IgnoreParenImpCasts();11381if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())11382S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);11383WorkList.push_back({E, CC, IsListInit});11384return;11385}1138611387if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {11388// Do a somewhat different check with comparison operators.11389if (BO->isComparisonOp())11390return AnalyzeComparison(S, BO);1139111392// And with simple assignments.11393if (BO->getOpcode() == BO_Assign)11394return AnalyzeAssignment(S, BO);11395// And with compound assignments.11396if (BO->isAssignmentOp())11397return AnalyzeCompoundAssignment(S, BO);11398}1139911400// These break the otherwise-useful invariant below. Fortunately,11401// we don't really need to recurse into them, because any internal11402// expressions should have been analyzed already when they were11403// built into statements.11404if (isa<StmtExpr>(E)) return;1140511406// Don't descend into unevaluated contexts.11407if (isa<UnaryExprOrTypeTraitExpr>(E)) return;1140811409// Now just recurse over the expression's children.11410CC = E->getExprLoc();11411BinaryOperator *BO = dyn_cast<BinaryOperator>(E);11412bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;11413for (Stmt *SubStmt : E->children()) {11414Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);11415if (!ChildExpr)11416continue;1141711418if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))11419if (ChildExpr == CSE->getOperand())11420// Do not recurse over a CoroutineSuspendExpr's operand.11421// The operand is also a subexpression of getCommonExpr(), and11422// recursing into it directly would produce duplicate diagnostics.11423continue;1142411425if (IsLogicalAndOperator &&11426isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))11427// Ignore checking string literals that are in logical and operators.11428// This is a common pattern for asserts.11429continue;11430WorkList.push_back({ChildExpr, CC, IsListInit});11431}1143211433if (BO && BO->isLogicalOp()) {11434Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();11435if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))11436::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());1143711438SubExpr = BO->getRHS()->IgnoreParenImpCasts();11439if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))11440::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());11441}1144211443if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {11444if (U->getOpcode() == UO_LNot) {11445::CheckBoolLikeConversion(S, U->getSubExpr(), CC);11446} else if (U->getOpcode() != UO_AddrOf) {11447if (U->getSubExpr()->getType()->isAtomicType())11448S.Diag(U->getSubExpr()->getBeginLoc(),11449diag::warn_atomic_implicit_seq_cst);11450}11451}11452}1145311454/// AnalyzeImplicitConversions - Find and report any interesting11455/// implicit conversions in the given expression. There are a couple11456/// of competing diagnostics here, -Wconversion and -Wsign-compare.11457static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,11458bool IsListInit/*= false*/) {11459llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;11460WorkList.push_back({OrigE, CC, IsListInit});11461while (!WorkList.empty())11462AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);11463}1146411465// Helper function for Sema::DiagnoseAlwaysNonNullPointer.11466// Returns true when emitting a warning about taking the address of a reference.11467static bool CheckForReference(Sema &SemaRef, const Expr *E,11468const PartialDiagnostic &PD) {11469E = E->IgnoreParenImpCasts();1147011471const FunctionDecl *FD = nullptr;1147211473if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {11474if (!DRE->getDecl()->getType()->isReferenceType())11475return false;11476} else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {11477if (!M->getMemberDecl()->getType()->isReferenceType())11478return false;11479} else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {11480if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())11481return false;11482FD = Call->getDirectCallee();11483} else {11484return false;11485}1148611487SemaRef.Diag(E->getExprLoc(), PD);1148811489// If possible, point to location of function.11490if (FD) {11491SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;11492}1149311494return true;11495}1149611497// Returns true if the SourceLocation is expanded from any macro body.11498// Returns false if the SourceLocation is invalid, is from not in a macro11499// expansion, or is from expanded from a top-level macro argument.11500static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {11501if (Loc.isInvalid())11502return false;1150311504while (Loc.isMacroID()) {11505if (SM.isMacroBodyExpansion(Loc))11506return true;11507Loc = SM.getImmediateMacroCallerLoc(Loc);11508}1150911510return false;11511}1151211513void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,11514Expr::NullPointerConstantKind NullKind,11515bool IsEqual, SourceRange Range) {11516if (!E)11517return;1151811519// Don't warn inside macros.11520if (E->getExprLoc().isMacroID()) {11521const SourceManager &SM = getSourceManager();11522if (IsInAnyMacroBody(SM, E->getExprLoc()) ||11523IsInAnyMacroBody(SM, Range.getBegin()))11524return;11525}11526E = E->IgnoreImpCasts();1152711528const bool IsCompare = NullKind != Expr::NPCK_NotNull;1152911530if (isa<CXXThisExpr>(E)) {11531unsigned DiagID = IsCompare ? diag::warn_this_null_compare11532: diag::warn_this_bool_conversion;11533Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;11534return;11535}1153611537bool IsAddressOf = false;1153811539if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {11540if (UO->getOpcode() != UO_AddrOf)11541return;11542IsAddressOf = true;11543E = UO->getSubExpr();11544}1154511546if (IsAddressOf) {11547unsigned DiagID = IsCompare11548? diag::warn_address_of_reference_null_compare11549: diag::warn_address_of_reference_bool_conversion;11550PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range11551<< IsEqual;11552if (CheckForReference(*this, E, PD)) {11553return;11554}11555}1155611557auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {11558bool IsParam = isa<NonNullAttr>(NonnullAttr);11559std::string Str;11560llvm::raw_string_ostream S(Str);11561E->printPretty(S, nullptr, getPrintingPolicy());11562unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare11563: diag::warn_cast_nonnull_to_bool;11564Diag(E->getExprLoc(), DiagID) << IsParam << S.str()11565<< E->getSourceRange() << Range << IsEqual;11566Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;11567};1156811569// If we have a CallExpr that is tagged with returns_nonnull, we can complain.11570if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {11571if (auto *Callee = Call->getDirectCallee()) {11572if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {11573ComplainAboutNonnullParamOrCall(A);11574return;11575}11576}11577}1157811579// Complain if we are converting a lambda expression to a boolean value11580// outside of instantiation.11581if (!inTemplateInstantiation()) {11582if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {11583if (const auto *MRecordDecl = MCallExpr->getRecordDecl();11584MRecordDecl && MRecordDecl->isLambda()) {11585Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)11586<< /*LambdaPointerConversionOperatorType=*/311587<< MRecordDecl->getSourceRange() << Range << IsEqual;11588return;11589}11590}11591}1159211593// Expect to find a single Decl. Skip anything more complicated.11594ValueDecl *D = nullptr;11595if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {11596D = R->getDecl();11597} else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {11598D = M->getMemberDecl();11599}1160011601// Weak Decls can be null.11602if (!D || D->isWeak())11603return;1160411605// Check for parameter decl with nonnull attribute11606if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {11607if (getCurFunction() &&11608!getCurFunction()->ModifiedNonNullParams.count(PV)) {11609if (const Attr *A = PV->getAttr<NonNullAttr>()) {11610ComplainAboutNonnullParamOrCall(A);11611return;11612}1161311614if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {11615// Skip function template not specialized yet.11616if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)11617return;11618auto ParamIter = llvm::find(FD->parameters(), PV);11619assert(ParamIter != FD->param_end());11620unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);1162111622for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {11623if (!NonNull->args_size()) {11624ComplainAboutNonnullParamOrCall(NonNull);11625return;11626}1162711628for (const ParamIdx &ArgNo : NonNull->args()) {11629if (ArgNo.getASTIndex() == ParamNo) {11630ComplainAboutNonnullParamOrCall(NonNull);11631return;11632}11633}11634}11635}11636}11637}1163811639QualType T = D->getType();11640const bool IsArray = T->isArrayType();11641const bool IsFunction = T->isFunctionType();1164211643// Address of function is used to silence the function warning.11644if (IsAddressOf && IsFunction) {11645return;11646}1164711648// Found nothing.11649if (!IsAddressOf && !IsFunction && !IsArray)11650return;1165111652// Pretty print the expression for the diagnostic.11653std::string Str;11654llvm::raw_string_ostream S(Str);11655E->printPretty(S, nullptr, getPrintingPolicy());1165611657unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare11658: diag::warn_impcast_pointer_to_bool;11659enum {11660AddressOf,11661FunctionPointer,11662ArrayPointer11663} DiagType;11664if (IsAddressOf)11665DiagType = AddressOf;11666else if (IsFunction)11667DiagType = FunctionPointer;11668else if (IsArray)11669DiagType = ArrayPointer;11670else11671llvm_unreachable("Could not determine diagnostic.");11672Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()11673<< Range << IsEqual;1167411675if (!IsFunction)11676return;1167711678// Suggest '&' to silence the function warning.11679Diag(E->getExprLoc(), diag::note_function_warning_silence)11680<< FixItHint::CreateInsertion(E->getBeginLoc(), "&");1168111682// Check to see if '()' fixit should be emitted.11683QualType ReturnType;11684UnresolvedSet<4> NonTemplateOverloads;11685tryExprAsCall(*E, ReturnType, NonTemplateOverloads);11686if (ReturnType.isNull())11687return;1168811689if (IsCompare) {11690// There are two cases here. If there is null constant, the only suggest11691// for a pointer return type. If the null is 0, then suggest if the return11692// type is a pointer or an integer type.11693if (!ReturnType->isPointerType()) {11694if (NullKind == Expr::NPCK_ZeroExpression ||11695NullKind == Expr::NPCK_ZeroLiteral) {11696if (!ReturnType->isIntegerType())11697return;11698} else {11699return;11700}11701}11702} else { // !IsCompare11703// For function to bool, only suggest if the function pointer has bool11704// return type.11705if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))11706return;11707}11708Diag(E->getExprLoc(), diag::note_function_to_function_call)11709<< FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");11710}1171111712void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {11713// Don't diagnose in unevaluated contexts.11714if (isUnevaluatedContext())11715return;1171611717// Don't diagnose for value- or type-dependent expressions.11718if (E->isTypeDependent() || E->isValueDependent())11719return;1172011721// Check for array bounds violations in cases where the check isn't triggered11722// elsewhere for other Expr types (like BinaryOperators), e.g. when an11723// ArraySubscriptExpr is on the RHS of a variable initialization.11724CheckArrayAccess(E);1172511726// This is not the right CC for (e.g.) a variable initialization.11727AnalyzeImplicitConversions(*this, E, CC);11728}1172911730void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {11731::CheckBoolLikeConversion(*this, E, CC);11732}1173311734void Sema::CheckForIntOverflow (const Expr *E) {11735// Use a work list to deal with nested struct initializers.11736SmallVector<const Expr *, 2> Exprs(1, E);1173711738do {11739const Expr *OriginalE = Exprs.pop_back_val();11740const Expr *E = OriginalE->IgnoreParenCasts();1174111742if (isa<BinaryOperator, UnaryOperator>(E)) {11743E->EvaluateForOverflow(Context);11744continue;11745}1174611747if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))11748Exprs.append(InitList->inits().begin(), InitList->inits().end());11749else if (isa<ObjCBoxedExpr>(OriginalE))11750E->EvaluateForOverflow(Context);11751else if (const auto *Call = dyn_cast<CallExpr>(E))11752Exprs.append(Call->arg_begin(), Call->arg_end());11753else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))11754Exprs.append(Message->arg_begin(), Message->arg_end());11755else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))11756Exprs.append(Construct->arg_begin(), Construct->arg_end());11757else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))11758Exprs.push_back(Temporary->getSubExpr());11759else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))11760Exprs.push_back(Array->getIdx());11761else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))11762Exprs.push_back(Compound->getInitializer());11763else if (const auto *New = dyn_cast<CXXNewExpr>(E);11764New && New->isArray()) {11765if (auto ArraySize = New->getArraySize())11766Exprs.push_back(*ArraySize);11767}11768} while (!Exprs.empty());11769}1177011771namespace {1177211773/// Visitor for expressions which looks for unsequenced operations on the11774/// same object.11775class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {11776using Base = ConstEvaluatedExprVisitor<SequenceChecker>;1177711778/// A tree of sequenced regions within an expression. Two regions are11779/// unsequenced if one is an ancestor or a descendent of the other. When we11780/// finish processing an expression with sequencing, such as a comma11781/// expression, we fold its tree nodes into its parent, since they are11782/// unsequenced with respect to nodes we will visit later.11783class SequenceTree {11784struct Value {11785explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}11786unsigned Parent : 31;11787LLVM_PREFERRED_TYPE(bool)11788unsigned Merged : 1;11789};11790SmallVector<Value, 8> Values;1179111792public:11793/// A region within an expression which may be sequenced with respect11794/// to some other region.11795class Seq {11796friend class SequenceTree;1179711798unsigned Index;1179911800explicit Seq(unsigned N) : Index(N) {}1180111802public:11803Seq() : Index(0) {}11804};1180511806SequenceTree() { Values.push_back(Value(0)); }11807Seq root() const { return Seq(0); }1180811809/// Create a new sequence of operations, which is an unsequenced11810/// subset of \p Parent. This sequence of operations is sequenced with11811/// respect to other children of \p Parent.11812Seq allocate(Seq Parent) {11813Values.push_back(Value(Parent.Index));11814return Seq(Values.size() - 1);11815}1181611817/// Merge a sequence of operations into its parent.11818void merge(Seq S) {11819Values[S.Index].Merged = true;11820}1182111822/// Determine whether two operations are unsequenced. This operation11823/// is asymmetric: \p Cur should be the more recent sequence, and \p Old11824/// should have been merged into its parent as appropriate.11825bool isUnsequenced(Seq Cur, Seq Old) {11826unsigned C = representative(Cur.Index);11827unsigned Target = representative(Old.Index);11828while (C >= Target) {11829if (C == Target)11830return true;11831C = Values[C].Parent;11832}11833return false;11834}1183511836private:11837/// Pick a representative for a sequence.11838unsigned representative(unsigned K) {11839if (Values[K].Merged)11840// Perform path compression as we go.11841return Values[K].Parent = representative(Values[K].Parent);11842return K;11843}11844};1184511846/// An object for which we can track unsequenced uses.11847using Object = const NamedDecl *;1184811849/// Different flavors of object usage which we track. We only track the11850/// least-sequenced usage of each kind.11851enum UsageKind {11852/// A read of an object. Multiple unsequenced reads are OK.11853UK_Use,1185411855/// A modification of an object which is sequenced before the value11856/// computation of the expression, such as ++n in C++.11857UK_ModAsValue,1185811859/// A modification of an object which is not sequenced before the value11860/// computation of the expression, such as n++.11861UK_ModAsSideEffect,1186211863UK_Count = UK_ModAsSideEffect + 111864};1186511866/// Bundle together a sequencing region and the expression corresponding11867/// to a specific usage. One Usage is stored for each usage kind in UsageInfo.11868struct Usage {11869const Expr *UsageExpr = nullptr;11870SequenceTree::Seq Seq;1187111872Usage() = default;11873};1187411875struct UsageInfo {11876Usage Uses[UK_Count];1187711878/// Have we issued a diagnostic for this object already?11879bool Diagnosed = false;1188011881UsageInfo();11882};11883using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;1188411885Sema &SemaRef;1188611887/// Sequenced regions within the expression.11888SequenceTree Tree;1188911890/// Declaration modifications and references which we have seen.11891UsageInfoMap UsageMap;1189211893/// The region we are currently within.11894SequenceTree::Seq Region;1189511896/// Filled in with declarations which were modified as a side-effect11897/// (that is, post-increment operations).11898SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;1189911900/// Expressions to check later. We defer checking these to reduce11901/// stack usage.11902SmallVectorImpl<const Expr *> &WorkList;1190311904/// RAII object wrapping the visitation of a sequenced subexpression of an11905/// expression. At the end of this process, the side-effects of the evaluation11906/// become sequenced with respect to the value computation of the result, so11907/// we downgrade any UK_ModAsSideEffect within the evaluation to11908/// UK_ModAsValue.11909struct SequencedSubexpression {11910SequencedSubexpression(SequenceChecker &Self)11911: Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {11912Self.ModAsSideEffect = &ModAsSideEffect;11913}1191411915~SequencedSubexpression() {11916for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {11917// Add a new usage with usage kind UK_ModAsValue, and then restore11918// the previous usage with UK_ModAsSideEffect (thus clearing it if11919// the previous one was empty).11920UsageInfo &UI = Self.UsageMap[M.first];11921auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];11922Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);11923SideEffectUsage = M.second;11924}11925Self.ModAsSideEffect = OldModAsSideEffect;11926}1192711928SequenceChecker &Self;11929SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;11930SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;11931};1193211933/// RAII object wrapping the visitation of a subexpression which we might11934/// choose to evaluate as a constant. If any subexpression is evaluated and11935/// found to be non-constant, this allows us to suppress the evaluation of11936/// the outer expression.11937class EvaluationTracker {11938public:11939EvaluationTracker(SequenceChecker &Self)11940: Self(Self), Prev(Self.EvalTracker) {11941Self.EvalTracker = this;11942}1194311944~EvaluationTracker() {11945Self.EvalTracker = Prev;11946if (Prev)11947Prev->EvalOK &= EvalOK;11948}1194911950bool evaluate(const Expr *E, bool &Result) {11951if (!EvalOK || E->isValueDependent())11952return false;11953EvalOK = E->EvaluateAsBooleanCondition(11954Result, Self.SemaRef.Context,11955Self.SemaRef.isConstantEvaluatedContext());11956return EvalOK;11957}1195811959private:11960SequenceChecker &Self;11961EvaluationTracker *Prev;11962bool EvalOK = true;11963} *EvalTracker = nullptr;1196411965/// Find the object which is produced by the specified expression,11966/// if any.11967Object getObject(const Expr *E, bool Mod) const {11968E = E->IgnoreParenCasts();11969if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {11970if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))11971return getObject(UO->getSubExpr(), Mod);11972} else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {11973if (BO->getOpcode() == BO_Comma)11974return getObject(BO->getRHS(), Mod);11975if (Mod && BO->isAssignmentOp())11976return getObject(BO->getLHS(), Mod);11977} else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {11978// FIXME: Check for more interesting cases, like "x.n = ++x.n".11979if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))11980return ME->getMemberDecl();11981} else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))11982// FIXME: If this is a reference, map through to its value.11983return DRE->getDecl();11984return nullptr;11985}1198611987/// Note that an object \p O was modified or used by an expression11988/// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for11989/// the object \p O as obtained via the \p UsageMap.11990void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {11991// Get the old usage for the given object and usage kind.11992Usage &U = UI.Uses[UK];11993if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {11994// If we have a modification as side effect and are in a sequenced11995// subexpression, save the old Usage so that we can restore it later11996// in SequencedSubexpression::~SequencedSubexpression.11997if (UK == UK_ModAsSideEffect && ModAsSideEffect)11998ModAsSideEffect->push_back(std::make_pair(O, U));11999// Then record the new usage with the current sequencing region.12000U.UsageExpr = UsageExpr;12001U.Seq = Region;12002}12003}1200412005/// Check whether a modification or use of an object \p O in an expression12006/// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is12007/// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.12008/// \p IsModMod is true when we are checking for a mod-mod unsequenced12009/// usage and false we are checking for a mod-use unsequenced usage.12010void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,12011UsageKind OtherKind, bool IsModMod) {12012if (UI.Diagnosed)12013return;1201412015const Usage &U = UI.Uses[OtherKind];12016if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))12017return;1201812019const Expr *Mod = U.UsageExpr;12020const Expr *ModOrUse = UsageExpr;12021if (OtherKind == UK_Use)12022std::swap(Mod, ModOrUse);1202312024SemaRef.DiagRuntimeBehavior(12025Mod->getExprLoc(), {Mod, ModOrUse},12026SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod12027: diag::warn_unsequenced_mod_use)12028<< O << SourceRange(ModOrUse->getExprLoc()));12029UI.Diagnosed = true;12030}1203112032// A note on note{Pre, Post}{Use, Mod}:12033//12034// (It helps to follow the algorithm with an expression such as12035// "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced12036// operations before C++17 and both are well-defined in C++17).12037//12038// When visiting a node which uses/modify an object we first call notePreUse12039// or notePreMod before visiting its sub-expression(s). At this point the12040// children of the current node have not yet been visited and so the eventual12041// uses/modifications resulting from the children of the current node have not12042// been recorded yet.12043//12044// We then visit the children of the current node. After that notePostUse or12045// notePostMod is called. These will 1) detect an unsequenced modification12046// as side effect (as in "k++ + k") and 2) add a new usage with the12047// appropriate usage kind.12048//12049// We also have to be careful that some operation sequences modification as12050// side effect as well (for example: || or ,). To account for this we wrap12051// the visitation of such a sub-expression (for example: the LHS of || or ,)12052// with SequencedSubexpression. SequencedSubexpression is an RAII object12053// which record usages which are modifications as side effect, and then12054// downgrade them (or more accurately restore the previous usage which was a12055// modification as side effect) when exiting the scope of the sequenced12056// subexpression.1205712058void notePreUse(Object O, const Expr *UseExpr) {12059UsageInfo &UI = UsageMap[O];12060// Uses conflict with other modifications.12061checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);12062}1206312064void notePostUse(Object O, const Expr *UseExpr) {12065UsageInfo &UI = UsageMap[O];12066checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,12067/*IsModMod=*/false);12068addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);12069}1207012071void notePreMod(Object O, const Expr *ModExpr) {12072UsageInfo &UI = UsageMap[O];12073// Modifications conflict with other modifications and with uses.12074checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);12075checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);12076}1207712078void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {12079UsageInfo &UI = UsageMap[O];12080checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,12081/*IsModMod=*/true);12082addUsage(O, UI, ModExpr, /*UsageKind=*/UK);12083}1208412085public:12086SequenceChecker(Sema &S, const Expr *E,12087SmallVectorImpl<const Expr *> &WorkList)12088: Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {12089Visit(E);12090// Silence a -Wunused-private-field since WorkList is now unused.12091// TODO: Evaluate if it can be used, and if not remove it.12092(void)this->WorkList;12093}1209412095void VisitStmt(const Stmt *S) {12096// Skip all statements which aren't expressions for now.12097}1209812099void VisitExpr(const Expr *E) {12100// By default, just recurse to evaluated subexpressions.12101Base::VisitStmt(E);12102}1210312104void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {12105for (auto *Sub : CSE->children()) {12106const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);12107if (!ChildExpr)12108continue;1210912110if (ChildExpr == CSE->getOperand())12111// Do not recurse over a CoroutineSuspendExpr's operand.12112// The operand is also a subexpression of getCommonExpr(), and12113// recursing into it directly could confuse object management12114// for the sake of sequence tracking.12115continue;1211612117Visit(Sub);12118}12119}1212012121void VisitCastExpr(const CastExpr *E) {12122Object O = Object();12123if (E->getCastKind() == CK_LValueToRValue)12124O = getObject(E->getSubExpr(), false);1212512126if (O)12127notePreUse(O, E);12128VisitExpr(E);12129if (O)12130notePostUse(O, E);12131}1213212133void VisitSequencedExpressions(const Expr *SequencedBefore,12134const Expr *SequencedAfter) {12135SequenceTree::Seq BeforeRegion = Tree.allocate(Region);12136SequenceTree::Seq AfterRegion = Tree.allocate(Region);12137SequenceTree::Seq OldRegion = Region;1213812139{12140SequencedSubexpression SeqBefore(*this);12141Region = BeforeRegion;12142Visit(SequencedBefore);12143}1214412145Region = AfterRegion;12146Visit(SequencedAfter);1214712148Region = OldRegion;1214912150Tree.merge(BeforeRegion);12151Tree.merge(AfterRegion);12152}1215312154void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {12155// C++17 [expr.sub]p1:12156// The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The12157// expression E1 is sequenced before the expression E2.12158if (SemaRef.getLangOpts().CPlusPlus17)12159VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());12160else {12161Visit(ASE->getLHS());12162Visit(ASE->getRHS());12163}12164}1216512166void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }12167void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }12168void VisitBinPtrMem(const BinaryOperator *BO) {12169// C++17 [expr.mptr.oper]p4:12170// Abbreviating pm-expression.*cast-expression as E1.*E2, [...]12171// the expression E1 is sequenced before the expression E2.12172if (SemaRef.getLangOpts().CPlusPlus17)12173VisitSequencedExpressions(BO->getLHS(), BO->getRHS());12174else {12175Visit(BO->getLHS());12176Visit(BO->getRHS());12177}12178}1217912180void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }12181void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }12182void VisitBinShlShr(const BinaryOperator *BO) {12183// C++17 [expr.shift]p4:12184// The expression E1 is sequenced before the expression E2.12185if (SemaRef.getLangOpts().CPlusPlus17)12186VisitSequencedExpressions(BO->getLHS(), BO->getRHS());12187else {12188Visit(BO->getLHS());12189Visit(BO->getRHS());12190}12191}1219212193void VisitBinComma(const BinaryOperator *BO) {12194// C++11 [expr.comma]p1:12195// Every value computation and side effect associated with the left12196// expression is sequenced before every value computation and side12197// effect associated with the right expression.12198VisitSequencedExpressions(BO->getLHS(), BO->getRHS());12199}1220012201void VisitBinAssign(const BinaryOperator *BO) {12202SequenceTree::Seq RHSRegion;12203SequenceTree::Seq LHSRegion;12204if (SemaRef.getLangOpts().CPlusPlus17) {12205RHSRegion = Tree.allocate(Region);12206LHSRegion = Tree.allocate(Region);12207} else {12208RHSRegion = Region;12209LHSRegion = Region;12210}12211SequenceTree::Seq OldRegion = Region;1221212213// C++11 [expr.ass]p1:12214// [...] the assignment is sequenced after the value computation12215// of the right and left operands, [...]12216//12217// so check it before inspecting the operands and update the12218// map afterwards.12219Object O = getObject(BO->getLHS(), /*Mod=*/true);12220if (O)12221notePreMod(O, BO);1222212223if (SemaRef.getLangOpts().CPlusPlus17) {12224// C++17 [expr.ass]p1:12225// [...] The right operand is sequenced before the left operand. [...]12226{12227SequencedSubexpression SeqBefore(*this);12228Region = RHSRegion;12229Visit(BO->getRHS());12230}1223112232Region = LHSRegion;12233Visit(BO->getLHS());1223412235if (O && isa<CompoundAssignOperator>(BO))12236notePostUse(O, BO);1223712238} else {12239// C++11 does not specify any sequencing between the LHS and RHS.12240Region = LHSRegion;12241Visit(BO->getLHS());1224212243if (O && isa<CompoundAssignOperator>(BO))12244notePostUse(O, BO);1224512246Region = RHSRegion;12247Visit(BO->getRHS());12248}1224912250// C++11 [expr.ass]p1:12251// the assignment is sequenced [...] before the value computation of the12252// assignment expression.12253// C11 6.5.16/3 has no such rule.12254Region = OldRegion;12255if (O)12256notePostMod(O, BO,12257SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue12258: UK_ModAsSideEffect);12259if (SemaRef.getLangOpts().CPlusPlus17) {12260Tree.merge(RHSRegion);12261Tree.merge(LHSRegion);12262}12263}1226412265void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {12266VisitBinAssign(CAO);12267}1226812269void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }12270void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }12271void VisitUnaryPreIncDec(const UnaryOperator *UO) {12272Object O = getObject(UO->getSubExpr(), true);12273if (!O)12274return VisitExpr(UO);1227512276notePreMod(O, UO);12277Visit(UO->getSubExpr());12278// C++11 [expr.pre.incr]p1:12279// the expression ++x is equivalent to x+=112280notePostMod(O, UO,12281SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue12282: UK_ModAsSideEffect);12283}1228412285void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }12286void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }12287void VisitUnaryPostIncDec(const UnaryOperator *UO) {12288Object O = getObject(UO->getSubExpr(), true);12289if (!O)12290return VisitExpr(UO);1229112292notePreMod(O, UO);12293Visit(UO->getSubExpr());12294notePostMod(O, UO, UK_ModAsSideEffect);12295}1229612297void VisitBinLOr(const BinaryOperator *BO) {12298// C++11 [expr.log.or]p2:12299// If the second expression is evaluated, every value computation and12300// side effect associated with the first expression is sequenced before12301// every value computation and side effect associated with the12302// second expression.12303SequenceTree::Seq LHSRegion = Tree.allocate(Region);12304SequenceTree::Seq RHSRegion = Tree.allocate(Region);12305SequenceTree::Seq OldRegion = Region;1230612307EvaluationTracker Eval(*this);12308{12309SequencedSubexpression Sequenced(*this);12310Region = LHSRegion;12311Visit(BO->getLHS());12312}1231312314// C++11 [expr.log.or]p1:12315// [...] the second operand is not evaluated if the first operand12316// evaluates to true.12317bool EvalResult = false;12318bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);12319bool ShouldVisitRHS = !EvalOK || !EvalResult;12320if (ShouldVisitRHS) {12321Region = RHSRegion;12322Visit(BO->getRHS());12323}1232412325Region = OldRegion;12326Tree.merge(LHSRegion);12327Tree.merge(RHSRegion);12328}1232912330void VisitBinLAnd(const BinaryOperator *BO) {12331// C++11 [expr.log.and]p2:12332// If the second expression is evaluated, every value computation and12333// side effect associated with the first expression is sequenced before12334// every value computation and side effect associated with the12335// second expression.12336SequenceTree::Seq LHSRegion = Tree.allocate(Region);12337SequenceTree::Seq RHSRegion = Tree.allocate(Region);12338SequenceTree::Seq OldRegion = Region;1233912340EvaluationTracker Eval(*this);12341{12342SequencedSubexpression Sequenced(*this);12343Region = LHSRegion;12344Visit(BO->getLHS());12345}1234612347// C++11 [expr.log.and]p1:12348// [...] the second operand is not evaluated if the first operand is false.12349bool EvalResult = false;12350bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);12351bool ShouldVisitRHS = !EvalOK || EvalResult;12352if (ShouldVisitRHS) {12353Region = RHSRegion;12354Visit(BO->getRHS());12355}1235612357Region = OldRegion;12358Tree.merge(LHSRegion);12359Tree.merge(RHSRegion);12360}1236112362void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {12363// C++11 [expr.cond]p1:12364// [...] Every value computation and side effect associated with the first12365// expression is sequenced before every value computation and side effect12366// associated with the second or third expression.12367SequenceTree::Seq ConditionRegion = Tree.allocate(Region);1236812369// No sequencing is specified between the true and false expression.12370// However since exactly one of both is going to be evaluated we can12371// consider them to be sequenced. This is needed to avoid warning on12372// something like "x ? y+= 1 : y += 2;" in the case where we will visit12373// both the true and false expressions because we can't evaluate x.12374// This will still allow us to detect an expression like (pre C++17)12375// "(x ? y += 1 : y += 2) = y".12376//12377// We don't wrap the visitation of the true and false expression with12378// SequencedSubexpression because we don't want to downgrade modifications12379// as side effect in the true and false expressions after the visition12380// is done. (for example in the expression "(x ? y++ : y++) + y" we should12381// not warn between the two "y++", but we should warn between the "y++"12382// and the "y".12383SequenceTree::Seq TrueRegion = Tree.allocate(Region);12384SequenceTree::Seq FalseRegion = Tree.allocate(Region);12385SequenceTree::Seq OldRegion = Region;1238612387EvaluationTracker Eval(*this);12388{12389SequencedSubexpression Sequenced(*this);12390Region = ConditionRegion;12391Visit(CO->getCond());12392}1239312394// C++11 [expr.cond]p1:12395// [...] The first expression is contextually converted to bool (Clause 4).12396// It is evaluated and if it is true, the result of the conditional12397// expression is the value of the second expression, otherwise that of the12398// third expression. Only one of the second and third expressions is12399// evaluated. [...]12400bool EvalResult = false;12401bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);12402bool ShouldVisitTrueExpr = !EvalOK || EvalResult;12403bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;12404if (ShouldVisitTrueExpr) {12405Region = TrueRegion;12406Visit(CO->getTrueExpr());12407}12408if (ShouldVisitFalseExpr) {12409Region = FalseRegion;12410Visit(CO->getFalseExpr());12411}1241212413Region = OldRegion;12414Tree.merge(ConditionRegion);12415Tree.merge(TrueRegion);12416Tree.merge(FalseRegion);12417}1241812419void VisitCallExpr(const CallExpr *CE) {12420// FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.1242112422if (CE->isUnevaluatedBuiltinCall(Context))12423return;1242412425// C++11 [intro.execution]p15:12426// When calling a function [...], every value computation and side effect12427// associated with any argument expression, or with the postfix expression12428// designating the called function, is sequenced before execution of every12429// expression or statement in the body of the function [and thus before12430// the value computation of its result].12431SequencedSubexpression Sequenced(*this);12432SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {12433// C++17 [expr.call]p512434// The postfix-expression is sequenced before each expression in the12435// expression-list and any default argument. [...]12436SequenceTree::Seq CalleeRegion;12437SequenceTree::Seq OtherRegion;12438if (SemaRef.getLangOpts().CPlusPlus17) {12439CalleeRegion = Tree.allocate(Region);12440OtherRegion = Tree.allocate(Region);12441} else {12442CalleeRegion = Region;12443OtherRegion = Region;12444}12445SequenceTree::Seq OldRegion = Region;1244612447// Visit the callee expression first.12448Region = CalleeRegion;12449if (SemaRef.getLangOpts().CPlusPlus17) {12450SequencedSubexpression Sequenced(*this);12451Visit(CE->getCallee());12452} else {12453Visit(CE->getCallee());12454}1245512456// Then visit the argument expressions.12457Region = OtherRegion;12458for (const Expr *Argument : CE->arguments())12459Visit(Argument);1246012461Region = OldRegion;12462if (SemaRef.getLangOpts().CPlusPlus17) {12463Tree.merge(CalleeRegion);12464Tree.merge(OtherRegion);12465}12466});12467}1246812469void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {12470// C++17 [over.match.oper]p2:12471// [...] the operator notation is first transformed to the equivalent12472// function-call notation as summarized in Table 12 (where @ denotes one12473// of the operators covered in the specified subclause). However, the12474// operands are sequenced in the order prescribed for the built-in12475// operator (Clause 8).12476//12477// From the above only overloaded binary operators and overloaded call12478// operators have sequencing rules in C++17 that we need to handle12479// separately.12480if (!SemaRef.getLangOpts().CPlusPlus17 ||12481(CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))12482return VisitCallExpr(CXXOCE);1248312484enum {12485NoSequencing,12486LHSBeforeRHS,12487RHSBeforeLHS,12488LHSBeforeRest12489} SequencingKind;12490switch (CXXOCE->getOperator()) {12491case OO_Equal:12492case OO_PlusEqual:12493case OO_MinusEqual:12494case OO_StarEqual:12495case OO_SlashEqual:12496case OO_PercentEqual:12497case OO_CaretEqual:12498case OO_AmpEqual:12499case OO_PipeEqual:12500case OO_LessLessEqual:12501case OO_GreaterGreaterEqual:12502SequencingKind = RHSBeforeLHS;12503break;1250412505case OO_LessLess:12506case OO_GreaterGreater:12507case OO_AmpAmp:12508case OO_PipePipe:12509case OO_Comma:12510case OO_ArrowStar:12511case OO_Subscript:12512SequencingKind = LHSBeforeRHS;12513break;1251412515case OO_Call:12516SequencingKind = LHSBeforeRest;12517break;1251812519default:12520SequencingKind = NoSequencing;12521break;12522}1252312524if (SequencingKind == NoSequencing)12525return VisitCallExpr(CXXOCE);1252612527// This is a call, so all subexpressions are sequenced before the result.12528SequencedSubexpression Sequenced(*this);1252912530SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {12531assert(SemaRef.getLangOpts().CPlusPlus17 &&12532"Should only get there with C++17 and above!");12533assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&12534"Should only get there with an overloaded binary operator"12535" or an overloaded call operator!");1253612537if (SequencingKind == LHSBeforeRest) {12538assert(CXXOCE->getOperator() == OO_Call &&12539"We should only have an overloaded call operator here!");1254012541// This is very similar to VisitCallExpr, except that we only have the12542// C++17 case. The postfix-expression is the first argument of the12543// CXXOperatorCallExpr. The expressions in the expression-list, if any,12544// are in the following arguments.12545//12546// Note that we intentionally do not visit the callee expression since12547// it is just a decayed reference to a function.12548SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);12549SequenceTree::Seq ArgsRegion = Tree.allocate(Region);12550SequenceTree::Seq OldRegion = Region;1255112552assert(CXXOCE->getNumArgs() >= 1 &&12553"An overloaded call operator must have at least one argument"12554" for the postfix-expression!");12555const Expr *PostfixExpr = CXXOCE->getArgs()[0];12556llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,12557CXXOCE->getNumArgs() - 1);1255812559// Visit the postfix-expression first.12560{12561Region = PostfixExprRegion;12562SequencedSubexpression Sequenced(*this);12563Visit(PostfixExpr);12564}1256512566// Then visit the argument expressions.12567Region = ArgsRegion;12568for (const Expr *Arg : Args)12569Visit(Arg);1257012571Region = OldRegion;12572Tree.merge(PostfixExprRegion);12573Tree.merge(ArgsRegion);12574} else {12575assert(CXXOCE->getNumArgs() == 2 &&12576"Should only have two arguments here!");12577assert((SequencingKind == LHSBeforeRHS ||12578SequencingKind == RHSBeforeLHS) &&12579"Unexpected sequencing kind!");1258012581// We do not visit the callee expression since it is just a decayed12582// reference to a function.12583const Expr *E1 = CXXOCE->getArg(0);12584const Expr *E2 = CXXOCE->getArg(1);12585if (SequencingKind == RHSBeforeLHS)12586std::swap(E1, E2);1258712588return VisitSequencedExpressions(E1, E2);12589}12590});12591}1259212593void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {12594// This is a call, so all subexpressions are sequenced before the result.12595SequencedSubexpression Sequenced(*this);1259612597if (!CCE->isListInitialization())12598return VisitExpr(CCE);1259912600// In C++11, list initializations are sequenced.12601SequenceExpressionsInOrder(12602llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));12603}1260412605void VisitInitListExpr(const InitListExpr *ILE) {12606if (!SemaRef.getLangOpts().CPlusPlus11)12607return VisitExpr(ILE);1260812609// In C++11, list initializations are sequenced.12610SequenceExpressionsInOrder(ILE->inits());12611}1261212613void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {12614// C++20 parenthesized list initializations are sequenced. See C++2012615// [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.12616SequenceExpressionsInOrder(PLIE->getInitExprs());12617}1261812619private:12620void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {12621SmallVector<SequenceTree::Seq, 32> Elts;12622SequenceTree::Seq Parent = Region;12623for (const Expr *E : ExpressionList) {12624if (!E)12625continue;12626Region = Tree.allocate(Parent);12627Elts.push_back(Region);12628Visit(E);12629}1263012631// Forget that the initializers are sequenced.12632Region = Parent;12633for (unsigned I = 0; I < Elts.size(); ++I)12634Tree.merge(Elts[I]);12635}12636};1263712638SequenceChecker::UsageInfo::UsageInfo() = default;1263912640} // namespace1264112642void Sema::CheckUnsequencedOperations(const Expr *E) {12643SmallVector<const Expr *, 8> WorkList;12644WorkList.push_back(E);12645while (!WorkList.empty()) {12646const Expr *Item = WorkList.pop_back_val();12647SequenceChecker(*this, Item, WorkList);12648}12649}1265012651void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,12652bool IsConstexpr) {12653llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,12654IsConstexpr || isa<ConstantExpr>(E));12655CheckImplicitConversions(E, CheckLoc);12656if (!E->isInstantiationDependent())12657CheckUnsequencedOperations(E);12658if (!IsConstexpr && !E->isValueDependent())12659CheckForIntOverflow(E);12660DiagnoseMisalignedMembers();12661}1266212663void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,12664FieldDecl *BitField,12665Expr *Init) {12666(void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);12667}1266812669static void diagnoseArrayStarInParamType(Sema &S, QualType PType,12670SourceLocation Loc) {12671if (!PType->isVariablyModifiedType())12672return;12673if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {12674diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);12675return;12676}12677if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {12678diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);12679return;12680}12681if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {12682diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);12683return;12684}1268512686const ArrayType *AT = S.Context.getAsArrayType(PType);12687if (!AT)12688return;1268912690if (AT->getSizeModifier() != ArraySizeModifier::Star) {12691diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);12692return;12693}1269412695S.Diag(Loc, diag::err_array_star_in_function_definition);12696}1269712698bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,12699bool CheckParameterNames) {12700bool HasInvalidParm = false;12701for (ParmVarDecl *Param : Parameters) {12702assert(Param && "null in a parameter list");12703// C99 6.7.5.3p4: the parameters in a parameter type list in a12704// function declarator that is part of a function definition of12705// that function shall not have incomplete type.12706//12707// C++23 [dcl.fct.def.general]/p212708// The type of a parameter [...] for a function definition12709// shall not be a (possibly cv-qualified) class type that is incomplete12710// or abstract within the function body unless the function is deleted.12711if (!Param->isInvalidDecl() &&12712(RequireCompleteType(Param->getLocation(), Param->getType(),12713diag::err_typecheck_decl_incomplete_type) ||12714RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),12715diag::err_abstract_type_in_decl,12716AbstractParamType))) {12717Param->setInvalidDecl();12718HasInvalidParm = true;12719}1272012721// C99 6.9.1p5: If the declarator includes a parameter type list, the12722// declaration of each parameter shall include an identifier.12723if (CheckParameterNames && Param->getIdentifier() == nullptr &&12724!Param->isImplicit() && !getLangOpts().CPlusPlus) {12725// Diagnose this as an extension in C17 and earlier.12726if (!getLangOpts().C23)12727Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);12728}1272912730// C99 6.7.5.3p12:12731// If the function declarator is not part of a definition of that12732// function, parameters may have incomplete type and may use the [*]12733// notation in their sequences of declarator specifiers to specify12734// variable length array types.12735QualType PType = Param->getOriginalType();12736// FIXME: This diagnostic should point the '[*]' if source-location12737// information is added for it.12738diagnoseArrayStarInParamType(*this, PType, Param->getLocation());1273912740// If the parameter is a c++ class type and it has to be destructed in the12741// callee function, declare the destructor so that it can be called by the12742// callee function. Do not perform any direct access check on the dtor here.12743if (!Param->isInvalidDecl()) {12744if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {12745if (!ClassDecl->isInvalidDecl() &&12746!ClassDecl->hasIrrelevantDestructor() &&12747!ClassDecl->isDependentContext() &&12748ClassDecl->isParamDestroyedInCallee()) {12749CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);12750MarkFunctionReferenced(Param->getLocation(), Destructor);12751DiagnoseUseOfDecl(Destructor, Param->getLocation());12752}12753}12754}1275512756// Parameters with the pass_object_size attribute only need to be marked12757// constant at function definitions. Because we lack information about12758// whether we're on a declaration or definition when we're instantiating the12759// attribute, we need to check for constness here.12760if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())12761if (!Param->getType().isConstQualified())12762Diag(Param->getLocation(), diag::err_attribute_pointers_only)12763<< Attr->getSpelling() << 1;1276412765// Check for parameter names shadowing fields from the class.12766if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {12767// The owning context for the parameter should be the function, but we12768// want to see if this function's declaration context is a record.12769DeclContext *DC = Param->getDeclContext();12770if (DC && DC->isFunctionOrMethod()) {12771if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))12772CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),12773RD, /*DeclIsField*/ false);12774}12775}1277612777if (!Param->isInvalidDecl() &&12778Param->getOriginalType()->isWebAssemblyTableType()) {12779Param->setInvalidDecl();12780HasInvalidParm = true;12781Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);12782}12783}1278412785return HasInvalidParm;12786}1278712788std::optional<std::pair<12789CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr12790*E,12791ASTContext12792&Ctx);1279312794/// Compute the alignment and offset of the base class object given the12795/// derived-to-base cast expression and the alignment and offset of the derived12796/// class object.12797static std::pair<CharUnits, CharUnits>12798getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,12799CharUnits BaseAlignment, CharUnits Offset,12800ASTContext &Ctx) {12801for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;12802++PathI) {12803const CXXBaseSpecifier *Base = *PathI;12804const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();12805if (Base->isVirtual()) {12806// The complete object may have a lower alignment than the non-virtual12807// alignment of the base, in which case the base may be misaligned. Choose12808// the smaller of the non-virtual alignment and BaseAlignment, which is a12809// conservative lower bound of the complete object alignment.12810CharUnits NonVirtualAlignment =12811Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();12812BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);12813Offset = CharUnits::Zero();12814} else {12815const ASTRecordLayout &RL =12816Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());12817Offset += RL.getBaseClassOffset(BaseDecl);12818}12819DerivedType = Base->getType();12820}1282112822return std::make_pair(BaseAlignment, Offset);12823}1282412825/// Compute the alignment and offset of a binary additive operator.12826static std::optional<std::pair<CharUnits, CharUnits>>12827getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,12828bool IsSub, ASTContext &Ctx) {12829QualType PointeeType = PtrE->getType()->getPointeeType();1283012831if (!PointeeType->isConstantSizeType())12832return std::nullopt;1283312834auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);1283512836if (!P)12837return std::nullopt;1283812839CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);12840if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {12841CharUnits Offset = EltSize * IdxRes->getExtValue();12842if (IsSub)12843Offset = -Offset;12844return std::make_pair(P->first, P->second + Offset);12845}1284612847// If the integer expression isn't a constant expression, compute the lower12848// bound of the alignment using the alignment and offset of the pointer12849// expression and the element size.12850return std::make_pair(12851P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),12852CharUnits::Zero());12853}1285412855/// This helper function takes an lvalue expression and returns the alignment of12856/// a VarDecl and a constant offset from the VarDecl.12857std::optional<std::pair<12858CharUnits,12859CharUnits>> static getBaseAlignmentAndOffsetFromLValue(const Expr *E,12860ASTContext &Ctx) {12861E = E->IgnoreParens();12862switch (E->getStmtClass()) {12863default:12864break;12865case Stmt::CStyleCastExprClass:12866case Stmt::CXXStaticCastExprClass:12867case Stmt::ImplicitCastExprClass: {12868auto *CE = cast<CastExpr>(E);12869const Expr *From = CE->getSubExpr();12870switch (CE->getCastKind()) {12871default:12872break;12873case CK_NoOp:12874return getBaseAlignmentAndOffsetFromLValue(From, Ctx);12875case CK_UncheckedDerivedToBase:12876case CK_DerivedToBase: {12877auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);12878if (!P)12879break;12880return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,12881P->second, Ctx);12882}12883}12884break;12885}12886case Stmt::ArraySubscriptExprClass: {12887auto *ASE = cast<ArraySubscriptExpr>(E);12888return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),12889false, Ctx);12890}12891case Stmt::DeclRefExprClass: {12892if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {12893// FIXME: If VD is captured by copy or is an escaping __block variable,12894// use the alignment of VD's type.12895if (!VD->getType()->isReferenceType()) {12896// Dependent alignment cannot be resolved -> bail out.12897if (VD->hasDependentAlignment())12898break;12899return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());12900}12901if (VD->hasInit())12902return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);12903}12904break;12905}12906case Stmt::MemberExprClass: {12907auto *ME = cast<MemberExpr>(E);12908auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());12909if (!FD || FD->getType()->isReferenceType() ||12910FD->getParent()->isInvalidDecl())12911break;12912std::optional<std::pair<CharUnits, CharUnits>> P;12913if (ME->isArrow())12914P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);12915else12916P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);12917if (!P)12918break;12919const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());12920uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());12921return std::make_pair(P->first,12922P->second + CharUnits::fromQuantity(Offset));12923}12924case Stmt::UnaryOperatorClass: {12925auto *UO = cast<UnaryOperator>(E);12926switch (UO->getOpcode()) {12927default:12928break;12929case UO_Deref:12930return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);12931}12932break;12933}12934case Stmt::BinaryOperatorClass: {12935auto *BO = cast<BinaryOperator>(E);12936auto Opcode = BO->getOpcode();12937switch (Opcode) {12938default:12939break;12940case BO_Comma:12941return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);12942}12943break;12944}12945}12946return std::nullopt;12947}1294812949/// This helper function takes a pointer expression and returns the alignment of12950/// a VarDecl and a constant offset from the VarDecl.12951std::optional<std::pair<12952CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr12953*E,12954ASTContext12955&Ctx) {12956E = E->IgnoreParens();12957switch (E->getStmtClass()) {12958default:12959break;12960case Stmt::CStyleCastExprClass:12961case Stmt::CXXStaticCastExprClass:12962case Stmt::ImplicitCastExprClass: {12963auto *CE = cast<CastExpr>(E);12964const Expr *From = CE->getSubExpr();12965switch (CE->getCastKind()) {12966default:12967break;12968case CK_NoOp:12969return getBaseAlignmentAndOffsetFromPtr(From, Ctx);12970case CK_ArrayToPointerDecay:12971return getBaseAlignmentAndOffsetFromLValue(From, Ctx);12972case CK_UncheckedDerivedToBase:12973case CK_DerivedToBase: {12974auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);12975if (!P)12976break;12977return getDerivedToBaseAlignmentAndOffset(12978CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);12979}12980}12981break;12982}12983case Stmt::CXXThisExprClass: {12984auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();12985CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();12986return std::make_pair(Alignment, CharUnits::Zero());12987}12988case Stmt::UnaryOperatorClass: {12989auto *UO = cast<UnaryOperator>(E);12990if (UO->getOpcode() == UO_AddrOf)12991return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);12992break;12993}12994case Stmt::BinaryOperatorClass: {12995auto *BO = cast<BinaryOperator>(E);12996auto Opcode = BO->getOpcode();12997switch (Opcode) {12998default:12999break;13000case BO_Add:13001case BO_Sub: {13002const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();13003if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())13004std::swap(LHS, RHS);13005return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,13006Ctx);13007}13008case BO_Comma:13009return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);13010}13011break;13012}13013}13014return std::nullopt;13015}1301613017static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {13018// See if we can compute the alignment of a VarDecl and an offset from it.13019std::optional<std::pair<CharUnits, CharUnits>> P =13020getBaseAlignmentAndOffsetFromPtr(E, S.Context);1302113022if (P)13023return P->first.alignmentAtOffset(P->second);1302413025// If that failed, return the type's alignment.13026return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());13027}1302813029void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {13030// This is actually a lot of work to potentially be doing on every13031// cast; don't do it if we're ignoring -Wcast_align (as is the default).13032if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))13033return;1303413035// Ignore dependent types.13036if (T->isDependentType() || Op->getType()->isDependentType())13037return;1303813039// Require that the destination be a pointer type.13040const PointerType *DestPtr = T->getAs<PointerType>();13041if (!DestPtr) return;1304213043// If the destination has alignment 1, we're done.13044QualType DestPointee = DestPtr->getPointeeType();13045if (DestPointee->isIncompleteType()) return;13046CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);13047if (DestAlign.isOne()) return;1304813049// Require that the source be a pointer type.13050const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();13051if (!SrcPtr) return;13052QualType SrcPointee = SrcPtr->getPointeeType();1305313054// Explicitly allow casts from cv void*. We already implicitly13055// allowed casts to cv void*, since they have alignment 1.13056// Also allow casts involving incomplete types, which implicitly13057// includes 'void'.13058if (SrcPointee->isIncompleteType()) return;1305913060CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);1306113062if (SrcAlign >= DestAlign) return;1306313064Diag(TRange.getBegin(), diag::warn_cast_align)13065<< Op->getType() << T13066<< static_cast<unsigned>(SrcAlign.getQuantity())13067<< static_cast<unsigned>(DestAlign.getQuantity())13068<< TRange << Op->getSourceRange();13069}1307013071void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,13072const ArraySubscriptExpr *ASE,13073bool AllowOnePastEnd, bool IndexNegated) {13074// Already diagnosed by the constant evaluator.13075if (isConstantEvaluatedContext())13076return;1307713078IndexExpr = IndexExpr->IgnoreParenImpCasts();13079if (IndexExpr->isValueDependent())13080return;1308113082const Type *EffectiveType =13083BaseExpr->getType()->getPointeeOrArrayElementType();13084BaseExpr = BaseExpr->IgnoreParenCasts();13085const ConstantArrayType *ArrayTy =13086Context.getAsConstantArrayType(BaseExpr->getType());1308713088LangOptions::StrictFlexArraysLevelKind13089StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();1309013091const Type *BaseType =13092ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();13093bool IsUnboundedArray =13094BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(13095Context, StrictFlexArraysLevel,13096/*IgnoreTemplateOrMacroSubstitution=*/true);13097if (EffectiveType->isDependentType() ||13098(!IsUnboundedArray && BaseType->isDependentType()))13099return;1310013101Expr::EvalResult Result;13102if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))13103return;1310413105llvm::APSInt index = Result.Val.getInt();13106if (IndexNegated) {13107index.setIsUnsigned(false);13108index = -index;13109}1311013111if (IsUnboundedArray) {13112if (EffectiveType->isFunctionType())13113return;13114if (index.isUnsigned() || !index.isNegative()) {13115const auto &ASTC = getASTContext();13116unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(13117EffectiveType->getCanonicalTypeInternal().getAddressSpace());13118if (index.getBitWidth() < AddrBits)13119index = index.zext(AddrBits);13120std::optional<CharUnits> ElemCharUnits =13121ASTC.getTypeSizeInCharsIfKnown(EffectiveType);13122// PR50741 - If EffectiveType has unknown size (e.g., if it's a void13123// pointer) bounds-checking isn't meaningful.13124if (!ElemCharUnits || ElemCharUnits->isZero())13125return;13126llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());13127// If index has more active bits than address space, we already know13128// we have a bounds violation to warn about. Otherwise, compute13129// address of (index + 1)th element, and warn about bounds violation13130// only if that address exceeds address space.13131if (index.getActiveBits() <= AddrBits) {13132bool Overflow;13133llvm::APInt Product(index);13134Product += 1;13135Product = Product.umul_ov(ElemBytes, Overflow);13136if (!Overflow && Product.getActiveBits() <= AddrBits)13137return;13138}1313913140// Need to compute max possible elements in address space, since that13141// is included in diag message.13142llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);13143MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));13144MaxElems += 1;13145ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());13146MaxElems = MaxElems.udiv(ElemBytes);1314713148unsigned DiagID =13149ASE ? diag::warn_array_index_exceeds_max_addressable_bounds13150: diag::warn_ptr_arith_exceeds_max_addressable_bounds;1315113152// Diag message shows element size in bits and in "bytes" (platform-13153// dependent CharUnits)13154DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,13155PDiag(DiagID)13156<< toString(index, 10, true) << AddrBits13157<< (unsigned)ASTC.toBits(*ElemCharUnits)13158<< toString(ElemBytes, 10, false)13159<< toString(MaxElems, 10, false)13160<< (unsigned)MaxElems.getLimitedValue(~0U)13161<< IndexExpr->getSourceRange());1316213163const NamedDecl *ND = nullptr;13164// Try harder to find a NamedDecl to point at in the note.13165while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))13166BaseExpr = ASE->getBase()->IgnoreParenCasts();13167if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))13168ND = DRE->getDecl();13169if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))13170ND = ME->getMemberDecl();1317113172if (ND)13173DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,13174PDiag(diag::note_array_declared_here) << ND);13175}13176return;13177}1317813179if (index.isUnsigned() || !index.isNegative()) {13180// It is possible that the type of the base expression after13181// IgnoreParenCasts is incomplete, even though the type of the base13182// expression before IgnoreParenCasts is complete (see PR39746 for an13183// example). In this case we have no information about whether the array13184// access exceeds the array bounds. However we can still diagnose an array13185// access which precedes the array bounds.13186if (BaseType->isIncompleteType())13187return;1318813189llvm::APInt size = ArrayTy->getSize();1319013191if (BaseType != EffectiveType) {13192// Make sure we're comparing apples to apples when comparing index to13193// size.13194uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);13195uint64_t array_typesize = Context.getTypeSize(BaseType);1319613197// Handle ptrarith_typesize being zero, such as when casting to void*.13198// Use the size in bits (what "getTypeSize()" returns) rather than bytes.13199if (!ptrarith_typesize)13200ptrarith_typesize = Context.getCharWidth();1320113202if (ptrarith_typesize != array_typesize) {13203// There's a cast to a different size type involved.13204uint64_t ratio = array_typesize / ptrarith_typesize;1320513206// TODO: Be smarter about handling cases where array_typesize is not a13207// multiple of ptrarith_typesize.13208if (ptrarith_typesize * ratio == array_typesize)13209size *= llvm::APInt(size.getBitWidth(), ratio);13210}13211}1321213213if (size.getBitWidth() > index.getBitWidth())13214index = index.zext(size.getBitWidth());13215else if (size.getBitWidth() < index.getBitWidth())13216size = size.zext(index.getBitWidth());1321713218// For array subscripting the index must be less than size, but for pointer13219// arithmetic also allow the index (offset) to be equal to size since13220// computing the next address after the end of the array is legal and13221// commonly done e.g. in C++ iterators and range-based for loops.13222if (AllowOnePastEnd ? index.ule(size) : index.ult(size))13223return;1322413225// Suppress the warning if the subscript expression (as identified by the13226// ']' location) and the index expression are both from macro expansions13227// within a system header.13228if (ASE) {13229SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(13230ASE->getRBracketLoc());13231if (SourceMgr.isInSystemHeader(RBracketLoc)) {13232SourceLocation IndexLoc =13233SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());13234if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))13235return;13236}13237}1323813239unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds13240: diag::warn_ptr_arith_exceeds_bounds;13241unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;13242QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();1324313244DiagRuntimeBehavior(13245BaseExpr->getBeginLoc(), BaseExpr,13246PDiag(DiagID) << toString(index, 10, true) << ArrayTy->desugar()13247<< CastMsg << CastMsgTy << IndexExpr->getSourceRange());13248} else {13249unsigned DiagID = diag::warn_array_index_precedes_bounds;13250if (!ASE) {13251DiagID = diag::warn_ptr_arith_precedes_bounds;13252if (index.isNegative()) index = -index;13253}1325413255DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,13256PDiag(DiagID) << toString(index, 10, true)13257<< IndexExpr->getSourceRange());13258}1325913260const NamedDecl *ND = nullptr;13261// Try harder to find a NamedDecl to point at in the note.13262while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))13263BaseExpr = ASE->getBase()->IgnoreParenCasts();13264if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))13265ND = DRE->getDecl();13266if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))13267ND = ME->getMemberDecl();1326813269if (ND)13270DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,13271PDiag(diag::note_array_declared_here) << ND);13272}1327313274void Sema::CheckArrayAccess(const Expr *expr) {13275int AllowOnePastEnd = 0;13276while (expr) {13277expr = expr->IgnoreParenImpCasts();13278switch (expr->getStmtClass()) {13279case Stmt::ArraySubscriptExprClass: {13280const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);13281CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,13282AllowOnePastEnd > 0);13283expr = ASE->getBase();13284break;13285}13286case Stmt::MemberExprClass: {13287expr = cast<MemberExpr>(expr)->getBase();13288break;13289}13290case Stmt::ArraySectionExprClass: {13291const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);13292// FIXME: We should probably be checking all of the elements to the13293// 'length' here as well.13294if (ASE->getLowerBound())13295CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),13296/*ASE=*/nullptr, AllowOnePastEnd > 0);13297return;13298}13299case Stmt::UnaryOperatorClass: {13300// Only unwrap the * and & unary operators13301const UnaryOperator *UO = cast<UnaryOperator>(expr);13302expr = UO->getSubExpr();13303switch (UO->getOpcode()) {13304case UO_AddrOf:13305AllowOnePastEnd++;13306break;13307case UO_Deref:13308AllowOnePastEnd--;13309break;13310default:13311return;13312}13313break;13314}13315case Stmt::ConditionalOperatorClass: {13316const ConditionalOperator *cond = cast<ConditionalOperator>(expr);13317if (const Expr *lhs = cond->getLHS())13318CheckArrayAccess(lhs);13319if (const Expr *rhs = cond->getRHS())13320CheckArrayAccess(rhs);13321return;13322}13323case Stmt::CXXOperatorCallExprClass: {13324const auto *OCE = cast<CXXOperatorCallExpr>(expr);13325for (const auto *Arg : OCE->arguments())13326CheckArrayAccess(Arg);13327return;13328}13329default:13330return;13331}13332}13333}1333413335static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,13336Expr *RHS, bool isProperty) {13337// Check if RHS is an Objective-C object literal, which also can get13338// immediately zapped in a weak reference. Note that we explicitly13339// allow ObjCStringLiterals, since those are designed to never really die.13340RHS = RHS->IgnoreParenImpCasts();1334113342// This enum needs to match with the 'select' in13343// warn_objc_arc_literal_assign (off-by-1).13344SemaObjC::ObjCLiteralKind Kind = S.ObjC().CheckLiteralKind(RHS);13345if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)13346return false;1334713348S.Diag(Loc, diag::warn_arc_literal_assign)13349<< (unsigned) Kind13350<< (isProperty ? 0 : 1)13351<< RHS->getSourceRange();1335213353return true;13354}1335513356static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,13357Qualifiers::ObjCLifetime LT,13358Expr *RHS, bool isProperty) {13359// Strip off any implicit cast added to get to the one ARC-specific.13360while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {13361if (cast->getCastKind() == CK_ARCConsumeObject) {13362S.Diag(Loc, diag::warn_arc_retained_assign)13363<< (LT == Qualifiers::OCL_ExplicitNone)13364<< (isProperty ? 0 : 1)13365<< RHS->getSourceRange();13366return true;13367}13368RHS = cast->getSubExpr();13369}1337013371if (LT == Qualifiers::OCL_Weak &&13372checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))13373return true;1337413375return false;13376}1337713378bool Sema::checkUnsafeAssigns(SourceLocation Loc,13379QualType LHS, Expr *RHS) {13380Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();1338113382if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)13383return false;1338413385if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))13386return true;1338713388return false;13389}1339013391void Sema::checkUnsafeExprAssigns(SourceLocation Loc,13392Expr *LHS, Expr *RHS) {13393QualType LHSType;13394// PropertyRef on LHS type need be directly obtained from13395// its declaration as it has a PseudoType.13396ObjCPropertyRefExpr *PRE13397= dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());13398if (PRE && !PRE->isImplicitProperty()) {13399const ObjCPropertyDecl *PD = PRE->getExplicitProperty();13400if (PD)13401LHSType = PD->getType();13402}1340313404if (LHSType.isNull())13405LHSType = LHS->getType();1340613407Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();1340813409if (LT == Qualifiers::OCL_Weak) {13410if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))13411getCurFunction()->markSafeWeakUse(LHS);13412}1341313414if (checkUnsafeAssigns(Loc, LHSType, RHS))13415return;1341613417// FIXME. Check for other life times.13418if (LT != Qualifiers::OCL_None)13419return;1342013421if (PRE) {13422if (PRE->isImplicitProperty())13423return;13424const ObjCPropertyDecl *PD = PRE->getExplicitProperty();13425if (!PD)13426return;1342713428unsigned Attributes = PD->getPropertyAttributes();13429if (Attributes & ObjCPropertyAttribute::kind_assign) {13430// when 'assign' attribute was not explicitly specified13431// by user, ignore it and rely on property type itself13432// for lifetime info.13433unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();13434if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&13435LHSType->isObjCRetainableType())13436return;1343713438while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {13439if (cast->getCastKind() == CK_ARCConsumeObject) {13440Diag(Loc, diag::warn_arc_retained_property_assign)13441<< RHS->getSourceRange();13442return;13443}13444RHS = cast->getSubExpr();13445}13446} else if (Attributes & ObjCPropertyAttribute::kind_weak) {13447if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))13448return;13449}13450}13451}1345213453//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//1345413455static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,13456SourceLocation StmtLoc,13457const NullStmt *Body) {13458// Do not warn if the body is a macro that expands to nothing, e.g:13459//13460// #define CALL(x)13461// if (condition)13462// CALL(0);13463if (Body->hasLeadingEmptyMacro())13464return false;1346513466// Get line numbers of statement and body.13467bool StmtLineInvalid;13468unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,13469&StmtLineInvalid);13470if (StmtLineInvalid)13471return false;1347213473bool BodyLineInvalid;13474unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),13475&BodyLineInvalid);13476if (BodyLineInvalid)13477return false;1347813479// Warn if null statement and body are on the same line.13480if (StmtLine != BodyLine)13481return false;1348213483return true;13484}1348513486void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,13487const Stmt *Body,13488unsigned DiagID) {13489// Since this is a syntactic check, don't emit diagnostic for template13490// instantiations, this just adds noise.13491if (CurrentInstantiationScope)13492return;1349313494// The body should be a null statement.13495const NullStmt *NBody = dyn_cast<NullStmt>(Body);13496if (!NBody)13497return;1349813499// Do the usual checks.13500if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))13501return;1350213503Diag(NBody->getSemiLoc(), DiagID);13504Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);13505}1350613507void Sema::DiagnoseEmptyLoopBody(const Stmt *S,13508const Stmt *PossibleBody) {13509assert(!CurrentInstantiationScope); // Ensured by caller1351013511SourceLocation StmtLoc;13512const Stmt *Body;13513unsigned DiagID;13514if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {13515StmtLoc = FS->getRParenLoc();13516Body = FS->getBody();13517DiagID = diag::warn_empty_for_body;13518} else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {13519StmtLoc = WS->getRParenLoc();13520Body = WS->getBody();13521DiagID = diag::warn_empty_while_body;13522} else13523return; // Neither `for' nor `while'.1352413525// The body should be a null statement.13526const NullStmt *NBody = dyn_cast<NullStmt>(Body);13527if (!NBody)13528return;1352913530// Skip expensive checks if diagnostic is disabled.13531if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))13532return;1353313534// Do the usual checks.13535if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))13536return;1353713538// `for(...);' and `while(...);' are popular idioms, so in order to keep13539// noise level low, emit diagnostics only if for/while is followed by a13540// CompoundStmt, e.g.:13541// for (int i = 0; i < n; i++);13542// {13543// a(i);13544// }13545// or if for/while is followed by a statement with more indentation13546// than for/while itself:13547// for (int i = 0; i < n; i++);13548// a(i);13549bool ProbableTypo = isa<CompoundStmt>(PossibleBody);13550if (!ProbableTypo) {13551bool BodyColInvalid;13552unsigned BodyCol = SourceMgr.getPresumedColumnNumber(13553PossibleBody->getBeginLoc(), &BodyColInvalid);13554if (BodyColInvalid)13555return;1355613557bool StmtColInvalid;13558unsigned StmtCol =13559SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);13560if (StmtColInvalid)13561return;1356213563if (BodyCol > StmtCol)13564ProbableTypo = true;13565}1356613567if (ProbableTypo) {13568Diag(NBody->getSemiLoc(), DiagID);13569Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);13570}13571}1357213573//===--- CHECK: Warn on self move with std::move. -------------------------===//1357413575void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,13576SourceLocation OpLoc) {13577if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))13578return;1357913580if (inTemplateInstantiation())13581return;1358213583// Strip parens and casts away.13584LHSExpr = LHSExpr->IgnoreParenImpCasts();13585RHSExpr = RHSExpr->IgnoreParenImpCasts();1358613587// Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue13588// which we can treat as an inlined std::move13589if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);13590CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())13591RHSExpr = CE->getArg(0);13592else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);13593CXXSCE && CXXSCE->isXValue())13594RHSExpr = CXXSCE->getSubExpr();13595else13596return;1359713598const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);13599const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);1360013601// Two DeclRefExpr's, check that the decls are the same.13602if (LHSDeclRef && RHSDeclRef) {13603if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())13604return;13605if (LHSDeclRef->getDecl()->getCanonicalDecl() !=13606RHSDeclRef->getDecl()->getCanonicalDecl())13607return;1360813609auto D = Diag(OpLoc, diag::warn_self_move)13610<< LHSExpr->getType() << LHSExpr->getSourceRange()13611<< RHSExpr->getSourceRange();13612if (const FieldDecl *F =13613getSelfAssignmentClassMemberCandidate(RHSDeclRef->getDecl()))13614D << 1 << F13615<< FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");13616else13617D << 0;13618return;13619}1362013621// Member variables require a different approach to check for self moves.13622// MemberExpr's are the same if every nested MemberExpr refers to the same13623// Decl and that the base Expr's are DeclRefExpr's with the same Decl or13624// the base Expr's are CXXThisExpr's.13625const Expr *LHSBase = LHSExpr;13626const Expr *RHSBase = RHSExpr;13627const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);13628const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);13629if (!LHSME || !RHSME)13630return;1363113632while (LHSME && RHSME) {13633if (LHSME->getMemberDecl()->getCanonicalDecl() !=13634RHSME->getMemberDecl()->getCanonicalDecl())13635return;1363613637LHSBase = LHSME->getBase();13638RHSBase = RHSME->getBase();13639LHSME = dyn_cast<MemberExpr>(LHSBase);13640RHSME = dyn_cast<MemberExpr>(RHSBase);13641}1364213643LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);13644RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);13645if (LHSDeclRef && RHSDeclRef) {13646if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())13647return;13648if (LHSDeclRef->getDecl()->getCanonicalDecl() !=13649RHSDeclRef->getDecl()->getCanonicalDecl())13650return;1365113652Diag(OpLoc, diag::warn_self_move)13653<< LHSExpr->getType() << 0 << LHSExpr->getSourceRange()13654<< RHSExpr->getSourceRange();13655return;13656}1365713658if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))13659Diag(OpLoc, diag::warn_self_move)13660<< LHSExpr->getType() << 0 << LHSExpr->getSourceRange()13661<< RHSExpr->getSourceRange();13662}1366313664//===--- Layout compatibility ----------------------------------------------//1366513666static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);1366713668/// Check if two enumeration types are layout-compatible.13669static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,13670const EnumDecl *ED2) {13671// C++11 [dcl.enum] p8:13672// Two enumeration types are layout-compatible if they have the same13673// underlying type.13674return ED1->isComplete() && ED2->isComplete() &&13675C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());13676}1367713678/// Check if two fields are layout-compatible.13679/// Can be used on union members, which are exempt from alignment requirement13680/// of common initial sequence.13681static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,13682const FieldDecl *Field2,13683bool AreUnionMembers = false) {13684[[maybe_unused]] const Type *Field1Parent =13685Field1->getParent()->getTypeForDecl();13686[[maybe_unused]] const Type *Field2Parent =13687Field2->getParent()->getTypeForDecl();13688assert(((Field1Parent->isStructureOrClassType() &&13689Field2Parent->isStructureOrClassType()) ||13690(Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&13691"Can't evaluate layout compatibility between a struct field and a "13692"union field.");13693assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||13694(AreUnionMembers && Field1Parent->isUnionType())) &&13695"AreUnionMembers should be 'true' for union fields (only).");1369613697if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))13698return false;1369913700if (Field1->isBitField() != Field2->isBitField())13701return false;1370213703if (Field1->isBitField()) {13704// Make sure that the bit-fields are the same length.13705unsigned Bits1 = Field1->getBitWidthValue(C);13706unsigned Bits2 = Field2->getBitWidthValue(C);1370713708if (Bits1 != Bits2)13709return false;13710}1371113712if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||13713Field2->hasAttr<clang::NoUniqueAddressAttr>())13714return false;1371513716if (!AreUnionMembers &&13717Field1->getMaxAlignment() != Field2->getMaxAlignment())13718return false;1371913720return true;13721}1372213723/// Check if two standard-layout structs are layout-compatible.13724/// (C++11 [class.mem] p17)13725static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,13726const RecordDecl *RD2) {13727// Get to the class where the fields are declared13728if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))13729RD1 = D1CXX->getStandardLayoutBaseWithFields();1373013731if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))13732RD2 = D2CXX->getStandardLayoutBaseWithFields();1373313734// Check the fields.13735return llvm::equal(RD1->fields(), RD2->fields(),13736[&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {13737return isLayoutCompatible(C, F1, F2);13738});13739}1374013741/// Check if two standard-layout unions are layout-compatible.13742/// (C++11 [class.mem] p18)13743static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,13744const RecordDecl *RD2) {13745llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields;13746for (auto *Field2 : RD2->fields())13747UnmatchedFields.insert(Field2);1374813749for (auto *Field1 : RD1->fields()) {13750auto I = UnmatchedFields.begin();13751auto E = UnmatchedFields.end();1375213753for ( ; I != E; ++I) {13754if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {13755bool Result = UnmatchedFields.erase(*I);13756(void) Result;13757assert(Result);13758break;13759}13760}13761if (I == E)13762return false;13763}1376413765return UnmatchedFields.empty();13766}1376713768static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,13769const RecordDecl *RD2) {13770if (RD1->isUnion() != RD2->isUnion())13771return false;1377213773if (RD1->isUnion())13774return isLayoutCompatibleUnion(C, RD1, RD2);13775else13776return isLayoutCompatibleStruct(C, RD1, RD2);13777}1377813779/// Check if two types are layout-compatible in C++11 sense.13780static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {13781if (T1.isNull() || T2.isNull())13782return false;1378313784// C++20 [basic.types] p11:13785// Two types cv1 T1 and cv2 T2 are layout-compatible types13786// if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),13787// or layout-compatible standard-layout class types (11.4).13788T1 = T1.getCanonicalType().getUnqualifiedType();13789T2 = T2.getCanonicalType().getUnqualifiedType();1379013791if (C.hasSameType(T1, T2))13792return true;1379313794const Type::TypeClass TC1 = T1->getTypeClass();13795const Type::TypeClass TC2 = T2->getTypeClass();1379613797if (TC1 != TC2)13798return false;1379913800if (TC1 == Type::Enum) {13801return isLayoutCompatible(C,13802cast<EnumType>(T1)->getDecl(),13803cast<EnumType>(T2)->getDecl());13804} else if (TC1 == Type::Record) {13805if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())13806return false;1380713808return isLayoutCompatible(C,13809cast<RecordType>(T1)->getDecl(),13810cast<RecordType>(T2)->getDecl());13811}1381213813return false;13814}1381513816bool Sema::IsLayoutCompatible(QualType T1, QualType T2) const {13817return isLayoutCompatible(getASTContext(), T1, T2);13818}1381913820//===-------------- Pointer interconvertibility ----------------------------//1382113822bool Sema::IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,13823const TypeSourceInfo *Derived) {13824QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();13825QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();1382613827if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&13828getASTContext().hasSameType(BaseT, DerivedT))13829return true;1383013831if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))13832return false;1383313834// Per [basic.compound]/4.3, containing object has to be standard-layout.13835if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())13836return true;1383713838return false;13839}1384013841//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//1384213843/// Given a type tag expression find the type tag itself.13844///13845/// \param TypeExpr Type tag expression, as it appears in user's code.13846///13847/// \param VD Declaration of an identifier that appears in a type tag.13848///13849/// \param MagicValue Type tag magic value.13850///13851/// \param isConstantEvaluated whether the evalaution should be performed in1385213853/// constant context.13854static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,13855const ValueDecl **VD, uint64_t *MagicValue,13856bool isConstantEvaluated) {13857while(true) {13858if (!TypeExpr)13859return false;1386013861TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();1386213863switch (TypeExpr->getStmtClass()) {13864case Stmt::UnaryOperatorClass: {13865const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);13866if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {13867TypeExpr = UO->getSubExpr();13868continue;13869}13870return false;13871}1387213873case Stmt::DeclRefExprClass: {13874const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);13875*VD = DRE->getDecl();13876return true;13877}1387813879case Stmt::IntegerLiteralClass: {13880const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);13881llvm::APInt MagicValueAPInt = IL->getValue();13882if (MagicValueAPInt.getActiveBits() <= 64) {13883*MagicValue = MagicValueAPInt.getZExtValue();13884return true;13885} else13886return false;13887}1388813889case Stmt::BinaryConditionalOperatorClass:13890case Stmt::ConditionalOperatorClass: {13891const AbstractConditionalOperator *ACO =13892cast<AbstractConditionalOperator>(TypeExpr);13893bool Result;13894if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,13895isConstantEvaluated)) {13896if (Result)13897TypeExpr = ACO->getTrueExpr();13898else13899TypeExpr = ACO->getFalseExpr();13900continue;13901}13902return false;13903}1390413905case Stmt::BinaryOperatorClass: {13906const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);13907if (BO->getOpcode() == BO_Comma) {13908TypeExpr = BO->getRHS();13909continue;13910}13911return false;13912}1391313914default:13915return false;13916}13917}13918}1391913920/// Retrieve the C type corresponding to type tag TypeExpr.13921///13922/// \param TypeExpr Expression that specifies a type tag.13923///13924/// \param MagicValues Registered magic values.13925///13926/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong13927/// kind.13928///13929/// \param TypeInfo Information about the corresponding C type.13930///13931/// \param isConstantEvaluated whether the evalaution should be performed in13932/// constant context.13933///13934/// \returns true if the corresponding C type was found.13935static bool GetMatchingCType(13936const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,13937const ASTContext &Ctx,13938const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>13939*MagicValues,13940bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,13941bool isConstantEvaluated) {13942FoundWrongKind = false;1394313944// Variable declaration that has type_tag_for_datatype attribute.13945const ValueDecl *VD = nullptr;1394613947uint64_t MagicValue;1394813949if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))13950return false;1395113952if (VD) {13953if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {13954if (I->getArgumentKind() != ArgumentKind) {13955FoundWrongKind = true;13956return false;13957}13958TypeInfo.Type = I->getMatchingCType();13959TypeInfo.LayoutCompatible = I->getLayoutCompatible();13960TypeInfo.MustBeNull = I->getMustBeNull();13961return true;13962}13963return false;13964}1396513966if (!MagicValues)13967return false;1396813969llvm::DenseMap<Sema::TypeTagMagicValue,13970Sema::TypeTagData>::const_iterator I =13971MagicValues->find(std::make_pair(ArgumentKind, MagicValue));13972if (I == MagicValues->end())13973return false;1397413975TypeInfo = I->second;13976return true;13977}1397813979void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,13980uint64_t MagicValue, QualType Type,13981bool LayoutCompatible,13982bool MustBeNull) {13983if (!TypeTagForDatatypeMagicValues)13984TypeTagForDatatypeMagicValues.reset(13985new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);1398613987TypeTagMagicValue Magic(ArgumentKind, MagicValue);13988(*TypeTagForDatatypeMagicValues)[Magic] =13989TypeTagData(Type, LayoutCompatible, MustBeNull);13990}1399113992static bool IsSameCharType(QualType T1, QualType T2) {13993const BuiltinType *BT1 = T1->getAs<BuiltinType>();13994if (!BT1)13995return false;1399613997const BuiltinType *BT2 = T2->getAs<BuiltinType>();13998if (!BT2)13999return false;1400014001BuiltinType::Kind T1Kind = BT1->getKind();14002BuiltinType::Kind T2Kind = BT2->getKind();1400314004return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||14005(T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||14006(T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||14007(T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);14008}1400914010void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,14011const ArrayRef<const Expr *> ExprArgs,14012SourceLocation CallSiteLoc) {14013const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();14014bool IsPointerAttr = Attr->getIsPointer();1401514016// Retrieve the argument representing the 'type_tag'.14017unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();14018if (TypeTagIdxAST >= ExprArgs.size()) {14019Diag(CallSiteLoc, diag::err_tag_index_out_of_range)14020<< 0 << Attr->getTypeTagIdx().getSourceIndex();14021return;14022}14023const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];14024bool FoundWrongKind;14025TypeTagData TypeInfo;14026if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,14027TypeTagForDatatypeMagicValues.get(), FoundWrongKind,14028TypeInfo, isConstantEvaluatedContext())) {14029if (FoundWrongKind)14030Diag(TypeTagExpr->getExprLoc(),14031diag::warn_type_tag_for_datatype_wrong_kind)14032<< TypeTagExpr->getSourceRange();14033return;14034}1403514036// Retrieve the argument representing the 'arg_idx'.14037unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();14038if (ArgumentIdxAST >= ExprArgs.size()) {14039Diag(CallSiteLoc, diag::err_tag_index_out_of_range)14040<< 1 << Attr->getArgumentIdx().getSourceIndex();14041return;14042}14043const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];14044if (IsPointerAttr) {14045// Skip implicit cast of pointer to `void *' (as a function argument).14046if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))14047if (ICE->getType()->isVoidPointerType() &&14048ICE->getCastKind() == CK_BitCast)14049ArgumentExpr = ICE->getSubExpr();14050}14051QualType ArgumentType = ArgumentExpr->getType();1405214053// Passing a `void*' pointer shouldn't trigger a warning.14054if (IsPointerAttr && ArgumentType->isVoidPointerType())14055return;1405614057if (TypeInfo.MustBeNull) {14058// Type tag with matching void type requires a null pointer.14059if (!ArgumentExpr->isNullPointerConstant(Context,14060Expr::NPC_ValueDependentIsNotNull)) {14061Diag(ArgumentExpr->getExprLoc(),14062diag::warn_type_safety_null_pointer_required)14063<< ArgumentKind->getName()14064<< ArgumentExpr->getSourceRange()14065<< TypeTagExpr->getSourceRange();14066}14067return;14068}1406914070QualType RequiredType = TypeInfo.Type;14071if (IsPointerAttr)14072RequiredType = Context.getPointerType(RequiredType);1407314074bool mismatch = false;14075if (!TypeInfo.LayoutCompatible) {14076mismatch = !Context.hasSameType(ArgumentType, RequiredType);1407714078// C++11 [basic.fundamental] p1:14079// Plain char, signed char, and unsigned char are three distinct types.14080//14081// But we treat plain `char' as equivalent to `signed char' or `unsigned14082// char' depending on the current char signedness mode.14083if (mismatch)14084if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),14085RequiredType->getPointeeType())) ||14086(!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))14087mismatch = false;14088} else14089if (IsPointerAttr)14090mismatch = !isLayoutCompatible(Context,14091ArgumentType->getPointeeType(),14092RequiredType->getPointeeType());14093else14094mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);1409514096if (mismatch)14097Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)14098<< ArgumentType << ArgumentKind14099<< TypeInfo.LayoutCompatible << RequiredType14100<< ArgumentExpr->getSourceRange()14101<< TypeTagExpr->getSourceRange();14102}1410314104void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,14105CharUnits Alignment) {14106MisalignedMembers.emplace_back(E, RD, MD, Alignment);14107}1410814109void Sema::DiagnoseMisalignedMembers() {14110for (MisalignedMember &m : MisalignedMembers) {14111const NamedDecl *ND = m.RD;14112if (ND->getName().empty()) {14113if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())14114ND = TD;14115}14116Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)14117<< m.MD << ND << m.E->getSourceRange();14118}14119MisalignedMembers.clear();14120}1412114122void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {14123E = E->IgnoreParens();14124if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())14125return;14126if (isa<UnaryOperator>(E) &&14127cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {14128auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();14129if (isa<MemberExpr>(Op)) {14130auto *MA = llvm::find(MisalignedMembers, MisalignedMember(Op));14131if (MA != MisalignedMembers.end() &&14132(T->isDependentType() || T->isIntegerType() ||14133(T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||14134Context.getTypeAlignInChars(14135T->getPointeeType()) <= MA->Alignment))))14136MisalignedMembers.erase(MA);14137}14138}14139}1414014141void Sema::RefersToMemberWithReducedAlignment(14142Expr *E,14143llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>14144Action) {14145const auto *ME = dyn_cast<MemberExpr>(E);14146if (!ME)14147return;1414814149// No need to check expressions with an __unaligned-qualified type.14150if (E->getType().getQualifiers().hasUnaligned())14151return;1415214153// For a chain of MemberExpr like "a.b.c.d" this list14154// will keep FieldDecl's like [d, c, b].14155SmallVector<FieldDecl *, 4> ReverseMemberChain;14156const MemberExpr *TopME = nullptr;14157bool AnyIsPacked = false;14158do {14159QualType BaseType = ME->getBase()->getType();14160if (BaseType->isDependentType())14161return;14162if (ME->isArrow())14163BaseType = BaseType->getPointeeType();14164RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();14165if (RD->isInvalidDecl())14166return;1416714168ValueDecl *MD = ME->getMemberDecl();14169auto *FD = dyn_cast<FieldDecl>(MD);14170// We do not care about non-data members.14171if (!FD || FD->isInvalidDecl())14172return;1417314174AnyIsPacked =14175AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());14176ReverseMemberChain.push_back(FD);1417714178TopME = ME;14179ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());14180} while (ME);14181assert(TopME && "We did not compute a topmost MemberExpr!");1418214183// Not the scope of this diagnostic.14184if (!AnyIsPacked)14185return;1418614187const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();14188const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);14189// TODO: The innermost base of the member expression may be too complicated.14190// For now, just disregard these cases. This is left for future14191// improvement.14192if (!DRE && !isa<CXXThisExpr>(TopBase))14193return;1419414195// Alignment expected by the whole expression.14196CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());1419714198// No need to do anything else with this case.14199if (ExpectedAlignment.isOne())14200return;1420114202// Synthesize offset of the whole access.14203CharUnits Offset;14204for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))14205Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));1420614207// Compute the CompleteObjectAlignment as the alignment of the whole chain.14208CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(14209ReverseMemberChain.back()->getParent()->getTypeForDecl());1421014211// The base expression of the innermost MemberExpr may give14212// stronger guarantees than the class containing the member.14213if (DRE && !TopME->isArrow()) {14214const ValueDecl *VD = DRE->getDecl();14215if (!VD->getType()->isReferenceType())14216CompleteObjectAlignment =14217std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));14218}1421914220// Check if the synthesized offset fulfills the alignment.14221if (Offset % ExpectedAlignment != 0 ||14222// It may fulfill the offset it but the effective alignment may still be14223// lower than the expected expression alignment.14224CompleteObjectAlignment < ExpectedAlignment) {14225// If this happens, we want to determine a sensible culprit of this.14226// Intuitively, watching the chain of member expressions from right to14227// left, we start with the required alignment (as required by the field14228// type) but some packed attribute in that chain has reduced the alignment.14229// It may happen that another packed structure increases it again. But if14230// we are here such increase has not been enough. So pointing the first14231// FieldDecl that either is packed or else its RecordDecl is,14232// seems reasonable.14233FieldDecl *FD = nullptr;14234CharUnits Alignment;14235for (FieldDecl *FDI : ReverseMemberChain) {14236if (FDI->hasAttr<PackedAttr>() ||14237FDI->getParent()->hasAttr<PackedAttr>()) {14238FD = FDI;14239Alignment = std::min(14240Context.getTypeAlignInChars(FD->getType()),14241Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));14242break;14243}14244}14245assert(FD && "We did not find a packed FieldDecl!");14246Action(E, FD->getParent(), FD, Alignment);14247}14248}1424914250void Sema::CheckAddressOfPackedMember(Expr *rhs) {14251using namespace std::placeholders;1425214253RefersToMemberWithReducedAlignment(14254rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,14255_2, _3, _4));14256}1425714258bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {14259if (checkArgCount(TheCall, 1))14260return true;1426114262ExprResult A = UsualUnaryConversions(TheCall->getArg(0));14263if (A.isInvalid())14264return true;1426514266TheCall->setArg(0, A.get());14267QualType TyA = A.get()->getType();1426814269if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))14270return true;1427114272TheCall->setType(TyA);14273return false;14274}1427514276bool Sema::BuiltinElementwiseMath(CallExpr *TheCall) {14277QualType Res;14278if (BuiltinVectorMath(TheCall, Res))14279return true;14280TheCall->setType(Res);14281return false;14282}1428314284bool Sema::BuiltinVectorToScalarMath(CallExpr *TheCall) {14285QualType Res;14286if (BuiltinVectorMath(TheCall, Res))14287return true;1428814289if (auto *VecTy0 = Res->getAs<VectorType>())14290TheCall->setType(VecTy0->getElementType());14291else14292TheCall->setType(Res);1429314294return false;14295}1429614297bool Sema::BuiltinVectorMath(CallExpr *TheCall, QualType &Res) {14298if (checkArgCount(TheCall, 2))14299return true;1430014301ExprResult A = TheCall->getArg(0);14302ExprResult B = TheCall->getArg(1);14303// Do standard promotions between the two arguments, returning their common14304// type.14305Res = UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);14306if (A.isInvalid() || B.isInvalid())14307return true;1430814309QualType TyA = A.get()->getType();14310QualType TyB = B.get()->getType();1431114312if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())14313return Diag(A.get()->getBeginLoc(),14314diag::err_typecheck_call_different_arg_types)14315<< TyA << TyB;1431614317if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))14318return true;1431914320TheCall->setArg(0, A.get());14321TheCall->setArg(1, B.get());14322return false;14323}1432414325bool Sema::BuiltinElementwiseTernaryMath(CallExpr *TheCall,14326bool CheckForFloatArgs) {14327if (checkArgCount(TheCall, 3))14328return true;1432914330Expr *Args[3];14331for (int I = 0; I < 3; ++I) {14332ExprResult Converted = UsualUnaryConversions(TheCall->getArg(I));14333if (Converted.isInvalid())14334return true;14335Args[I] = Converted.get();14336}1433714338if (CheckForFloatArgs) {14339int ArgOrdinal = 1;14340for (Expr *Arg : Args) {14341if (checkFPMathBuiltinElementType(*this, Arg->getBeginLoc(),14342Arg->getType(), ArgOrdinal++))14343return true;14344}14345} else {14346int ArgOrdinal = 1;14347for (Expr *Arg : Args) {14348if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),14349ArgOrdinal++))14350return true;14351}14352}1435314354for (int I = 1; I < 3; ++I) {14355if (Args[0]->getType().getCanonicalType() !=14356Args[I]->getType().getCanonicalType()) {14357return Diag(Args[0]->getBeginLoc(),14358diag::err_typecheck_call_different_arg_types)14359<< Args[0]->getType() << Args[I]->getType();14360}1436114362TheCall->setArg(I, Args[I]);14363}1436414365TheCall->setType(Args[0]->getType());14366return false;14367}1436814369bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {14370if (checkArgCount(TheCall, 1))14371return true;1437214373ExprResult A = UsualUnaryConversions(TheCall->getArg(0));14374if (A.isInvalid())14375return true;1437614377TheCall->setArg(0, A.get());14378return false;14379}1438014381bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {14382if (checkArgCount(TheCall, 1))14383return true;1438414385ExprResult Arg = TheCall->getArg(0);14386QualType TyArg = Arg.get()->getType();1438714388if (!TyArg->isBuiltinType() && !TyArg->isVectorType())14389return Diag(TheCall->getArg(0)->getBeginLoc(), diag::err_builtin_invalid_arg_type)14390<< 1 << /*vector, integer or floating point ty*/ 0 << TyArg;1439114392TheCall->setType(TyArg);14393return false;14394}1439514396ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,14397ExprResult CallResult) {14398if (checkArgCount(TheCall, 1))14399return ExprError();1440014401ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));14402if (MatrixArg.isInvalid())14403return MatrixArg;14404Expr *Matrix = MatrixArg.get();1440514406auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();14407if (!MType) {14408Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)14409<< 1 << /* matrix ty*/ 1 << Matrix->getType();14410return ExprError();14411}1441214413// Create returned matrix type by swapping rows and columns of the argument14414// matrix type.14415QualType ResultType = Context.getConstantMatrixType(14416MType->getElementType(), MType->getNumColumns(), MType->getNumRows());1441714418// Change the return type to the type of the returned matrix.14419TheCall->setType(ResultType);1442014421// Update call argument to use the possibly converted matrix argument.14422TheCall->setArg(0, Matrix);14423return CallResult;14424}1442514426// Get and verify the matrix dimensions.14427static std::optional<unsigned>14428getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {14429SourceLocation ErrorPos;14430std::optional<llvm::APSInt> Value =14431Expr->getIntegerConstantExpr(S.Context, &ErrorPos);14432if (!Value) {14433S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)14434<< Name;14435return {};14436}14437uint64_t Dim = Value->getZExtValue();14438if (!ConstantMatrixType::isDimensionValid(Dim)) {14439S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)14440<< Name << ConstantMatrixType::getMaxElementsPerDimension();14441return {};14442}14443return Dim;14444}1444514446ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,14447ExprResult CallResult) {14448if (!getLangOpts().MatrixTypes) {14449Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);14450return ExprError();14451}1445214453if (checkArgCount(TheCall, 4))14454return ExprError();1445514456unsigned PtrArgIdx = 0;14457Expr *PtrExpr = TheCall->getArg(PtrArgIdx);14458Expr *RowsExpr = TheCall->getArg(1);14459Expr *ColumnsExpr = TheCall->getArg(2);14460Expr *StrideExpr = TheCall->getArg(3);1446114462bool ArgError = false;1446314464// Check pointer argument.14465{14466ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);14467if (PtrConv.isInvalid())14468return PtrConv;14469PtrExpr = PtrConv.get();14470TheCall->setArg(0, PtrExpr);14471if (PtrExpr->isTypeDependent()) {14472TheCall->setType(Context.DependentTy);14473return TheCall;14474}14475}1447614477auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();14478QualType ElementTy;14479if (!PtrTy) {14480Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)14481<< PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();14482ArgError = true;14483} else {14484ElementTy = PtrTy->getPointeeType().getUnqualifiedType();1448514486if (!ConstantMatrixType::isValidElementType(ElementTy)) {14487Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)14488<< PtrArgIdx + 1 << /* pointer to element ty*/ 214489<< PtrExpr->getType();14490ArgError = true;14491}14492}1449314494// Apply default Lvalue conversions and convert the expression to size_t.14495auto ApplyArgumentConversions = [this](Expr *E) {14496ExprResult Conv = DefaultLvalueConversion(E);14497if (Conv.isInvalid())14498return Conv;1449914500return tryConvertExprToType(Conv.get(), Context.getSizeType());14501};1450214503// Apply conversion to row and column expressions.14504ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);14505if (!RowsConv.isInvalid()) {14506RowsExpr = RowsConv.get();14507TheCall->setArg(1, RowsExpr);14508} else14509RowsExpr = nullptr;1451014511ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);14512if (!ColumnsConv.isInvalid()) {14513ColumnsExpr = ColumnsConv.get();14514TheCall->setArg(2, ColumnsExpr);14515} else14516ColumnsExpr = nullptr;1451714518// If any part of the result matrix type is still pending, just use14519// Context.DependentTy, until all parts are resolved.14520if ((RowsExpr && RowsExpr->isTypeDependent()) ||14521(ColumnsExpr && ColumnsExpr->isTypeDependent())) {14522TheCall->setType(Context.DependentTy);14523return CallResult;14524}1452514526// Check row and column dimensions.14527std::optional<unsigned> MaybeRows;14528if (RowsExpr)14529MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);1453014531std::optional<unsigned> MaybeColumns;14532if (ColumnsExpr)14533MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);1453414535// Check stride argument.14536ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);14537if (StrideConv.isInvalid())14538return ExprError();14539StrideExpr = StrideConv.get();14540TheCall->setArg(3, StrideExpr);1454114542if (MaybeRows) {14543if (std::optional<llvm::APSInt> Value =14544StrideExpr->getIntegerConstantExpr(Context)) {14545uint64_t Stride = Value->getZExtValue();14546if (Stride < *MaybeRows) {14547Diag(StrideExpr->getBeginLoc(),14548diag::err_builtin_matrix_stride_too_small);14549ArgError = true;14550}14551}14552}1455314554if (ArgError || !MaybeRows || !MaybeColumns)14555return ExprError();1455614557TheCall->setType(14558Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));14559return CallResult;14560}1456114562ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,14563ExprResult CallResult) {14564if (checkArgCount(TheCall, 3))14565return ExprError();1456614567unsigned PtrArgIdx = 1;14568Expr *MatrixExpr = TheCall->getArg(0);14569Expr *PtrExpr = TheCall->getArg(PtrArgIdx);14570Expr *StrideExpr = TheCall->getArg(2);1457114572bool ArgError = false;1457314574{14575ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);14576if (MatrixConv.isInvalid())14577return MatrixConv;14578MatrixExpr = MatrixConv.get();14579TheCall->setArg(0, MatrixExpr);14580}14581if (MatrixExpr->isTypeDependent()) {14582TheCall->setType(Context.DependentTy);14583return TheCall;14584}1458514586auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();14587if (!MatrixTy) {14588Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)14589<< 1 << /*matrix ty */ 1 << MatrixExpr->getType();14590ArgError = true;14591}1459214593{14594ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);14595if (PtrConv.isInvalid())14596return PtrConv;14597PtrExpr = PtrConv.get();14598TheCall->setArg(1, PtrExpr);14599if (PtrExpr->isTypeDependent()) {14600TheCall->setType(Context.DependentTy);14601return TheCall;14602}14603}1460414605// Check pointer argument.14606auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();14607if (!PtrTy) {14608Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)14609<< PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();14610ArgError = true;14611} else {14612QualType ElementTy = PtrTy->getPointeeType();14613if (ElementTy.isConstQualified()) {14614Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);14615ArgError = true;14616}14617ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();14618if (MatrixTy &&14619!Context.hasSameType(ElementTy, MatrixTy->getElementType())) {14620Diag(PtrExpr->getBeginLoc(),14621diag::err_builtin_matrix_pointer_arg_mismatch)14622<< ElementTy << MatrixTy->getElementType();14623ArgError = true;14624}14625}1462614627// Apply default Lvalue conversions and convert the stride expression to14628// size_t.14629{14630ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);14631if (StrideConv.isInvalid())14632return StrideConv;1463314634StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());14635if (StrideConv.isInvalid())14636return StrideConv;14637StrideExpr = StrideConv.get();14638TheCall->setArg(2, StrideExpr);14639}1464014641// Check stride argument.14642if (MatrixTy) {14643if (std::optional<llvm::APSInt> Value =14644StrideExpr->getIntegerConstantExpr(Context)) {14645uint64_t Stride = Value->getZExtValue();14646if (Stride < MatrixTy->getNumRows()) {14647Diag(StrideExpr->getBeginLoc(),14648diag::err_builtin_matrix_stride_too_small);14649ArgError = true;14650}14651}14652}1465314654if (ArgError)14655return ExprError();1465614657return CallResult;14658}1465914660void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,14661const NamedDecl *Callee) {14662// This warning does not make sense in code that has no runtime behavior.14663if (isUnevaluatedContext())14664return;1466514666const NamedDecl *Caller = getCurFunctionOrMethodDecl();1466714668if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())14669return;1467014671// Search through the enforce_tcb and enforce_tcb_leaf attributes to find14672// all TCBs the callee is a part of.14673llvm::StringSet<> CalleeTCBs;14674for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())14675CalleeTCBs.insert(A->getTCBName());14676for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())14677CalleeTCBs.insert(A->getTCBName());1467814679// Go through the TCBs the caller is a part of and emit warnings if Caller14680// is in a TCB that the Callee is not.14681for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {14682StringRef CallerTCB = A->getTCBName();14683if (CalleeTCBs.count(CallerTCB) == 0) {14684this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)14685<< Callee << CallerTCB;14686}14687}14688}146891469014691