Path: blob/main/contrib/llvm-project/clang/lib/AST/Expr.cpp
35259 views
//===--- Expr.cpp - Expression AST Node Implementation --------------------===//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 the Expr class and subclasses.9//10//===----------------------------------------------------------------------===//1112#include "clang/AST/Expr.h"13#include "clang/AST/APValue.h"14#include "clang/AST/ASTContext.h"15#include "clang/AST/Attr.h"16#include "clang/AST/ComputeDependence.h"17#include "clang/AST/DeclCXX.h"18#include "clang/AST/DeclObjC.h"19#include "clang/AST/DeclTemplate.h"20#include "clang/AST/DependenceFlags.h"21#include "clang/AST/EvaluatedExprVisitor.h"22#include "clang/AST/ExprCXX.h"23#include "clang/AST/IgnoreExpr.h"24#include "clang/AST/Mangle.h"25#include "clang/AST/RecordLayout.h"26#include "clang/AST/StmtVisitor.h"27#include "clang/Basic/Builtins.h"28#include "clang/Basic/CharInfo.h"29#include "clang/Basic/SourceManager.h"30#include "clang/Basic/TargetInfo.h"31#include "clang/Lex/Lexer.h"32#include "clang/Lex/LiteralSupport.h"33#include "clang/Lex/Preprocessor.h"34#include "llvm/Support/ErrorHandling.h"35#include "llvm/Support/Format.h"36#include "llvm/Support/raw_ostream.h"37#include <algorithm>38#include <cstring>39#include <optional>40using namespace clang;4142const Expr *Expr::getBestDynamicClassTypeExpr() const {43const Expr *E = this;44while (true) {45E = E->IgnoreParenBaseCasts();4647// Follow the RHS of a comma operator.48if (auto *BO = dyn_cast<BinaryOperator>(E)) {49if (BO->getOpcode() == BO_Comma) {50E = BO->getRHS();51continue;52}53}5455// Step into initializer for materialized temporaries.56if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {57E = MTE->getSubExpr();58continue;59}6061break;62}6364return E;65}6667const CXXRecordDecl *Expr::getBestDynamicClassType() const {68const Expr *E = getBestDynamicClassTypeExpr();69QualType DerivedType = E->getType();70if (const PointerType *PTy = DerivedType->getAs<PointerType>())71DerivedType = PTy->getPointeeType();7273if (DerivedType->isDependentType())74return nullptr;7576const RecordType *Ty = DerivedType->castAs<RecordType>();77Decl *D = Ty->getDecl();78return cast<CXXRecordDecl>(D);79}8081const Expr *Expr::skipRValueSubobjectAdjustments(82SmallVectorImpl<const Expr *> &CommaLHSs,83SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {84const Expr *E = this;85while (true) {86E = E->IgnoreParens();8788if (const auto *CE = dyn_cast<CastExpr>(E)) {89if ((CE->getCastKind() == CK_DerivedToBase ||90CE->getCastKind() == CK_UncheckedDerivedToBase) &&91E->getType()->isRecordType()) {92E = CE->getSubExpr();93const auto *Derived =94cast<CXXRecordDecl>(E->getType()->castAs<RecordType>()->getDecl());95Adjustments.push_back(SubobjectAdjustment(CE, Derived));96continue;97}9899if (CE->getCastKind() == CK_NoOp) {100E = CE->getSubExpr();101continue;102}103} else if (const auto *ME = dyn_cast<MemberExpr>(E)) {104if (!ME->isArrow()) {105assert(ME->getBase()->getType()->getAsRecordDecl());106if (const auto *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {107if (!Field->isBitField() && !Field->getType()->isReferenceType()) {108E = ME->getBase();109Adjustments.push_back(SubobjectAdjustment(Field));110continue;111}112}113}114} else if (const auto *BO = dyn_cast<BinaryOperator>(E)) {115if (BO->getOpcode() == BO_PtrMemD) {116assert(BO->getRHS()->isPRValue());117E = BO->getLHS();118const auto *MPT = BO->getRHS()->getType()->getAs<MemberPointerType>();119Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));120continue;121}122if (BO->getOpcode() == BO_Comma) {123CommaLHSs.push_back(BO->getLHS());124E = BO->getRHS();125continue;126}127}128129// Nothing changed.130break;131}132return E;133}134135bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {136const Expr *E = IgnoreParens();137138// If this value has _Bool type, it is obvious 0/1.139if (E->getType()->isBooleanType()) return true;140// If this is a non-scalar-integer type, we don't care enough to try.141if (!E->getType()->isIntegralOrEnumerationType()) return false;142143if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {144switch (UO->getOpcode()) {145case UO_Plus:146return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);147case UO_LNot:148return true;149default:150return false;151}152}153154// Only look through implicit casts. If the user writes155// '(int) (a && b)' treat it as an arbitrary int.156// FIXME: Should we look through any cast expression in !Semantic mode?157if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))158return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);159160if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {161switch (BO->getOpcode()) {162default: return false;163case BO_LT: // Relational operators.164case BO_GT:165case BO_LE:166case BO_GE:167case BO_EQ: // Equality operators.168case BO_NE:169case BO_LAnd: // AND operator.170case BO_LOr: // Logical OR operator.171return true;172173case BO_And: // Bitwise AND operator.174case BO_Xor: // Bitwise XOR operator.175case BO_Or: // Bitwise OR operator.176// Handle things like (x==2)|(y==12).177return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&178BO->getRHS()->isKnownToHaveBooleanValue(Semantic);179180case BO_Comma:181case BO_Assign:182return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);183}184}185186if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))187return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&188CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);189190if (isa<ObjCBoolLiteralExpr>(E))191return true;192193if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))194return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);195196if (const FieldDecl *FD = E->getSourceBitField())197if (!Semantic && FD->getType()->isUnsignedIntegerType() &&198!FD->getBitWidth()->isValueDependent() &&199FD->getBitWidthValue(FD->getASTContext()) == 1)200return true;201202return false;203}204205bool Expr::isFlexibleArrayMemberLike(206ASTContext &Ctx,207LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,208bool IgnoreTemplateOrMacroSubstitution) const {209const Expr *E = IgnoreParens();210const Decl *D = nullptr;211212if (const auto *ME = dyn_cast<MemberExpr>(E))213D = ME->getMemberDecl();214else if (const auto *DRE = dyn_cast<DeclRefExpr>(E))215D = DRE->getDecl();216else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))217D = IRE->getDecl();218219return Decl::isFlexibleArrayMemberLike(Ctx, D, E->getType(),220StrictFlexArraysLevel,221IgnoreTemplateOrMacroSubstitution);222}223224const ValueDecl *225Expr::getAsBuiltinConstantDeclRef(const ASTContext &Context) const {226Expr::EvalResult Eval;227228if (EvaluateAsConstantExpr(Eval, Context)) {229APValue &Value = Eval.Val;230231if (Value.isMemberPointer())232return Value.getMemberPointerDecl();233234if (Value.isLValue() && Value.getLValueOffset().isZero())235return Value.getLValueBase().dyn_cast<const ValueDecl *>();236}237238return nullptr;239}240241// Amusing macro metaprogramming hack: check whether a class provides242// a more specific implementation of getExprLoc().243//244// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.245namespace {246/// This implementation is used when a class provides a custom247/// implementation of getExprLoc.248template <class E, class T>249SourceLocation getExprLocImpl(const Expr *expr,250SourceLocation (T::*v)() const) {251return static_cast<const E*>(expr)->getExprLoc();252}253254/// This implementation is used when a class doesn't provide255/// a custom implementation of getExprLoc. Overload resolution256/// should pick it over the implementation above because it's257/// more specialized according to function template partial ordering.258template <class E>259SourceLocation getExprLocImpl(const Expr *expr,260SourceLocation (Expr::*v)() const) {261return static_cast<const E *>(expr)->getBeginLoc();262}263}264265QualType Expr::getEnumCoercedType(const ASTContext &Ctx) const {266if (isa<EnumType>(getType()))267return getType();268if (const auto *ECD = getEnumConstantDecl()) {269const auto *ED = cast<EnumDecl>(ECD->getDeclContext());270if (ED->isCompleteDefinition())271return Ctx.getTypeDeclType(ED);272}273return getType();274}275276SourceLocation Expr::getExprLoc() const {277switch (getStmtClass()) {278case Stmt::NoStmtClass: llvm_unreachable("statement without class");279#define ABSTRACT_STMT(type)280#define STMT(type, base) \281case Stmt::type##Class: break;282#define EXPR(type, base) \283case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);284#include "clang/AST/StmtNodes.inc"285}286llvm_unreachable("unknown expression kind");287}288289//===----------------------------------------------------------------------===//290// Primary Expressions.291//===----------------------------------------------------------------------===//292293static void AssertResultStorageKind(ConstantResultStorageKind Kind) {294assert((Kind == ConstantResultStorageKind::APValue ||295Kind == ConstantResultStorageKind::Int64 ||296Kind == ConstantResultStorageKind::None) &&297"Invalid StorageKind Value");298(void)Kind;299}300301ConstantResultStorageKind ConstantExpr::getStorageKind(const APValue &Value) {302switch (Value.getKind()) {303case APValue::None:304case APValue::Indeterminate:305return ConstantResultStorageKind::None;306case APValue::Int:307if (!Value.getInt().needsCleanup())308return ConstantResultStorageKind::Int64;309[[fallthrough]];310default:311return ConstantResultStorageKind::APValue;312}313}314315ConstantResultStorageKind316ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {317if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)318return ConstantResultStorageKind::Int64;319return ConstantResultStorageKind::APValue;320}321322ConstantExpr::ConstantExpr(Expr *SubExpr, ConstantResultStorageKind StorageKind,323bool IsImmediateInvocation)324: FullExpr(ConstantExprClass, SubExpr) {325ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);326ConstantExprBits.APValueKind = APValue::None;327ConstantExprBits.IsUnsigned = false;328ConstantExprBits.BitWidth = 0;329ConstantExprBits.HasCleanup = false;330ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation;331332if (StorageKind == ConstantResultStorageKind::APValue)333::new (getTrailingObjects<APValue>()) APValue();334}335336ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,337ConstantResultStorageKind StorageKind,338bool IsImmediateInvocation) {339assert(!isa<ConstantExpr>(E));340AssertResultStorageKind(StorageKind);341342unsigned Size = totalSizeToAlloc<APValue, uint64_t>(343StorageKind == ConstantResultStorageKind::APValue,344StorageKind == ConstantResultStorageKind::Int64);345void *Mem = Context.Allocate(Size, alignof(ConstantExpr));346return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);347}348349ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,350const APValue &Result) {351ConstantResultStorageKind StorageKind = getStorageKind(Result);352ConstantExpr *Self = Create(Context, E, StorageKind);353Self->SetResult(Result, Context);354return Self;355}356357ConstantExpr::ConstantExpr(EmptyShell Empty,358ConstantResultStorageKind StorageKind)359: FullExpr(ConstantExprClass, Empty) {360ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);361362if (StorageKind == ConstantResultStorageKind::APValue)363::new (getTrailingObjects<APValue>()) APValue();364}365366ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,367ConstantResultStorageKind StorageKind) {368AssertResultStorageKind(StorageKind);369370unsigned Size = totalSizeToAlloc<APValue, uint64_t>(371StorageKind == ConstantResultStorageKind::APValue,372StorageKind == ConstantResultStorageKind::Int64);373void *Mem = Context.Allocate(Size, alignof(ConstantExpr));374return new (Mem) ConstantExpr(EmptyShell(), StorageKind);375}376377void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {378assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&379"Invalid storage for this value kind");380ConstantExprBits.APValueKind = Value.getKind();381switch (getResultStorageKind()) {382case ConstantResultStorageKind::None:383return;384case ConstantResultStorageKind::Int64:385Int64Result() = *Value.getInt().getRawData();386ConstantExprBits.BitWidth = Value.getInt().getBitWidth();387ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();388return;389case ConstantResultStorageKind::APValue:390if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {391ConstantExprBits.HasCleanup = true;392Context.addDestruction(&APValueResult());393}394APValueResult() = std::move(Value);395return;396}397llvm_unreachable("Invalid ResultKind Bits");398}399400llvm::APSInt ConstantExpr::getResultAsAPSInt() const {401switch (getResultStorageKind()) {402case ConstantResultStorageKind::APValue:403return APValueResult().getInt();404case ConstantResultStorageKind::Int64:405return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),406ConstantExprBits.IsUnsigned);407default:408llvm_unreachable("invalid Accessor");409}410}411412APValue ConstantExpr::getAPValueResult() const {413414switch (getResultStorageKind()) {415case ConstantResultStorageKind::APValue:416return APValueResult();417case ConstantResultStorageKind::Int64:418return APValue(419llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),420ConstantExprBits.IsUnsigned));421case ConstantResultStorageKind::None:422if (ConstantExprBits.APValueKind == APValue::Indeterminate)423return APValue::IndeterminateValue();424return APValue();425}426llvm_unreachable("invalid ResultKind");427}428429DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,430bool RefersToEnclosingVariableOrCapture, QualType T,431ExprValueKind VK, SourceLocation L,432const DeclarationNameLoc &LocInfo,433NonOdrUseReason NOUR)434: Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {435DeclRefExprBits.HasQualifier = false;436DeclRefExprBits.HasTemplateKWAndArgsInfo = false;437DeclRefExprBits.HasFoundDecl = false;438DeclRefExprBits.HadMultipleCandidates = false;439DeclRefExprBits.RefersToEnclosingVariableOrCapture =440RefersToEnclosingVariableOrCapture;441DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;442DeclRefExprBits.NonOdrUseReason = NOUR;443DeclRefExprBits.IsImmediateEscalating = false;444DeclRefExprBits.Loc = L;445setDependence(computeDependence(this, Ctx));446}447448DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,449NestedNameSpecifierLoc QualifierLoc,450SourceLocation TemplateKWLoc, ValueDecl *D,451bool RefersToEnclosingVariableOrCapture,452const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,453const TemplateArgumentListInfo *TemplateArgs,454QualType T, ExprValueKind VK, NonOdrUseReason NOUR)455: Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),456DNLoc(NameInfo.getInfo()) {457DeclRefExprBits.Loc = NameInfo.getLoc();458DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;459if (QualifierLoc)460new (getTrailingObjects<NestedNameSpecifierLoc>())461NestedNameSpecifierLoc(QualifierLoc);462DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;463if (FoundD)464*getTrailingObjects<NamedDecl *>() = FoundD;465DeclRefExprBits.HasTemplateKWAndArgsInfo466= (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;467DeclRefExprBits.RefersToEnclosingVariableOrCapture =468RefersToEnclosingVariableOrCapture;469DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;470DeclRefExprBits.NonOdrUseReason = NOUR;471if (TemplateArgs) {472auto Deps = TemplateArgumentDependence::None;473getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(474TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),475Deps);476assert(!(Deps & TemplateArgumentDependence::Dependent) &&477"built a DeclRefExpr with dependent template args");478} else if (TemplateKWLoc.isValid()) {479getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(480TemplateKWLoc);481}482DeclRefExprBits.IsImmediateEscalating = false;483DeclRefExprBits.HadMultipleCandidates = 0;484setDependence(computeDependence(this, Ctx));485}486487DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,488NestedNameSpecifierLoc QualifierLoc,489SourceLocation TemplateKWLoc, ValueDecl *D,490bool RefersToEnclosingVariableOrCapture,491SourceLocation NameLoc, QualType T,492ExprValueKind VK, NamedDecl *FoundD,493const TemplateArgumentListInfo *TemplateArgs,494NonOdrUseReason NOUR) {495return Create(Context, QualifierLoc, TemplateKWLoc, D,496RefersToEnclosingVariableOrCapture,497DeclarationNameInfo(D->getDeclName(), NameLoc),498T, VK, FoundD, TemplateArgs, NOUR);499}500501DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,502NestedNameSpecifierLoc QualifierLoc,503SourceLocation TemplateKWLoc, ValueDecl *D,504bool RefersToEnclosingVariableOrCapture,505const DeclarationNameInfo &NameInfo,506QualType T, ExprValueKind VK,507NamedDecl *FoundD,508const TemplateArgumentListInfo *TemplateArgs,509NonOdrUseReason NOUR) {510// Filter out cases where the found Decl is the same as the value refenenced.511if (D == FoundD)512FoundD = nullptr;513514bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();515std::size_t Size =516totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,517ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(518QualifierLoc ? 1 : 0, FoundD ? 1 : 0,519HasTemplateKWAndArgsInfo ? 1 : 0,520TemplateArgs ? TemplateArgs->size() : 0);521522void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));523return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,524RefersToEnclosingVariableOrCapture, NameInfo,525FoundD, TemplateArgs, T, VK, NOUR);526}527528DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,529bool HasQualifier,530bool HasFoundDecl,531bool HasTemplateKWAndArgsInfo,532unsigned NumTemplateArgs) {533assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);534std::size_t Size =535totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,536ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(537HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,538NumTemplateArgs);539void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));540return new (Mem) DeclRefExpr(EmptyShell());541}542543void DeclRefExpr::setDecl(ValueDecl *NewD) {544D = NewD;545if (getType()->isUndeducedType())546setType(NewD->getType());547setDependence(computeDependence(this, NewD->getASTContext()));548}549550SourceLocation DeclRefExpr::getBeginLoc() const {551if (hasQualifier())552return getQualifierLoc().getBeginLoc();553return getNameInfo().getBeginLoc();554}555SourceLocation DeclRefExpr::getEndLoc() const {556if (hasExplicitTemplateArgs())557return getRAngleLoc();558return getNameInfo().getEndLoc();559}560561SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(SourceLocation OpLoc,562SourceLocation LParen,563SourceLocation RParen,564QualType ResultTy,565TypeSourceInfo *TSI)566: Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary),567OpLoc(OpLoc), LParen(LParen), RParen(RParen) {568setTypeSourceInfo(TSI);569setDependence(computeDependence(this));570}571572SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty,573QualType ResultTy)574: Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}575576SYCLUniqueStableNameExpr *577SYCLUniqueStableNameExpr::Create(const ASTContext &Ctx, SourceLocation OpLoc,578SourceLocation LParen, SourceLocation RParen,579TypeSourceInfo *TSI) {580QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());581return new (Ctx)582SYCLUniqueStableNameExpr(OpLoc, LParen, RParen, ResultTy, TSI);583}584585SYCLUniqueStableNameExpr *586SYCLUniqueStableNameExpr::CreateEmpty(const ASTContext &Ctx) {587QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());588return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy);589}590591std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context) const {592return SYCLUniqueStableNameExpr::ComputeName(Context,593getTypeSourceInfo()->getType());594}595596std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context,597QualType Ty) {598auto MangleCallback = [](ASTContext &Ctx,599const NamedDecl *ND) -> std::optional<unsigned> {600if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))601return RD->getDeviceLambdaManglingNumber();602return std::nullopt;603};604605std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(606Context, Context.getDiagnostics(), MangleCallback)};607608std::string Buffer;609Buffer.reserve(128);610llvm::raw_string_ostream Out(Buffer);611Ctx->mangleCanonicalTypeName(Ty, Out);612613return Out.str();614}615616PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy,617PredefinedIdentKind IK, bool IsTransparent,618StringLiteral *SL)619: Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {620PredefinedExprBits.Kind = llvm::to_underlying(IK);621assert((getIdentKind() == IK) &&622"IdentKind do not fit in PredefinedExprBitfields!");623bool HasFunctionName = SL != nullptr;624PredefinedExprBits.HasFunctionName = HasFunctionName;625PredefinedExprBits.IsTransparent = IsTransparent;626PredefinedExprBits.Loc = L;627if (HasFunctionName)628setFunctionName(SL);629setDependence(computeDependence(this));630}631632PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)633: Expr(PredefinedExprClass, Empty) {634PredefinedExprBits.HasFunctionName = HasFunctionName;635}636637PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,638QualType FNTy, PredefinedIdentKind IK,639bool IsTransparent, StringLiteral *SL) {640bool HasFunctionName = SL != nullptr;641void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),642alignof(PredefinedExpr));643return new (Mem) PredefinedExpr(L, FNTy, IK, IsTransparent, SL);644}645646PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,647bool HasFunctionName) {648void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),649alignof(PredefinedExpr));650return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);651}652653StringRef PredefinedExpr::getIdentKindName(PredefinedIdentKind IK) {654switch (IK) {655case PredefinedIdentKind::Func:656return "__func__";657case PredefinedIdentKind::Function:658return "__FUNCTION__";659case PredefinedIdentKind::FuncDName:660return "__FUNCDNAME__";661case PredefinedIdentKind::LFunction:662return "L__FUNCTION__";663case PredefinedIdentKind::PrettyFunction:664return "__PRETTY_FUNCTION__";665case PredefinedIdentKind::FuncSig:666return "__FUNCSIG__";667case PredefinedIdentKind::LFuncSig:668return "L__FUNCSIG__";669case PredefinedIdentKind::PrettyFunctionNoVirtual:670break;671}672llvm_unreachable("Unknown ident kind for PredefinedExpr");673}674675// FIXME: Maybe this should use DeclPrinter with a special "print predefined676// expr" policy instead.677std::string PredefinedExpr::ComputeName(PredefinedIdentKind IK,678const Decl *CurrentDecl,679bool ForceElaboratedPrinting) {680ASTContext &Context = CurrentDecl->getASTContext();681682if (IK == PredefinedIdentKind::FuncDName) {683if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {684std::unique_ptr<MangleContext> MC;685MC.reset(Context.createMangleContext());686687if (MC->shouldMangleDeclName(ND)) {688SmallString<256> Buffer;689llvm::raw_svector_ostream Out(Buffer);690GlobalDecl GD;691if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))692GD = GlobalDecl(CD, Ctor_Base);693else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))694GD = GlobalDecl(DD, Dtor_Base);695else if (ND->hasAttr<CUDAGlobalAttr>())696GD = GlobalDecl(cast<FunctionDecl>(ND));697else698GD = GlobalDecl(ND);699MC->mangleName(GD, Out);700701if (!Buffer.empty() && Buffer.front() == '\01')702return std::string(Buffer.substr(1));703return std::string(Buffer);704}705return std::string(ND->getIdentifier()->getName());706}707return "";708}709if (isa<BlockDecl>(CurrentDecl)) {710// For blocks we only emit something if it is enclosed in a function711// For top-level block we'd like to include the name of variable, but we712// don't have it at this point.713auto DC = CurrentDecl->getDeclContext();714if (DC->isFileContext())715return "";716717SmallString<256> Buffer;718llvm::raw_svector_ostream Out(Buffer);719if (auto *DCBlock = dyn_cast<BlockDecl>(DC))720// For nested blocks, propagate up to the parent.721Out << ComputeName(IK, DCBlock);722else if (auto *DCDecl = dyn_cast<Decl>(DC))723Out << ComputeName(IK, DCDecl) << "_block_invoke";724return std::string(Out.str());725}726if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {727const auto &LO = Context.getLangOpts();728bool IsFuncOrFunctionInNonMSVCCompatEnv =729((IK == PredefinedIdentKind::Func ||730IK == PredefinedIdentKind ::Function) &&731!LO.MSVCCompat);732bool IsLFunctionInMSVCCommpatEnv =733IK == PredefinedIdentKind::LFunction && LO.MSVCCompat;734bool IsFuncOrFunctionOrLFunctionOrFuncDName =735IK != PredefinedIdentKind::PrettyFunction &&736IK != PredefinedIdentKind::PrettyFunctionNoVirtual &&737IK != PredefinedIdentKind::FuncSig &&738IK != PredefinedIdentKind::LFuncSig;739if ((ForceElaboratedPrinting &&740(IsFuncOrFunctionInNonMSVCCompatEnv || IsLFunctionInMSVCCommpatEnv)) ||741(!ForceElaboratedPrinting && IsFuncOrFunctionOrLFunctionOrFuncDName))742return FD->getNameAsString();743744SmallString<256> Name;745llvm::raw_svector_ostream Out(Name);746747if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {748if (MD->isVirtual() && IK != PredefinedIdentKind::PrettyFunctionNoVirtual)749Out << "virtual ";750if (MD->isStatic())751Out << "static ";752}753754class PrettyCallbacks final : public PrintingCallbacks {755public:756PrettyCallbacks(const LangOptions &LO) : LO(LO) {}757std::string remapPath(StringRef Path) const override {758SmallString<128> p(Path);759LO.remapPathPrefix(p);760return std::string(p);761}762763private:764const LangOptions &LO;765};766PrintingPolicy Policy(Context.getLangOpts());767PrettyCallbacks PrettyCB(Context.getLangOpts());768Policy.Callbacks = &PrettyCB;769if (IK == PredefinedIdentKind::Function && ForceElaboratedPrinting)770Policy.SuppressTagKeyword = !LO.MSVCCompat;771std::string Proto;772llvm::raw_string_ostream POut(Proto);773774const FunctionDecl *Decl = FD;775if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())776Decl = Pattern;777const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();778const FunctionProtoType *FT = nullptr;779if (FD->hasWrittenPrototype())780FT = dyn_cast<FunctionProtoType>(AFT);781782if (IK == PredefinedIdentKind::FuncSig ||783IK == PredefinedIdentKind::LFuncSig) {784switch (AFT->getCallConv()) {785case CC_C: POut << "__cdecl "; break;786case CC_X86StdCall: POut << "__stdcall "; break;787case CC_X86FastCall: POut << "__fastcall "; break;788case CC_X86ThisCall: POut << "__thiscall "; break;789case CC_X86VectorCall: POut << "__vectorcall "; break;790case CC_X86RegCall: POut << "__regcall "; break;791// Only bother printing the conventions that MSVC knows about.792default: break;793}794}795796FD->printQualifiedName(POut, Policy);797798if (IK == PredefinedIdentKind::Function) {799POut.flush();800Out << Proto;801return std::string(Name);802}803804POut << "(";805if (FT) {806for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {807if (i) POut << ", ";808POut << Decl->getParamDecl(i)->getType().stream(Policy);809}810811if (FT->isVariadic()) {812if (FD->getNumParams()) POut << ", ";813POut << "...";814} else if ((IK == PredefinedIdentKind::FuncSig ||815IK == PredefinedIdentKind::LFuncSig ||816!Context.getLangOpts().CPlusPlus) &&817!Decl->getNumParams()) {818POut << "void";819}820}821POut << ")";822823if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {824assert(FT && "We must have a written prototype in this case.");825if (FT->isConst())826POut << " const";827if (FT->isVolatile())828POut << " volatile";829RefQualifierKind Ref = MD->getRefQualifier();830if (Ref == RQ_LValue)831POut << " &";832else if (Ref == RQ_RValue)833POut << " &&";834}835836typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;837SpecsTy Specs;838const DeclContext *Ctx = FD->getDeclContext();839while (isa_and_nonnull<NamedDecl>(Ctx)) {840const ClassTemplateSpecializationDecl *Spec841= dyn_cast<ClassTemplateSpecializationDecl>(Ctx);842if (Spec && !Spec->isExplicitSpecialization())843Specs.push_back(Spec);844Ctx = Ctx->getParent();845}846847std::string TemplateParams;848llvm::raw_string_ostream TOut(TemplateParams);849for (const ClassTemplateSpecializationDecl *D : llvm::reverse(Specs)) {850const TemplateParameterList *Params =851D->getSpecializedTemplate()->getTemplateParameters();852const TemplateArgumentList &Args = D->getTemplateArgs();853assert(Params->size() == Args.size());854for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {855StringRef Param = Params->getParam(i)->getName();856if (Param.empty()) continue;857TOut << Param << " = ";858Args.get(i).print(Policy, TOut,859TemplateParameterList::shouldIncludeTypeForArgument(860Policy, Params, i));861TOut << ", ";862}863}864865FunctionTemplateSpecializationInfo *FSI866= FD->getTemplateSpecializationInfo();867if (FSI && !FSI->isExplicitSpecialization()) {868const TemplateParameterList* Params869= FSI->getTemplate()->getTemplateParameters();870const TemplateArgumentList* Args = FSI->TemplateArguments;871assert(Params->size() == Args->size());872for (unsigned i = 0, e = Params->size(); i != e; ++i) {873StringRef Param = Params->getParam(i)->getName();874if (Param.empty()) continue;875TOut << Param << " = ";876Args->get(i).print(Policy, TOut, /*IncludeType*/ true);877TOut << ", ";878}879}880881TOut.flush();882if (!TemplateParams.empty()) {883// remove the trailing comma and space884TemplateParams.resize(TemplateParams.size() - 2);885POut << " [" << TemplateParams << "]";886}887888POut.flush();889890// Print "auto" for all deduced return types. This includes C++1y return891// type deduction and lambdas. For trailing return types resolve the892// decltype expression. Otherwise print the real type when this is893// not a constructor or destructor.894if (isa<CXXMethodDecl>(FD) &&895cast<CXXMethodDecl>(FD)->getParent()->isLambda())896Proto = "auto " + Proto;897else if (FT && FT->getReturnType()->getAs<DecltypeType>())898FT->getReturnType()899->getAs<DecltypeType>()900->getUnderlyingType()901.getAsStringInternal(Proto, Policy);902else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))903AFT->getReturnType().getAsStringInternal(Proto, Policy);904905Out << Proto;906907return std::string(Name);908}909if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {910for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())911// Skip to its enclosing function or method, but not its enclosing912// CapturedDecl.913if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {914const Decl *D = Decl::castFromDeclContext(DC);915return ComputeName(IK, D);916}917llvm_unreachable("CapturedDecl not inside a function or method");918}919if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {920SmallString<256> Name;921llvm::raw_svector_ostream Out(Name);922Out << (MD->isInstanceMethod() ? '-' : '+');923Out << '[';924925// For incorrect code, there might not be an ObjCInterfaceDecl. Do926// a null check to avoid a crash.927if (const ObjCInterfaceDecl *ID = MD->getClassInterface())928Out << *ID;929930if (const ObjCCategoryImplDecl *CID =931dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))932Out << '(' << *CID << ')';933934Out << ' ';935MD->getSelector().print(Out);936Out << ']';937938return std::string(Name);939}940if (isa<TranslationUnitDecl>(CurrentDecl) &&941IK == PredefinedIdentKind::PrettyFunction) {942// __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.943return "top level";944}945return "";946}947948void APNumericStorage::setIntValue(const ASTContext &C,949const llvm::APInt &Val) {950if (hasAllocation())951C.Deallocate(pVal);952953BitWidth = Val.getBitWidth();954unsigned NumWords = Val.getNumWords();955const uint64_t* Words = Val.getRawData();956if (NumWords > 1) {957pVal = new (C) uint64_t[NumWords];958std::copy(Words, Words + NumWords, pVal);959} else if (NumWords == 1)960VAL = Words[0];961else962VAL = 0;963}964965IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,966QualType type, SourceLocation l)967: Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) {968assert(type->isIntegerType() && "Illegal type in IntegerLiteral");969assert(V.getBitWidth() == C.getIntWidth(type) &&970"Integer type is not the correct size for constant.");971setValue(C, V);972setDependence(ExprDependence::None);973}974975IntegerLiteral *976IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,977QualType type, SourceLocation l) {978return new (C) IntegerLiteral(C, V, type, l);979}980981IntegerLiteral *982IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {983return new (C) IntegerLiteral(Empty);984}985986FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,987QualType type, SourceLocation l,988unsigned Scale)989: Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l),990Scale(Scale) {991assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");992assert(V.getBitWidth() == C.getTypeInfo(type).Width &&993"Fixed point type is not the correct size for constant.");994setValue(C, V);995setDependence(ExprDependence::None);996}997998FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,999const llvm::APInt &V,1000QualType type,1001SourceLocation l,1002unsigned Scale) {1003return new (C) FixedPointLiteral(C, V, type, l, Scale);1004}10051006FixedPointLiteral *FixedPointLiteral::Create(const ASTContext &C,1007EmptyShell Empty) {1008return new (C) FixedPointLiteral(Empty);1009}10101011std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {1012// Currently the longest decimal number that can be printed is the max for an1013// unsigned long _Accum: 4294967295.999999999767169356346130371093751014// which is 43 characters.1015SmallString<64> S;1016FixedPointValueToString(1017S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);1018return std::string(S);1019}10201021void CharacterLiteral::print(unsigned Val, CharacterLiteralKind Kind,1022raw_ostream &OS) {1023switch (Kind) {1024case CharacterLiteralKind::Ascii:1025break; // no prefix.1026case CharacterLiteralKind::Wide:1027OS << 'L';1028break;1029case CharacterLiteralKind::UTF8:1030OS << "u8";1031break;1032case CharacterLiteralKind::UTF16:1033OS << 'u';1034break;1035case CharacterLiteralKind::UTF32:1036OS << 'U';1037break;1038}10391040StringRef Escaped = escapeCStyle<EscapeChar::Single>(Val);1041if (!Escaped.empty()) {1042OS << "'" << Escaped << "'";1043} else {1044// A character literal might be sign-extended, which1045// would result in an invalid \U escape sequence.1046// FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'1047// are not correctly handled.1048if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteralKind::Ascii)1049Val &= 0xFFu;1050if (Val < 256 && isPrintable((unsigned char)Val))1051OS << "'" << (char)Val << "'";1052else if (Val < 256)1053OS << "'\\x" << llvm::format("%02x", Val) << "'";1054else if (Val <= 0xFFFF)1055OS << "'\\u" << llvm::format("%04x", Val) << "'";1056else1057OS << "'\\U" << llvm::format("%08x", Val) << "'";1058}1059}10601061FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,1062bool isexact, QualType Type, SourceLocation L)1063: Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) {1064setSemantics(V.getSemantics());1065FloatingLiteralBits.IsExact = isexact;1066setValue(C, V);1067setDependence(ExprDependence::None);1068}10691070FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)1071: Expr(FloatingLiteralClass, Empty) {1072setRawSemantics(llvm::APFloatBase::S_IEEEhalf);1073FloatingLiteralBits.IsExact = false;1074}10751076FloatingLiteral *1077FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,1078bool isexact, QualType Type, SourceLocation L) {1079return new (C) FloatingLiteral(C, V, isexact, Type, L);1080}10811082FloatingLiteral *1083FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {1084return new (C) FloatingLiteral(C, Empty);1085}10861087/// getValueAsApproximateDouble - This returns the value as an inaccurate1088/// double. Note that this may cause loss of precision, but is useful for1089/// debugging dumps, etc.1090double FloatingLiteral::getValueAsApproximateDouble() const {1091llvm::APFloat V = getValue();1092bool ignored;1093V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,1094&ignored);1095return V.convertToDouble();1096}10971098unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,1099StringLiteralKind SK) {1100unsigned CharByteWidth = 0;1101switch (SK) {1102case StringLiteralKind::Ordinary:1103case StringLiteralKind::UTF8:1104CharByteWidth = Target.getCharWidth();1105break;1106case StringLiteralKind::Wide:1107CharByteWidth = Target.getWCharWidth();1108break;1109case StringLiteralKind::UTF16:1110CharByteWidth = Target.getChar16Width();1111break;1112case StringLiteralKind::UTF32:1113CharByteWidth = Target.getChar32Width();1114break;1115case StringLiteralKind::Unevaluated:1116return sizeof(char); // Host;1117}1118assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");1119CharByteWidth /= 8;1120assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&1121"The only supported character byte widths are 1,2 and 4!");1122return CharByteWidth;1123}11241125StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,1126StringLiteralKind Kind, bool Pascal, QualType Ty,1127const SourceLocation *Loc,1128unsigned NumConcatenated)1129: Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {11301131unsigned Length = Str.size();11321133StringLiteralBits.Kind = llvm::to_underlying(Kind);1134StringLiteralBits.NumConcatenated = NumConcatenated;11351136if (Kind != StringLiteralKind::Unevaluated) {1137assert(Ctx.getAsConstantArrayType(Ty) &&1138"StringLiteral must be of constant array type!");1139unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);1140unsigned ByteLength = Str.size();1141assert((ByteLength % CharByteWidth == 0) &&1142"The size of the data must be a multiple of CharByteWidth!");11431144// Avoid the expensive division. The compiler should be able to figure it1145// out by itself. However as of clang 7, even with the appropriate1146// llvm_unreachable added just here, it is not able to do so.1147switch (CharByteWidth) {1148case 1:1149Length = ByteLength;1150break;1151case 2:1152Length = ByteLength / 2;1153break;1154case 4:1155Length = ByteLength / 4;1156break;1157default:1158llvm_unreachable("Unsupported character width!");1159}11601161StringLiteralBits.CharByteWidth = CharByteWidth;1162StringLiteralBits.IsPascal = Pascal;1163} else {1164assert(!Pascal && "Can't make an unevaluated Pascal string");1165StringLiteralBits.CharByteWidth = 1;1166StringLiteralBits.IsPascal = false;1167}11681169*getTrailingObjects<unsigned>() = Length;11701171// Initialize the trailing array of SourceLocation.1172// This is safe since SourceLocation is POD-like.1173std::memcpy(getTrailingObjects<SourceLocation>(), Loc,1174NumConcatenated * sizeof(SourceLocation));11751176// Initialize the trailing array of char holding the string data.1177std::memcpy(getTrailingObjects<char>(), Str.data(), Str.size());11781179setDependence(ExprDependence::None);1180}11811182StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,1183unsigned Length, unsigned CharByteWidth)1184: Expr(StringLiteralClass, Empty) {1185StringLiteralBits.CharByteWidth = CharByteWidth;1186StringLiteralBits.NumConcatenated = NumConcatenated;1187*getTrailingObjects<unsigned>() = Length;1188}11891190StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,1191StringLiteralKind Kind, bool Pascal,1192QualType Ty, const SourceLocation *Loc,1193unsigned NumConcatenated) {1194void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(11951, NumConcatenated, Str.size()),1196alignof(StringLiteral));1197return new (Mem)1198StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);1199}12001201StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,1202unsigned NumConcatenated,1203unsigned Length,1204unsigned CharByteWidth) {1205void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(12061, NumConcatenated, Length * CharByteWidth),1207alignof(StringLiteral));1208return new (Mem)1209StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);1210}12111212void StringLiteral::outputString(raw_ostream &OS) const {1213switch (getKind()) {1214case StringLiteralKind::Unevaluated:1215case StringLiteralKind::Ordinary:1216break; // no prefix.1217case StringLiteralKind::Wide:1218OS << 'L';1219break;1220case StringLiteralKind::UTF8:1221OS << "u8";1222break;1223case StringLiteralKind::UTF16:1224OS << 'u';1225break;1226case StringLiteralKind::UTF32:1227OS << 'U';1228break;1229}1230OS << '"';1231static const char Hex[] = "0123456789ABCDEF";12321233unsigned LastSlashX = getLength();1234for (unsigned I = 0, N = getLength(); I != N; ++I) {1235uint32_t Char = getCodeUnit(I);1236StringRef Escaped = escapeCStyle<EscapeChar::Double>(Char);1237if (Escaped.empty()) {1238// FIXME: Convert UTF-8 back to codepoints before rendering.12391240// Convert UTF-16 surrogate pairs back to codepoints before rendering.1241// Leave invalid surrogates alone; we'll use \x for those.1242if (getKind() == StringLiteralKind::UTF16 && I != N - 1 &&1243Char >= 0xd800 && Char <= 0xdbff) {1244uint32_t Trail = getCodeUnit(I + 1);1245if (Trail >= 0xdc00 && Trail <= 0xdfff) {1246Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);1247++I;1248}1249}12501251if (Char > 0xff) {1252// If this is a wide string, output characters over 0xff using \x1253// escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a1254// codepoint: use \x escapes for invalid codepoints.1255if (getKind() == StringLiteralKind::Wide ||1256(Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {1257// FIXME: Is this the best way to print wchar_t?1258OS << "\\x";1259int Shift = 28;1260while ((Char >> Shift) == 0)1261Shift -= 4;1262for (/**/; Shift >= 0; Shift -= 4)1263OS << Hex[(Char >> Shift) & 15];1264LastSlashX = I;1265continue;1266}12671268if (Char > 0xffff)1269OS << "\\U00"1270<< Hex[(Char >> 20) & 15]1271<< Hex[(Char >> 16) & 15];1272else1273OS << "\\u";1274OS << Hex[(Char >> 12) & 15]1275<< Hex[(Char >> 8) & 15]1276<< Hex[(Char >> 4) & 15]1277<< Hex[(Char >> 0) & 15];1278continue;1279}12801281// If we used \x... for the previous character, and this character is a1282// hexadecimal digit, prevent it being slurped as part of the \x.1283if (LastSlashX + 1 == I) {1284switch (Char) {1285case '0': case '1': case '2': case '3': case '4':1286case '5': case '6': case '7': case '8': case '9':1287case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':1288case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':1289OS << "\"\"";1290}1291}12921293assert(Char <= 0xff &&1294"Characters above 0xff should already have been handled.");12951296if (isPrintable(Char))1297OS << (char)Char;1298else // Output anything hard as an octal escape.1299OS << '\\'1300<< (char)('0' + ((Char >> 6) & 7))1301<< (char)('0' + ((Char >> 3) & 7))1302<< (char)('0' + ((Char >> 0) & 7));1303} else {1304// Handle some common non-printable cases to make dumps prettier.1305OS << Escaped;1306}1307}1308OS << '"';1309}13101311/// getLocationOfByte - Return a source location that points to the specified1312/// byte of this string literal.1313///1314/// Strings are amazingly complex. They can be formed from multiple tokens and1315/// can have escape sequences in them in addition to the usual trigraph and1316/// escaped newline business. This routine handles this complexity.1317///1318/// The *StartToken sets the first token to be searched in this function and1319/// the *StartTokenByteOffset is the byte offset of the first token. Before1320/// returning, it updates the *StartToken to the TokNo of the token being found1321/// and sets *StartTokenByteOffset to the byte offset of the token in the1322/// string.1323/// Using these two parameters can reduce the time complexity from O(n^2) to1324/// O(n) if one wants to get the location of byte for all the tokens in a1325/// string.1326///1327SourceLocation1328StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,1329const LangOptions &Features,1330const TargetInfo &Target, unsigned *StartToken,1331unsigned *StartTokenByteOffset) const {1332assert((getKind() == StringLiteralKind::Ordinary ||1333getKind() == StringLiteralKind::UTF8 ||1334getKind() == StringLiteralKind::Unevaluated) &&1335"Only narrow string literals are currently supported");13361337// Loop over all of the tokens in this string until we find the one that1338// contains the byte we're looking for.1339unsigned TokNo = 0;1340unsigned StringOffset = 0;1341if (StartToken)1342TokNo = *StartToken;1343if (StartTokenByteOffset) {1344StringOffset = *StartTokenByteOffset;1345ByteNo -= StringOffset;1346}1347while (true) {1348assert(TokNo < getNumConcatenated() && "Invalid byte number!");1349SourceLocation StrTokLoc = getStrTokenLoc(TokNo);13501351// Get the spelling of the string so that we can get the data that makes up1352// the string literal, not the identifier for the macro it is potentially1353// expanded through.1354SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);13551356// Re-lex the token to get its length and original spelling.1357std::pair<FileID, unsigned> LocInfo =1358SM.getDecomposedLoc(StrTokSpellingLoc);1359bool Invalid = false;1360StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);1361if (Invalid) {1362if (StartTokenByteOffset != nullptr)1363*StartTokenByteOffset = StringOffset;1364if (StartToken != nullptr)1365*StartToken = TokNo;1366return StrTokSpellingLoc;1367}13681369const char *StrData = Buffer.data()+LocInfo.second;13701371// Create a lexer starting at the beginning of this token.1372Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,1373Buffer.begin(), StrData, Buffer.end());1374Token TheTok;1375TheLexer.LexFromRawLexer(TheTok);13761377// Use the StringLiteralParser to compute the length of the string in bytes.1378StringLiteralParser SLP(TheTok, SM, Features, Target);1379unsigned TokNumBytes = SLP.GetStringLength();13801381// If the byte is in this token, return the location of the byte.1382if (ByteNo < TokNumBytes ||1383(ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {1384unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);13851386// Now that we know the offset of the token in the spelling, use the1387// preprocessor to get the offset in the original source.1388if (StartTokenByteOffset != nullptr)1389*StartTokenByteOffset = StringOffset;1390if (StartToken != nullptr)1391*StartToken = TokNo;1392return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);1393}13941395// Move to the next string token.1396StringOffset += TokNumBytes;1397++TokNo;1398ByteNo -= TokNumBytes;1399}1400}14011402/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it1403/// corresponds to, e.g. "sizeof" or "[pre]++".1404StringRef UnaryOperator::getOpcodeStr(Opcode Op) {1405switch (Op) {1406#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;1407#include "clang/AST/OperationKinds.def"1408}1409llvm_unreachable("Unknown unary operator");1410}14111412UnaryOperatorKind1413UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {1414switch (OO) {1415default: llvm_unreachable("No unary operator for overloaded function");1416case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;1417case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;1418case OO_Amp: return UO_AddrOf;1419case OO_Star: return UO_Deref;1420case OO_Plus: return UO_Plus;1421case OO_Minus: return UO_Minus;1422case OO_Tilde: return UO_Not;1423case OO_Exclaim: return UO_LNot;1424case OO_Coawait: return UO_Coawait;1425}1426}14271428OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {1429switch (Opc) {1430case UO_PostInc: case UO_PreInc: return OO_PlusPlus;1431case UO_PostDec: case UO_PreDec: return OO_MinusMinus;1432case UO_AddrOf: return OO_Amp;1433case UO_Deref: return OO_Star;1434case UO_Plus: return OO_Plus;1435case UO_Minus: return OO_Minus;1436case UO_Not: return OO_Tilde;1437case UO_LNot: return OO_Exclaim;1438case UO_Coawait: return OO_Coawait;1439default: return OO_None;1440}1441}144214431444//===----------------------------------------------------------------------===//1445// Postfix Operators.1446//===----------------------------------------------------------------------===//14471448CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,1449ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,1450SourceLocation RParenLoc, FPOptionsOverride FPFeatures,1451unsigned MinNumArgs, ADLCallKind UsesADL)1452: Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {1453NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);1454unsigned NumPreArgs = PreArgs.size();1455CallExprBits.NumPreArgs = NumPreArgs;1456assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");14571458unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);1459CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;1460assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&1461"OffsetToTrailingObjects overflow!");14621463CallExprBits.UsesADL = static_cast<bool>(UsesADL);14641465setCallee(Fn);1466for (unsigned I = 0; I != NumPreArgs; ++I)1467setPreArg(I, PreArgs[I]);1468for (unsigned I = 0; I != Args.size(); ++I)1469setArg(I, Args[I]);1470for (unsigned I = Args.size(); I != NumArgs; ++I)1471setArg(I, nullptr);14721473this->computeDependence();14741475CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();1476if (hasStoredFPFeatures())1477setStoredFPFeatures(FPFeatures);1478}14791480CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,1481bool HasFPFeatures, EmptyShell Empty)1482: Expr(SC, Empty), NumArgs(NumArgs) {1483CallExprBits.NumPreArgs = NumPreArgs;1484assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");14851486unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);1487CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;1488assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&1489"OffsetToTrailingObjects overflow!");1490CallExprBits.HasFPFeatures = HasFPFeatures;1491}14921493CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,1494ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,1495SourceLocation RParenLoc,1496FPOptionsOverride FPFeatures, unsigned MinNumArgs,1497ADLCallKind UsesADL) {1498unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);1499unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(1500/*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());1501void *Mem =1502Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));1503return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,1504RParenLoc, FPFeatures, MinNumArgs, UsesADL);1505}15061507CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,1508ExprValueKind VK, SourceLocation RParenLoc,1509ADLCallKind UsesADL) {1510assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&1511"Misaligned memory in CallExpr::CreateTemporary!");1512return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,1513VK, RParenLoc, FPOptionsOverride(),1514/*MinNumArgs=*/0, UsesADL);1515}15161517CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,1518bool HasFPFeatures, EmptyShell Empty) {1519unsigned SizeOfTrailingObjects =1520CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);1521void *Mem =1522Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));1523return new (Mem)1524CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty);1525}15261527unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {1528switch (SC) {1529case CallExprClass:1530return sizeof(CallExpr);1531case CXXOperatorCallExprClass:1532return sizeof(CXXOperatorCallExpr);1533case CXXMemberCallExprClass:1534return sizeof(CXXMemberCallExpr);1535case UserDefinedLiteralClass:1536return sizeof(UserDefinedLiteral);1537case CUDAKernelCallExprClass:1538return sizeof(CUDAKernelCallExpr);1539default:1540llvm_unreachable("unexpected class deriving from CallExpr!");1541}1542}15431544Decl *Expr::getReferencedDeclOfCallee() {1545Expr *CEE = IgnoreParenImpCasts();15461547while (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE))1548CEE = NTTP->getReplacement()->IgnoreParenImpCasts();15491550// If we're calling a dereference, look at the pointer instead.1551while (true) {1552if (auto *BO = dyn_cast<BinaryOperator>(CEE)) {1553if (BO->isPtrMemOp()) {1554CEE = BO->getRHS()->IgnoreParenImpCasts();1555continue;1556}1557} else if (auto *UO = dyn_cast<UnaryOperator>(CEE)) {1558if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||1559UO->getOpcode() == UO_Plus) {1560CEE = UO->getSubExpr()->IgnoreParenImpCasts();1561continue;1562}1563}1564break;1565}15661567if (auto *DRE = dyn_cast<DeclRefExpr>(CEE))1568return DRE->getDecl();1569if (auto *ME = dyn_cast<MemberExpr>(CEE))1570return ME->getMemberDecl();1571if (auto *BE = dyn_cast<BlockExpr>(CEE))1572return BE->getBlockDecl();15731574return nullptr;1575}15761577/// If this is a call to a builtin, return the builtin ID. If not, return 0.1578unsigned CallExpr::getBuiltinCallee() const {1579const auto *FDecl = getDirectCallee();1580return FDecl ? FDecl->getBuiltinID() : 0;1581}15821583bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {1584if (unsigned BI = getBuiltinCallee())1585return Ctx.BuiltinInfo.isUnevaluated(BI);1586return false;1587}15881589QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {1590const Expr *Callee = getCallee();1591QualType CalleeType = Callee->getType();1592if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {1593CalleeType = FnTypePtr->getPointeeType();1594} else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {1595CalleeType = BPT->getPointeeType();1596} else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {1597if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))1598return Ctx.VoidTy;15991600if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens()))1601return Ctx.DependentTy;16021603// This should never be overloaded and so should never return null.1604CalleeType = Expr::findBoundMemberType(Callee);1605assert(!CalleeType.isNull());1606} else if (CalleeType->isRecordType()) {1607// If the Callee is a record type, then it is a not-yet-resolved1608// dependent call to the call operator of that type.1609return Ctx.DependentTy;1610} else if (CalleeType->isDependentType() ||1611CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {1612return Ctx.DependentTy;1613}16141615const FunctionType *FnType = CalleeType->castAs<FunctionType>();1616return FnType->getReturnType();1617}16181619const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {1620// If the return type is a struct, union, or enum that is marked nodiscard,1621// then return the return type attribute.1622if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())1623if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())1624return A;16251626for (const auto *TD = getCallReturnType(Ctx)->getAs<TypedefType>(); TD;1627TD = TD->desugar()->getAs<TypedefType>())1628if (const auto *A = TD->getDecl()->getAttr<WarnUnusedResultAttr>())1629return A;16301631// Otherwise, see if the callee is marked nodiscard and return that attribute1632// instead.1633const Decl *D = getCalleeDecl();1634return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;1635}16361637SourceLocation CallExpr::getBeginLoc() const {1638if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(this))1639return OCE->getBeginLoc();16401641SourceLocation begin = getCallee()->getBeginLoc();1642if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))1643begin = getArg(0)->getBeginLoc();1644return begin;1645}1646SourceLocation CallExpr::getEndLoc() const {1647if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(this))1648return OCE->getEndLoc();16491650SourceLocation end = getRParenLoc();1651if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))1652end = getArg(getNumArgs() - 1)->getEndLoc();1653return end;1654}16551656OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,1657SourceLocation OperatorLoc,1658TypeSourceInfo *tsi,1659ArrayRef<OffsetOfNode> comps,1660ArrayRef<Expr*> exprs,1661SourceLocation RParenLoc) {1662void *Mem = C.Allocate(1663totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));16641665return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,1666RParenLoc);1667}16681669OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,1670unsigned numComps, unsigned numExprs) {1671void *Mem =1672C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));1673return new (Mem) OffsetOfExpr(numComps, numExprs);1674}16751676OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,1677SourceLocation OperatorLoc, TypeSourceInfo *tsi,1678ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs,1679SourceLocation RParenLoc)1680: Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary),1681OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),1682NumComps(comps.size()), NumExprs(exprs.size()) {1683for (unsigned i = 0; i != comps.size(); ++i)1684setComponent(i, comps[i]);1685for (unsigned i = 0; i != exprs.size(); ++i)1686setIndexExpr(i, exprs[i]);16871688setDependence(computeDependence(this));1689}16901691IdentifierInfo *OffsetOfNode::getFieldName() const {1692assert(getKind() == Field || getKind() == Identifier);1693if (getKind() == Field)1694return getField()->getIdentifier();16951696return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);1697}16981699UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(1700UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,1701SourceLocation op, SourceLocation rp)1702: Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary),1703OpLoc(op), RParenLoc(rp) {1704assert(ExprKind <= UETT_Last && "invalid enum value!");1705UnaryExprOrTypeTraitExprBits.Kind = ExprKind;1706assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&1707"UnaryExprOrTypeTraitExprBits.Kind overflow!");1708UnaryExprOrTypeTraitExprBits.IsType = false;1709Argument.Ex = E;1710setDependence(computeDependence(this));1711}17121713MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,1714NestedNameSpecifierLoc QualifierLoc,1715SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,1716DeclAccessPair FoundDecl,1717const DeclarationNameInfo &NameInfo,1718const TemplateArgumentListInfo *TemplateArgs, QualType T,1719ExprValueKind VK, ExprObjectKind OK,1720NonOdrUseReason NOUR)1721: Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),1722MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {1723assert(!NameInfo.getName() ||1724MemberDecl->getDeclName() == NameInfo.getName());1725MemberExprBits.IsArrow = IsArrow;1726MemberExprBits.HasQualifier = QualifierLoc.hasQualifier();1727MemberExprBits.HasFoundDecl =1728FoundDecl.getDecl() != MemberDecl ||1729FoundDecl.getAccess() != MemberDecl->getAccess();1730MemberExprBits.HasTemplateKWAndArgsInfo =1731TemplateArgs || TemplateKWLoc.isValid();1732MemberExprBits.HadMultipleCandidates = false;1733MemberExprBits.NonOdrUseReason = NOUR;1734MemberExprBits.OperatorLoc = OperatorLoc;17351736if (hasQualifier())1737new (getTrailingObjects<NestedNameSpecifierLoc>())1738NestedNameSpecifierLoc(QualifierLoc);1739if (hasFoundDecl())1740*getTrailingObjects<DeclAccessPair>() = FoundDecl;1741if (TemplateArgs) {1742auto Deps = TemplateArgumentDependence::None;1743getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(1744TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),1745Deps);1746} else if (TemplateKWLoc.isValid()) {1747getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(1748TemplateKWLoc);1749}1750setDependence(computeDependence(this));1751}17521753MemberExpr *MemberExpr::Create(1754const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,1755NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,1756ValueDecl *MemberDecl, DeclAccessPair FoundDecl,1757DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,1758QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {1759bool HasQualifier = QualifierLoc.hasQualifier();1760bool HasFoundDecl = FoundDecl.getDecl() != MemberDecl ||1761FoundDecl.getAccess() != MemberDecl->getAccess();1762bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();1763std::size_t Size =1764totalSizeToAlloc<NestedNameSpecifierLoc, DeclAccessPair,1765ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(1766HasQualifier, HasFoundDecl, HasTemplateKWAndArgsInfo,1767TemplateArgs ? TemplateArgs->size() : 0);17681769void *Mem = C.Allocate(Size, alignof(MemberExpr));1770return new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, QualifierLoc,1771TemplateKWLoc, MemberDecl, FoundDecl, NameInfo,1772TemplateArgs, T, VK, OK, NOUR);1773}17741775MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,1776bool HasQualifier, bool HasFoundDecl,1777bool HasTemplateKWAndArgsInfo,1778unsigned NumTemplateArgs) {1779assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&1780"template args but no template arg info?");1781std::size_t Size =1782totalSizeToAlloc<NestedNameSpecifierLoc, DeclAccessPair,1783ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(1784HasQualifier, HasFoundDecl, HasTemplateKWAndArgsInfo,1785NumTemplateArgs);1786void *Mem = Context.Allocate(Size, alignof(MemberExpr));1787return new (Mem) MemberExpr(EmptyShell());1788}17891790void MemberExpr::setMemberDecl(ValueDecl *NewD) {1791MemberDecl = NewD;1792if (getType()->isUndeducedType())1793setType(NewD->getType());1794setDependence(computeDependence(this));1795}17961797SourceLocation MemberExpr::getBeginLoc() const {1798if (isImplicitAccess()) {1799if (hasQualifier())1800return getQualifierLoc().getBeginLoc();1801return MemberLoc;1802}18031804// FIXME: We don't want this to happen. Rather, we should be able to1805// detect all kinds of implicit accesses more cleanly.1806SourceLocation BaseStartLoc = getBase()->getBeginLoc();1807if (BaseStartLoc.isValid())1808return BaseStartLoc;1809return MemberLoc;1810}1811SourceLocation MemberExpr::getEndLoc() const {1812SourceLocation EndLoc = getMemberNameInfo().getEndLoc();1813if (hasExplicitTemplateArgs())1814EndLoc = getRAngleLoc();1815else if (EndLoc.isInvalid())1816EndLoc = getBase()->getEndLoc();1817return EndLoc;1818}18191820bool CastExpr::CastConsistency() const {1821switch (getCastKind()) {1822case CK_DerivedToBase:1823case CK_UncheckedDerivedToBase:1824case CK_DerivedToBaseMemberPointer:1825case CK_BaseToDerived:1826case CK_BaseToDerivedMemberPointer:1827assert(!path_empty() && "Cast kind should have a base path!");1828break;18291830case CK_CPointerToObjCPointerCast:1831assert(getType()->isObjCObjectPointerType());1832assert(getSubExpr()->getType()->isPointerType());1833goto CheckNoBasePath;18341835case CK_BlockPointerToObjCPointerCast:1836assert(getType()->isObjCObjectPointerType());1837assert(getSubExpr()->getType()->isBlockPointerType());1838goto CheckNoBasePath;18391840case CK_ReinterpretMemberPointer:1841assert(getType()->isMemberPointerType());1842assert(getSubExpr()->getType()->isMemberPointerType());1843goto CheckNoBasePath;18441845case CK_BitCast:1846// Arbitrary casts to C pointer types count as bitcasts.1847// Otherwise, we should only have block and ObjC pointer casts1848// here if they stay within the type kind.1849if (!getType()->isPointerType()) {1850assert(getType()->isObjCObjectPointerType() ==1851getSubExpr()->getType()->isObjCObjectPointerType());1852assert(getType()->isBlockPointerType() ==1853getSubExpr()->getType()->isBlockPointerType());1854}1855goto CheckNoBasePath;18561857case CK_AnyPointerToBlockPointerCast:1858assert(getType()->isBlockPointerType());1859assert(getSubExpr()->getType()->isAnyPointerType() &&1860!getSubExpr()->getType()->isBlockPointerType());1861goto CheckNoBasePath;18621863case CK_CopyAndAutoreleaseBlockObject:1864assert(getType()->isBlockPointerType());1865assert(getSubExpr()->getType()->isBlockPointerType());1866goto CheckNoBasePath;18671868case CK_FunctionToPointerDecay:1869assert(getType()->isPointerType());1870assert(getSubExpr()->getType()->isFunctionType());1871goto CheckNoBasePath;18721873case CK_AddressSpaceConversion: {1874auto Ty = getType();1875auto SETy = getSubExpr()->getType();1876assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));1877if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {1878Ty = Ty->getPointeeType();1879SETy = SETy->getPointeeType();1880}1881assert((Ty->isDependentType() || SETy->isDependentType()) ||1882(!Ty.isNull() && !SETy.isNull() &&1883Ty.getAddressSpace() != SETy.getAddressSpace()));1884goto CheckNoBasePath;1885}1886// These should not have an inheritance path.1887case CK_Dynamic:1888case CK_ToUnion:1889case CK_ArrayToPointerDecay:1890case CK_NullToMemberPointer:1891case CK_NullToPointer:1892case CK_ConstructorConversion:1893case CK_IntegralToPointer:1894case CK_PointerToIntegral:1895case CK_ToVoid:1896case CK_VectorSplat:1897case CK_IntegralCast:1898case CK_BooleanToSignedIntegral:1899case CK_IntegralToFloating:1900case CK_FloatingToIntegral:1901case CK_FloatingCast:1902case CK_ObjCObjectLValueCast:1903case CK_FloatingRealToComplex:1904case CK_FloatingComplexToReal:1905case CK_FloatingComplexCast:1906case CK_FloatingComplexToIntegralComplex:1907case CK_IntegralRealToComplex:1908case CK_IntegralComplexToReal:1909case CK_IntegralComplexCast:1910case CK_IntegralComplexToFloatingComplex:1911case CK_ARCProduceObject:1912case CK_ARCConsumeObject:1913case CK_ARCReclaimReturnedObject:1914case CK_ARCExtendBlockObject:1915case CK_ZeroToOCLOpaqueType:1916case CK_IntToOCLSampler:1917case CK_FloatingToFixedPoint:1918case CK_FixedPointToFloating:1919case CK_FixedPointCast:1920case CK_FixedPointToIntegral:1921case CK_IntegralToFixedPoint:1922case CK_MatrixCast:1923case CK_HLSLVectorTruncation:1924assert(!getType()->isBooleanType() && "unheralded conversion to bool");1925goto CheckNoBasePath;19261927case CK_Dependent:1928case CK_LValueToRValue:1929case CK_NoOp:1930case CK_AtomicToNonAtomic:1931case CK_NonAtomicToAtomic:1932case CK_PointerToBoolean:1933case CK_IntegralToBoolean:1934case CK_FloatingToBoolean:1935case CK_MemberPointerToBoolean:1936case CK_FloatingComplexToBoolean:1937case CK_IntegralComplexToBoolean:1938case CK_LValueBitCast: // -> bool&1939case CK_LValueToRValueBitCast:1940case CK_UserDefinedConversion: // operator bool()1941case CK_BuiltinFnToFnPtr:1942case CK_FixedPointToBoolean:1943case CK_HLSLArrayRValue:1944CheckNoBasePath:1945assert(path_empty() && "Cast kind should not have a base path!");1946break;1947}1948return true;1949}19501951const char *CastExpr::getCastKindName(CastKind CK) {1952switch (CK) {1953#define CAST_OPERATION(Name) case CK_##Name: return #Name;1954#include "clang/AST/OperationKinds.def"1955}1956llvm_unreachable("Unhandled cast kind!");1957}19581959namespace {1960// Skip over implicit nodes produced as part of semantic analysis.1961// Designed for use with IgnoreExprNodes.1962static Expr *ignoreImplicitSemaNodes(Expr *E) {1963if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))1964return Materialize->getSubExpr();19651966if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))1967return Binder->getSubExpr();19681969if (auto *Full = dyn_cast<FullExpr>(E))1970return Full->getSubExpr();19711972if (auto *CPLIE = dyn_cast<CXXParenListInitExpr>(E);1973CPLIE && CPLIE->getInitExprs().size() == 1)1974return CPLIE->getInitExprs()[0];19751976return E;1977}1978} // namespace19791980Expr *CastExpr::getSubExprAsWritten() {1981const Expr *SubExpr = nullptr;19821983for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {1984SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);19851986// Conversions by constructor and conversion functions have a1987// subexpression describing the call; strip it off.1988if (E->getCastKind() == CK_ConstructorConversion) {1989SubExpr = IgnoreExprNodes(cast<CXXConstructExpr>(SubExpr)->getArg(0),1990ignoreImplicitSemaNodes);1991} else if (E->getCastKind() == CK_UserDefinedConversion) {1992assert((isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) &&1993"Unexpected SubExpr for CK_UserDefinedConversion.");1994if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))1995SubExpr = MCE->getImplicitObjectArgument();1996}1997}19981999return const_cast<Expr *>(SubExpr);2000}20012002NamedDecl *CastExpr::getConversionFunction() const {2003const Expr *SubExpr = nullptr;20042005for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {2006SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);20072008if (E->getCastKind() == CK_ConstructorConversion)2009return cast<CXXConstructExpr>(SubExpr)->getConstructor();20102011if (E->getCastKind() == CK_UserDefinedConversion) {2012if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))2013return MCE->getMethodDecl();2014}2015}20162017return nullptr;2018}20192020CXXBaseSpecifier **CastExpr::path_buffer() {2021switch (getStmtClass()) {2022#define ABSTRACT_STMT(x)2023#define CASTEXPR(Type, Base) \2024case Stmt::Type##Class: \2025return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();2026#define STMT(Type, Base)2027#include "clang/AST/StmtNodes.inc"2028default:2029llvm_unreachable("non-cast expressions not possible here");2030}2031}20322033const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,2034QualType opType) {2035auto RD = unionType->castAs<RecordType>()->getDecl();2036return getTargetFieldForToUnionCast(RD, opType);2037}20382039const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,2040QualType OpType) {2041auto &Ctx = RD->getASTContext();2042RecordDecl::field_iterator Field, FieldEnd;2043for (Field = RD->field_begin(), FieldEnd = RD->field_end();2044Field != FieldEnd; ++Field) {2045if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&2046!Field->isUnnamedBitField()) {2047return *Field;2048}2049}2050return nullptr;2051}20522053FPOptionsOverride *CastExpr::getTrailingFPFeatures() {2054assert(hasStoredFPFeatures());2055switch (getStmtClass()) {2056case ImplicitCastExprClass:2057return static_cast<ImplicitCastExpr *>(this)2058->getTrailingObjects<FPOptionsOverride>();2059case CStyleCastExprClass:2060return static_cast<CStyleCastExpr *>(this)2061->getTrailingObjects<FPOptionsOverride>();2062case CXXFunctionalCastExprClass:2063return static_cast<CXXFunctionalCastExpr *>(this)2064->getTrailingObjects<FPOptionsOverride>();2065case CXXStaticCastExprClass:2066return static_cast<CXXStaticCastExpr *>(this)2067->getTrailingObjects<FPOptionsOverride>();2068default:2069llvm_unreachable("Cast does not have FPFeatures");2070}2071}20722073ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,2074CastKind Kind, Expr *Operand,2075const CXXCastPath *BasePath,2076ExprValueKind VK,2077FPOptionsOverride FPO) {2078unsigned PathSize = (BasePath ? BasePath->size() : 0);2079void *Buffer =2080C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(2081PathSize, FPO.requiresTrailingStorage()));2082// Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and2083// std::nullptr_t have special semantics not captured by CK_LValueToRValue.2084assert((Kind != CK_LValueToRValue ||2085!(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&2086"invalid type for lvalue-to-rvalue conversion");2087ImplicitCastExpr *E =2088new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK);2089if (PathSize)2090std::uninitialized_copy_n(BasePath->data(), BasePath->size(),2091E->getTrailingObjects<CXXBaseSpecifier *>());2092return E;2093}20942095ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,2096unsigned PathSize,2097bool HasFPFeatures) {2098void *Buffer =2099C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(2100PathSize, HasFPFeatures));2101return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures);2102}21032104CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,2105ExprValueKind VK, CastKind K, Expr *Op,2106const CXXCastPath *BasePath,2107FPOptionsOverride FPO,2108TypeSourceInfo *WrittenTy,2109SourceLocation L, SourceLocation R) {2110unsigned PathSize = (BasePath ? BasePath->size() : 0);2111void *Buffer =2112C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(2113PathSize, FPO.requiresTrailingStorage()));2114CStyleCastExpr *E =2115new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R);2116if (PathSize)2117std::uninitialized_copy_n(BasePath->data(), BasePath->size(),2118E->getTrailingObjects<CXXBaseSpecifier *>());2119return E;2120}21212122CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,2123unsigned PathSize,2124bool HasFPFeatures) {2125void *Buffer =2126C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(2127PathSize, HasFPFeatures));2128return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures);2129}21302131/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it2132/// corresponds to, e.g. "<<=".2133StringRef BinaryOperator::getOpcodeStr(Opcode Op) {2134switch (Op) {2135#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;2136#include "clang/AST/OperationKinds.def"2137}2138llvm_unreachable("Invalid OpCode!");2139}21402141BinaryOperatorKind2142BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {2143switch (OO) {2144default: llvm_unreachable("Not an overloadable binary operator");2145case OO_Plus: return BO_Add;2146case OO_Minus: return BO_Sub;2147case OO_Star: return BO_Mul;2148case OO_Slash: return BO_Div;2149case OO_Percent: return BO_Rem;2150case OO_Caret: return BO_Xor;2151case OO_Amp: return BO_And;2152case OO_Pipe: return BO_Or;2153case OO_Equal: return BO_Assign;2154case OO_Spaceship: return BO_Cmp;2155case OO_Less: return BO_LT;2156case OO_Greater: return BO_GT;2157case OO_PlusEqual: return BO_AddAssign;2158case OO_MinusEqual: return BO_SubAssign;2159case OO_StarEqual: return BO_MulAssign;2160case OO_SlashEqual: return BO_DivAssign;2161case OO_PercentEqual: return BO_RemAssign;2162case OO_CaretEqual: return BO_XorAssign;2163case OO_AmpEqual: return BO_AndAssign;2164case OO_PipeEqual: return BO_OrAssign;2165case OO_LessLess: return BO_Shl;2166case OO_GreaterGreater: return BO_Shr;2167case OO_LessLessEqual: return BO_ShlAssign;2168case OO_GreaterGreaterEqual: return BO_ShrAssign;2169case OO_EqualEqual: return BO_EQ;2170case OO_ExclaimEqual: return BO_NE;2171case OO_LessEqual: return BO_LE;2172case OO_GreaterEqual: return BO_GE;2173case OO_AmpAmp: return BO_LAnd;2174case OO_PipePipe: return BO_LOr;2175case OO_Comma: return BO_Comma;2176case OO_ArrowStar: return BO_PtrMemI;2177}2178}21792180OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {2181static const OverloadedOperatorKind OverOps[] = {2182/* .* Cannot be overloaded */OO_None, OO_ArrowStar,2183OO_Star, OO_Slash, OO_Percent,2184OO_Plus, OO_Minus,2185OO_LessLess, OO_GreaterGreater,2186OO_Spaceship,2187OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,2188OO_EqualEqual, OO_ExclaimEqual,2189OO_Amp,2190OO_Caret,2191OO_Pipe,2192OO_AmpAmp,2193OO_PipePipe,2194OO_Equal, OO_StarEqual,2195OO_SlashEqual, OO_PercentEqual,2196OO_PlusEqual, OO_MinusEqual,2197OO_LessLessEqual, OO_GreaterGreaterEqual,2198OO_AmpEqual, OO_CaretEqual,2199OO_PipeEqual,2200OO_Comma2201};2202return OverOps[Opc];2203}22042205bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,2206Opcode Opc,2207const Expr *LHS,2208const Expr *RHS) {2209if (Opc != BO_Add)2210return false;22112212// Check that we have one pointer and one integer operand.2213const Expr *PExp;2214if (LHS->getType()->isPointerType()) {2215if (!RHS->getType()->isIntegerType())2216return false;2217PExp = LHS;2218} else if (RHS->getType()->isPointerType()) {2219if (!LHS->getType()->isIntegerType())2220return false;2221PExp = RHS;2222} else {2223return false;2224}22252226// Check that the pointer is a nullptr.2227if (!PExp->IgnoreParenCasts()2228->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))2229return false;22302231// Check that the pointee type is char-sized.2232const PointerType *PTy = PExp->getType()->getAs<PointerType>();2233if (!PTy || !PTy->getPointeeType()->isCharType())2234return false;22352236return true;2237}22382239SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Kind,2240QualType ResultTy, SourceLocation BLoc,2241SourceLocation RParenLoc,2242DeclContext *ParentContext)2243: Expr(SourceLocExprClass, ResultTy, VK_PRValue, OK_Ordinary),2244BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {2245SourceLocExprBits.Kind = llvm::to_underlying(Kind);2246// In dependent contexts, function names may change.2247setDependence(MayBeDependent(Kind) && ParentContext->isDependentContext()2248? ExprDependence::Value2249: ExprDependence::None);2250}22512252StringRef SourceLocExpr::getBuiltinStr() const {2253switch (getIdentKind()) {2254case SourceLocIdentKind::File:2255return "__builtin_FILE";2256case SourceLocIdentKind::FileName:2257return "__builtin_FILE_NAME";2258case SourceLocIdentKind::Function:2259return "__builtin_FUNCTION";2260case SourceLocIdentKind::FuncSig:2261return "__builtin_FUNCSIG";2262case SourceLocIdentKind::Line:2263return "__builtin_LINE";2264case SourceLocIdentKind::Column:2265return "__builtin_COLUMN";2266case SourceLocIdentKind::SourceLocStruct:2267return "__builtin_source_location";2268}2269llvm_unreachable("unexpected IdentKind!");2270}22712272APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,2273const Expr *DefaultExpr) const {2274SourceLocation Loc;2275const DeclContext *Context;22762277if (const auto *DIE = dyn_cast_if_present<CXXDefaultInitExpr>(DefaultExpr)) {2278Loc = DIE->getUsedLocation();2279Context = DIE->getUsedContext();2280} else if (const auto *DAE =2281dyn_cast_if_present<CXXDefaultArgExpr>(DefaultExpr)) {2282Loc = DAE->getUsedLocation();2283Context = DAE->getUsedContext();2284} else {2285Loc = getLocation();2286Context = getParentContext();2287}22882289PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(2290Ctx.getSourceManager().getExpansionRange(Loc).getEnd());22912292auto MakeStringLiteral = [&](StringRef Tmp) {2293using LValuePathEntry = APValue::LValuePathEntry;2294StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);2295// Decay the string to a pointer to the first character.2296LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};2297return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);2298};22992300switch (getIdentKind()) {2301case SourceLocIdentKind::FileName: {2302// __builtin_FILE_NAME() is a Clang-specific extension that expands to the2303// the last part of __builtin_FILE().2304SmallString<256> FileName;2305clang::Preprocessor::processPathToFileName(2306FileName, PLoc, Ctx.getLangOpts(), Ctx.getTargetInfo());2307return MakeStringLiteral(FileName);2308}2309case SourceLocIdentKind::File: {2310SmallString<256> Path(PLoc.getFilename());2311clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(),2312Ctx.getTargetInfo());2313return MakeStringLiteral(Path);2314}2315case SourceLocIdentKind::Function:2316case SourceLocIdentKind::FuncSig: {2317const auto *CurDecl = dyn_cast<Decl>(Context);2318const auto Kind = getIdentKind() == SourceLocIdentKind::Function2319? PredefinedIdentKind::Function2320: PredefinedIdentKind::FuncSig;2321return MakeStringLiteral(2322CurDecl ? PredefinedExpr::ComputeName(Kind, CurDecl) : std::string(""));2323}2324case SourceLocIdentKind::Line:2325return APValue(Ctx.MakeIntValue(PLoc.getLine(), Ctx.UnsignedIntTy));2326case SourceLocIdentKind::Column:2327return APValue(Ctx.MakeIntValue(PLoc.getColumn(), Ctx.UnsignedIntTy));2328case SourceLocIdentKind::SourceLocStruct: {2329// Fill in a std::source_location::__impl structure, by creating an2330// artificial file-scoped CompoundLiteralExpr, and returning a pointer to2331// that.2332const CXXRecordDecl *ImplDecl = getType()->getPointeeCXXRecordDecl();2333assert(ImplDecl);23342335// Construct an APValue for the __impl struct, and get or create a Decl2336// corresponding to that. Note that we've already verified that the shape of2337// the ImplDecl type is as expected.23382339APValue Value(APValue::UninitStruct(), 0, 4);2340for (const FieldDecl *F : ImplDecl->fields()) {2341StringRef Name = F->getName();2342if (Name == "_M_file_name") {2343SmallString<256> Path(PLoc.getFilename());2344clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(),2345Ctx.getTargetInfo());2346Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(Path);2347} else if (Name == "_M_function_name") {2348// Note: this emits the PrettyFunction name -- different than what2349// __builtin_FUNCTION() above returns!2350const auto *CurDecl = dyn_cast<Decl>(Context);2351Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(2352CurDecl && !isa<TranslationUnitDecl>(CurDecl)2353? StringRef(PredefinedExpr::ComputeName(2354PredefinedIdentKind::PrettyFunction, CurDecl))2355: "");2356} else if (Name == "_M_line") {2357llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getLine(), F->getType());2358Value.getStructField(F->getFieldIndex()) = APValue(IntVal);2359} else if (Name == "_M_column") {2360llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getColumn(), F->getType());2361Value.getStructField(F->getFieldIndex()) = APValue(IntVal);2362}2363}23642365UnnamedGlobalConstantDecl *GV =2366Ctx.getUnnamedGlobalConstantDecl(getType()->getPointeeType(), Value);23672368return APValue(GV, CharUnits::Zero(), ArrayRef<APValue::LValuePathEntry>{},2369false);2370}2371}2372llvm_unreachable("unhandled case");2373}23742375EmbedExpr::EmbedExpr(const ASTContext &Ctx, SourceLocation Loc,2376EmbedDataStorage *Data, unsigned Begin,2377unsigned NumOfElements)2378: Expr(EmbedExprClass, Ctx.IntTy, VK_PRValue, OK_Ordinary),2379EmbedKeywordLoc(Loc), Ctx(&Ctx), Data(Data), Begin(Begin),2380NumOfElements(NumOfElements) {2381setDependence(ExprDependence::None);2382FakeChildNode = IntegerLiteral::Create(2383Ctx, llvm::APInt::getZero(Ctx.getTypeSize(getType())), getType(), Loc);2384}23852386InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,2387ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)2388: Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),2389InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),2390RBraceLoc(rbraceloc), AltForm(nullptr, true) {2391sawArrayRangeDesignator(false);2392InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());23932394setDependence(computeDependence(this));2395}23962397void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {2398if (NumInits > InitExprs.size())2399InitExprs.reserve(C, NumInits);2400}24012402void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {2403InitExprs.resize(C, NumInits, nullptr);2404}24052406Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {2407if (Init >= InitExprs.size()) {2408InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);2409setInit(Init, expr);2410return nullptr;2411}24122413Expr *Result = cast_or_null<Expr>(InitExprs[Init]);2414setInit(Init, expr);2415return Result;2416}24172418void InitListExpr::setArrayFiller(Expr *filler) {2419assert(!hasArrayFiller() && "Filler already set!");2420ArrayFillerOrUnionFieldInit = filler;2421// Fill out any "holes" in the array due to designated initializers.2422Expr **inits = getInits();2423for (unsigned i = 0, e = getNumInits(); i != e; ++i)2424if (inits[i] == nullptr)2425inits[i] = filler;2426}24272428bool InitListExpr::isStringLiteralInit() const {2429if (getNumInits() != 1)2430return false;2431const ArrayType *AT = getType()->getAsArrayTypeUnsafe();2432if (!AT || !AT->getElementType()->isIntegerType())2433return false;2434// It is possible for getInit() to return null.2435const Expr *Init = getInit(0);2436if (!Init)2437return false;2438Init = Init->IgnoreParenImpCasts();2439return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);2440}24412442bool InitListExpr::isTransparent() const {2443assert(isSemanticForm() && "syntactic form never semantically transparent");24442445// A glvalue InitListExpr is always just sugar.2446if (isGLValue()) {2447assert(getNumInits() == 1 && "multiple inits in glvalue init list");2448return true;2449}24502451// Otherwise, we're sugar if and only if we have exactly one initializer that2452// is of the same type.2453if (getNumInits() != 1 || !getInit(0))2454return false;24552456// Don't confuse aggregate initialization of a struct X { X &x; }; with a2457// transparent struct copy.2458if (!getInit(0)->isPRValue() && getType()->isRecordType())2459return false;24602461return getType().getCanonicalType() ==2462getInit(0)->getType().getCanonicalType();2463}24642465bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {2466assert(isSyntacticForm() && "only test syntactic form as zero initializer");24672468if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {2469return false;2470}24712472const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());2473return Lit && Lit->getValue() == 0;2474}24752476SourceLocation InitListExpr::getBeginLoc() const {2477if (InitListExpr *SyntacticForm = getSyntacticForm())2478return SyntacticForm->getBeginLoc();2479SourceLocation Beg = LBraceLoc;2480if (Beg.isInvalid()) {2481// Find the first non-null initializer.2482for (InitExprsTy::const_iterator I = InitExprs.begin(),2483E = InitExprs.end();2484I != E; ++I) {2485if (Stmt *S = *I) {2486Beg = S->getBeginLoc();2487break;2488}2489}2490}2491return Beg;2492}24932494SourceLocation InitListExpr::getEndLoc() const {2495if (InitListExpr *SyntacticForm = getSyntacticForm())2496return SyntacticForm->getEndLoc();2497SourceLocation End = RBraceLoc;2498if (End.isInvalid()) {2499// Find the first non-null initializer from the end.2500for (Stmt *S : llvm::reverse(InitExprs)) {2501if (S) {2502End = S->getEndLoc();2503break;2504}2505}2506}2507return End;2508}25092510/// getFunctionType - Return the underlying function type for this block.2511///2512const FunctionProtoType *BlockExpr::getFunctionType() const {2513// The block pointer is never sugared, but the function type might be.2514return cast<BlockPointerType>(getType())2515->getPointeeType()->castAs<FunctionProtoType>();2516}25172518SourceLocation BlockExpr::getCaretLocation() const {2519return TheBlock->getCaretLocation();2520}2521const Stmt *BlockExpr::getBody() const {2522return TheBlock->getBody();2523}2524Stmt *BlockExpr::getBody() {2525return TheBlock->getBody();2526}252725282529//===----------------------------------------------------------------------===//2530// Generic Expression Routines2531//===----------------------------------------------------------------------===//25322533bool Expr::isReadIfDiscardedInCPlusPlus11() const {2534// In C++11, discarded-value expressions of a certain form are special,2535// according to [expr]p10:2536// The lvalue-to-rvalue conversion (4.1) is applied only if the2537// expression is a glvalue of volatile-qualified type and it has2538// one of the following forms:2539if (!isGLValue() || !getType().isVolatileQualified())2540return false;25412542const Expr *E = IgnoreParens();25432544// - id-expression (5.1.1),2545if (isa<DeclRefExpr>(E))2546return true;25472548// - subscripting (5.2.1),2549if (isa<ArraySubscriptExpr>(E))2550return true;25512552// - class member access (5.2.5),2553if (isa<MemberExpr>(E))2554return true;25552556// - indirection (5.3.1),2557if (auto *UO = dyn_cast<UnaryOperator>(E))2558if (UO->getOpcode() == UO_Deref)2559return true;25602561if (auto *BO = dyn_cast<BinaryOperator>(E)) {2562// - pointer-to-member operation (5.5),2563if (BO->isPtrMemOp())2564return true;25652566// - comma expression (5.18) where the right operand is one of the above.2567if (BO->getOpcode() == BO_Comma)2568return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();2569}25702571// - conditional expression (5.16) where both the second and the third2572// operands are one of the above, or2573if (auto *CO = dyn_cast<ConditionalOperator>(E))2574return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&2575CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();2576// The related edge case of "*x ?: *x".2577if (auto *BCO =2578dyn_cast<BinaryConditionalOperator>(E)) {2579if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))2580return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&2581BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();2582}25832584// Objective-C++ extensions to the rule.2585if (isa<ObjCIvarRefExpr>(E))2586return true;2587if (const auto *POE = dyn_cast<PseudoObjectExpr>(E)) {2588if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(POE->getSyntacticForm()))2589return true;2590}25912592return false;2593}25942595/// isUnusedResultAWarning - Return true if this immediate expression should2596/// be warned about if the result is unused. If so, fill in Loc and Ranges2597/// with location to warn on and the source range[s] to report with the2598/// warning.2599bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,2600SourceRange &R1, SourceRange &R2,2601ASTContext &Ctx) const {2602// Don't warn if the expr is type dependent. The type could end up2603// instantiating to void.2604if (isTypeDependent())2605return false;26062607switch (getStmtClass()) {2608default:2609if (getType()->isVoidType())2610return false;2611WarnE = this;2612Loc = getExprLoc();2613R1 = getSourceRange();2614return true;2615case ParenExprClass:2616return cast<ParenExpr>(this)->getSubExpr()->2617isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2618case GenericSelectionExprClass:2619return cast<GenericSelectionExpr>(this)->getResultExpr()->2620isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2621case CoawaitExprClass:2622case CoyieldExprClass:2623return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->2624isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2625case ChooseExprClass:2626return cast<ChooseExpr>(this)->getChosenSubExpr()->2627isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2628case UnaryOperatorClass: {2629const UnaryOperator *UO = cast<UnaryOperator>(this);26302631switch (UO->getOpcode()) {2632case UO_Plus:2633case UO_Minus:2634case UO_AddrOf:2635case UO_Not:2636case UO_LNot:2637case UO_Deref:2638break;2639case UO_Coawait:2640// This is just the 'operator co_await' call inside the guts of a2641// dependent co_await call.2642case UO_PostInc:2643case UO_PostDec:2644case UO_PreInc:2645case UO_PreDec: // ++/--2646return false; // Not a warning.2647case UO_Real:2648case UO_Imag:2649// accessing a piece of a volatile complex is a side-effect.2650if (Ctx.getCanonicalType(UO->getSubExpr()->getType())2651.isVolatileQualified())2652return false;2653break;2654case UO_Extension:2655return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2656}2657WarnE = this;2658Loc = UO->getOperatorLoc();2659R1 = UO->getSubExpr()->getSourceRange();2660return true;2661}2662case BinaryOperatorClass: {2663const BinaryOperator *BO = cast<BinaryOperator>(this);2664switch (BO->getOpcode()) {2665default:2666break;2667// Consider the RHS of comma for side effects. LHS was checked by2668// Sema::CheckCommaOperands.2669case BO_Comma:2670// ((foo = <blah>), 0) is an idiom for hiding the result (and2671// lvalue-ness) of an assignment written in a macro.2672if (IntegerLiteral *IE =2673dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))2674if (IE->getValue() == 0)2675return false;2676return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2677// Consider '||', '&&' to have side effects if the LHS or RHS does.2678case BO_LAnd:2679case BO_LOr:2680if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||2681!BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))2682return false;2683break;2684}2685if (BO->isAssignmentOp())2686return false;2687WarnE = this;2688Loc = BO->getOperatorLoc();2689R1 = BO->getLHS()->getSourceRange();2690R2 = BO->getRHS()->getSourceRange();2691return true;2692}2693case CompoundAssignOperatorClass:2694case VAArgExprClass:2695case AtomicExprClass:2696return false;26972698case ConditionalOperatorClass: {2699// If only one of the LHS or RHS is a warning, the operator might2700// be being used for control flow. Only warn if both the LHS and2701// RHS are warnings.2702const auto *Exp = cast<ConditionalOperator>(this);2703return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&2704Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2705}2706case BinaryConditionalOperatorClass: {2707const auto *Exp = cast<BinaryConditionalOperator>(this);2708return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2709}27102711case MemberExprClass:2712WarnE = this;2713Loc = cast<MemberExpr>(this)->getMemberLoc();2714R1 = SourceRange(Loc, Loc);2715R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();2716return true;27172718case ArraySubscriptExprClass:2719WarnE = this;2720Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();2721R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();2722R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();2723return true;27242725case CXXOperatorCallExprClass: {2726// Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator2727// overloads as there is no reasonable way to define these such that they2728// have non-trivial, desirable side-effects. See the -Wunused-comparison2729// warning: operators == and != are commonly typo'ed, and so warning on them2730// provides additional value as well. If this list is updated,2731// DiagnoseUnusedComparison should be as well.2732const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);2733switch (Op->getOperator()) {2734default:2735break;2736case OO_EqualEqual:2737case OO_ExclaimEqual:2738case OO_Less:2739case OO_Greater:2740case OO_GreaterEqual:2741case OO_LessEqual:2742if (Op->getCallReturnType(Ctx)->isReferenceType() ||2743Op->getCallReturnType(Ctx)->isVoidType())2744break;2745WarnE = this;2746Loc = Op->getOperatorLoc();2747R1 = Op->getSourceRange();2748return true;2749}27502751// Fallthrough for generic call handling.2752[[fallthrough]];2753}2754case CallExprClass:2755case CXXMemberCallExprClass:2756case UserDefinedLiteralClass: {2757// If this is a direct call, get the callee.2758const CallExpr *CE = cast<CallExpr>(this);2759if (const Decl *FD = CE->getCalleeDecl()) {2760// If the callee has attribute pure, const, or warn_unused_result, warn2761// about it. void foo() { strlen("bar"); } should warn.2762//2763// Note: If new cases are added here, DiagnoseUnusedExprResult should be2764// updated to match for QoI.2765if (CE->hasUnusedResultAttr(Ctx) ||2766FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {2767WarnE = this;2768Loc = CE->getCallee()->getBeginLoc();2769R1 = CE->getCallee()->getSourceRange();27702771if (unsigned NumArgs = CE->getNumArgs())2772R2 = SourceRange(CE->getArg(0)->getBeginLoc(),2773CE->getArg(NumArgs - 1)->getEndLoc());2774return true;2775}2776}2777return false;2778}27792780// If we don't know precisely what we're looking at, let's not warn.2781case UnresolvedLookupExprClass:2782case CXXUnresolvedConstructExprClass:2783case RecoveryExprClass:2784return false;27852786case CXXTemporaryObjectExprClass:2787case CXXConstructExprClass: {2788if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {2789const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();2790if (Type->hasAttr<WarnUnusedAttr>() ||2791(WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {2792WarnE = this;2793Loc = getBeginLoc();2794R1 = getSourceRange();2795return true;2796}2797}27982799const auto *CE = cast<CXXConstructExpr>(this);2800if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {2801const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();2802if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {2803WarnE = this;2804Loc = getBeginLoc();2805R1 = getSourceRange();28062807if (unsigned NumArgs = CE->getNumArgs())2808R2 = SourceRange(CE->getArg(0)->getBeginLoc(),2809CE->getArg(NumArgs - 1)->getEndLoc());2810return true;2811}2812}28132814return false;2815}28162817case ObjCMessageExprClass: {2818const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);2819if (Ctx.getLangOpts().ObjCAutoRefCount &&2820ME->isInstanceMessage() &&2821!ME->getType()->isVoidType() &&2822ME->getMethodFamily() == OMF_init) {2823WarnE = this;2824Loc = getExprLoc();2825R1 = ME->getSourceRange();2826return true;2827}28282829if (const ObjCMethodDecl *MD = ME->getMethodDecl())2830if (MD->hasAttr<WarnUnusedResultAttr>()) {2831WarnE = this;2832Loc = getExprLoc();2833return true;2834}28352836return false;2837}28382839case ObjCPropertyRefExprClass:2840case ObjCSubscriptRefExprClass:2841WarnE = this;2842Loc = getExprLoc();2843R1 = getSourceRange();2844return true;28452846case PseudoObjectExprClass: {2847const auto *POE = cast<PseudoObjectExpr>(this);28482849// For some syntactic forms, we should always warn.2850if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(2851POE->getSyntacticForm())) {2852WarnE = this;2853Loc = getExprLoc();2854R1 = getSourceRange();2855return true;2856}28572858// For others, we should never warn.2859if (auto *BO = dyn_cast<BinaryOperator>(POE->getSyntacticForm()))2860if (BO->isAssignmentOp())2861return false;2862if (auto *UO = dyn_cast<UnaryOperator>(POE->getSyntacticForm()))2863if (UO->isIncrementDecrementOp())2864return false;28652866// Otherwise, warn if the result expression would warn.2867const Expr *Result = POE->getResultExpr();2868return Result && Result->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2869}28702871case StmtExprClass: {2872// Statement exprs don't logically have side effects themselves, but are2873// sometimes used in macros in ways that give them a type that is unused.2874// For example ({ blah; foo(); }) will end up with a type if foo has a type.2875// however, if the result of the stmt expr is dead, we don't want to emit a2876// warning.2877const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();2878if (!CS->body_empty()) {2879if (const Expr *E = dyn_cast<Expr>(CS->body_back()))2880return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2881if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))2882if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))2883return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2884}28852886if (getType()->isVoidType())2887return false;2888WarnE = this;2889Loc = cast<StmtExpr>(this)->getLParenLoc();2890R1 = getSourceRange();2891return true;2892}2893case CXXFunctionalCastExprClass:2894case CStyleCastExprClass: {2895// Ignore an explicit cast to void, except in C++98 if the operand is a2896// volatile glvalue for which we would trigger an implicit read in any2897// other language mode. (Such an implicit read always happens as part of2898// the lvalue conversion in C, and happens in C++ for expressions of all2899// forms where it seems likely the user intended to trigger a volatile2900// load.)2901const CastExpr *CE = cast<CastExpr>(this);2902const Expr *SubE = CE->getSubExpr()->IgnoreParens();2903if (CE->getCastKind() == CK_ToVoid) {2904if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&2905SubE->isReadIfDiscardedInCPlusPlus11()) {2906// Suppress the "unused value" warning for idiomatic usage of2907// '(void)var;' used to suppress "unused variable" warnings.2908if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))2909if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))2910if (!VD->isExternallyVisible())2911return false;29122913// The lvalue-to-rvalue conversion would have no effect for an array.2914// It's implausible that the programmer expected this to result in a2915// volatile array load, so don't warn.2916if (SubE->getType()->isArrayType())2917return false;29182919return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2920}2921return false;2922}29232924// If this is a cast to a constructor conversion, check the operand.2925// Otherwise, the result of the cast is unused.2926if (CE->getCastKind() == CK_ConstructorConversion)2927return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2928if (CE->getCastKind() == CK_Dependent)2929return false;29302931WarnE = this;2932if (const CXXFunctionalCastExpr *CXXCE =2933dyn_cast<CXXFunctionalCastExpr>(this)) {2934Loc = CXXCE->getBeginLoc();2935R1 = CXXCE->getSubExpr()->getSourceRange();2936} else {2937const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);2938Loc = CStyleCE->getLParenLoc();2939R1 = CStyleCE->getSubExpr()->getSourceRange();2940}2941return true;2942}2943case ImplicitCastExprClass: {2944const CastExpr *ICE = cast<ImplicitCastExpr>(this);29452946// lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.2947if (ICE->getCastKind() == CK_LValueToRValue &&2948ICE->getSubExpr()->getType().isVolatileQualified())2949return false;29502951return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2952}2953case CXXDefaultArgExprClass:2954return (cast<CXXDefaultArgExpr>(this)2955->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));2956case CXXDefaultInitExprClass:2957return (cast<CXXDefaultInitExpr>(this)2958->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));29592960case CXXNewExprClass:2961// FIXME: In theory, there might be new expressions that don't have side2962// effects (e.g. a placement new with an uninitialized POD).2963case CXXDeleteExprClass:2964return false;2965case MaterializeTemporaryExprClass:2966return cast<MaterializeTemporaryExpr>(this)2967->getSubExpr()2968->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2969case CXXBindTemporaryExprClass:2970return cast<CXXBindTemporaryExpr>(this)->getSubExpr()2971->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2972case ExprWithCleanupsClass:2973return cast<ExprWithCleanups>(this)->getSubExpr()2974->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2975}2976}29772978/// isOBJCGCCandidate - Check if an expression is objc gc'able.2979/// returns true, if it is; false otherwise.2980bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {2981const Expr *E = IgnoreParens();2982switch (E->getStmtClass()) {2983default:2984return false;2985case ObjCIvarRefExprClass:2986return true;2987case Expr::UnaryOperatorClass:2988return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);2989case ImplicitCastExprClass:2990return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);2991case MaterializeTemporaryExprClass:2992return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(2993Ctx);2994case CStyleCastExprClass:2995return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);2996case DeclRefExprClass: {2997const Decl *D = cast<DeclRefExpr>(E)->getDecl();29982999if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {3000if (VD->hasGlobalStorage())3001return true;3002QualType T = VD->getType();3003// dereferencing to a pointer is always a gc'able candidate,3004// unless it is __weak.3005return T->isPointerType() &&3006(Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);3007}3008return false;3009}3010case MemberExprClass: {3011const MemberExpr *M = cast<MemberExpr>(E);3012return M->getBase()->isOBJCGCCandidate(Ctx);3013}3014case ArraySubscriptExprClass:3015return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);3016}3017}30183019bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {3020if (isTypeDependent())3021return false;3022return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;3023}30243025QualType Expr::findBoundMemberType(const Expr *expr) {3026assert(expr->hasPlaceholderType(BuiltinType::BoundMember));30273028// Bound member expressions are always one of these possibilities:3029// x->m x.m x->*y x.*y3030// (possibly parenthesized)30313032expr = expr->IgnoreParens();3033if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {3034assert(isa<CXXMethodDecl>(mem->getMemberDecl()));3035return mem->getMemberDecl()->getType();3036}30373038if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {3039QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()3040->getPointeeType();3041assert(type->isFunctionType());3042return type;3043}30443045assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));3046return QualType();3047}30483049Expr *Expr::IgnoreImpCasts() {3050return IgnoreExprNodes(this, IgnoreImplicitCastsSingleStep);3051}30523053Expr *Expr::IgnoreCasts() {3054return IgnoreExprNodes(this, IgnoreCastsSingleStep);3055}30563057Expr *Expr::IgnoreImplicit() {3058return IgnoreExprNodes(this, IgnoreImplicitSingleStep);3059}30603061Expr *Expr::IgnoreImplicitAsWritten() {3062return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep);3063}30643065Expr *Expr::IgnoreParens() {3066return IgnoreExprNodes(this, IgnoreParensSingleStep);3067}30683069Expr *Expr::IgnoreParenImpCasts() {3070return IgnoreExprNodes(this, IgnoreParensSingleStep,3071IgnoreImplicitCastsExtraSingleStep);3072}30733074Expr *Expr::IgnoreParenCasts() {3075return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);3076}30773078Expr *Expr::IgnoreConversionOperatorSingleStep() {3079if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {3080if (isa_and_nonnull<CXXConversionDecl>(MCE->getMethodDecl()))3081return MCE->getImplicitObjectArgument();3082}3083return this;3084}30853086Expr *Expr::IgnoreParenLValueCasts() {3087return IgnoreExprNodes(this, IgnoreParensSingleStep,3088IgnoreLValueCastsSingleStep);3089}30903091Expr *Expr::IgnoreParenBaseCasts() {3092return IgnoreExprNodes(this, IgnoreParensSingleStep,3093IgnoreBaseCastsSingleStep);3094}30953096Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {3097auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {3098if (auto *CE = dyn_cast<CastExpr>(E)) {3099// We ignore integer <-> casts that are of the same width, ptr<->ptr and3100// ptr<->int casts of the same width. We also ignore all identity casts.3101Expr *SubExpr = CE->getSubExpr();3102bool IsIdentityCast =3103Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());3104bool IsSameWidthCast = (E->getType()->isPointerType() ||3105E->getType()->isIntegralType(Ctx)) &&3106(SubExpr->getType()->isPointerType() ||3107SubExpr->getType()->isIntegralType(Ctx)) &&3108(Ctx.getTypeSize(E->getType()) ==3109Ctx.getTypeSize(SubExpr->getType()));31103111if (IsIdentityCast || IsSameWidthCast)3112return SubExpr;3113} else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))3114return NTTP->getReplacement();31153116return E;3117};3118return IgnoreExprNodes(this, IgnoreParensSingleStep,3119IgnoreNoopCastsSingleStep);3120}31213122Expr *Expr::IgnoreUnlessSpelledInSource() {3123auto IgnoreImplicitConstructorSingleStep = [](Expr *E) {3124if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) {3125auto *SE = Cast->getSubExpr();3126if (SE->getSourceRange() == E->getSourceRange())3127return SE;3128}31293130if (auto *C = dyn_cast<CXXConstructExpr>(E)) {3131auto NumArgs = C->getNumArgs();3132if (NumArgs == 1 ||3133(NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {3134Expr *A = C->getArg(0);3135if (A->getSourceRange() == E->getSourceRange() || C->isElidable())3136return A;3137}3138}3139return E;3140};3141auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {3142if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {3143Expr *ExprNode = C->getImplicitObjectArgument();3144if (ExprNode->getSourceRange() == E->getSourceRange()) {3145return ExprNode;3146}3147if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {3148if (PE->getSourceRange() == C->getSourceRange()) {3149return cast<Expr>(PE);3150}3151}3152ExprNode = ExprNode->IgnoreParenImpCasts();3153if (ExprNode->getSourceRange() == E->getSourceRange())3154return ExprNode;3155}3156return E;3157};3158return IgnoreExprNodes(3159this, IgnoreImplicitSingleStep, IgnoreImplicitCastsExtraSingleStep,3160IgnoreParensOnlySingleStep, IgnoreImplicitConstructorSingleStep,3161IgnoreImplicitMemberCallSingleStep);3162}31633164bool Expr::isDefaultArgument() const {3165const Expr *E = this;3166if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))3167E = M->getSubExpr();31683169while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))3170E = ICE->getSubExprAsWritten();31713172return isa<CXXDefaultArgExpr>(E);3173}31743175/// Skip over any no-op casts and any temporary-binding3176/// expressions.3177static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {3178if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))3179E = M->getSubExpr();31803181while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {3182if (ICE->getCastKind() == CK_NoOp)3183E = ICE->getSubExpr();3184else3185break;3186}31873188while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))3189E = BE->getSubExpr();31903191while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {3192if (ICE->getCastKind() == CK_NoOp)3193E = ICE->getSubExpr();3194else3195break;3196}31973198return E->IgnoreParens();3199}32003201/// isTemporaryObject - Determines if this expression produces a3202/// temporary of the given class type.3203bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {3204if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))3205return false;32063207const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);32083209// Temporaries are by definition pr-values of class type.3210if (!E->Classify(C).isPRValue()) {3211// In this context, property reference is a message call and is pr-value.3212if (!isa<ObjCPropertyRefExpr>(E))3213return false;3214}32153216// Black-list a few cases which yield pr-values of class type that don't3217// refer to temporaries of that type:32183219// - implicit derived-to-base conversions3220if (isa<ImplicitCastExpr>(E)) {3221switch (cast<ImplicitCastExpr>(E)->getCastKind()) {3222case CK_DerivedToBase:3223case CK_UncheckedDerivedToBase:3224return false;3225default:3226break;3227}3228}32293230// - member expressions (all)3231if (isa<MemberExpr>(E))3232return false;32333234if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))3235if (BO->isPtrMemOp())3236return false;32373238// - opaque values (all)3239if (isa<OpaqueValueExpr>(E))3240return false;32413242return true;3243}32443245bool Expr::isImplicitCXXThis() const {3246const Expr *E = this;32473248// Strip away parentheses and casts we don't care about.3249while (true) {3250if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {3251E = Paren->getSubExpr();3252continue;3253}32543255if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {3256if (ICE->getCastKind() == CK_NoOp ||3257ICE->getCastKind() == CK_LValueToRValue ||3258ICE->getCastKind() == CK_DerivedToBase ||3259ICE->getCastKind() == CK_UncheckedDerivedToBase) {3260E = ICE->getSubExpr();3261continue;3262}3263}32643265if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {3266if (UnOp->getOpcode() == UO_Extension) {3267E = UnOp->getSubExpr();3268continue;3269}3270}32713272if (const MaterializeTemporaryExpr *M3273= dyn_cast<MaterializeTemporaryExpr>(E)) {3274E = M->getSubExpr();3275continue;3276}32773278break;3279}32803281if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))3282return This->isImplicit();32833284return false;3285}32863287/// hasAnyTypeDependentArguments - Determines if any of the expressions3288/// in Exprs is type-dependent.3289bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {3290for (unsigned I = 0; I < Exprs.size(); ++I)3291if (Exprs[I]->isTypeDependent())3292return true;32933294return false;3295}32963297bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,3298const Expr **Culprit) const {3299assert(!isValueDependent() &&3300"Expression evaluator can't be called on a dependent expression.");33013302// This function is attempting whether an expression is an initializer3303// which can be evaluated at compile-time. It very closely parallels3304// ConstExprEmitter in CGExprConstant.cpp; if they don't match, it3305// will lead to unexpected results. Like ConstExprEmitter, it falls back3306// to isEvaluatable most of the time.3307//3308// If we ever capture reference-binding directly in the AST, we can3309// kill the second parameter.33103311if (IsForRef) {3312if (auto *EWC = dyn_cast<ExprWithCleanups>(this))3313return EWC->getSubExpr()->isConstantInitializer(Ctx, true, Culprit);3314if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(this))3315return MTE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);3316EvalResult Result;3317if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)3318return true;3319if (Culprit)3320*Culprit = this;3321return false;3322}33233324switch (getStmtClass()) {3325default: break;3326case Stmt::ExprWithCleanupsClass:3327return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(3328Ctx, IsForRef, Culprit);3329case StringLiteralClass:3330case ObjCEncodeExprClass:3331return true;3332case CXXTemporaryObjectExprClass:3333case CXXConstructExprClass: {3334const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);33353336if (CE->getConstructor()->isTrivial() &&3337CE->getConstructor()->getParent()->hasTrivialDestructor()) {3338// Trivial default constructor3339if (!CE->getNumArgs()) return true;33403341// Trivial copy constructor3342assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");3343return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);3344}33453346break;3347}3348case ConstantExprClass: {3349// FIXME: We should be able to return "true" here, but it can lead to extra3350// error messages. E.g. in Sema/array-init.c.3351const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();3352return Exp->isConstantInitializer(Ctx, false, Culprit);3353}3354case CompoundLiteralExprClass: {3355// This handles gcc's extension that allows global initializers like3356// "struct x {int x;} x = (struct x) {};".3357// FIXME: This accepts other cases it shouldn't!3358const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();3359return Exp->isConstantInitializer(Ctx, false, Culprit);3360}3361case DesignatedInitUpdateExprClass: {3362const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);3363return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&3364DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);3365}3366case InitListExprClass: {3367// C++ [dcl.init.aggr]p2:3368// The elements of an aggregate are:3369// - for an array, the array elements in increasing subscript order, or3370// - for a class, the direct base classes in declaration order, followed3371// by the direct non-static data members (11.4) that are not members of3372// an anonymous union, in declaration order.3373const InitListExpr *ILE = cast<InitListExpr>(this);3374assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");3375if (ILE->getType()->isArrayType()) {3376unsigned numInits = ILE->getNumInits();3377for (unsigned i = 0; i < numInits; i++) {3378if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))3379return false;3380}3381return true;3382}33833384if (ILE->getType()->isRecordType()) {3385unsigned ElementNo = 0;3386RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();33873388// In C++17, bases were added to the list of members used by aggregate3389// initialization.3390if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {3391for (unsigned i = 0, e = CXXRD->getNumBases(); i < e; i++) {3392if (ElementNo < ILE->getNumInits()) {3393const Expr *Elt = ILE->getInit(ElementNo++);3394if (!Elt->isConstantInitializer(Ctx, false, Culprit))3395return false;3396}3397}3398}33993400for (const auto *Field : RD->fields()) {3401// If this is a union, skip all the fields that aren't being initialized.3402if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)3403continue;34043405// Don't emit anonymous bitfields, they just affect layout.3406if (Field->isUnnamedBitField())3407continue;34083409if (ElementNo < ILE->getNumInits()) {3410const Expr *Elt = ILE->getInit(ElementNo++);3411if (Field->isBitField()) {3412// Bitfields have to evaluate to an integer.3413EvalResult Result;3414if (!Elt->EvaluateAsInt(Result, Ctx)) {3415if (Culprit)3416*Culprit = Elt;3417return false;3418}3419} else {3420bool RefType = Field->getType()->isReferenceType();3421if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))3422return false;3423}3424}3425}3426return true;3427}34283429break;3430}3431case ImplicitValueInitExprClass:3432case NoInitExprClass:3433return true;3434case ParenExprClass:3435return cast<ParenExpr>(this)->getSubExpr()3436->isConstantInitializer(Ctx, IsForRef, Culprit);3437case GenericSelectionExprClass:3438return cast<GenericSelectionExpr>(this)->getResultExpr()3439->isConstantInitializer(Ctx, IsForRef, Culprit);3440case ChooseExprClass:3441if (cast<ChooseExpr>(this)->isConditionDependent()) {3442if (Culprit)3443*Culprit = this;3444return false;3445}3446return cast<ChooseExpr>(this)->getChosenSubExpr()3447->isConstantInitializer(Ctx, IsForRef, Culprit);3448case UnaryOperatorClass: {3449const UnaryOperator* Exp = cast<UnaryOperator>(this);3450if (Exp->getOpcode() == UO_Extension)3451return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);3452break;3453}3454case PackIndexingExprClass: {3455return cast<PackIndexingExpr>(this)3456->getSelectedExpr()3457->isConstantInitializer(Ctx, false, Culprit);3458}3459case CXXFunctionalCastExprClass:3460case CXXStaticCastExprClass:3461case ImplicitCastExprClass:3462case CStyleCastExprClass:3463case ObjCBridgedCastExprClass:3464case CXXDynamicCastExprClass:3465case CXXReinterpretCastExprClass:3466case CXXAddrspaceCastExprClass:3467case CXXConstCastExprClass: {3468const CastExpr *CE = cast<CastExpr>(this);34693470// Handle misc casts we want to ignore.3471if (CE->getCastKind() == CK_NoOp ||3472CE->getCastKind() == CK_LValueToRValue ||3473CE->getCastKind() == CK_ToUnion ||3474CE->getCastKind() == CK_ConstructorConversion ||3475CE->getCastKind() == CK_NonAtomicToAtomic ||3476CE->getCastKind() == CK_AtomicToNonAtomic ||3477CE->getCastKind() == CK_NullToPointer ||3478CE->getCastKind() == CK_IntToOCLSampler)3479return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);34803481break;3482}3483case MaterializeTemporaryExprClass:3484return cast<MaterializeTemporaryExpr>(this)3485->getSubExpr()3486->isConstantInitializer(Ctx, false, Culprit);34873488case SubstNonTypeTemplateParmExprClass:3489return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()3490->isConstantInitializer(Ctx, false, Culprit);3491case CXXDefaultArgExprClass:3492return cast<CXXDefaultArgExpr>(this)->getExpr()3493->isConstantInitializer(Ctx, false, Culprit);3494case CXXDefaultInitExprClass:3495return cast<CXXDefaultInitExpr>(this)->getExpr()3496->isConstantInitializer(Ctx, false, Culprit);3497}3498// Allow certain forms of UB in constant initializers: signed integer3499// overflow and floating-point division by zero. We'll give a warning on3500// these, but they're common enough that we have to accept them.3501if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))3502return true;3503if (Culprit)3504*Culprit = this;3505return false;3506}35073508bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {3509unsigned BuiltinID = getBuiltinCallee();3510if (BuiltinID != Builtin::BI__assume &&3511BuiltinID != Builtin::BI__builtin_assume)3512return false;35133514const Expr* Arg = getArg(0);3515bool ArgVal;3516return !Arg->isValueDependent() &&3517Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;3518}35193520bool CallExpr::isCallToStdMove() const {3521return getBuiltinCallee() == Builtin::BImove;3522}35233524namespace {3525/// Look for any side effects within a Stmt.3526class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {3527typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;3528const bool IncludePossibleEffects;3529bool HasSideEffects;35303531public:3532explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)3533: Inherited(Context),3534IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }35353536bool hasSideEffects() const { return HasSideEffects; }35373538void VisitDecl(const Decl *D) {3539if (!D)3540return;35413542// We assume the caller checks subexpressions (eg, the initializer, VLA3543// bounds) for side-effects on our behalf.3544if (auto *VD = dyn_cast<VarDecl>(D)) {3545// Registering a destructor is a side-effect.3546if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&3547VD->needsDestruction(Context))3548HasSideEffects = true;3549}3550}35513552void VisitDeclStmt(const DeclStmt *DS) {3553for (auto *D : DS->decls())3554VisitDecl(D);3555Inherited::VisitDeclStmt(DS);3556}35573558void VisitExpr(const Expr *E) {3559if (!HasSideEffects &&3560E->HasSideEffects(Context, IncludePossibleEffects))3561HasSideEffects = true;3562}3563};3564}35653566bool Expr::HasSideEffects(const ASTContext &Ctx,3567bool IncludePossibleEffects) const {3568// In circumstances where we care about definite side effects instead of3569// potential side effects, we want to ignore expressions that are part of a3570// macro expansion as a potential side effect.3571if (!IncludePossibleEffects && getExprLoc().isMacroID())3572return false;35733574switch (getStmtClass()) {3575case NoStmtClass:3576#define ABSTRACT_STMT(Type)3577#define STMT(Type, Base) case Type##Class:3578#define EXPR(Type, Base)3579#include "clang/AST/StmtNodes.inc"3580llvm_unreachable("unexpected Expr kind");35813582case DependentScopeDeclRefExprClass:3583case CXXUnresolvedConstructExprClass:3584case CXXDependentScopeMemberExprClass:3585case UnresolvedLookupExprClass:3586case UnresolvedMemberExprClass:3587case PackExpansionExprClass:3588case SubstNonTypeTemplateParmPackExprClass:3589case FunctionParmPackExprClass:3590case TypoExprClass:3591case RecoveryExprClass:3592case CXXFoldExprClass:3593// Make a conservative assumption for dependent nodes.3594return IncludePossibleEffects;35953596case DeclRefExprClass:3597case ObjCIvarRefExprClass:3598case PredefinedExprClass:3599case IntegerLiteralClass:3600case FixedPointLiteralClass:3601case FloatingLiteralClass:3602case ImaginaryLiteralClass:3603case StringLiteralClass:3604case CharacterLiteralClass:3605case OffsetOfExprClass:3606case ImplicitValueInitExprClass:3607case UnaryExprOrTypeTraitExprClass:3608case AddrLabelExprClass:3609case GNUNullExprClass:3610case ArrayInitIndexExprClass:3611case NoInitExprClass:3612case CXXBoolLiteralExprClass:3613case CXXNullPtrLiteralExprClass:3614case CXXThisExprClass:3615case CXXScalarValueInitExprClass:3616case TypeTraitExprClass:3617case ArrayTypeTraitExprClass:3618case ExpressionTraitExprClass:3619case CXXNoexceptExprClass:3620case SizeOfPackExprClass:3621case ObjCStringLiteralClass:3622case ObjCEncodeExprClass:3623case ObjCBoolLiteralExprClass:3624case ObjCAvailabilityCheckExprClass:3625case CXXUuidofExprClass:3626case OpaqueValueExprClass:3627case SourceLocExprClass:3628case EmbedExprClass:3629case ConceptSpecializationExprClass:3630case RequiresExprClass:3631case SYCLUniqueStableNameExprClass:3632case PackIndexingExprClass:3633// These never have a side-effect.3634return false;36353636case ConstantExprClass:3637// FIXME: Move this into the "return false;" block above.3638return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(3639Ctx, IncludePossibleEffects);36403641case CallExprClass:3642case CXXOperatorCallExprClass:3643case CXXMemberCallExprClass:3644case CUDAKernelCallExprClass:3645case UserDefinedLiteralClass: {3646// We don't know a call definitely has side effects, except for calls3647// to pure/const functions that definitely don't.3648// If the call itself is considered side-effect free, check the operands.3649const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();3650bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());3651if (IsPure || !IncludePossibleEffects)3652break;3653return true;3654}36553656case BlockExprClass:3657case CXXBindTemporaryExprClass:3658if (!IncludePossibleEffects)3659break;3660return true;36613662case MSPropertyRefExprClass:3663case MSPropertySubscriptExprClass:3664case CompoundAssignOperatorClass:3665case VAArgExprClass:3666case AtomicExprClass:3667case CXXThrowExprClass:3668case CXXNewExprClass:3669case CXXDeleteExprClass:3670case CoawaitExprClass:3671case DependentCoawaitExprClass:3672case CoyieldExprClass:3673// These always have a side-effect.3674return true;36753676case StmtExprClass: {3677// StmtExprs have a side-effect if any substatement does.3678SideEffectFinder Finder(Ctx, IncludePossibleEffects);3679Finder.Visit(cast<StmtExpr>(this)->getSubStmt());3680return Finder.hasSideEffects();3681}36823683case ExprWithCleanupsClass:3684if (IncludePossibleEffects)3685if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())3686return true;3687break;36883689case ParenExprClass:3690case ArraySubscriptExprClass:3691case MatrixSubscriptExprClass:3692case ArraySectionExprClass:3693case OMPArrayShapingExprClass:3694case OMPIteratorExprClass:3695case MemberExprClass:3696case ConditionalOperatorClass:3697case BinaryConditionalOperatorClass:3698case CompoundLiteralExprClass:3699case ExtVectorElementExprClass:3700case DesignatedInitExprClass:3701case DesignatedInitUpdateExprClass:3702case ArrayInitLoopExprClass:3703case ParenListExprClass:3704case CXXPseudoDestructorExprClass:3705case CXXRewrittenBinaryOperatorClass:3706case CXXStdInitializerListExprClass:3707case SubstNonTypeTemplateParmExprClass:3708case MaterializeTemporaryExprClass:3709case ShuffleVectorExprClass:3710case ConvertVectorExprClass:3711case AsTypeExprClass:3712case CXXParenListInitExprClass:3713// These have a side-effect if any subexpression does.3714break;37153716case UnaryOperatorClass:3717if (cast<UnaryOperator>(this)->isIncrementDecrementOp())3718return true;3719break;37203721case BinaryOperatorClass:3722if (cast<BinaryOperator>(this)->isAssignmentOp())3723return true;3724break;37253726case InitListExprClass:3727// FIXME: The children for an InitListExpr doesn't include the array filler.3728if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())3729if (E->HasSideEffects(Ctx, IncludePossibleEffects))3730return true;3731break;37323733case GenericSelectionExprClass:3734return cast<GenericSelectionExpr>(this)->getResultExpr()->3735HasSideEffects(Ctx, IncludePossibleEffects);37363737case ChooseExprClass:3738return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(3739Ctx, IncludePossibleEffects);37403741case CXXDefaultArgExprClass:3742return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(3743Ctx, IncludePossibleEffects);37443745case CXXDefaultInitExprClass: {3746const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();3747if (const Expr *E = FD->getInClassInitializer())3748return E->HasSideEffects(Ctx, IncludePossibleEffects);3749// If we've not yet parsed the initializer, assume it has side-effects.3750return true;3751}37523753case CXXDynamicCastExprClass: {3754// A dynamic_cast expression has side-effects if it can throw.3755const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);3756if (DCE->getTypeAsWritten()->isReferenceType() &&3757DCE->getCastKind() == CK_Dynamic)3758return true;3759}3760[[fallthrough]];3761case ImplicitCastExprClass:3762case CStyleCastExprClass:3763case CXXStaticCastExprClass:3764case CXXReinterpretCastExprClass:3765case CXXConstCastExprClass:3766case CXXAddrspaceCastExprClass:3767case CXXFunctionalCastExprClass:3768case BuiltinBitCastExprClass: {3769// While volatile reads are side-effecting in both C and C++, we treat them3770// as having possible (not definite) side-effects. This allows idiomatic3771// code to behave without warning, such as sizeof(*v) for a volatile-3772// qualified pointer.3773if (!IncludePossibleEffects)3774break;37753776const CastExpr *CE = cast<CastExpr>(this);3777if (CE->getCastKind() == CK_LValueToRValue &&3778CE->getSubExpr()->getType().isVolatileQualified())3779return true;3780break;3781}37823783case CXXTypeidExprClass: {3784const auto *TE = cast<CXXTypeidExpr>(this);3785if (!TE->isPotentiallyEvaluated())3786return false;37873788// If this type id expression can throw because of a null pointer, that is a3789// side-effect independent of if the operand has a side-effect3790if (IncludePossibleEffects && TE->hasNullCheck())3791return true;37923793break;3794}37953796case CXXConstructExprClass:3797case CXXTemporaryObjectExprClass: {3798const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);3799if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)3800return true;3801// A trivial constructor does not add any side-effects of its own. Just look3802// at its arguments.3803break;3804}38053806case CXXInheritedCtorInitExprClass: {3807const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);3808if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)3809return true;3810break;3811}38123813case LambdaExprClass: {3814const LambdaExpr *LE = cast<LambdaExpr>(this);3815for (Expr *E : LE->capture_inits())3816if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))3817return true;3818return false;3819}38203821case PseudoObjectExprClass: {3822// Only look for side-effects in the semantic form, and look past3823// OpaqueValueExpr bindings in that form.3824const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);3825for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),3826E = PO->semantics_end();3827I != E; ++I) {3828const Expr *Subexpr = *I;3829if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))3830Subexpr = OVE->getSourceExpr();3831if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))3832return true;3833}3834return false;3835}38363837case ObjCBoxedExprClass:3838case ObjCArrayLiteralClass:3839case ObjCDictionaryLiteralClass:3840case ObjCSelectorExprClass:3841case ObjCProtocolExprClass:3842case ObjCIsaExprClass:3843case ObjCIndirectCopyRestoreExprClass:3844case ObjCSubscriptRefExprClass:3845case ObjCBridgedCastExprClass:3846case ObjCMessageExprClass:3847case ObjCPropertyRefExprClass:3848// FIXME: Classify these cases better.3849if (IncludePossibleEffects)3850return true;3851break;3852}38533854// Recurse to children.3855for (const Stmt *SubStmt : children())3856if (SubStmt &&3857cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))3858return true;38593860return false;3861}38623863FPOptions Expr::getFPFeaturesInEffect(const LangOptions &LO) const {3864if (auto Call = dyn_cast<CallExpr>(this))3865return Call->getFPFeaturesInEffect(LO);3866if (auto UO = dyn_cast<UnaryOperator>(this))3867return UO->getFPFeaturesInEffect(LO);3868if (auto BO = dyn_cast<BinaryOperator>(this))3869return BO->getFPFeaturesInEffect(LO);3870if (auto Cast = dyn_cast<CastExpr>(this))3871return Cast->getFPFeaturesInEffect(LO);3872return FPOptions::defaultWithoutTrailingStorage(LO);3873}38743875namespace {3876/// Look for a call to a non-trivial function within an expression.3877class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>3878{3879typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;38803881bool NonTrivial;38823883public:3884explicit NonTrivialCallFinder(const ASTContext &Context)3885: Inherited(Context), NonTrivial(false) { }38863887bool hasNonTrivialCall() const { return NonTrivial; }38883889void VisitCallExpr(const CallExpr *E) {3890if (const CXXMethodDecl *Method3891= dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {3892if (Method->isTrivial()) {3893// Recurse to children of the call.3894Inherited::VisitStmt(E);3895return;3896}3897}38983899NonTrivial = true;3900}39013902void VisitCXXConstructExpr(const CXXConstructExpr *E) {3903if (E->getConstructor()->isTrivial()) {3904// Recurse to children of the call.3905Inherited::VisitStmt(E);3906return;3907}39083909NonTrivial = true;3910}39113912void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {3913// Destructor of the temporary might be null if destructor declaration3914// is not valid.3915if (const CXXDestructorDecl *DtorDecl =3916E->getTemporary()->getDestructor()) {3917if (DtorDecl->isTrivial()) {3918Inherited::VisitStmt(E);3919return;3920}3921}39223923NonTrivial = true;3924}3925};3926}39273928bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {3929NonTrivialCallFinder Finder(Ctx);3930Finder.Visit(this);3931return Finder.hasNonTrivialCall();3932}39333934/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null3935/// pointer constant or not, as well as the specific kind of constant detected.3936/// Null pointer constants can be integer constant expressions with the3937/// value zero, casts of zero to void*, nullptr (C++0X), or __null3938/// (a GNU extension).3939Expr::NullPointerConstantKind3940Expr::isNullPointerConstant(ASTContext &Ctx,3941NullPointerConstantValueDependence NPC) const {3942if (isValueDependent() &&3943(!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {3944// Error-dependent expr should never be a null pointer.3945if (containsErrors())3946return NPCK_NotNull;3947switch (NPC) {3948case NPC_NeverValueDependent:3949llvm_unreachable("Unexpected value dependent expression!");3950case NPC_ValueDependentIsNull:3951if (isTypeDependent() || getType()->isIntegralType(Ctx))3952return NPCK_ZeroExpression;3953else3954return NPCK_NotNull;39553956case NPC_ValueDependentIsNotNull:3957return NPCK_NotNull;3958}3959}39603961// Strip off a cast to void*, if it exists. Except in C++.3962if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {3963if (!Ctx.getLangOpts().CPlusPlus) {3964// Check that it is a cast to void*.3965if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {3966QualType Pointee = PT->getPointeeType();3967Qualifiers Qs = Pointee.getQualifiers();3968// Only (void*)0 or equivalent are treated as nullptr. If pointee type3969// has non-default address space it is not treated as nullptr.3970// (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr3971// since it cannot be assigned to a pointer to constant address space.3972if (Ctx.getLangOpts().OpenCL &&3973Pointee.getAddressSpace() == Ctx.getDefaultOpenCLPointeeAddrSpace())3974Qs.removeAddressSpace();39753976if (Pointee->isVoidType() && Qs.empty() && // to void*3977CE->getSubExpr()->getType()->isIntegerType()) // from int3978return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);3979}3980}3981} else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {3982// Ignore the ImplicitCastExpr type entirely.3983return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);3984} else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {3985// Accept ((void*)0) as a null pointer constant, as many other3986// implementations do.3987return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);3988} else if (const GenericSelectionExpr *GE =3989dyn_cast<GenericSelectionExpr>(this)) {3990if (GE->isResultDependent())3991return NPCK_NotNull;3992return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);3993} else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {3994if (CE->isConditionDependent())3995return NPCK_NotNull;3996return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);3997} else if (const CXXDefaultArgExpr *DefaultArg3998= dyn_cast<CXXDefaultArgExpr>(this)) {3999// See through default argument expressions.4000return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);4001} else if (const CXXDefaultInitExpr *DefaultInit4002= dyn_cast<CXXDefaultInitExpr>(this)) {4003// See through default initializer expressions.4004return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);4005} else if (isa<GNUNullExpr>(this)) {4006// The GNU __null extension is always a null pointer constant.4007return NPCK_GNUNull;4008} else if (const MaterializeTemporaryExpr *M4009= dyn_cast<MaterializeTemporaryExpr>(this)) {4010return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);4011} else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {4012if (const Expr *Source = OVE->getSourceExpr())4013return Source->isNullPointerConstant(Ctx, NPC);4014}40154016// If the expression has no type information, it cannot be a null pointer4017// constant.4018if (getType().isNull())4019return NPCK_NotNull;40204021// C++11/C23 nullptr_t is always a null pointer constant.4022if (getType()->isNullPtrType())4023return NPCK_CXX11_nullptr;40244025if (const RecordType *UT = getType()->getAsUnionType())4026if (!Ctx.getLangOpts().CPlusPlus11 &&4027UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())4028if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){4029const Expr *InitExpr = CLE->getInitializer();4030if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))4031return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);4032}4033// This expression must be an integer type.4034if (!getType()->isIntegerType() ||4035(Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))4036return NPCK_NotNull;40374038if (Ctx.getLangOpts().CPlusPlus11) {4039// C++11 [conv.ptr]p1: A null pointer constant is an integer literal with4040// value zero or a prvalue of type std::nullptr_t.4041// Microsoft mode permits C++98 rules reflecting MSVC behavior.4042const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);4043if (Lit && !Lit->getValue())4044return NPCK_ZeroLiteral;4045if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))4046return NPCK_NotNull;4047} else {4048// If we have an integer constant expression, we need to *evaluate* it and4049// test for the value 0.4050if (!isIntegerConstantExpr(Ctx))4051return NPCK_NotNull;4052}40534054if (EvaluateKnownConstInt(Ctx) != 0)4055return NPCK_NotNull;40564057if (isa<IntegerLiteral>(this))4058return NPCK_ZeroLiteral;4059return NPCK_ZeroExpression;4060}40614062/// If this expression is an l-value for an Objective C4063/// property, find the underlying property reference expression.4064const ObjCPropertyRefExpr *Expr::getObjCProperty() const {4065const Expr *E = this;4066while (true) {4067assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&4068"expression is not a property reference");4069E = E->IgnoreParenCasts();4070if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {4071if (BO->getOpcode() == BO_Comma) {4072E = BO->getRHS();4073continue;4074}4075}40764077break;4078}40794080return cast<ObjCPropertyRefExpr>(E);4081}40824083bool Expr::isObjCSelfExpr() const {4084const Expr *E = IgnoreParenImpCasts();40854086const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);4087if (!DRE)4088return false;40894090const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());4091if (!Param)4092return false;40934094const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());4095if (!M)4096return false;40974098return M->getSelfDecl() == Param;4099}41004101FieldDecl *Expr::getSourceBitField() {4102Expr *E = this->IgnoreParens();41034104while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {4105if (ICE->getCastKind() == CK_LValueToRValue ||4106(ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))4107E = ICE->getSubExpr()->IgnoreParens();4108else4109break;4110}41114112if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))4113if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))4114if (Field->isBitField())4115return Field;41164117if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {4118FieldDecl *Ivar = IvarRef->getDecl();4119if (Ivar->isBitField())4120return Ivar;4121}41224123if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {4124if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))4125if (Field->isBitField())4126return Field;41274128if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))4129if (Expr *E = BD->getBinding())4130return E->getSourceBitField();4131}41324133if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {4134if (BinOp->isAssignmentOp() && BinOp->getLHS())4135return BinOp->getLHS()->getSourceBitField();41364137if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())4138return BinOp->getRHS()->getSourceBitField();4139}41404141if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))4142if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())4143return UnOp->getSubExpr()->getSourceBitField();41444145return nullptr;4146}41474148EnumConstantDecl *Expr::getEnumConstantDecl() {4149Expr *E = this->IgnoreParenImpCasts();4150if (auto *DRE = dyn_cast<DeclRefExpr>(E))4151return dyn_cast<EnumConstantDecl>(DRE->getDecl());4152return nullptr;4153}41544155bool Expr::refersToVectorElement() const {4156// FIXME: Why do we not just look at the ObjectKind here?4157const Expr *E = this->IgnoreParens();41584159while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {4160if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)4161E = ICE->getSubExpr()->IgnoreParens();4162else4163break;4164}41654166if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))4167return ASE->getBase()->getType()->isVectorType();41684169if (isa<ExtVectorElementExpr>(E))4170return true;41714172if (auto *DRE = dyn_cast<DeclRefExpr>(E))4173if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))4174if (auto *E = BD->getBinding())4175return E->refersToVectorElement();41764177return false;4178}41794180bool Expr::refersToGlobalRegisterVar() const {4181const Expr *E = this->IgnoreParenImpCasts();41824183if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))4184if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))4185if (VD->getStorageClass() == SC_Register &&4186VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())4187return true;41884189return false;4190}41914192bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {4193E1 = E1->IgnoreParens();4194E2 = E2->IgnoreParens();41954196if (E1->getStmtClass() != E2->getStmtClass())4197return false;41984199switch (E1->getStmtClass()) {4200default:4201return false;4202case CXXThisExprClass:4203return true;4204case DeclRefExprClass: {4205// DeclRefExpr without an ImplicitCastExpr can happen for integral4206// template parameters.4207const auto *DRE1 = cast<DeclRefExpr>(E1);4208const auto *DRE2 = cast<DeclRefExpr>(E2);4209return DRE1->isPRValue() && DRE2->isPRValue() &&4210DRE1->getDecl() == DRE2->getDecl();4211}4212case ImplicitCastExprClass: {4213// Peel off implicit casts.4214while (true) {4215const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);4216const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);4217if (!ICE1 || !ICE2)4218return false;4219if (ICE1->getCastKind() != ICE2->getCastKind())4220return false;4221E1 = ICE1->getSubExpr()->IgnoreParens();4222E2 = ICE2->getSubExpr()->IgnoreParens();4223// The final cast must be one of these types.4224if (ICE1->getCastKind() == CK_LValueToRValue ||4225ICE1->getCastKind() == CK_ArrayToPointerDecay ||4226ICE1->getCastKind() == CK_FunctionToPointerDecay) {4227break;4228}4229}42304231const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);4232const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);4233if (DRE1 && DRE2)4234return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());42354236const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);4237const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);4238if (Ivar1 && Ivar2) {4239return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&4240declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());4241}42424243const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);4244const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);4245if (Array1 && Array2) {4246if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))4247return false;42484249auto Idx1 = Array1->getIdx();4250auto Idx2 = Array2->getIdx();4251const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);4252const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);4253if (Integer1 && Integer2) {4254if (!llvm::APInt::isSameValue(Integer1->getValue(),4255Integer2->getValue()))4256return false;4257} else {4258if (!isSameComparisonOperand(Idx1, Idx2))4259return false;4260}42614262return true;4263}42644265// Walk the MemberExpr chain.4266while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {4267const auto *ME1 = cast<MemberExpr>(E1);4268const auto *ME2 = cast<MemberExpr>(E2);4269if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))4270return false;4271if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))4272if (D->isStaticDataMember())4273return true;4274E1 = ME1->getBase()->IgnoreParenImpCasts();4275E2 = ME2->getBase()->IgnoreParenImpCasts();4276}42774278if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))4279return true;42804281// A static member variable can end the MemberExpr chain with either4282// a MemberExpr or a DeclRefExpr.4283auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {4284if (const auto *DRE = dyn_cast<DeclRefExpr>(E))4285return DRE->getDecl();4286if (const auto *ME = dyn_cast<MemberExpr>(E))4287return ME->getMemberDecl();4288return nullptr;4289};42904291const ValueDecl *VD1 = getAnyDecl(E1);4292const ValueDecl *VD2 = getAnyDecl(E2);4293return declaresSameEntity(VD1, VD2);4294}4295}4296}42974298/// isArrow - Return true if the base expression is a pointer to vector,4299/// return false if the base expression is a vector.4300bool ExtVectorElementExpr::isArrow() const {4301return getBase()->getType()->isPointerType();4302}43034304unsigned ExtVectorElementExpr::getNumElements() const {4305if (const VectorType *VT = getType()->getAs<VectorType>())4306return VT->getNumElements();4307return 1;4308}43094310/// containsDuplicateElements - Return true if any element access is repeated.4311bool ExtVectorElementExpr::containsDuplicateElements() const {4312// FIXME: Refactor this code to an accessor on the AST node which returns the4313// "type" of component access, and share with code below and in Sema.4314StringRef Comp = Accessor->getName();43154316// Halving swizzles do not contain duplicate elements.4317if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")4318return false;43194320// Advance past s-char prefix on hex swizzles.4321if (Comp[0] == 's' || Comp[0] == 'S')4322Comp = Comp.substr(1);43234324for (unsigned i = 0, e = Comp.size(); i != e; ++i)4325if (Comp.substr(i + 1).contains(Comp[i]))4326return true;43274328return false;4329}43304331/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.4332void ExtVectorElementExpr::getEncodedElementAccess(4333SmallVectorImpl<uint32_t> &Elts) const {4334StringRef Comp = Accessor->getName();4335bool isNumericAccessor = false;4336if (Comp[0] == 's' || Comp[0] == 'S') {4337Comp = Comp.substr(1);4338isNumericAccessor = true;4339}43404341bool isHi = Comp == "hi";4342bool isLo = Comp == "lo";4343bool isEven = Comp == "even";4344bool isOdd = Comp == "odd";43454346for (unsigned i = 0, e = getNumElements(); i != e; ++i) {4347uint64_t Index;43484349if (isHi)4350Index = e + i;4351else if (isLo)4352Index = i;4353else if (isEven)4354Index = 2 * i;4355else if (isOdd)4356Index = 2 * i + 1;4357else4358Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);43594360Elts.push_back(Index);4361}4362}43634364ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args,4365QualType Type, SourceLocation BLoc,4366SourceLocation RP)4367: Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),4368BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) {4369SubExprs = new (C) Stmt*[args.size()];4370for (unsigned i = 0; i != args.size(); i++)4371SubExprs[i] = args[i];43724373setDependence(computeDependence(this));4374}43754376void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {4377if (SubExprs) C.Deallocate(SubExprs);43784379this->NumExprs = Exprs.size();4380SubExprs = new (C) Stmt*[NumExprs];4381memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());4382}43834384GenericSelectionExpr::GenericSelectionExpr(4385const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,4386ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,4387SourceLocation DefaultLoc, SourceLocation RParenLoc,4388bool ContainsUnexpandedParameterPack, unsigned ResultIndex)4389: Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),4390AssocExprs[ResultIndex]->getValueKind(),4391AssocExprs[ResultIndex]->getObjectKind()),4392NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),4393IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {4394assert(AssocTypes.size() == AssocExprs.size() &&4395"Must have the same number of association expressions"4396" and TypeSourceInfo!");4397assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");43984399GenericSelectionExprBits.GenericLoc = GenericLoc;4400getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =4401ControllingExpr;4402std::copy(AssocExprs.begin(), AssocExprs.end(),4403getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());4404std::copy(AssocTypes.begin(), AssocTypes.end(),4405getTrailingObjects<TypeSourceInfo *>() +4406getIndexOfStartOfAssociatedTypes());44074408setDependence(computeDependence(this, ContainsUnexpandedParameterPack));4409}44104411GenericSelectionExpr::GenericSelectionExpr(4412const ASTContext &, SourceLocation GenericLoc,4413TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,4414ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,4415SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,4416unsigned ResultIndex)4417: Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),4418AssocExprs[ResultIndex]->getValueKind(),4419AssocExprs[ResultIndex]->getObjectKind()),4420NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),4421IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {4422assert(AssocTypes.size() == AssocExprs.size() &&4423"Must have the same number of association expressions"4424" and TypeSourceInfo!");4425assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");44264427GenericSelectionExprBits.GenericLoc = GenericLoc;4428getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =4429ControllingType;4430std::copy(AssocExprs.begin(), AssocExprs.end(),4431getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());4432std::copy(AssocTypes.begin(), AssocTypes.end(),4433getTrailingObjects<TypeSourceInfo *>() +4434getIndexOfStartOfAssociatedTypes());44354436setDependence(computeDependence(this, ContainsUnexpandedParameterPack));4437}44384439GenericSelectionExpr::GenericSelectionExpr(4440const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,4441ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,4442SourceLocation DefaultLoc, SourceLocation RParenLoc,4443bool ContainsUnexpandedParameterPack)4444: Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,4445OK_Ordinary),4446NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),4447IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {4448assert(AssocTypes.size() == AssocExprs.size() &&4449"Must have the same number of association expressions"4450" and TypeSourceInfo!");44514452GenericSelectionExprBits.GenericLoc = GenericLoc;4453getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =4454ControllingExpr;4455std::copy(AssocExprs.begin(), AssocExprs.end(),4456getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());4457std::copy(AssocTypes.begin(), AssocTypes.end(),4458getTrailingObjects<TypeSourceInfo *>() +4459getIndexOfStartOfAssociatedTypes());44604461setDependence(computeDependence(this, ContainsUnexpandedParameterPack));4462}44634464GenericSelectionExpr::GenericSelectionExpr(4465const ASTContext &Context, SourceLocation GenericLoc,4466TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,4467ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,4468SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack)4469: Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,4470OK_Ordinary),4471NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),4472IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {4473assert(AssocTypes.size() == AssocExprs.size() &&4474"Must have the same number of association expressions"4475" and TypeSourceInfo!");44764477GenericSelectionExprBits.GenericLoc = GenericLoc;4478getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =4479ControllingType;4480std::copy(AssocExprs.begin(), AssocExprs.end(),4481getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());4482std::copy(AssocTypes.begin(), AssocTypes.end(),4483getTrailingObjects<TypeSourceInfo *>() +4484getIndexOfStartOfAssociatedTypes());44854486setDependence(computeDependence(this, ContainsUnexpandedParameterPack));4487}44884489GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)4490: Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}44914492GenericSelectionExpr *GenericSelectionExpr::Create(4493const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,4494ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,4495SourceLocation DefaultLoc, SourceLocation RParenLoc,4496bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {4497unsigned NumAssocs = AssocExprs.size();4498void *Mem = Context.Allocate(4499totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),4500alignof(GenericSelectionExpr));4501return new (Mem) GenericSelectionExpr(4502Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,4503RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);4504}45054506GenericSelectionExpr *GenericSelectionExpr::Create(4507const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,4508ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,4509SourceLocation DefaultLoc, SourceLocation RParenLoc,4510bool ContainsUnexpandedParameterPack) {4511unsigned NumAssocs = AssocExprs.size();4512void *Mem = Context.Allocate(4513totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),4514alignof(GenericSelectionExpr));4515return new (Mem) GenericSelectionExpr(4516Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,4517RParenLoc, ContainsUnexpandedParameterPack);4518}45194520GenericSelectionExpr *GenericSelectionExpr::Create(4521const ASTContext &Context, SourceLocation GenericLoc,4522TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,4523ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,4524SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,4525unsigned ResultIndex) {4526unsigned NumAssocs = AssocExprs.size();4527void *Mem = Context.Allocate(4528totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),4529alignof(GenericSelectionExpr));4530return new (Mem) GenericSelectionExpr(4531Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,4532RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);4533}45344535GenericSelectionExpr *GenericSelectionExpr::Create(4536const ASTContext &Context, SourceLocation GenericLoc,4537TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,4538ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,4539SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) {4540unsigned NumAssocs = AssocExprs.size();4541void *Mem = Context.Allocate(4542totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),4543alignof(GenericSelectionExpr));4544return new (Mem) GenericSelectionExpr(4545Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,4546RParenLoc, ContainsUnexpandedParameterPack);4547}45484549GenericSelectionExpr *4550GenericSelectionExpr::CreateEmpty(const ASTContext &Context,4551unsigned NumAssocs) {4552void *Mem = Context.Allocate(4553totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),4554alignof(GenericSelectionExpr));4555return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);4556}45574558//===----------------------------------------------------------------------===//4559// DesignatedInitExpr4560//===----------------------------------------------------------------------===//45614562const IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {4563assert(isFieldDesignator() && "Only valid on a field designator");4564if (FieldInfo.NameOrField & 0x01)4565return reinterpret_cast<IdentifierInfo *>(FieldInfo.NameOrField & ~0x01);4566return getFieldDecl()->getIdentifier();4567}45684569DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,4570llvm::ArrayRef<Designator> Designators,4571SourceLocation EqualOrColonLoc,4572bool GNUSyntax,4573ArrayRef<Expr *> IndexExprs, Expr *Init)4574: Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),4575Init->getObjectKind()),4576EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),4577NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {4578this->Designators = new (C) Designator[NumDesignators];45794580// Record the initializer itself.4581child_iterator Child = child_begin();4582*Child++ = Init;45834584// Copy the designators and their subexpressions, computing4585// value-dependence along the way.4586unsigned IndexIdx = 0;4587for (unsigned I = 0; I != NumDesignators; ++I) {4588this->Designators[I] = Designators[I];4589if (this->Designators[I].isArrayDesignator()) {4590// Copy the index expressions into permanent storage.4591*Child++ = IndexExprs[IndexIdx++];4592} else if (this->Designators[I].isArrayRangeDesignator()) {4593// Copy the start/end expressions into permanent storage.4594*Child++ = IndexExprs[IndexIdx++];4595*Child++ = IndexExprs[IndexIdx++];4596}4597}45984599assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");4600setDependence(computeDependence(this));4601}46024603DesignatedInitExpr *4604DesignatedInitExpr::Create(const ASTContext &C,4605llvm::ArrayRef<Designator> Designators,4606ArrayRef<Expr*> IndexExprs,4607SourceLocation ColonOrEqualLoc,4608bool UsesColonSyntax, Expr *Init) {4609void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),4610alignof(DesignatedInitExpr));4611return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,4612ColonOrEqualLoc, UsesColonSyntax,4613IndexExprs, Init);4614}46154616DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,4617unsigned NumIndexExprs) {4618void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),4619alignof(DesignatedInitExpr));4620return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);4621}46224623void DesignatedInitExpr::setDesignators(const ASTContext &C,4624const Designator *Desigs,4625unsigned NumDesigs) {4626Designators = new (C) Designator[NumDesigs];4627NumDesignators = NumDesigs;4628for (unsigned I = 0; I != NumDesigs; ++I)4629Designators[I] = Desigs[I];4630}46314632SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {4633DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);4634if (size() == 1)4635return DIE->getDesignator(0)->getSourceRange();4636return SourceRange(DIE->getDesignator(0)->getBeginLoc(),4637DIE->getDesignator(size() - 1)->getEndLoc());4638}46394640SourceLocation DesignatedInitExpr::getBeginLoc() const {4641auto *DIE = const_cast<DesignatedInitExpr *>(this);4642Designator &First = *DIE->getDesignator(0);4643if (First.isFieldDesignator()) {4644// Skip past implicit designators for anonymous structs/unions, since4645// these do not have valid source locations.4646for (unsigned int i = 0; i < DIE->size(); i++) {4647Designator &Des = *DIE->getDesignator(i);4648SourceLocation retval = GNUSyntax ? Des.getFieldLoc() : Des.getDotLoc();4649if (!retval.isValid())4650continue;4651return retval;4652}4653}4654return First.getLBracketLoc();4655}46564657SourceLocation DesignatedInitExpr::getEndLoc() const {4658return getInit()->getEndLoc();4659}46604661Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {4662assert(D.isArrayDesignator() && "Requires array designator");4663return getSubExpr(D.getArrayIndex() + 1);4664}46654666Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {4667assert(D.isArrayRangeDesignator() && "Requires array range designator");4668return getSubExpr(D.getArrayIndex() + 1);4669}46704671Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {4672assert(D.isArrayRangeDesignator() && "Requires array range designator");4673return getSubExpr(D.getArrayIndex() + 2);4674}46754676/// Replaces the designator at index @p Idx with the series4677/// of designators in [First, Last).4678void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,4679const Designator *First,4680const Designator *Last) {4681unsigned NumNewDesignators = Last - First;4682if (NumNewDesignators == 0) {4683std::copy_backward(Designators + Idx + 1,4684Designators + NumDesignators,4685Designators + Idx);4686--NumNewDesignators;4687return;4688}4689if (NumNewDesignators == 1) {4690Designators[Idx] = *First;4691return;4692}46934694Designator *NewDesignators4695= new (C) Designator[NumDesignators - 1 + NumNewDesignators];4696std::copy(Designators, Designators + Idx, NewDesignators);4697std::copy(First, Last, NewDesignators + Idx);4698std::copy(Designators + Idx + 1, Designators + NumDesignators,4699NewDesignators + Idx + NumNewDesignators);4700Designators = NewDesignators;4701NumDesignators = NumDesignators - 1 + NumNewDesignators;4702}47034704DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,4705SourceLocation lBraceLoc,4706Expr *baseExpr,4707SourceLocation rBraceLoc)4708: Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,4709OK_Ordinary) {4710BaseAndUpdaterExprs[0] = baseExpr;47114712InitListExpr *ILE =4713new (C) InitListExpr(C, lBraceLoc, std::nullopt, rBraceLoc);4714ILE->setType(baseExpr->getType());4715BaseAndUpdaterExprs[1] = ILE;47164717// FIXME: this is wrong, set it correctly.4718setDependence(ExprDependence::None);4719}47204721SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {4722return getBase()->getBeginLoc();4723}47244725SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {4726return getBase()->getEndLoc();4727}47284729ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,4730SourceLocation RParenLoc)4731: Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),4732LParenLoc(LParenLoc), RParenLoc(RParenLoc) {4733ParenListExprBits.NumExprs = Exprs.size();47344735for (unsigned I = 0, N = Exprs.size(); I != N; ++I)4736getTrailingObjects<Stmt *>()[I] = Exprs[I];4737setDependence(computeDependence(this));4738}47394740ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)4741: Expr(ParenListExprClass, Empty) {4742ParenListExprBits.NumExprs = NumExprs;4743}47444745ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,4746SourceLocation LParenLoc,4747ArrayRef<Expr *> Exprs,4748SourceLocation RParenLoc) {4749void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),4750alignof(ParenListExpr));4751return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);4752}47534754ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,4755unsigned NumExprs) {4756void *Mem =4757Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));4758return new (Mem) ParenListExpr(EmptyShell(), NumExprs);4759}47604761BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,4762Opcode opc, QualType ResTy, ExprValueKind VK,4763ExprObjectKind OK, SourceLocation opLoc,4764FPOptionsOverride FPFeatures)4765: Expr(BinaryOperatorClass, ResTy, VK, OK) {4766BinaryOperatorBits.Opc = opc;4767assert(!isCompoundAssignmentOp() &&4768"Use CompoundAssignOperator for compound assignments");4769BinaryOperatorBits.OpLoc = opLoc;4770SubExprs[LHS] = lhs;4771SubExprs[RHS] = rhs;4772BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();4773if (hasStoredFPFeatures())4774setStoredFPFeatures(FPFeatures);4775setDependence(computeDependence(this));4776}47774778BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,4779Opcode opc, QualType ResTy, ExprValueKind VK,4780ExprObjectKind OK, SourceLocation opLoc,4781FPOptionsOverride FPFeatures, bool dead2)4782: Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {4783BinaryOperatorBits.Opc = opc;4784assert(isCompoundAssignmentOp() &&4785"Use CompoundAssignOperator for compound assignments");4786BinaryOperatorBits.OpLoc = opLoc;4787SubExprs[LHS] = lhs;4788SubExprs[RHS] = rhs;4789BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();4790if (hasStoredFPFeatures())4791setStoredFPFeatures(FPFeatures);4792setDependence(computeDependence(this));4793}47944795BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C,4796bool HasFPFeatures) {4797unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);4798void *Mem =4799C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));4800return new (Mem) BinaryOperator(EmptyShell());4801}48024803BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs,4804Expr *rhs, Opcode opc, QualType ResTy,4805ExprValueKind VK, ExprObjectKind OK,4806SourceLocation opLoc,4807FPOptionsOverride FPFeatures) {4808bool HasFPFeatures = FPFeatures.requiresTrailingStorage();4809unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);4810void *Mem =4811C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));4812return new (Mem)4813BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);4814}48154816CompoundAssignOperator *4817CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) {4818unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);4819void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,4820alignof(CompoundAssignOperator));4821return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);4822}48234824CompoundAssignOperator *4825CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs,4826Opcode opc, QualType ResTy, ExprValueKind VK,4827ExprObjectKind OK, SourceLocation opLoc,4828FPOptionsOverride FPFeatures,4829QualType CompLHSType, QualType CompResultType) {4830bool HasFPFeatures = FPFeatures.requiresTrailingStorage();4831unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);4832void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,4833alignof(CompoundAssignOperator));4834return new (Mem)4835CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,4836CompLHSType, CompResultType);4837}48384839UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C,4840bool hasFPFeatures) {4841void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),4842alignof(UnaryOperator));4843return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());4844}48454846UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc,4847QualType type, ExprValueKind VK, ExprObjectKind OK,4848SourceLocation l, bool CanOverflow,4849FPOptionsOverride FPFeatures)4850: Expr(UnaryOperatorClass, type, VK, OK), Val(input) {4851UnaryOperatorBits.Opc = opc;4852UnaryOperatorBits.CanOverflow = CanOverflow;4853UnaryOperatorBits.Loc = l;4854UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();4855if (hasStoredFPFeatures())4856setStoredFPFeatures(FPFeatures);4857setDependence(computeDependence(this, Ctx));4858}48594860UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input,4861Opcode opc, QualType type,4862ExprValueKind VK, ExprObjectKind OK,4863SourceLocation l, bool CanOverflow,4864FPOptionsOverride FPFeatures) {4865bool HasFPFeatures = FPFeatures.requiresTrailingStorage();4866unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);4867void *Mem = C.Allocate(Size, alignof(UnaryOperator));4868return new (Mem)4869UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);4870}48714872const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {4873if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))4874e = ewc->getSubExpr();4875if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))4876e = m->getSubExpr();4877e = cast<CXXConstructExpr>(e)->getArg(0);4878while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))4879e = ice->getSubExpr();4880return cast<OpaqueValueExpr>(e);4881}48824883PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,4884EmptyShell sh,4885unsigned numSemanticExprs) {4886void *buffer =4887Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),4888alignof(PseudoObjectExpr));4889return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);4890}48914892PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)4893: Expr(PseudoObjectExprClass, shell) {4894PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;4895}48964897PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,4898ArrayRef<Expr*> semantics,4899unsigned resultIndex) {4900assert(syntax && "no syntactic expression!");4901assert(semantics.size() && "no semantic expressions!");49024903QualType type;4904ExprValueKind VK;4905if (resultIndex == NoResult) {4906type = C.VoidTy;4907VK = VK_PRValue;4908} else {4909assert(resultIndex < semantics.size());4910type = semantics[resultIndex]->getType();4911VK = semantics[resultIndex]->getValueKind();4912assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);4913}49144915void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),4916alignof(PseudoObjectExpr));4917return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,4918resultIndex);4919}49204921PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,4922Expr *syntax, ArrayRef<Expr *> semantics,4923unsigned resultIndex)4924: Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {4925PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;4926PseudoObjectExprBits.ResultIndex = resultIndex + 1;49274928for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {4929Expr *E = (i == 0 ? syntax : semantics[i-1]);4930getSubExprsBuffer()[i] = E;49314932if (isa<OpaqueValueExpr>(E))4933assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&4934"opaque-value semantic expressions for pseudo-object "4935"operations must have sources");4936}49374938setDependence(computeDependence(this));4939}49404941//===----------------------------------------------------------------------===//4942// Child Iterators for iterating over subexpressions/substatements4943//===----------------------------------------------------------------------===//49444945// UnaryExprOrTypeTraitExpr4946Stmt::child_range UnaryExprOrTypeTraitExpr::children() {4947const_child_range CCR =4948const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();4949return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));4950}49514952Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {4953// If this is of a type and the type is a VLA type (and not a typedef), the4954// size expression of the VLA needs to be treated as an executable expression.4955// Why isn't this weirdness documented better in StmtIterator?4956if (isArgumentType()) {4957if (const VariableArrayType *T =4958dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))4959return const_child_range(const_child_iterator(T), const_child_iterator());4960return const_child_range(const_child_iterator(), const_child_iterator());4961}4962return const_child_range(&Argument.Ex, &Argument.Ex + 1);4963}49644965AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t,4966AtomicOp op, SourceLocation RP)4967: Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),4968NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {4969assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");4970for (unsigned i = 0; i != args.size(); i++)4971SubExprs[i] = args[i];4972setDependence(computeDependence(this));4973}49744975unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {4976switch (Op) {4977case AO__c11_atomic_init:4978case AO__opencl_atomic_init:4979case AO__c11_atomic_load:4980case AO__atomic_load_n:4981return 2;49824983case AO__scoped_atomic_load_n:4984case AO__opencl_atomic_load:4985case AO__hip_atomic_load:4986case AO__c11_atomic_store:4987case AO__c11_atomic_exchange:4988case AO__atomic_load:4989case AO__atomic_store:4990case AO__atomic_store_n:4991case AO__atomic_exchange_n:4992case AO__c11_atomic_fetch_add:4993case AO__c11_atomic_fetch_sub:4994case AO__c11_atomic_fetch_and:4995case AO__c11_atomic_fetch_or:4996case AO__c11_atomic_fetch_xor:4997case AO__c11_atomic_fetch_nand:4998case AO__c11_atomic_fetch_max:4999case AO__c11_atomic_fetch_min:5000case AO__atomic_fetch_add:5001case AO__atomic_fetch_sub:5002case AO__atomic_fetch_and:5003case AO__atomic_fetch_or:5004case AO__atomic_fetch_xor:5005case AO__atomic_fetch_nand:5006case AO__atomic_add_fetch:5007case AO__atomic_sub_fetch:5008case AO__atomic_and_fetch:5009case AO__atomic_or_fetch:5010case AO__atomic_xor_fetch:5011case AO__atomic_nand_fetch:5012case AO__atomic_min_fetch:5013case AO__atomic_max_fetch:5014case AO__atomic_fetch_min:5015case AO__atomic_fetch_max:5016return 3;50175018case AO__scoped_atomic_load:5019case AO__scoped_atomic_store:5020case AO__scoped_atomic_store_n:5021case AO__scoped_atomic_fetch_add:5022case AO__scoped_atomic_fetch_sub:5023case AO__scoped_atomic_fetch_and:5024case AO__scoped_atomic_fetch_or:5025case AO__scoped_atomic_fetch_xor:5026case AO__scoped_atomic_fetch_nand:5027case AO__scoped_atomic_add_fetch:5028case AO__scoped_atomic_sub_fetch:5029case AO__scoped_atomic_and_fetch:5030case AO__scoped_atomic_or_fetch:5031case AO__scoped_atomic_xor_fetch:5032case AO__scoped_atomic_nand_fetch:5033case AO__scoped_atomic_min_fetch:5034case AO__scoped_atomic_max_fetch:5035case AO__scoped_atomic_fetch_min:5036case AO__scoped_atomic_fetch_max:5037case AO__scoped_atomic_exchange_n:5038case AO__hip_atomic_exchange:5039case AO__hip_atomic_fetch_add:5040case AO__hip_atomic_fetch_sub:5041case AO__hip_atomic_fetch_and:5042case AO__hip_atomic_fetch_or:5043case AO__hip_atomic_fetch_xor:5044case AO__hip_atomic_fetch_min:5045case AO__hip_atomic_fetch_max:5046case AO__opencl_atomic_store:5047case AO__hip_atomic_store:5048case AO__opencl_atomic_exchange:5049case AO__opencl_atomic_fetch_add:5050case AO__opencl_atomic_fetch_sub:5051case AO__opencl_atomic_fetch_and:5052case AO__opencl_atomic_fetch_or:5053case AO__opencl_atomic_fetch_xor:5054case AO__opencl_atomic_fetch_min:5055case AO__opencl_atomic_fetch_max:5056case AO__atomic_exchange:5057return 4;50585059case AO__scoped_atomic_exchange:5060case AO__c11_atomic_compare_exchange_strong:5061case AO__c11_atomic_compare_exchange_weak:5062return 5;5063case AO__hip_atomic_compare_exchange_strong:5064case AO__opencl_atomic_compare_exchange_strong:5065case AO__opencl_atomic_compare_exchange_weak:5066case AO__hip_atomic_compare_exchange_weak:5067case AO__atomic_compare_exchange:5068case AO__atomic_compare_exchange_n:5069return 6;50705071case AO__scoped_atomic_compare_exchange:5072case AO__scoped_atomic_compare_exchange_n:5073return 7;5074}5075llvm_unreachable("unknown atomic op");5076}50775078QualType AtomicExpr::getValueType() const {5079auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();5080if (auto AT = T->getAs<AtomicType>())5081return AT->getValueType();5082return T;5083}50845085QualType ArraySectionExpr::getBaseOriginalType(const Expr *Base) {5086unsigned ArraySectionCount = 0;5087while (auto *OASE = dyn_cast<ArraySectionExpr>(Base->IgnoreParens())) {5088Base = OASE->getBase();5089++ArraySectionCount;5090}5091while (auto *ASE =5092dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {5093Base = ASE->getBase();5094++ArraySectionCount;5095}5096Base = Base->IgnoreParenImpCasts();5097auto OriginalTy = Base->getType();5098if (auto *DRE = dyn_cast<DeclRefExpr>(Base))5099if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))5100OriginalTy = PVD->getOriginalType().getNonReferenceType();51015102for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {5103if (OriginalTy->isAnyPointerType())5104OriginalTy = OriginalTy->getPointeeType();5105else if (OriginalTy->isArrayType())5106OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();5107else5108return {};5109}5110return OriginalTy;5111}51125113RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,5114SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)5115: Expr(RecoveryExprClass, T.getNonReferenceType(),5116T->isDependentType() ? VK_LValue : getValueKindForType(T),5117OK_Ordinary),5118BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {5119assert(!T.isNull());5120assert(!llvm::is_contained(SubExprs, nullptr));51215122llvm::copy(SubExprs, getTrailingObjects<Expr *>());5123setDependence(computeDependence(this));5124}51255126RecoveryExpr *RecoveryExpr::Create(ASTContext &Ctx, QualType T,5127SourceLocation BeginLoc,5128SourceLocation EndLoc,5129ArrayRef<Expr *> SubExprs) {5130void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()),5131alignof(RecoveryExpr));5132return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs);5133}51345135RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) {5136void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs),5137alignof(RecoveryExpr));5138return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs);5139}51405141void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) {5142assert(5143NumDims == Dims.size() &&5144"Preallocated number of dimensions is different from the provided one.");5145llvm::copy(Dims, getTrailingObjects<Expr *>());5146}51475148void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) {5149assert(5150NumDims == BR.size() &&5151"Preallocated number of dimensions is different from the provided one.");5152llvm::copy(BR, getTrailingObjects<SourceRange>());5153}51545155OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op,5156SourceLocation L, SourceLocation R,5157ArrayRef<Expr *> Dims)5158: Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L),5159RPLoc(R), NumDims(Dims.size()) {5160setBase(Op);5161setDimensions(Dims);5162setDependence(computeDependence(this));5163}51645165OMPArrayShapingExpr *5166OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op,5167SourceLocation L, SourceLocation R,5168ArrayRef<Expr *> Dims,5169ArrayRef<SourceRange> BracketRanges) {5170assert(Dims.size() == BracketRanges.size() &&5171"Different number of dimensions and brackets ranges.");5172void *Mem = Context.Allocate(5173totalSizeToAlloc<Expr *, SourceRange>(Dims.size() + 1, Dims.size()),5174alignof(OMPArrayShapingExpr));5175auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims);5176E->setBracketsRanges(BracketRanges);5177return E;5178}51795180OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context,5181unsigned NumDims) {5182void *Mem = Context.Allocate(5183totalSizeToAlloc<Expr *, SourceRange>(NumDims + 1, NumDims),5184alignof(OMPArrayShapingExpr));5185return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims);5186}51875188void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) {5189assert(I < NumIterators &&5190"Idx is greater or equal the number of iterators definitions.");5191getTrailingObjects<Decl *>()[I] = D;5192}51935194void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) {5195assert(I < NumIterators &&5196"Idx is greater or equal the number of iterators definitions.");5197getTrailingObjects<5198SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +5199static_cast<int>(RangeLocOffset::AssignLoc)] = Loc;5200}52015202void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin,5203SourceLocation ColonLoc, Expr *End,5204SourceLocation SecondColonLoc,5205Expr *Step) {5206assert(I < NumIterators &&5207"Idx is greater or equal the number of iterators definitions.");5208getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +5209static_cast<int>(RangeExprOffset::Begin)] =5210Begin;5211getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +5212static_cast<int>(RangeExprOffset::End)] = End;5213getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +5214static_cast<int>(RangeExprOffset::Step)] = Step;5215getTrailingObjects<5216SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +5217static_cast<int>(RangeLocOffset::FirstColonLoc)] =5218ColonLoc;5219getTrailingObjects<5220SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +5221static_cast<int>(RangeLocOffset::SecondColonLoc)] =5222SecondColonLoc;5223}52245225Decl *OMPIteratorExpr::getIteratorDecl(unsigned I) {5226return getTrailingObjects<Decl *>()[I];5227}52285229OMPIteratorExpr::IteratorRange OMPIteratorExpr::getIteratorRange(unsigned I) {5230IteratorRange Res;5231Res.Begin =5232getTrailingObjects<Expr *>()[I * static_cast<int>(5233RangeExprOffset::Total) +5234static_cast<int>(RangeExprOffset::Begin)];5235Res.End =5236getTrailingObjects<Expr *>()[I * static_cast<int>(5237RangeExprOffset::Total) +5238static_cast<int>(RangeExprOffset::End)];5239Res.Step =5240getTrailingObjects<Expr *>()[I * static_cast<int>(5241RangeExprOffset::Total) +5242static_cast<int>(RangeExprOffset::Step)];5243return Res;5244}52455246SourceLocation OMPIteratorExpr::getAssignLoc(unsigned I) const {5247return getTrailingObjects<5248SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +5249static_cast<int>(RangeLocOffset::AssignLoc)];5250}52515252SourceLocation OMPIteratorExpr::getColonLoc(unsigned I) const {5253return getTrailingObjects<5254SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +5255static_cast<int>(RangeLocOffset::FirstColonLoc)];5256}52575258SourceLocation OMPIteratorExpr::getSecondColonLoc(unsigned I) const {5259return getTrailingObjects<5260SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +5261static_cast<int>(RangeLocOffset::SecondColonLoc)];5262}52635264void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) {5265getTrailingObjects<OMPIteratorHelperData>()[I] = D;5266}52675268OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) {5269return getTrailingObjects<OMPIteratorHelperData>()[I];5270}52715272const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const {5273return getTrailingObjects<OMPIteratorHelperData>()[I];5274}52755276OMPIteratorExpr::OMPIteratorExpr(5277QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L,5278SourceLocation R, ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,5279ArrayRef<OMPIteratorHelperData> Helpers)5280: Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary),5281IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R),5282NumIterators(Data.size()) {5283for (unsigned I = 0, E = Data.size(); I < E; ++I) {5284const IteratorDefinition &D = Data[I];5285setIteratorDeclaration(I, D.IteratorDecl);5286setAssignmentLoc(I, D.AssignmentLoc);5287setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End,5288D.SecondColonLoc, D.Range.Step);5289setHelper(I, Helpers[I]);5290}5291setDependence(computeDependence(this));5292}52935294OMPIteratorExpr *5295OMPIteratorExpr::Create(const ASTContext &Context, QualType T,5296SourceLocation IteratorKwLoc, SourceLocation L,5297SourceLocation R,5298ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,5299ArrayRef<OMPIteratorHelperData> Helpers) {5300assert(Data.size() == Helpers.size() &&5301"Data and helpers must have the same size.");5302void *Mem = Context.Allocate(5303totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(5304Data.size(), Data.size() * static_cast<int>(RangeExprOffset::Total),5305Data.size() * static_cast<int>(RangeLocOffset::Total),5306Helpers.size()),5307alignof(OMPIteratorExpr));5308return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers);5309}53105311OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context,5312unsigned NumIterators) {5313void *Mem = Context.Allocate(5314totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(5315NumIterators, NumIterators * static_cast<int>(RangeExprOffset::Total),5316NumIterators * static_cast<int>(RangeLocOffset::Total), NumIterators),5317alignof(OMPIteratorExpr));5318return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators);5319}532053215322