brintos

brintos / llvm-project-archived public Read only

0
0
Text · 82.9 KiB · c7f0ff0 Raw
2023 lines · cpp
1//===- ExprCXX.cpp - (C++) Expression AST Node Implementation -------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// This file implements the subclesses of Expr class declared in ExprCXX.h10//11//===----------------------------------------------------------------------===//12 13#include "clang/AST/ExprCXX.h"14#include "clang/AST/ASTContext.h"15#include "clang/AST/Attr.h"16#include "clang/AST/ComputeDependence.h"17#include "clang/AST/Decl.h"18#include "clang/AST/DeclAccessPair.h"19#include "clang/AST/DeclBase.h"20#include "clang/AST/DeclCXX.h"21#include "clang/AST/DeclTemplate.h"22#include "clang/AST/DeclarationName.h"23#include "clang/AST/DependenceFlags.h"24#include "clang/AST/Expr.h"25#include "clang/AST/LambdaCapture.h"26#include "clang/AST/NestedNameSpecifier.h"27#include "clang/AST/TemplateBase.h"28#include "clang/AST/Type.h"29#include "clang/AST/TypeLoc.h"30#include "clang/Basic/LLVM.h"31#include "clang/Basic/OperatorKinds.h"32#include "clang/Basic/SourceLocation.h"33#include "clang/Basic/Specifiers.h"34#include "llvm/ADT/ArrayRef.h"35#include "llvm/Support/ErrorHandling.h"36#include <cassert>37#include <cstddef>38#include <cstring>39#include <memory>40#include <optional>41 42using namespace clang;43 44//===----------------------------------------------------------------------===//45//  Child Iterators for iterating over subexpressions/substatements46//===----------------------------------------------------------------------===//47 48bool CXXOperatorCallExpr::isInfixBinaryOp() const {49  // An infix binary operator is any operator with two arguments other than50  // operator() and operator[]. Note that none of these operators can have51  // default arguments, so it suffices to check the number of argument52  // expressions.53  if (getNumArgs() != 2)54    return false;55 56  switch (getOperator()) {57  case OO_Call: case OO_Subscript:58    return false;59  default:60    return true;61  }62}63 64CXXRewrittenBinaryOperator::DecomposedForm65CXXRewrittenBinaryOperator::getDecomposedForm() const {66  DecomposedForm Result = {};67  const Expr *E = getSemanticForm()->IgnoreImplicit();68 69  // Remove an outer '!' if it exists (only happens for a '!=' rewrite).70  bool SkippedNot = false;71  if (auto *NotEq = dyn_cast<UnaryOperator>(E)) {72    assert(NotEq->getOpcode() == UO_LNot);73    E = NotEq->getSubExpr()->IgnoreImplicit();74    SkippedNot = true;75  }76 77  // Decompose the outer binary operator.78  if (auto *BO = dyn_cast<BinaryOperator>(E)) {79    assert(!SkippedNot || BO->getOpcode() == BO_EQ);80    Result.Opcode = SkippedNot ? BO_NE : BO->getOpcode();81    Result.LHS = BO->getLHS();82    Result.RHS = BO->getRHS();83    Result.InnerBinOp = BO;84  } else if (auto *BO = dyn_cast<CXXOperatorCallExpr>(E)) {85    assert(!SkippedNot || BO->getOperator() == OO_EqualEqual);86    assert(BO->isInfixBinaryOp());87    switch (BO->getOperator()) {88    case OO_Less: Result.Opcode = BO_LT; break;89    case OO_LessEqual: Result.Opcode = BO_LE; break;90    case OO_Greater: Result.Opcode = BO_GT; break;91    case OO_GreaterEqual: Result.Opcode = BO_GE; break;92    case OO_Spaceship: Result.Opcode = BO_Cmp; break;93    case OO_EqualEqual: Result.Opcode = SkippedNot ? BO_NE : BO_EQ; break;94    default: llvm_unreachable("unexpected binop in rewritten operator expr");95    }96    Result.LHS = BO->getArg(0);97    Result.RHS = BO->getArg(1);98    Result.InnerBinOp = BO;99  } else {100    llvm_unreachable("unexpected rewritten operator form");101  }102 103  // Put the operands in the right order for == and !=, and canonicalize the104  // <=> subexpression onto the LHS for all other forms.105  if (isReversed())106    std::swap(Result.LHS, Result.RHS);107 108  // If this isn't a spaceship rewrite, we're done.109  if (Result.Opcode == BO_EQ || Result.Opcode == BO_NE)110    return Result;111 112  // Otherwise, we expect a <=> to now be on the LHS.113  E = Result.LHS->IgnoreUnlessSpelledInSource();114  if (auto *BO = dyn_cast<BinaryOperator>(E)) {115    assert(BO->getOpcode() == BO_Cmp);116    Result.LHS = BO->getLHS();117    Result.RHS = BO->getRHS();118    Result.InnerBinOp = BO;119  } else if (auto *BO = dyn_cast<CXXOperatorCallExpr>(E)) {120    assert(BO->getOperator() == OO_Spaceship);121    Result.LHS = BO->getArg(0);122    Result.RHS = BO->getArg(1);123    Result.InnerBinOp = BO;124  } else {125    llvm_unreachable("unexpected rewritten operator form");126  }127 128  // Put the comparison operands in the right order.129  if (isReversed())130    std::swap(Result.LHS, Result.RHS);131  return Result;132}133 134bool CXXTypeidExpr::isPotentiallyEvaluated() const {135  if (isTypeOperand())136    return false;137 138  // C++11 [expr.typeid]p3:139  //   When typeid is applied to an expression other than a glvalue of140  //   polymorphic class type, [...] the expression is an unevaluated operand.141  const Expr *E = getExprOperand();142  if (const CXXRecordDecl *RD = E->getType()->getAsCXXRecordDecl())143    if (RD->isPolymorphic() && E->isGLValue())144      return true;145 146  return false;147}148 149bool CXXTypeidExpr::isMostDerived(const ASTContext &Context) const {150  assert(!isTypeOperand() && "Cannot call isMostDerived for typeid(type)");151  const Expr *E = getExprOperand()->IgnoreParenNoopCasts(Context);152  if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {153    QualType Ty = DRE->getDecl()->getType();154    if (!Ty->isPointerOrReferenceType())155      return true;156  }157 158  return false;159}160 161QualType CXXTypeidExpr::getTypeOperand(const ASTContext &Context) const {162  assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");163  Qualifiers Quals;164  return Context.getUnqualifiedArrayType(165      cast<TypeSourceInfo *>(Operand)->getType().getNonReferenceType(), Quals);166}167 168static bool isGLValueFromPointerDeref(const Expr *E) {169  E = E->IgnoreParens();170 171  if (const auto *CE = dyn_cast<CastExpr>(E)) {172    if (!CE->getSubExpr()->isGLValue())173      return false;174    return isGLValueFromPointerDeref(CE->getSubExpr());175  }176 177  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))178    return isGLValueFromPointerDeref(OVE->getSourceExpr());179 180  if (const auto *BO = dyn_cast<BinaryOperator>(E))181    if (BO->getOpcode() == BO_Comma)182      return isGLValueFromPointerDeref(BO->getRHS());183 184  if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))185    return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||186           isGLValueFromPointerDeref(ACO->getFalseExpr());187 188  // C++11 [expr.sub]p1:189  //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))190  if (isa<ArraySubscriptExpr>(E))191    return true;192 193  if (const auto *UO = dyn_cast<UnaryOperator>(E))194    if (UO->getOpcode() == UO_Deref)195      return true;196 197  return false;198}199 200bool CXXTypeidExpr::hasNullCheck() const {201  if (!isPotentiallyEvaluated())202    return false;203 204  // C++ [expr.typeid]p2:205  //   If the glvalue expression is obtained by applying the unary * operator to206  //   a pointer and the pointer is a null pointer value, the typeid expression207  //   throws the std::bad_typeid exception.208  //209  // However, this paragraph's intent is not clear.  We choose a very generous210  // interpretation which implores us to consider comma operators, conditional211  // operators, parentheses and other such constructs.212  return isGLValueFromPointerDeref(getExprOperand());213}214 215QualType CXXUuidofExpr::getTypeOperand(ASTContext &Context) const {216  assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");217  Qualifiers Quals;218  return Context.getUnqualifiedArrayType(219      cast<TypeSourceInfo *>(Operand)->getType().getNonReferenceType(), Quals);220}221 222// CXXScalarValueInitExpr223SourceLocation CXXScalarValueInitExpr::getBeginLoc() const {224  return TypeInfo ? TypeInfo->getTypeLoc().getBeginLoc() : getRParenLoc();225}226 227// CXXNewExpr228CXXNewExpr::CXXNewExpr(bool IsGlobalNew, FunctionDecl *OperatorNew,229                       FunctionDecl *OperatorDelete,230                       const ImplicitAllocationParameters &IAP,231                       bool UsualArrayDeleteWantsSize,232                       ArrayRef<Expr *> PlacementArgs, SourceRange TypeIdParens,233                       std::optional<Expr *> ArraySize,234                       CXXNewInitializationStyle InitializationStyle,235                       Expr *Initializer, QualType Ty,236                       TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,237                       SourceRange DirectInitRange)238    : Expr(CXXNewExprClass, Ty, VK_PRValue, OK_Ordinary),239      OperatorNew(OperatorNew), OperatorDelete(OperatorDelete),240      AllocatedTypeInfo(AllocatedTypeInfo), Range(Range),241      DirectInitRange(DirectInitRange) {242 243  assert((Initializer != nullptr ||244          InitializationStyle == CXXNewInitializationStyle::None) &&245         "Only CXXNewInitializationStyle::None can have no initializer!");246 247  CXXNewExprBits.IsGlobalNew = IsGlobalNew;248  CXXNewExprBits.IsArray = ArraySize.has_value();249  CXXNewExprBits.ShouldPassAlignment = isAlignedAllocation(IAP.PassAlignment);250  CXXNewExprBits.ShouldPassTypeIdentity =251      isTypeAwareAllocation(IAP.PassTypeIdentity);252  CXXNewExprBits.UsualArrayDeleteWantsSize = UsualArrayDeleteWantsSize;253  CXXNewExprBits.HasInitializer = Initializer != nullptr;254  CXXNewExprBits.StoredInitializationStyle =255      llvm::to_underlying(InitializationStyle);256  bool IsParenTypeId = TypeIdParens.isValid();257  CXXNewExprBits.IsParenTypeId = IsParenTypeId;258  CXXNewExprBits.NumPlacementArgs = PlacementArgs.size();259 260  if (ArraySize)261    getTrailingObjects<Stmt *>()[arraySizeOffset()] = *ArraySize;262  if (Initializer)263    getTrailingObjects<Stmt *>()[initExprOffset()] = Initializer;264  llvm::copy(PlacementArgs,265             getTrailingObjects<Stmt *>() + placementNewArgsOffset());266  if (IsParenTypeId)267    getTrailingObjects<SourceRange>()[0] = TypeIdParens;268 269  switch (getInitializationStyle()) {270  case CXXNewInitializationStyle::Parens:271    this->Range.setEnd(DirectInitRange.getEnd());272    break;273  case CXXNewInitializationStyle::Braces:274    this->Range.setEnd(getInitializer()->getSourceRange().getEnd());275    break;276  default:277    if (IsParenTypeId)278      this->Range.setEnd(TypeIdParens.getEnd());279    break;280  }281 282  setDependence(computeDependence(this));283}284 285CXXNewExpr::CXXNewExpr(EmptyShell Empty, bool IsArray,286                       unsigned NumPlacementArgs, bool IsParenTypeId)287    : Expr(CXXNewExprClass, Empty) {288  CXXNewExprBits.IsArray = IsArray;289  CXXNewExprBits.NumPlacementArgs = NumPlacementArgs;290  CXXNewExprBits.IsParenTypeId = IsParenTypeId;291}292 293CXXNewExpr *CXXNewExpr::Create(294    const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew,295    FunctionDecl *OperatorDelete, const ImplicitAllocationParameters &IAP,296    bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs,297    SourceRange TypeIdParens, std::optional<Expr *> ArraySize,298    CXXNewInitializationStyle InitializationStyle, Expr *Initializer,299    QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,300    SourceRange DirectInitRange) {301  bool IsArray = ArraySize.has_value();302  bool HasInit = Initializer != nullptr;303  unsigned NumPlacementArgs = PlacementArgs.size();304  bool IsParenTypeId = TypeIdParens.isValid();305  void *Mem =306      Ctx.Allocate(totalSizeToAlloc<Stmt *, SourceRange>(307                       IsArray + HasInit + NumPlacementArgs, IsParenTypeId),308                   alignof(CXXNewExpr));309  return new (Mem) CXXNewExpr(310      IsGlobalNew, OperatorNew, OperatorDelete, IAP, UsualArrayDeleteWantsSize,311      PlacementArgs, TypeIdParens, ArraySize, InitializationStyle, Initializer,312      Ty, AllocatedTypeInfo, Range, DirectInitRange);313}314 315CXXNewExpr *CXXNewExpr::CreateEmpty(const ASTContext &Ctx, bool IsArray,316                                    bool HasInit, unsigned NumPlacementArgs,317                                    bool IsParenTypeId) {318  void *Mem =319      Ctx.Allocate(totalSizeToAlloc<Stmt *, SourceRange>(320                       IsArray + HasInit + NumPlacementArgs, IsParenTypeId),321                   alignof(CXXNewExpr));322  return new (Mem)323      CXXNewExpr(EmptyShell(), IsArray, NumPlacementArgs, IsParenTypeId);324}325 326bool CXXNewExpr::shouldNullCheckAllocation() const {327  if (getOperatorNew()->getLangOpts().CheckNew)328    return true;329  return !getOperatorNew()->hasAttr<ReturnsNonNullAttr>() &&330         getOperatorNew()331             ->getType()332             ->castAs<FunctionProtoType>()333             ->isNothrow() &&334         !getOperatorNew()->isReservedGlobalPlacementOperator();335}336 337// CXXDeleteExpr338QualType CXXDeleteExpr::getDestroyedType() const {339  const Expr *Arg = getArgument();340 341  // For a destroying operator delete, we may have implicitly converted the342  // pointer type to the type of the parameter of the 'operator delete'343  // function.344  while (const auto *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {345    if (ICE->getCastKind() == CK_DerivedToBase ||346        ICE->getCastKind() == CK_UncheckedDerivedToBase ||347        ICE->getCastKind() == CK_NoOp) {348      assert((ICE->getCastKind() == CK_NoOp ||349              getOperatorDelete()->isDestroyingOperatorDelete()) &&350             "only a destroying operator delete can have a converted arg");351      Arg = ICE->getSubExpr();352    } else353      break;354  }355 356  // The type-to-delete may not be a pointer if it's a dependent type.357  const QualType ArgType = Arg->getType();358 359  if (ArgType->isDependentType() && !ArgType->isPointerType())360    return QualType();361 362  return ArgType->castAs<PointerType>()->getPointeeType();363}364 365// CXXPseudoDestructorExpr366PseudoDestructorTypeStorage::PseudoDestructorTypeStorage(TypeSourceInfo *Info)367    : Type(Info) {368  Location = Info->getTypeLoc().getBeginLoc();369}370 371CXXPseudoDestructorExpr::CXXPseudoDestructorExpr(372    const ASTContext &Context, Expr *Base, bool isArrow,373    SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,374    TypeSourceInfo *ScopeType, SourceLocation ColonColonLoc,375    SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType)376    : Expr(CXXPseudoDestructorExprClass, Context.BoundMemberTy, VK_PRValue,377           OK_Ordinary),378      Base(static_cast<Stmt *>(Base)), IsArrow(isArrow),379      OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),380      ScopeType(ScopeType), ColonColonLoc(ColonColonLoc), TildeLoc(TildeLoc),381      DestroyedType(DestroyedType) {382  setDependence(computeDependence(this));383}384 385QualType CXXPseudoDestructorExpr::getDestroyedType() const {386  if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo())387    return TInfo->getType();388 389  return QualType();390}391 392SourceLocation CXXPseudoDestructorExpr::getEndLoc() const {393  SourceLocation End = DestroyedType.getLocation();394  if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo())395    End = TInfo->getTypeLoc().getSourceRange().getEnd();396  return End;397}398 399static bool UnresolvedLookupExprIsVariableOrConceptParameterPack(400    UnresolvedSetIterator Begin, UnresolvedSetIterator End) {401  if (std::distance(Begin, End) != 1)402    return false;403  NamedDecl *ND = *Begin;404  if (const auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(ND))405    return TTP->isParameterPack();406  return false;407}408 409// UnresolvedLookupExpr410UnresolvedLookupExpr::UnresolvedLookupExpr(411    const ASTContext &Context, CXXRecordDecl *NamingClass,412    NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,413    const DeclarationNameInfo &NameInfo, bool RequiresADL,414    const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,415    UnresolvedSetIterator End, bool KnownDependent,416    bool KnownInstantiationDependent)417    : OverloadExpr(418          UnresolvedLookupExprClass, Context, QualifierLoc, TemplateKWLoc,419          NameInfo, TemplateArgs, Begin, End, KnownDependent,420          KnownInstantiationDependent,421          UnresolvedLookupExprIsVariableOrConceptParameterPack(Begin, End)),422      NamingClass(NamingClass) {423  UnresolvedLookupExprBits.RequiresADL = RequiresADL;424}425 426UnresolvedLookupExpr::UnresolvedLookupExpr(EmptyShell Empty,427                                           unsigned NumResults,428                                           bool HasTemplateKWAndArgsInfo)429    : OverloadExpr(UnresolvedLookupExprClass, Empty, NumResults,430                   HasTemplateKWAndArgsInfo) {}431 432UnresolvedLookupExpr *UnresolvedLookupExpr::Create(433    const ASTContext &Context, CXXRecordDecl *NamingClass,434    NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo,435    bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End,436    bool KnownDependent, bool KnownInstantiationDependent) {437  unsigned NumResults = End - Begin;438  unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,439                                   TemplateArgumentLoc>(NumResults, 0, 0);440  void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));441  return new (Mem) UnresolvedLookupExpr(442      Context, NamingClass, QualifierLoc,443      /*TemplateKWLoc=*/SourceLocation(), NameInfo, RequiresADL,444      /*TemplateArgs=*/nullptr, Begin, End, KnownDependent,445      KnownInstantiationDependent);446}447 448UnresolvedLookupExpr *UnresolvedLookupExpr::Create(449    const ASTContext &Context, CXXRecordDecl *NamingClass,450    NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,451    const DeclarationNameInfo &NameInfo, bool RequiresADL,452    const TemplateArgumentListInfo *Args, UnresolvedSetIterator Begin,453    UnresolvedSetIterator End, bool KnownDependent,454    bool KnownInstantiationDependent) {455  unsigned NumResults = End - Begin;456  bool HasTemplateKWAndArgsInfo = Args || TemplateKWLoc.isValid();457  unsigned NumTemplateArgs = Args ? Args->size() : 0;458  unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,459                                   TemplateArgumentLoc>(460      NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);461  void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));462  return new (Mem) UnresolvedLookupExpr(463      Context, NamingClass, QualifierLoc, TemplateKWLoc, NameInfo, RequiresADL,464      Args, Begin, End, KnownDependent, KnownInstantiationDependent);465}466 467UnresolvedLookupExpr *UnresolvedLookupExpr::CreateEmpty(468    const ASTContext &Context, unsigned NumResults,469    bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) {470  assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);471  unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,472                                   TemplateArgumentLoc>(473      NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);474  void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));475  return new (Mem)476      UnresolvedLookupExpr(EmptyShell(), NumResults, HasTemplateKWAndArgsInfo);477}478 479OverloadExpr::OverloadExpr(StmtClass SC, const ASTContext &Context,480                           NestedNameSpecifierLoc QualifierLoc,481                           SourceLocation TemplateKWLoc,482                           const DeclarationNameInfo &NameInfo,483                           const TemplateArgumentListInfo *TemplateArgs,484                           UnresolvedSetIterator Begin,485                           UnresolvedSetIterator End, bool KnownDependent,486                           bool KnownInstantiationDependent,487                           bool KnownContainsUnexpandedParameterPack)488    : Expr(SC, Context.OverloadTy, VK_LValue, OK_Ordinary), NameInfo(NameInfo),489      QualifierLoc(QualifierLoc) {490  unsigned NumResults = End - Begin;491  OverloadExprBits.NumResults = NumResults;492  OverloadExprBits.HasTemplateKWAndArgsInfo =493      (TemplateArgs != nullptr ) || TemplateKWLoc.isValid();494 495  if (NumResults) {496    // Copy the results to the trailing array past UnresolvedLookupExpr497    // or UnresolvedMemberExpr.498    DeclAccessPair *Results = getTrailingResults();499    memcpy(Results, Begin.I, NumResults * sizeof(DeclAccessPair));500  }501 502  if (TemplateArgs) {503    auto Deps = TemplateArgumentDependence::None;504    getTrailingASTTemplateKWAndArgsInfo()->initializeFrom(505        TemplateKWLoc, *TemplateArgs, getTrailingTemplateArgumentLoc(), Deps);506  } else if (TemplateKWLoc.isValid()) {507    getTrailingASTTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);508  }509 510  setDependence(computeDependence(this, KnownDependent,511                                  KnownInstantiationDependent,512                                  KnownContainsUnexpandedParameterPack));513  if (isTypeDependent())514    setType(Context.DependentTy);515}516 517OverloadExpr::OverloadExpr(StmtClass SC, EmptyShell Empty, unsigned NumResults,518                           bool HasTemplateKWAndArgsInfo)519    : Expr(SC, Empty) {520  OverloadExprBits.NumResults = NumResults;521  OverloadExprBits.HasTemplateKWAndArgsInfo = HasTemplateKWAndArgsInfo;522}523 524// DependentScopeDeclRefExpr525DependentScopeDeclRefExpr::DependentScopeDeclRefExpr(526    QualType Ty, NestedNameSpecifierLoc QualifierLoc,527    SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo,528    const TemplateArgumentListInfo *Args)529    : Expr(DependentScopeDeclRefExprClass, Ty, VK_LValue, OK_Ordinary),530      QualifierLoc(QualifierLoc), NameInfo(NameInfo) {531  DependentScopeDeclRefExprBits.HasTemplateKWAndArgsInfo =532      (Args != nullptr) || TemplateKWLoc.isValid();533  if (Args) {534    auto Deps = TemplateArgumentDependence::None;535    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(536        TemplateKWLoc, *Args, getTrailingObjects<TemplateArgumentLoc>(), Deps);537  } else if (TemplateKWLoc.isValid()) {538    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(539        TemplateKWLoc);540  }541  setDependence(computeDependence(this));542}543 544DependentScopeDeclRefExpr *DependentScopeDeclRefExpr::Create(545    const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,546    SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo,547    const TemplateArgumentListInfo *Args) {548  assert(QualifierLoc && "should be created for dependent qualifiers");549  bool HasTemplateKWAndArgsInfo = Args || TemplateKWLoc.isValid();550  std::size_t Size =551      totalSizeToAlloc<ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(552          HasTemplateKWAndArgsInfo, Args ? Args->size() : 0);553  void *Mem = Context.Allocate(Size);554  return new (Mem) DependentScopeDeclRefExpr(Context.DependentTy, QualifierLoc,555                                             TemplateKWLoc, NameInfo, Args);556}557 558DependentScopeDeclRefExpr *559DependentScopeDeclRefExpr::CreateEmpty(const ASTContext &Context,560                                       bool HasTemplateKWAndArgsInfo,561                                       unsigned NumTemplateArgs) {562  assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);563  std::size_t Size =564      totalSizeToAlloc<ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(565          HasTemplateKWAndArgsInfo, NumTemplateArgs);566  void *Mem = Context.Allocate(Size);567  auto *E = new (Mem) DependentScopeDeclRefExpr(568      QualType(), NestedNameSpecifierLoc(), SourceLocation(),569      DeclarationNameInfo(), nullptr);570  E->DependentScopeDeclRefExprBits.HasTemplateKWAndArgsInfo =571      HasTemplateKWAndArgsInfo;572  return E;573}574 575SourceLocation CXXConstructExpr::getBeginLoc() const {576  if (const auto *TOE = dyn_cast<CXXTemporaryObjectExpr>(this))577    return TOE->getBeginLoc();578  return getLocation();579}580 581SourceLocation CXXConstructExpr::getEndLoc() const {582  if (const auto *TOE = dyn_cast<CXXTemporaryObjectExpr>(this))583    return TOE->getEndLoc();584 585  if (ParenOrBraceRange.isValid())586    return ParenOrBraceRange.getEnd();587 588  SourceLocation End = getLocation();589  for (unsigned I = getNumArgs(); I > 0; --I) {590    const Expr *Arg = getArg(I-1);591    if (!Arg->isDefaultArgument()) {592      SourceLocation NewEnd = Arg->getEndLoc();593      if (NewEnd.isValid()) {594        End = NewEnd;595        break;596      }597    }598  }599 600  return End;601}602 603CXXOperatorCallExpr::CXXOperatorCallExpr(OverloadedOperatorKind OpKind,604                                         Expr *Fn, ArrayRef<Expr *> Args,605                                         QualType Ty, ExprValueKind VK,606                                         SourceLocation OperatorLoc,607                                         FPOptionsOverride FPFeatures,608                                         ADLCallKind UsesADL)609    : CallExpr(CXXOperatorCallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,610               OperatorLoc, FPFeatures, /*MinNumArgs=*/0, UsesADL) {611  CXXOperatorCallExprBits.OperatorKind = OpKind;612  assert(613      (CXXOperatorCallExprBits.OperatorKind == static_cast<unsigned>(OpKind)) &&614      "OperatorKind overflow!");615  BeginLoc = getSourceRangeImpl().getBegin();616}617 618CXXOperatorCallExpr::CXXOperatorCallExpr(unsigned NumArgs, bool HasFPFeatures,619                                         EmptyShell Empty)620    : CallExpr(CXXOperatorCallExprClass, /*NumPreArgs=*/0, NumArgs,621               HasFPFeatures, Empty) {}622 623CXXOperatorCallExpr *624CXXOperatorCallExpr::Create(const ASTContext &Ctx,625                            OverloadedOperatorKind OpKind, Expr *Fn,626                            ArrayRef<Expr *> Args, QualType Ty,627                            ExprValueKind VK, SourceLocation OperatorLoc,628                            FPOptionsOverride FPFeatures, ADLCallKind UsesADL) {629  // Allocate storage for the trailing objects of CallExpr.630  unsigned NumArgs = Args.size();631  unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(632      /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());633  void *Mem =634      Ctx.Allocate(sizeToAllocateForCallExprSubclass<CXXOperatorCallExpr>(635                       SizeOfTrailingObjects),636                   alignof(CXXOperatorCallExpr));637  return new (Mem) CXXOperatorCallExpr(OpKind, Fn, Args, Ty, VK, OperatorLoc,638                                       FPFeatures, UsesADL);639}640 641CXXOperatorCallExpr *CXXOperatorCallExpr::CreateEmpty(const ASTContext &Ctx,642                                                      unsigned NumArgs,643                                                      bool HasFPFeatures,644                                                      EmptyShell Empty) {645  // Allocate storage for the trailing objects of CallExpr.646  unsigned SizeOfTrailingObjects =647      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);648  void *Mem =649      Ctx.Allocate(sizeToAllocateForCallExprSubclass<CXXOperatorCallExpr>(650                       SizeOfTrailingObjects),651                   alignof(CXXOperatorCallExpr));652  return new (Mem) CXXOperatorCallExpr(NumArgs, HasFPFeatures, Empty);653}654 655SourceRange CXXOperatorCallExpr::getSourceRangeImpl() const {656  OverloadedOperatorKind Kind = getOperator();657  if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {658    if (getNumArgs() == 1)659      // Prefix operator660      return SourceRange(getOperatorLoc(), getArg(0)->getEndLoc());661    else662      // Postfix operator663      return SourceRange(getArg(0)->getBeginLoc(), getOperatorLoc());664  } else if (Kind == OO_Arrow) {665    return SourceRange(getArg(0)->getBeginLoc(), getOperatorLoc());666  } else if (Kind == OO_Call) {667    return SourceRange(getArg(0)->getBeginLoc(), getRParenLoc());668  } else if (Kind == OO_Subscript) {669    return SourceRange(getArg(0)->getBeginLoc(), getRParenLoc());670  } else if (getNumArgs() == 1) {671    return SourceRange(getOperatorLoc(), getArg(0)->getEndLoc());672  } else if (getNumArgs() == 2) {673    return SourceRange(getArg(0)->getBeginLoc(), getArg(1)->getEndLoc());674  } else {675    return getOperatorLoc();676  }677}678 679CXXMemberCallExpr::CXXMemberCallExpr(Expr *Fn, ArrayRef<Expr *> Args,680                                     QualType Ty, ExprValueKind VK,681                                     SourceLocation RP,682                                     FPOptionsOverride FPOptions,683                                     unsigned MinNumArgs)684    : CallExpr(CXXMemberCallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK, RP,685               FPOptions, MinNumArgs, NotADL) {}686 687CXXMemberCallExpr::CXXMemberCallExpr(unsigned NumArgs, bool HasFPFeatures,688                                     EmptyShell Empty)689    : CallExpr(CXXMemberCallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures,690               Empty) {}691 692CXXMemberCallExpr *CXXMemberCallExpr::Create(const ASTContext &Ctx, Expr *Fn,693                                             ArrayRef<Expr *> Args, QualType Ty,694                                             ExprValueKind VK,695                                             SourceLocation RP,696                                             FPOptionsOverride FPFeatures,697                                             unsigned MinNumArgs) {698  // Allocate storage for the trailing objects of CallExpr.699  unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);700  unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(701      /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());702  void *Mem = Ctx.Allocate(sizeToAllocateForCallExprSubclass<CXXMemberCallExpr>(703                               SizeOfTrailingObjects),704                           alignof(CXXMemberCallExpr));705  return new (Mem)706      CXXMemberCallExpr(Fn, Args, Ty, VK, RP, FPFeatures, MinNumArgs);707}708 709CXXMemberCallExpr *CXXMemberCallExpr::CreateEmpty(const ASTContext &Ctx,710                                                  unsigned NumArgs,711                                                  bool HasFPFeatures,712                                                  EmptyShell Empty) {713  // Allocate storage for the trailing objects of CallExpr.714  unsigned SizeOfTrailingObjects =715      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);716  void *Mem = Ctx.Allocate(sizeToAllocateForCallExprSubclass<CXXMemberCallExpr>(717                               SizeOfTrailingObjects),718                           alignof(CXXMemberCallExpr));719  return new (Mem) CXXMemberCallExpr(NumArgs, HasFPFeatures, Empty);720}721 722Expr *CXXMemberCallExpr::getImplicitObjectArgument() const {723  const Expr *Callee = getCallee()->IgnoreParens();724  if (const auto *MemExpr = dyn_cast<MemberExpr>(Callee))725    return MemExpr->getBase();726  if (const auto *BO = dyn_cast<BinaryOperator>(Callee))727    if (BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)728      return BO->getLHS();729 730  // FIXME: Will eventually need to cope with member pointers.731  return nullptr;732}733 734QualType CXXMemberCallExpr::getObjectType() const {735  QualType Ty = getImplicitObjectArgument()->getType();736  if (Ty->isPointerType())737    Ty = Ty->getPointeeType();738  return Ty;739}740 741CXXMethodDecl *CXXMemberCallExpr::getMethodDecl() const {742  if (const auto *MemExpr = dyn_cast<MemberExpr>(getCallee()->IgnoreParens()))743    return cast<CXXMethodDecl>(MemExpr->getMemberDecl());744 745  // FIXME: Will eventually need to cope with member pointers.746  // NOTE: Update makeTailCallIfSwiftAsync on fixing this.747  return nullptr;748}749 750CXXRecordDecl *CXXMemberCallExpr::getRecordDecl() const {751  Expr* ThisArg = getImplicitObjectArgument();752  if (!ThisArg)753    return nullptr;754 755  if (ThisArg->getType()->isAnyPointerType())756    return ThisArg->getType()->getPointeeType()->getAsCXXRecordDecl();757 758  return ThisArg->getType()->getAsCXXRecordDecl();759}760 761//===----------------------------------------------------------------------===//762//  Named casts763//===----------------------------------------------------------------------===//764 765/// getCastName - Get the name of the C++ cast being used, e.g.,766/// "static_cast", "dynamic_cast", "reinterpret_cast", or767/// "const_cast". The returned pointer must not be freed.768const char *CXXNamedCastExpr::getCastName() const {769  switch (getStmtClass()) {770  case CXXStaticCastExprClass:      return "static_cast";771  case CXXDynamicCastExprClass:     return "dynamic_cast";772  case CXXReinterpretCastExprClass: return "reinterpret_cast";773  case CXXConstCastExprClass:       return "const_cast";774  case CXXAddrspaceCastExprClass:   return "addrspace_cast";775  default:                          return "<invalid cast>";776  }777}778 779CXXStaticCastExpr *780CXXStaticCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK,781                          CastKind K, Expr *Op, const CXXCastPath *BasePath,782                          TypeSourceInfo *WrittenTy, FPOptionsOverride FPO,783                          SourceLocation L, SourceLocation RParenLoc,784                          SourceRange AngleBrackets) {785  unsigned PathSize = (BasePath ? BasePath->size() : 0);786  void *Buffer =787      C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(788          PathSize, FPO.requiresTrailingStorage()));789  auto *E = new (Buffer) CXXStaticCastExpr(T, VK, K, Op, PathSize, WrittenTy,790                                           FPO, L, RParenLoc, AngleBrackets);791  if (PathSize)792    llvm::uninitialized_copy(*BasePath,793                             E->getTrailingObjects<CXXBaseSpecifier *>());794  return E;795}796 797CXXStaticCastExpr *CXXStaticCastExpr::CreateEmpty(const ASTContext &C,798                                                  unsigned PathSize,799                                                  bool HasFPFeatures) {800  void *Buffer =801      C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(802          PathSize, HasFPFeatures));803  return new (Buffer) CXXStaticCastExpr(EmptyShell(), PathSize, HasFPFeatures);804}805 806CXXDynamicCastExpr *CXXDynamicCastExpr::Create(const ASTContext &C, QualType T,807                                               ExprValueKind VK,808                                               CastKind K, Expr *Op,809                                               const CXXCastPath *BasePath,810                                               TypeSourceInfo *WrittenTy,811                                               SourceLocation L,812                                               SourceLocation RParenLoc,813                                               SourceRange AngleBrackets) {814  unsigned PathSize = (BasePath ? BasePath->size() : 0);815  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));816  auto *E =817      new (Buffer) CXXDynamicCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,818                                      RParenLoc, AngleBrackets);819  if (PathSize)820    llvm::uninitialized_copy(*BasePath, E->getTrailingObjects());821  return E;822}823 824CXXDynamicCastExpr *CXXDynamicCastExpr::CreateEmpty(const ASTContext &C,825                                                    unsigned PathSize) {826  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));827  return new (Buffer) CXXDynamicCastExpr(EmptyShell(), PathSize);828}829 830/// isAlwaysNull - Return whether the result of the dynamic_cast is proven831/// to always be null. For example:832///833/// struct A { };834/// struct B final : A { };835/// struct C { };836///837/// C *f(B* b) { return dynamic_cast<C*>(b); }838bool CXXDynamicCastExpr::isAlwaysNull() const {839  if (isValueDependent() || getCastKind() != CK_Dynamic)840    return false;841 842  QualType SrcType = getSubExpr()->getType();843  QualType DestType = getType();844 845  if (DestType->isVoidPointerType())846    return false;847 848  if (DestType->isPointerType()) {849    SrcType = SrcType->getPointeeType();850    DestType = DestType->getPointeeType();851  }852 853  const auto *SrcRD = SrcType->getAsCXXRecordDecl();854  const auto *DestRD = DestType->getAsCXXRecordDecl();855  assert(SrcRD && DestRD);856 857  if (SrcRD->isEffectivelyFinal()) {858    assert(!SrcRD->isDerivedFrom(DestRD) &&859           "upcasts should not use CK_Dynamic");860    return true;861  }862 863  if (DestRD->isEffectivelyFinal() && !DestRD->isDerivedFrom(SrcRD))864    return true;865 866  return false;867}868 869CXXReinterpretCastExpr *870CXXReinterpretCastExpr::Create(const ASTContext &C, QualType T,871                               ExprValueKind VK, CastKind K, Expr *Op,872                               const CXXCastPath *BasePath,873                               TypeSourceInfo *WrittenTy, SourceLocation L,874                               SourceLocation RParenLoc,875                               SourceRange AngleBrackets) {876  unsigned PathSize = (BasePath ? BasePath->size() : 0);877  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));878  auto *E =879      new (Buffer) CXXReinterpretCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,880                                          RParenLoc, AngleBrackets);881  if (PathSize)882    llvm::uninitialized_copy(*BasePath, E->getTrailingObjects());883  return E;884}885 886CXXReinterpretCastExpr *887CXXReinterpretCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) {888  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));889  return new (Buffer) CXXReinterpretCastExpr(EmptyShell(), PathSize);890}891 892CXXConstCastExpr *CXXConstCastExpr::Create(const ASTContext &C, QualType T,893                                           ExprValueKind VK, Expr *Op,894                                           TypeSourceInfo *WrittenTy,895                                           SourceLocation L,896                                           SourceLocation RParenLoc,897                                           SourceRange AngleBrackets) {898  return new (C) CXXConstCastExpr(T, VK, Op, WrittenTy, L, RParenLoc, AngleBrackets);899}900 901CXXConstCastExpr *CXXConstCastExpr::CreateEmpty(const ASTContext &C) {902  return new (C) CXXConstCastExpr(EmptyShell());903}904 905CXXAddrspaceCastExpr *906CXXAddrspaceCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK,907                             CastKind K, Expr *Op, TypeSourceInfo *WrittenTy,908                             SourceLocation L, SourceLocation RParenLoc,909                             SourceRange AngleBrackets) {910  return new (C) CXXAddrspaceCastExpr(T, VK, K, Op, WrittenTy, L, RParenLoc,911                                      AngleBrackets);912}913 914CXXAddrspaceCastExpr *CXXAddrspaceCastExpr::CreateEmpty(const ASTContext &C) {915  return new (C) CXXAddrspaceCastExpr(EmptyShell());916}917 918CXXFunctionalCastExpr *CXXFunctionalCastExpr::Create(919    const ASTContext &C, QualType T, ExprValueKind VK, TypeSourceInfo *Written,920    CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,921    SourceLocation L, SourceLocation R) {922  unsigned PathSize = (BasePath ? BasePath->size() : 0);923  void *Buffer =924      C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(925          PathSize, FPO.requiresTrailingStorage()));926  auto *E = new (Buffer)927      CXXFunctionalCastExpr(T, VK, Written, K, Op, PathSize, FPO, L, R);928  if (PathSize)929    llvm::uninitialized_copy(*BasePath,930                             E->getTrailingObjects<CXXBaseSpecifier *>());931  return E;932}933 934CXXFunctionalCastExpr *CXXFunctionalCastExpr::CreateEmpty(const ASTContext &C,935                                                          unsigned PathSize,936                                                          bool HasFPFeatures) {937  void *Buffer =938      C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(939          PathSize, HasFPFeatures));940  return new (Buffer)941      CXXFunctionalCastExpr(EmptyShell(), PathSize, HasFPFeatures);942}943 944SourceLocation CXXFunctionalCastExpr::getBeginLoc() const {945  return getTypeInfoAsWritten()->getTypeLoc().getBeginLoc();946}947 948SourceLocation CXXFunctionalCastExpr::getEndLoc() const {949  return RParenLoc.isValid() ? RParenLoc : getSubExpr()->getEndLoc();950}951 952UserDefinedLiteral::UserDefinedLiteral(Expr *Fn, ArrayRef<Expr *> Args,953                                       QualType Ty, ExprValueKind VK,954                                       SourceLocation LitEndLoc,955                                       SourceLocation SuffixLoc,956                                       FPOptionsOverride FPFeatures)957    : CallExpr(UserDefinedLiteralClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,958               LitEndLoc, FPFeatures, /*MinNumArgs=*/0, NotADL),959      UDSuffixLoc(SuffixLoc) {}960 961UserDefinedLiteral::UserDefinedLiteral(unsigned NumArgs, bool HasFPFeatures,962                                       EmptyShell Empty)963    : CallExpr(UserDefinedLiteralClass, /*NumPreArgs=*/0, NumArgs,964               HasFPFeatures, Empty) {}965 966UserDefinedLiteral *UserDefinedLiteral::Create(const ASTContext &Ctx, Expr *Fn,967                                               ArrayRef<Expr *> Args,968                                               QualType Ty, ExprValueKind VK,969                                               SourceLocation LitEndLoc,970                                               SourceLocation SuffixLoc,971                                               FPOptionsOverride FPFeatures) {972  // Allocate storage for the trailing objects of CallExpr.973  unsigned NumArgs = Args.size();974  unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(975      /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());976  void *Mem =977      Ctx.Allocate(sizeToAllocateForCallExprSubclass<UserDefinedLiteral>(978                       SizeOfTrailingObjects),979                   alignof(UserDefinedLiteral));980  return new (Mem)981      UserDefinedLiteral(Fn, Args, Ty, VK, LitEndLoc, SuffixLoc, FPFeatures);982}983 984UserDefinedLiteral *UserDefinedLiteral::CreateEmpty(const ASTContext &Ctx,985                                                    unsigned NumArgs,986                                                    bool HasFPOptions,987                                                    EmptyShell Empty) {988  // Allocate storage for the trailing objects of CallExpr.989  unsigned SizeOfTrailingObjects =990      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPOptions);991  void *Mem =992      Ctx.Allocate(sizeToAllocateForCallExprSubclass<UserDefinedLiteral>(993                       SizeOfTrailingObjects),994                   alignof(UserDefinedLiteral));995  return new (Mem) UserDefinedLiteral(NumArgs, HasFPOptions, Empty);996}997 998UserDefinedLiteral::LiteralOperatorKind999UserDefinedLiteral::getLiteralOperatorKind() const {1000  if (getNumArgs() == 0)1001    return LOK_Template;1002  if (getNumArgs() == 2)1003    return LOK_String;1004 1005  assert(getNumArgs() == 1 && "unexpected #args in literal operator call");1006  QualType ParamTy =1007    cast<FunctionDecl>(getCalleeDecl())->getParamDecl(0)->getType();1008  if (ParamTy->isPointerType())1009    return LOK_Raw;1010  if (ParamTy->isAnyCharacterType())1011    return LOK_Character;1012  if (ParamTy->isIntegerType())1013    return LOK_Integer;1014  if (ParamTy->isFloatingType())1015    return LOK_Floating;1016 1017  llvm_unreachable("unknown kind of literal operator");1018}1019 1020Expr *UserDefinedLiteral::getCookedLiteral() {1021#ifndef NDEBUG1022  LiteralOperatorKind LOK = getLiteralOperatorKind();1023  assert(LOK != LOK_Template && LOK != LOK_Raw && "not a cooked literal");1024#endif1025  return getArg(0);1026}1027 1028const IdentifierInfo *UserDefinedLiteral::getUDSuffix() const {1029  return cast<FunctionDecl>(getCalleeDecl())->getLiteralIdentifier();1030}1031 1032CXXDefaultArgExpr *CXXDefaultArgExpr::CreateEmpty(const ASTContext &C,1033                                                  bool HasRewrittenInit) {1034  size_t Size = totalSizeToAlloc<Expr *>(HasRewrittenInit);1035  auto *Mem = C.Allocate(Size, alignof(CXXDefaultArgExpr));1036  return new (Mem) CXXDefaultArgExpr(EmptyShell(), HasRewrittenInit);1037}1038 1039CXXDefaultArgExpr *CXXDefaultArgExpr::Create(const ASTContext &C,1040                                             SourceLocation Loc,1041                                             ParmVarDecl *Param,1042                                             Expr *RewrittenExpr,1043                                             DeclContext *UsedContext) {1044  size_t Size = totalSizeToAlloc<Expr *>(RewrittenExpr != nullptr);1045  auto *Mem = C.Allocate(Size, alignof(CXXDefaultArgExpr));1046  return new (Mem) CXXDefaultArgExpr(CXXDefaultArgExprClass, Loc, Param,1047                                     RewrittenExpr, UsedContext);1048}1049 1050Expr *CXXDefaultArgExpr::getExpr() {1051  return CXXDefaultArgExprBits.HasRewrittenInit ? getAdjustedRewrittenExpr()1052                                                : getParam()->getDefaultArg();1053}1054 1055Expr *CXXDefaultArgExpr::getAdjustedRewrittenExpr() {1056  assert(hasRewrittenInit() &&1057         "expected this CXXDefaultArgExpr to have a rewritten init.");1058  Expr *Init = getRewrittenExpr();1059  if (auto *E = dyn_cast_if_present<FullExpr>(Init))1060    if (!isa<ConstantExpr>(E))1061      return E->getSubExpr();1062  return Init;1063}1064 1065CXXDefaultInitExpr::CXXDefaultInitExpr(const ASTContext &Ctx,1066                                       SourceLocation Loc, FieldDecl *Field,1067                                       QualType Ty, DeclContext *UsedContext,1068                                       Expr *RewrittenInitExpr)1069    : Expr(CXXDefaultInitExprClass, Ty.getNonLValueExprType(Ctx),1070           Ty->isLValueReferenceType()   ? VK_LValue1071           : Ty->isRValueReferenceType() ? VK_XValue1072                                         : VK_PRValue,1073           /*FIXME*/ OK_Ordinary),1074      Field(Field), UsedContext(UsedContext) {1075  CXXDefaultInitExprBits.Loc = Loc;1076  CXXDefaultInitExprBits.HasRewrittenInit = RewrittenInitExpr != nullptr;1077 1078  if (CXXDefaultInitExprBits.HasRewrittenInit)1079    *getTrailingObjects() = RewrittenInitExpr;1080 1081  assert(Field->hasInClassInitializer());1082 1083  setDependence(computeDependence(this));1084}1085 1086CXXDefaultInitExpr *CXXDefaultInitExpr::CreateEmpty(const ASTContext &C,1087                                                    bool HasRewrittenInit) {1088  size_t Size = totalSizeToAlloc<Expr *>(HasRewrittenInit);1089  auto *Mem = C.Allocate(Size, alignof(CXXDefaultInitExpr));1090  return new (Mem) CXXDefaultInitExpr(EmptyShell(), HasRewrittenInit);1091}1092 1093CXXDefaultInitExpr *CXXDefaultInitExpr::Create(const ASTContext &Ctx,1094                                               SourceLocation Loc,1095                                               FieldDecl *Field,1096                                               DeclContext *UsedContext,1097                                               Expr *RewrittenInitExpr) {1098 1099  size_t Size = totalSizeToAlloc<Expr *>(RewrittenInitExpr != nullptr);1100  auto *Mem = Ctx.Allocate(Size, alignof(CXXDefaultInitExpr));1101  return new (Mem) CXXDefaultInitExpr(Ctx, Loc, Field, Field->getType(),1102                                      UsedContext, RewrittenInitExpr);1103}1104 1105Expr *CXXDefaultInitExpr::getExpr() {1106  assert(Field->getInClassInitializer() && "initializer hasn't been parsed");1107  if (hasRewrittenInit())1108    return getRewrittenExpr();1109 1110  return Field->getInClassInitializer();1111}1112 1113CXXTemporary *CXXTemporary::Create(const ASTContext &C,1114                                   const CXXDestructorDecl *Destructor) {1115  return new (C) CXXTemporary(Destructor);1116}1117 1118CXXBindTemporaryExpr *CXXBindTemporaryExpr::Create(const ASTContext &C,1119                                                   CXXTemporary *Temp,1120                                                   Expr* SubExpr) {1121  assert((SubExpr->getType()->isRecordType() ||1122          SubExpr->getType()->isArrayType()) &&1123         "Expression bound to a temporary must have record or array type!");1124 1125  return new (C) CXXBindTemporaryExpr(Temp, SubExpr);1126}1127 1128CXXTemporaryObjectExpr::CXXTemporaryObjectExpr(1129    CXXConstructorDecl *Cons, QualType Ty, TypeSourceInfo *TSI,1130    ArrayRef<Expr *> Args, SourceRange ParenOrBraceRange,1131    bool HadMultipleCandidates, bool ListInitialization,1132    bool StdInitListInitialization, bool ZeroInitialization)1133    : CXXConstructExpr(1134          CXXTemporaryObjectExprClass, Ty, TSI->getTypeLoc().getBeginLoc(),1135          Cons, /* Elidable=*/false, Args, HadMultipleCandidates,1136          ListInitialization, StdInitListInitialization, ZeroInitialization,1137          CXXConstructionKind::Complete, ParenOrBraceRange),1138      TSI(TSI) {1139  setDependence(computeDependence(this));1140}1141 1142CXXTemporaryObjectExpr::CXXTemporaryObjectExpr(EmptyShell Empty,1143                                               unsigned NumArgs)1144    : CXXConstructExpr(CXXTemporaryObjectExprClass, Empty, NumArgs) {}1145 1146CXXTemporaryObjectExpr *CXXTemporaryObjectExpr::Create(1147    const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty,1148    TypeSourceInfo *TSI, ArrayRef<Expr *> Args, SourceRange ParenOrBraceRange,1149    bool HadMultipleCandidates, bool ListInitialization,1150    bool StdInitListInitialization, bool ZeroInitialization) {1151  unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(Args.size());1152  void *Mem =1153      Ctx.Allocate(sizeof(CXXTemporaryObjectExpr) + SizeOfTrailingObjects,1154                   alignof(CXXTemporaryObjectExpr));1155  return new (Mem) CXXTemporaryObjectExpr(1156      Cons, Ty, TSI, Args, ParenOrBraceRange, HadMultipleCandidates,1157      ListInitialization, StdInitListInitialization, ZeroInitialization);1158}1159 1160CXXTemporaryObjectExpr *1161CXXTemporaryObjectExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs) {1162  unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(NumArgs);1163  void *Mem =1164      Ctx.Allocate(sizeof(CXXTemporaryObjectExpr) + SizeOfTrailingObjects,1165                   alignof(CXXTemporaryObjectExpr));1166  return new (Mem) CXXTemporaryObjectExpr(EmptyShell(), NumArgs);1167}1168 1169SourceLocation CXXTemporaryObjectExpr::getBeginLoc() const {1170  return getTypeSourceInfo()->getTypeLoc().getBeginLoc();1171}1172 1173SourceLocation CXXTemporaryObjectExpr::getEndLoc() const {1174  SourceLocation Loc = getParenOrBraceRange().getEnd();1175  if (Loc.isInvalid() && getNumArgs())1176    Loc = getArg(getNumArgs() - 1)->getEndLoc();1177  return Loc;1178}1179 1180CXXConstructExpr *CXXConstructExpr::Create(1181    const ASTContext &Ctx, QualType Ty, SourceLocation Loc,1182    CXXConstructorDecl *Ctor, bool Elidable, ArrayRef<Expr *> Args,1183    bool HadMultipleCandidates, bool ListInitialization,1184    bool StdInitListInitialization, bool ZeroInitialization,1185    CXXConstructionKind ConstructKind, SourceRange ParenOrBraceRange) {1186  unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(Args.size());1187  void *Mem = Ctx.Allocate(sizeof(CXXConstructExpr) + SizeOfTrailingObjects,1188                           alignof(CXXConstructExpr));1189  return new (Mem) CXXConstructExpr(1190      CXXConstructExprClass, Ty, Loc, Ctor, Elidable, Args,1191      HadMultipleCandidates, ListInitialization, StdInitListInitialization,1192      ZeroInitialization, ConstructKind, ParenOrBraceRange);1193}1194 1195CXXConstructExpr *CXXConstructExpr::CreateEmpty(const ASTContext &Ctx,1196                                                unsigned NumArgs) {1197  unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(NumArgs);1198  void *Mem = Ctx.Allocate(sizeof(CXXConstructExpr) + SizeOfTrailingObjects,1199                           alignof(CXXConstructExpr));1200  return new (Mem)1201      CXXConstructExpr(CXXConstructExprClass, EmptyShell(), NumArgs);1202}1203 1204CXXConstructExpr::CXXConstructExpr(1205    StmtClass SC, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor,1206    bool Elidable, ArrayRef<Expr *> Args, bool HadMultipleCandidates,1207    bool ListInitialization, bool StdInitListInitialization,1208    bool ZeroInitialization, CXXConstructionKind ConstructKind,1209    SourceRange ParenOrBraceRange)1210    : Expr(SC, Ty, VK_PRValue, OK_Ordinary), Constructor(Ctor),1211      ParenOrBraceRange(ParenOrBraceRange), NumArgs(Args.size()) {1212  CXXConstructExprBits.Elidable = Elidable;1213  CXXConstructExprBits.HadMultipleCandidates = HadMultipleCandidates;1214  CXXConstructExprBits.ListInitialization = ListInitialization;1215  CXXConstructExprBits.StdInitListInitialization = StdInitListInitialization;1216  CXXConstructExprBits.ZeroInitialization = ZeroInitialization;1217  CXXConstructExprBits.ConstructionKind = llvm::to_underlying(ConstructKind);1218  CXXConstructExprBits.IsImmediateEscalating = false;1219  CXXConstructExprBits.Loc = Loc;1220 1221  Stmt **TrailingArgs = getTrailingArgs();1222  llvm::copy(Args, TrailingArgs);1223  assert(!llvm::is_contained(Args, nullptr));1224 1225  // CXXTemporaryObjectExpr does this itself after setting its TypeSourceInfo.1226  if (SC == CXXConstructExprClass)1227    setDependence(computeDependence(this));1228}1229 1230CXXConstructExpr::CXXConstructExpr(StmtClass SC, EmptyShell Empty,1231                                   unsigned NumArgs)1232    : Expr(SC, Empty), NumArgs(NumArgs) {}1233 1234LambdaCapture::LambdaCapture(SourceLocation Loc, bool Implicit,1235                             LambdaCaptureKind Kind, ValueDecl *Var,1236                             SourceLocation EllipsisLoc)1237    : DeclAndBits(Var, 0), Loc(Loc), EllipsisLoc(EllipsisLoc) {1238  unsigned Bits = 0;1239  if (Implicit)1240    Bits |= Capture_Implicit;1241 1242  switch (Kind) {1243  case LCK_StarThis:1244    Bits |= Capture_ByCopy;1245    [[fallthrough]];1246  case LCK_This:1247    assert(!Var && "'this' capture cannot have a variable!");1248    Bits |= Capture_This;1249    break;1250 1251  case LCK_ByCopy:1252    Bits |= Capture_ByCopy;1253    [[fallthrough]];1254  case LCK_ByRef:1255    assert(Var && "capture must have a variable!");1256    break;1257  case LCK_VLAType:1258    assert(!Var && "VLA type capture cannot have a variable!");1259    break;1260  }1261  DeclAndBits.setInt(Bits);1262}1263 1264LambdaCaptureKind LambdaCapture::getCaptureKind() const {1265  if (capturesVLAType())1266    return LCK_VLAType;1267  bool CapByCopy = DeclAndBits.getInt() & Capture_ByCopy;1268  if (capturesThis())1269    return CapByCopy ? LCK_StarThis : LCK_This;1270  return CapByCopy ? LCK_ByCopy : LCK_ByRef;1271}1272 1273LambdaExpr::LambdaExpr(QualType T, SourceRange IntroducerRange,1274                       LambdaCaptureDefault CaptureDefault,1275                       SourceLocation CaptureDefaultLoc, bool ExplicitParams,1276                       bool ExplicitResultType, ArrayRef<Expr *> CaptureInits,1277                       SourceLocation ClosingBrace,1278                       bool ContainsUnexpandedParameterPack)1279    : Expr(LambdaExprClass, T, VK_PRValue, OK_Ordinary),1280      IntroducerRange(IntroducerRange), CaptureDefaultLoc(CaptureDefaultLoc),1281      ClosingBrace(ClosingBrace) {1282  LambdaExprBits.NumCaptures = CaptureInits.size();1283  LambdaExprBits.CaptureDefault = CaptureDefault;1284  LambdaExprBits.ExplicitParams = ExplicitParams;1285  LambdaExprBits.ExplicitResultType = ExplicitResultType;1286 1287  CXXRecordDecl *Class = getLambdaClass();1288  (void)Class;1289  assert(capture_size() == Class->capture_size() && "Wrong number of captures");1290  assert(getCaptureDefault() == Class->getLambdaCaptureDefault());1291 1292  // Copy initialization expressions for the non-static data members.1293  Stmt **Stored = getStoredStmts();1294  for (unsigned I = 0, N = CaptureInits.size(); I != N; ++I)1295    *Stored++ = CaptureInits[I];1296 1297  // Copy the body of the lambda.1298  *Stored++ = getCallOperator()->getBody();1299 1300  setDependence(computeDependence(this, ContainsUnexpandedParameterPack));1301}1302 1303LambdaExpr::LambdaExpr(EmptyShell Empty, unsigned NumCaptures)1304    : Expr(LambdaExprClass, Empty) {1305  LambdaExprBits.NumCaptures = NumCaptures;1306 1307  // Initially don't initialize the body of the LambdaExpr. The body will1308  // be lazily deserialized when needed.1309  getStoredStmts()[NumCaptures] = nullptr; // Not one past the end.1310}1311 1312LambdaExpr *LambdaExpr::Create(const ASTContext &Context, CXXRecordDecl *Class,1313                               SourceRange IntroducerRange,1314                               LambdaCaptureDefault CaptureDefault,1315                               SourceLocation CaptureDefaultLoc,1316                               bool ExplicitParams, bool ExplicitResultType,1317                               ArrayRef<Expr *> CaptureInits,1318                               SourceLocation ClosingBrace,1319                               bool ContainsUnexpandedParameterPack) {1320  // Determine the type of the expression (i.e., the type of the1321  // function object we're creating).1322  CanQualType T = Context.getCanonicalTagType(Class);1323 1324  unsigned Size = totalSizeToAlloc<Stmt *>(CaptureInits.size() + 1);1325  void *Mem = Context.Allocate(Size);1326  return new (Mem)1327      LambdaExpr(T, IntroducerRange, CaptureDefault, CaptureDefaultLoc,1328                 ExplicitParams, ExplicitResultType, CaptureInits, ClosingBrace,1329                 ContainsUnexpandedParameterPack);1330}1331 1332LambdaExpr *LambdaExpr::CreateDeserialized(const ASTContext &C,1333                                           unsigned NumCaptures) {1334  unsigned Size = totalSizeToAlloc<Stmt *>(NumCaptures + 1);1335  void *Mem = C.Allocate(Size);1336  return new (Mem) LambdaExpr(EmptyShell(), NumCaptures);1337}1338 1339void LambdaExpr::initBodyIfNeeded() const {1340  if (!getStoredStmts()[capture_size()]) {1341    auto *This = const_cast<LambdaExpr *>(this);1342    This->getStoredStmts()[capture_size()] = getCallOperator()->getBody();1343  }1344}1345 1346Stmt *LambdaExpr::getBody() const {1347  initBodyIfNeeded();1348  return getStoredStmts()[capture_size()];1349}1350 1351const CompoundStmt *LambdaExpr::getCompoundStmtBody() const {1352  Stmt *Body = getBody();1353  if (const auto *CoroBody = dyn_cast<CoroutineBodyStmt>(Body))1354    return cast<CompoundStmt>(CoroBody->getBody());1355  return cast<CompoundStmt>(Body);1356}1357 1358bool LambdaExpr::isInitCapture(const LambdaCapture *C) const {1359  return C->capturesVariable() && C->getCapturedVar()->isInitCapture() &&1360         getCallOperator() == C->getCapturedVar()->getDeclContext();1361}1362 1363LambdaExpr::capture_iterator LambdaExpr::capture_begin() const {1364  return getLambdaClass()->captures_begin();1365}1366 1367LambdaExpr::capture_iterator LambdaExpr::capture_end() const {1368  return getLambdaClass()->captures_end();1369}1370 1371LambdaExpr::capture_range LambdaExpr::captures() const {1372  return capture_range(capture_begin(), capture_end());1373}1374 1375LambdaExpr::capture_iterator LambdaExpr::explicit_capture_begin() const {1376  return capture_begin();1377}1378 1379LambdaExpr::capture_iterator LambdaExpr::explicit_capture_end() const {1380  return capture_begin() +1381         getLambdaClass()->getLambdaData().NumExplicitCaptures;1382}1383 1384LambdaExpr::capture_range LambdaExpr::explicit_captures() const {1385  return capture_range(explicit_capture_begin(), explicit_capture_end());1386}1387 1388LambdaExpr::capture_iterator LambdaExpr::implicit_capture_begin() const {1389  return explicit_capture_end();1390}1391 1392LambdaExpr::capture_iterator LambdaExpr::implicit_capture_end() const {1393  return capture_end();1394}1395 1396LambdaExpr::capture_range LambdaExpr::implicit_captures() const {1397  return capture_range(implicit_capture_begin(), implicit_capture_end());1398}1399 1400CXXRecordDecl *LambdaExpr::getLambdaClass() const {1401  return getType()->getAsCXXRecordDecl();1402}1403 1404CXXMethodDecl *LambdaExpr::getCallOperator() const {1405  CXXRecordDecl *Record = getLambdaClass();1406  return Record->getLambdaCallOperator();1407}1408 1409FunctionTemplateDecl *LambdaExpr::getDependentCallOperator() const {1410  CXXRecordDecl *Record = getLambdaClass();1411  return Record->getDependentLambdaCallOperator();1412}1413 1414TemplateParameterList *LambdaExpr::getTemplateParameterList() const {1415  CXXRecordDecl *Record = getLambdaClass();1416  return Record->getGenericLambdaTemplateParameterList();1417}1418 1419ArrayRef<NamedDecl *> LambdaExpr::getExplicitTemplateParameters() const {1420  const CXXRecordDecl *Record = getLambdaClass();1421  return Record->getLambdaExplicitTemplateParameters();1422}1423 1424const AssociatedConstraint &LambdaExpr::getTrailingRequiresClause() const {1425  return getCallOperator()->getTrailingRequiresClause();1426}1427 1428bool LambdaExpr::isMutable() const { return !getCallOperator()->isConst(); }1429 1430LambdaExpr::child_range LambdaExpr::children() {1431  initBodyIfNeeded();1432  return child_range(getStoredStmts(), getStoredStmts() + capture_size() + 1);1433}1434 1435LambdaExpr::const_child_range LambdaExpr::children() const {1436  initBodyIfNeeded();1437  return const_child_range(getStoredStmts(),1438                           getStoredStmts() + capture_size() + 1);1439}1440 1441ExprWithCleanups::ExprWithCleanups(Expr *subexpr,1442                                   bool CleanupsHaveSideEffects,1443                                   ArrayRef<CleanupObject> objects)1444    : FullExpr(ExprWithCleanupsClass, subexpr) {1445  ExprWithCleanupsBits.CleanupsHaveSideEffects = CleanupsHaveSideEffects;1446  ExprWithCleanupsBits.NumObjects = objects.size();1447  llvm::copy(objects, getTrailingObjects());1448}1449 1450ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C, Expr *subexpr,1451                                           bool CleanupsHaveSideEffects,1452                                           ArrayRef<CleanupObject> objects) {1453  void *buffer = C.Allocate(totalSizeToAlloc<CleanupObject>(objects.size()),1454                            alignof(ExprWithCleanups));1455  return new (buffer)1456      ExprWithCleanups(subexpr, CleanupsHaveSideEffects, objects);1457}1458 1459ExprWithCleanups::ExprWithCleanups(EmptyShell empty, unsigned numObjects)1460    : FullExpr(ExprWithCleanupsClass, empty) {1461  ExprWithCleanupsBits.NumObjects = numObjects;1462}1463 1464ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C,1465                                           EmptyShell empty,1466                                           unsigned numObjects) {1467  void *buffer = C.Allocate(totalSizeToAlloc<CleanupObject>(numObjects),1468                            alignof(ExprWithCleanups));1469  return new (buffer) ExprWithCleanups(empty, numObjects);1470}1471 1472CXXUnresolvedConstructExpr::CXXUnresolvedConstructExpr(1473    QualType T, TypeSourceInfo *TSI, SourceLocation LParenLoc,1474    ArrayRef<Expr *> Args, SourceLocation RParenLoc, bool IsListInit)1475    : Expr(CXXUnresolvedConstructExprClass, T,1476           (TSI->getType()->isLValueReferenceType()   ? VK_LValue1477            : TSI->getType()->isRValueReferenceType() ? VK_XValue1478                                                      : VK_PRValue),1479           OK_Ordinary),1480      TypeAndInitForm(TSI, IsListInit), LParenLoc(LParenLoc),1481      RParenLoc(RParenLoc) {1482  CXXUnresolvedConstructExprBits.NumArgs = Args.size();1483  auto **StoredArgs = getTrailingObjects();1484  llvm::copy(Args, StoredArgs);1485  setDependence(computeDependence(this));1486}1487 1488CXXUnresolvedConstructExpr *CXXUnresolvedConstructExpr::Create(1489    const ASTContext &Context, QualType T, TypeSourceInfo *TSI,1490    SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc,1491    bool IsListInit) {1492  void *Mem = Context.Allocate(totalSizeToAlloc<Expr *>(Args.size()));1493  return new (Mem) CXXUnresolvedConstructExpr(T, TSI, LParenLoc, Args,1494                                              RParenLoc, IsListInit);1495}1496 1497CXXUnresolvedConstructExpr *1498CXXUnresolvedConstructExpr::CreateEmpty(const ASTContext &Context,1499                                        unsigned NumArgs) {1500  void *Mem = Context.Allocate(totalSizeToAlloc<Expr *>(NumArgs));1501  return new (Mem) CXXUnresolvedConstructExpr(EmptyShell(), NumArgs);1502}1503 1504SourceLocation CXXUnresolvedConstructExpr::getBeginLoc() const {1505  return TypeAndInitForm.getPointer()->getTypeLoc().getBeginLoc();1506}1507 1508CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(1509    const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,1510    SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,1511    SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,1512    DeclarationNameInfo MemberNameInfo,1513    const TemplateArgumentListInfo *TemplateArgs)1514    : Expr(CXXDependentScopeMemberExprClass, Ctx.DependentTy, VK_LValue,1515           OK_Ordinary),1516      Base(Base), BaseType(BaseType), QualifierLoc(QualifierLoc),1517      MemberNameInfo(MemberNameInfo) {1518  CXXDependentScopeMemberExprBits.IsArrow = IsArrow;1519  CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo =1520      (TemplateArgs != nullptr) || TemplateKWLoc.isValid();1521  CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope =1522      FirstQualifierFoundInScope != nullptr;1523  CXXDependentScopeMemberExprBits.OperatorLoc = OperatorLoc;1524 1525  if (TemplateArgs) {1526    auto Deps = TemplateArgumentDependence::None;1527    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(1528        TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),1529        Deps);1530  } else if (TemplateKWLoc.isValid()) {1531    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(1532        TemplateKWLoc);1533  }1534 1535  if (hasFirstQualifierFoundInScope())1536    *getTrailingObjects<NamedDecl *>() = FirstQualifierFoundInScope;1537  setDependence(computeDependence(this));1538}1539 1540CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(1541    EmptyShell Empty, bool HasTemplateKWAndArgsInfo,1542    bool HasFirstQualifierFoundInScope)1543    : Expr(CXXDependentScopeMemberExprClass, Empty) {1544  CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo =1545      HasTemplateKWAndArgsInfo;1546  CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope =1547      HasFirstQualifierFoundInScope;1548}1549 1550CXXDependentScopeMemberExpr *CXXDependentScopeMemberExpr::Create(1551    const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,1552    SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,1553    SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,1554    DeclarationNameInfo MemberNameInfo,1555    const TemplateArgumentListInfo *TemplateArgs) {1556  bool HasTemplateKWAndArgsInfo =1557      (TemplateArgs != nullptr) || TemplateKWLoc.isValid();1558  unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;1559  bool HasFirstQualifierFoundInScope = FirstQualifierFoundInScope != nullptr;1560 1561  unsigned Size = totalSizeToAlloc<ASTTemplateKWAndArgsInfo,1562                                   TemplateArgumentLoc, NamedDecl *>(1563      HasTemplateKWAndArgsInfo, NumTemplateArgs, HasFirstQualifierFoundInScope);1564 1565  void *Mem = Ctx.Allocate(Size, alignof(CXXDependentScopeMemberExpr));1566  return new (Mem) CXXDependentScopeMemberExpr(1567      Ctx, Base, BaseType, IsArrow, OperatorLoc, QualifierLoc, TemplateKWLoc,1568      FirstQualifierFoundInScope, MemberNameInfo, TemplateArgs);1569}1570 1571CXXDependentScopeMemberExpr *CXXDependentScopeMemberExpr::CreateEmpty(1572    const ASTContext &Ctx, bool HasTemplateKWAndArgsInfo,1573    unsigned NumTemplateArgs, bool HasFirstQualifierFoundInScope) {1574  assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);1575 1576  unsigned Size = totalSizeToAlloc<ASTTemplateKWAndArgsInfo,1577                                   TemplateArgumentLoc, NamedDecl *>(1578      HasTemplateKWAndArgsInfo, NumTemplateArgs, HasFirstQualifierFoundInScope);1579 1580  void *Mem = Ctx.Allocate(Size, alignof(CXXDependentScopeMemberExpr));1581  return new (Mem) CXXDependentScopeMemberExpr(1582      EmptyShell(), HasTemplateKWAndArgsInfo, HasFirstQualifierFoundInScope);1583}1584 1585CXXThisExpr *CXXThisExpr::Create(const ASTContext &Ctx, SourceLocation L,1586                                 QualType Ty, bool IsImplicit) {1587  return new (Ctx) CXXThisExpr(L, Ty, IsImplicit,1588                               Ctx.getLangOpts().HLSL ? VK_LValue : VK_PRValue);1589}1590 1591CXXThisExpr *CXXThisExpr::CreateEmpty(const ASTContext &Ctx) {1592  return new (Ctx) CXXThisExpr(EmptyShell());1593}1594 1595static bool hasOnlyNonStaticMemberFunctions(UnresolvedSetIterator begin,1596                                            UnresolvedSetIterator end) {1597  do {1598    NamedDecl *decl = *begin;1599    if (isa<UnresolvedUsingValueDecl>(decl))1600      return false;1601 1602    // Unresolved member expressions should only contain methods and1603    // method templates.1604    if (cast<CXXMethodDecl>(decl->getUnderlyingDecl()->getAsFunction())1605            ->isStatic())1606      return false;1607  } while (++begin != end);1608 1609  return true;1610}1611 1612UnresolvedMemberExpr::UnresolvedMemberExpr(1613    const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,1614    QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,1615    NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,1616    const DeclarationNameInfo &MemberNameInfo,1617    const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,1618    UnresolvedSetIterator End)1619    : OverloadExpr(1620          UnresolvedMemberExprClass, Context, QualifierLoc, TemplateKWLoc,1621          MemberNameInfo, TemplateArgs, Begin, End,1622          // Dependent1623          ((Base && Base->isTypeDependent()) || BaseType->isDependentType()),1624          ((Base && Base->isInstantiationDependent()) ||1625           BaseType->isInstantiationDependentType()),1626          // Contains unexpanded parameter pack1627          ((Base && Base->containsUnexpandedParameterPack()) ||1628           BaseType->containsUnexpandedParameterPack())),1629      Base(Base), BaseType(BaseType), OperatorLoc(OperatorLoc) {1630  UnresolvedMemberExprBits.IsArrow = IsArrow;1631  UnresolvedMemberExprBits.HasUnresolvedUsing = HasUnresolvedUsing;1632 1633  // Check whether all of the members are non-static member functions,1634  // and if so, mark give this bound-member type instead of overload type.1635  if (hasOnlyNonStaticMemberFunctions(Begin, End))1636    setType(Context.BoundMemberTy);1637}1638 1639UnresolvedMemberExpr::UnresolvedMemberExpr(EmptyShell Empty,1640                                           unsigned NumResults,1641                                           bool HasTemplateKWAndArgsInfo)1642    : OverloadExpr(UnresolvedMemberExprClass, Empty, NumResults,1643                   HasTemplateKWAndArgsInfo) {}1644 1645bool UnresolvedMemberExpr::isImplicitAccess() const {1646  if (!Base)1647    return true;1648 1649  return cast<Expr>(Base)->isImplicitCXXThis();1650}1651 1652UnresolvedMemberExpr *UnresolvedMemberExpr::Create(1653    const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,1654    QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,1655    NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,1656    const DeclarationNameInfo &MemberNameInfo,1657    const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,1658    UnresolvedSetIterator End) {1659  unsigned NumResults = End - Begin;1660  bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();1661  unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;1662  unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,1663                                   TemplateArgumentLoc>(1664      NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);1665  void *Mem = Context.Allocate(Size, alignof(UnresolvedMemberExpr));1666  return new (Mem) UnresolvedMemberExpr(1667      Context, HasUnresolvedUsing, Base, BaseType, IsArrow, OperatorLoc,1668      QualifierLoc, TemplateKWLoc, MemberNameInfo, TemplateArgs, Begin, End);1669}1670 1671UnresolvedMemberExpr *UnresolvedMemberExpr::CreateEmpty(1672    const ASTContext &Context, unsigned NumResults,1673    bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) {1674  assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);1675  unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,1676                                   TemplateArgumentLoc>(1677      NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);1678  void *Mem = Context.Allocate(Size, alignof(UnresolvedMemberExpr));1679  return new (Mem)1680      UnresolvedMemberExpr(EmptyShell(), NumResults, HasTemplateKWAndArgsInfo);1681}1682 1683CXXRecordDecl *UnresolvedMemberExpr::getNamingClass() {1684  // Unlike for UnresolvedLookupExpr, it is very easy to re-derive this.1685 1686  // If there was a nested name specifier, it names the naming class.1687  // It can't be dependent: after all, we were actually able to do the1688  // lookup.1689  CXXRecordDecl *Record = nullptr;1690  if (NestedNameSpecifier Qualifier = getQualifier();1691      Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {1692    const Type *T = getQualifier().getAsType();1693    Record = T->getAsCXXRecordDecl();1694    assert(Record && "qualifier in member expression does not name record");1695  }1696  // Otherwise the naming class must have been the base class.1697  else {1698    QualType BaseType = getBaseType().getNonReferenceType();1699    if (isArrow())1700      BaseType = BaseType->castAs<PointerType>()->getPointeeType();1701 1702    Record = BaseType->getAsCXXRecordDecl();1703    assert(Record && "base of member expression does not name record");1704  }1705 1706  return Record;1707}1708 1709SizeOfPackExpr *SizeOfPackExpr::Create(ASTContext &Context,1710                                       SourceLocation OperatorLoc,1711                                       NamedDecl *Pack, SourceLocation PackLoc,1712                                       SourceLocation RParenLoc,1713                                       UnsignedOrNone Length,1714                                       ArrayRef<TemplateArgument> PartialArgs) {1715  void *Storage =1716      Context.Allocate(totalSizeToAlloc<TemplateArgument>(PartialArgs.size()));1717  return new (Storage) SizeOfPackExpr(Context.getSizeType(), OperatorLoc, Pack,1718                                      PackLoc, RParenLoc, Length, PartialArgs);1719}1720 1721SizeOfPackExpr *SizeOfPackExpr::CreateDeserialized(ASTContext &Context,1722                                                   unsigned NumPartialArgs) {1723  void *Storage =1724      Context.Allocate(totalSizeToAlloc<TemplateArgument>(NumPartialArgs));1725  return new (Storage) SizeOfPackExpr(EmptyShell(), NumPartialArgs);1726}1727 1728NonTypeTemplateParmDecl *SubstNonTypeTemplateParmExpr::getParameter() const {1729  return cast<NonTypeTemplateParmDecl>(1730      std::get<0>(getReplacedTemplateParameter(getAssociatedDecl(), Index)));1731}1732 1733PackIndexingExpr *PackIndexingExpr::Create(1734    ASTContext &Context, SourceLocation EllipsisLoc, SourceLocation RSquareLoc,1735    Expr *PackIdExpr, Expr *IndexExpr, std::optional<int64_t> Index,1736    ArrayRef<Expr *> SubstitutedExprs, bool FullySubstituted) {1737  QualType Type;1738  if (Index && FullySubstituted && !SubstitutedExprs.empty())1739    Type = SubstitutedExprs[*Index]->getType();1740  else1741    Type = PackIdExpr->getType();1742 1743  void *Storage =1744      Context.Allocate(totalSizeToAlloc<Expr *>(SubstitutedExprs.size()));1745  return new (Storage)1746      PackIndexingExpr(Type, EllipsisLoc, RSquareLoc, PackIdExpr, IndexExpr,1747                       SubstitutedExprs, FullySubstituted);1748}1749 1750NamedDecl *PackIndexingExpr::getPackDecl() const {1751  if (auto *D = dyn_cast<DeclRefExpr>(getPackIdExpression()); D) {1752    NamedDecl *ND = dyn_cast<NamedDecl>(D->getDecl());1753    assert(ND && "exected a named decl");1754    return ND;1755  }1756  assert(false && "invalid declaration kind in pack indexing expression");1757  return nullptr;1758}1759 1760PackIndexingExpr *1761PackIndexingExpr::CreateDeserialized(ASTContext &Context,1762                                     unsigned NumTransformedExprs) {1763  void *Storage =1764      Context.Allocate(totalSizeToAlloc<Expr *>(NumTransformedExprs));1765  return new (Storage) PackIndexingExpr(EmptyShell{});1766}1767 1768QualType SubstNonTypeTemplateParmExpr::getParameterType(1769    const ASTContext &Context) const {1770  // Note that, for a class type NTTP, we will have an lvalue of type 'const1771  // T', so we can't just compute this from the type and value category.1772 1773  QualType Type = getType();1774 1775  if (isReferenceParameter())1776    return Context.getLValueReferenceType(Type);1777  return Type.getUnqualifiedType();1778}1779 1780SubstNonTypeTemplateParmPackExpr::SubstNonTypeTemplateParmPackExpr(1781    QualType T, ExprValueKind ValueKind, SourceLocation NameLoc,1782    const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index,1783    bool Final)1784    : Expr(SubstNonTypeTemplateParmPackExprClass, T, ValueKind, OK_Ordinary),1785      AssociatedDecl(AssociatedDecl), Arguments(ArgPack.pack_begin()),1786      NumArguments(ArgPack.pack_size()), Final(Final), Index(Index),1787      NameLoc(NameLoc) {1788  assert(AssociatedDecl != nullptr);1789  setDependence(ExprDependence::TypeValueInstantiation |1790                ExprDependence::UnexpandedPack);1791}1792 1793NonTypeTemplateParmDecl *1794SubstNonTypeTemplateParmPackExpr::getParameterPack() const {1795  return cast<NonTypeTemplateParmDecl>(1796      std::get<0>(getReplacedTemplateParameter(getAssociatedDecl(), Index)));1797}1798 1799TemplateArgument SubstNonTypeTemplateParmPackExpr::getArgumentPack() const {1800  return TemplateArgument(ArrayRef(Arguments, NumArguments));1801}1802 1803FunctionParmPackExpr::FunctionParmPackExpr(QualType T, ValueDecl *ParamPack,1804                                           SourceLocation NameLoc,1805                                           unsigned NumParams,1806                                           ValueDecl *const *Params)1807    : Expr(FunctionParmPackExprClass, T, VK_LValue, OK_Ordinary),1808      ParamPack(ParamPack), NameLoc(NameLoc), NumParameters(NumParams) {1809  if (Params)1810    std::uninitialized_copy(Params, Params + NumParams, getTrailingObjects());1811  setDependence(ExprDependence::TypeValueInstantiation |1812                ExprDependence::UnexpandedPack);1813}1814 1815FunctionParmPackExpr *1816FunctionParmPackExpr::Create(const ASTContext &Context, QualType T,1817                             ValueDecl *ParamPack, SourceLocation NameLoc,1818                             ArrayRef<ValueDecl *> Params) {1819  return new (Context.Allocate(totalSizeToAlloc<ValueDecl *>(Params.size())))1820      FunctionParmPackExpr(T, ParamPack, NameLoc, Params.size(), Params.data());1821}1822 1823FunctionParmPackExpr *1824FunctionParmPackExpr::CreateEmpty(const ASTContext &Context,1825                                  unsigned NumParams) {1826  return new (Context.Allocate(totalSizeToAlloc<ValueDecl *>(NumParams)))1827      FunctionParmPackExpr(QualType(), nullptr, SourceLocation(), 0, nullptr);1828}1829 1830MaterializeTemporaryExpr::MaterializeTemporaryExpr(1831    QualType T, Expr *Temporary, bool BoundToLvalueReference,1832    LifetimeExtendedTemporaryDecl *MTD)1833    : Expr(MaterializeTemporaryExprClass, T,1834           BoundToLvalueReference ? VK_LValue : VK_XValue, OK_Ordinary) {1835  if (MTD) {1836    State = MTD;1837    MTD->ExprWithTemporary = Temporary;1838    return;1839  }1840  State = Temporary;1841  setDependence(computeDependence(this));1842}1843 1844void MaterializeTemporaryExpr::setExtendingDecl(ValueDecl *ExtendedBy,1845                                                unsigned ManglingNumber) {1846  // We only need extra state if we have to remember more than just the Stmt.1847  if (!ExtendedBy)1848    return;1849 1850  // We may need to allocate extra storage for the mangling number and the1851  // extended-by ValueDecl.1852  if (!isa<LifetimeExtendedTemporaryDecl *>(State))1853    State = LifetimeExtendedTemporaryDecl::Create(1854        cast<Expr>(cast<Stmt *>(State)), ExtendedBy, ManglingNumber);1855 1856  auto ES = cast<LifetimeExtendedTemporaryDecl *>(State);1857  ES->ExtendingDecl = ExtendedBy;1858  ES->ManglingNumber = ManglingNumber;1859}1860 1861bool MaterializeTemporaryExpr::isUsableInConstantExpressions(1862    const ASTContext &Context) const {1863  // C++20 [expr.const]p4:1864  //   An object or reference is usable in constant expressions if it is [...]1865  //   a temporary object of non-volatile const-qualified literal type1866  //   whose lifetime is extended to that of a variable that is usable1867  //   in constant expressions1868  auto *VD = dyn_cast_or_null<VarDecl>(getExtendingDecl());1869  return VD && getType().isConstant(Context) &&1870         !getType().isVolatileQualified() &&1871         getType()->isLiteralType(Context) &&1872         VD->isUsableInConstantExpressions(Context);1873}1874 1875TypeTraitExpr::TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,1876                             ArrayRef<TypeSourceInfo *> Args,1877                             SourceLocation RParenLoc,1878                             std::variant<bool, APValue> Value)1879    : Expr(TypeTraitExprClass, T, VK_PRValue, OK_Ordinary), Loc(Loc),1880      RParenLoc(RParenLoc) {1881  assert(Kind <= TT_Last && "invalid enum value!");1882 1883  TypeTraitExprBits.Kind = Kind;1884  assert(static_cast<unsigned>(Kind) == TypeTraitExprBits.Kind &&1885         "TypeTraitExprBits.Kind overflow!");1886 1887  TypeTraitExprBits.IsBooleanTypeTrait = std::holds_alternative<bool>(Value);1888  if (TypeTraitExprBits.IsBooleanTypeTrait)1889    TypeTraitExprBits.Value = std::get<bool>(Value);1890  else1891    ::new (getTrailingObjects<APValue>())1892        APValue(std::get<APValue>(std::move(Value)));1893 1894  TypeTraitExprBits.NumArgs = Args.size();1895  assert(Args.size() == TypeTraitExprBits.NumArgs &&1896         "TypeTraitExprBits.NumArgs overflow!");1897  auto **ToArgs = getTrailingObjects<TypeSourceInfo *>();1898  llvm::copy(Args, ToArgs);1899 1900  setDependence(computeDependence(this));1901 1902  assert((TypeTraitExprBits.IsBooleanTypeTrait || isValueDependent() ||1903          getAPValue().isInt() || getAPValue().isAbsent()) &&1904         "Only int values are supported by clang");1905}1906 1907TypeTraitExpr::TypeTraitExpr(EmptyShell Empty, bool IsStoredAsBool)1908    : Expr(TypeTraitExprClass, Empty) {1909  TypeTraitExprBits.IsBooleanTypeTrait = IsStoredAsBool;1910  if (!IsStoredAsBool)1911    ::new (getTrailingObjects<APValue>()) APValue();1912}1913 1914TypeTraitExpr *TypeTraitExpr::Create(const ASTContext &C, QualType T,1915                                     SourceLocation Loc,1916                                     TypeTrait Kind,1917                                     ArrayRef<TypeSourceInfo *> Args,1918                                     SourceLocation RParenLoc,1919                                     bool Value) {1920  void *Mem =1921      C.Allocate(totalSizeToAlloc<APValue, TypeSourceInfo *>(0, Args.size()));1922  return new (Mem) TypeTraitExpr(T, Loc, Kind, Args, RParenLoc, Value);1923}1924 1925TypeTraitExpr *TypeTraitExpr::Create(const ASTContext &C, QualType T,1926                                     SourceLocation Loc, TypeTrait Kind,1927                                     ArrayRef<TypeSourceInfo *> Args,1928                                     SourceLocation RParenLoc, APValue Value) {1929  void *Mem =1930      C.Allocate(totalSizeToAlloc<APValue, TypeSourceInfo *>(1, Args.size()));1931  return new (Mem) TypeTraitExpr(T, Loc, Kind, Args, RParenLoc, Value);1932}1933 1934TypeTraitExpr *TypeTraitExpr::CreateDeserialized(const ASTContext &C,1935                                                 bool IsStoredAsBool,1936                                                 unsigned NumArgs) {1937  void *Mem = C.Allocate(totalSizeToAlloc<APValue, TypeSourceInfo *>(1938      IsStoredAsBool ? 0 : 1, NumArgs));1939  return new (Mem) TypeTraitExpr(EmptyShell(), IsStoredAsBool);1940}1941 1942CUDAKernelCallExpr::CUDAKernelCallExpr(Expr *Fn, CallExpr *Config,1943                                       ArrayRef<Expr *> Args, QualType Ty,1944                                       ExprValueKind VK, SourceLocation RP,1945                                       FPOptionsOverride FPFeatures,1946                                       unsigned MinNumArgs)1947    : CallExpr(CUDAKernelCallExprClass, Fn, /*PreArgs=*/Config, Args, Ty, VK,1948               RP, FPFeatures, MinNumArgs, NotADL) {}1949 1950CUDAKernelCallExpr::CUDAKernelCallExpr(unsigned NumArgs, bool HasFPFeatures,1951                                       EmptyShell Empty)1952    : CallExpr(CUDAKernelCallExprClass, /*NumPreArgs=*/END_PREARG, NumArgs,1953               HasFPFeatures, Empty) {}1954 1955CUDAKernelCallExpr *1956CUDAKernelCallExpr::Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config,1957                           ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,1958                           SourceLocation RP, FPOptionsOverride FPFeatures,1959                           unsigned MinNumArgs) {1960  // Allocate storage for the trailing objects of CallExpr.1961  unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);1962  unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(1963      /*NumPreArgs=*/END_PREARG, NumArgs, FPFeatures.requiresTrailingStorage());1964  void *Mem =1965      Ctx.Allocate(sizeToAllocateForCallExprSubclass<CUDAKernelCallExpr>(1966                       SizeOfTrailingObjects),1967                   alignof(CUDAKernelCallExpr));1968  return new (Mem)1969      CUDAKernelCallExpr(Fn, Config, Args, Ty, VK, RP, FPFeatures, MinNumArgs);1970}1971 1972CUDAKernelCallExpr *CUDAKernelCallExpr::CreateEmpty(const ASTContext &Ctx,1973                                                    unsigned NumArgs,1974                                                    bool HasFPFeatures,1975                                                    EmptyShell Empty) {1976  // Allocate storage for the trailing objects of CallExpr.1977  unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(1978      /*NumPreArgs=*/END_PREARG, NumArgs, HasFPFeatures);1979  void *Mem =1980      Ctx.Allocate(sizeToAllocateForCallExprSubclass<CUDAKernelCallExpr>(1981                       SizeOfTrailingObjects),1982                   alignof(CUDAKernelCallExpr));1983  return new (Mem) CUDAKernelCallExpr(NumArgs, HasFPFeatures, Empty);1984}1985 1986CXXParenListInitExpr *1987CXXParenListInitExpr::Create(ASTContext &C, ArrayRef<Expr *> Args, QualType T,1988                             unsigned NumUserSpecifiedExprs,1989                             SourceLocation InitLoc, SourceLocation LParenLoc,1990                             SourceLocation RParenLoc) {1991  void *Mem = C.Allocate(totalSizeToAlloc<Expr *>(Args.size()));1992  return new (Mem) CXXParenListInitExpr(Args, T, NumUserSpecifiedExprs, InitLoc,1993                                        LParenLoc, RParenLoc);1994}1995 1996CXXParenListInitExpr *CXXParenListInitExpr::CreateEmpty(ASTContext &C,1997                                                        unsigned NumExprs,1998                                                        EmptyShell Empty) {1999  void *Mem = C.Allocate(totalSizeToAlloc<Expr *>(NumExprs),2000                         alignof(CXXParenListInitExpr));2001  return new (Mem) CXXParenListInitExpr(Empty, NumExprs);2002}2003 2004CXXFoldExpr::CXXFoldExpr(QualType T, UnresolvedLookupExpr *Callee,2005                         SourceLocation LParenLoc, Expr *LHS,2006                         BinaryOperatorKind Opcode, SourceLocation EllipsisLoc,2007                         Expr *RHS, SourceLocation RParenLoc,2008                         UnsignedOrNone NumExpansions)2009    : Expr(CXXFoldExprClass, T, VK_PRValue, OK_Ordinary), LParenLoc(LParenLoc),2010      EllipsisLoc(EllipsisLoc), RParenLoc(RParenLoc),2011      NumExpansions(NumExpansions) {2012  CXXFoldExprBits.Opcode = Opcode;2013  // We rely on asserted invariant to distinguish left and right folds.2014  if (LHS && RHS)2015    assert(LHS->containsUnexpandedParameterPack() !=2016               RHS->containsUnexpandedParameterPack() &&2017           "Exactly one of LHS or RHS should contain an unexpanded pack");2018  SubExprs[SubExpr::Callee] = Callee;2019  SubExprs[SubExpr::LHS] = LHS;2020  SubExprs[SubExpr::RHS] = RHS;2021  setDependence(computeDependence(this));2022}2023