brintos

brintos / llvm-project-archived public Read only

0
0
Text · 192.5 KiB · 35205f4 Raw
4725 lines · cpp
1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/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//  This file implements C++ template instantiation.9//10//===----------------------------------------------------------------------===/11 12#include "TreeTransform.h"13#include "clang/AST/ASTConcept.h"14#include "clang/AST/ASTConsumer.h"15#include "clang/AST/ASTContext.h"16#include "clang/AST/ASTLambda.h"17#include "clang/AST/ASTMutationListener.h"18#include "clang/AST/DeclBase.h"19#include "clang/AST/DeclTemplate.h"20#include "clang/AST/DynamicRecursiveASTVisitor.h"21#include "clang/AST/Expr.h"22#include "clang/AST/ExprConcepts.h"23#include "clang/AST/PrettyDeclStackTrace.h"24#include "clang/AST/Type.h"25#include "clang/AST/TypeLoc.h"26#include "clang/AST/TypeVisitor.h"27#include "clang/Basic/LangOptions.h"28#include "clang/Basic/TargetInfo.h"29#include "clang/Sema/DeclSpec.h"30#include "clang/Sema/EnterExpressionEvaluationContext.h"31#include "clang/Sema/Initialization.h"32#include "clang/Sema/Sema.h"33#include "clang/Sema/SemaConcept.h"34#include "clang/Sema/SemaInternal.h"35#include "clang/Sema/Template.h"36#include "clang/Sema/TemplateDeduction.h"37#include "clang/Sema/TemplateInstCallback.h"38#include "llvm/ADT/SmallVectorExtras.h"39#include "llvm/ADT/StringExtras.h"40#include "llvm/Support/ErrorHandling.h"41#include "llvm/Support/SaveAndRestore.h"42#include "llvm/Support/TimeProfiler.h"43#include <optional>44 45using namespace clang;46using namespace sema;47 48//===----------------------------------------------------------------------===/49// Template Instantiation Support50//===----------------------------------------------------------------------===/51 52namespace {53namespace TemplateInstArgsHelpers {54struct Response {55  const Decl *NextDecl = nullptr;56  bool IsDone = false;57  bool ClearRelativeToPrimary = true;58  static Response Done() {59    Response R;60    R.IsDone = true;61    return R;62  }63  static Response ChangeDecl(const Decl *ND) {64    Response R;65    R.NextDecl = ND;66    return R;67  }68  static Response ChangeDecl(const DeclContext *Ctx) {69    Response R;70    R.NextDecl = Decl::castFromDeclContext(Ctx);71    return R;72  }73 74  static Response UseNextDecl(const Decl *CurDecl) {75    return ChangeDecl(CurDecl->getDeclContext());76  }77 78  static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {79    Response R = Response::UseNextDecl(CurDecl);80    R.ClearRelativeToPrimary = false;81    return R;82  }83};84 85// Retrieve the primary template for a lambda call operator. It's86// unfortunate that we only have the mappings of call operators rather87// than lambda classes.88const FunctionDecl *89getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) {90  if (!isLambdaCallOperator(LambdaCallOperator))91    return LambdaCallOperator;92  while (true) {93    if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>(94            LambdaCallOperator->getDescribedTemplate());95        FTD && FTD->getInstantiatedFromMemberTemplate()) {96      LambdaCallOperator =97          FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl();98    } else if (LambdaCallOperator->getPrimaryTemplate()) {99      // Cases where the lambda operator is instantiated in100      // TemplateDeclInstantiator::VisitCXXMethodDecl.101      LambdaCallOperator =102          LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl();103    } else if (auto *Prev = cast<CXXMethodDecl>(LambdaCallOperator)104                                ->getInstantiatedFromMemberFunction())105      LambdaCallOperator = Prev;106    else107      break;108  }109  return LambdaCallOperator;110}111 112struct EnclosingTypeAliasTemplateDetails {113  TypeAliasTemplateDecl *Template = nullptr;114  TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr;115  ArrayRef<TemplateArgument> AssociatedTemplateArguments;116 117  explicit operator bool() noexcept { return Template; }118};119 120// Find the enclosing type alias template Decl from CodeSynthesisContexts, as121// well as its primary template and instantiating template arguments.122EnclosingTypeAliasTemplateDetails123getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) {124  for (auto &CSC : llvm::reverse(SemaRef.CodeSynthesisContexts)) {125    if (CSC.Kind != Sema::CodeSynthesisContext::SynthesisKind::126                        TypeAliasTemplateInstantiation)127      continue;128    EnclosingTypeAliasTemplateDetails Result;129    auto *TATD = cast<TypeAliasTemplateDecl>(CSC.Entity),130         *Next = TATD->getInstantiatedFromMemberTemplate();131    Result = {132        /*Template=*/TATD,133        /*PrimaryTypeAliasDecl=*/TATD,134        /*AssociatedTemplateArguments=*/CSC.template_arguments(),135    };136    while (Next) {137      Result.PrimaryTypeAliasDecl = Next;138      Next = Next->getInstantiatedFromMemberTemplate();139    }140    return Result;141  }142  return {};143}144 145// Check if we are currently inside of a lambda expression that is146// surrounded by a using alias declaration. e.g.147//   template <class> using type = decltype([](auto) { ^ }());148// We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never149// a DeclContext, nor does it have an associated specialization Decl from which150// we could collect these template arguments.151bool isLambdaEnclosedByTypeAliasDecl(152    const FunctionDecl *LambdaCallOperator,153    const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) {154  struct Visitor : DynamicRecursiveASTVisitor {155    Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {}156    bool VisitLambdaExpr(LambdaExpr *LE) override {157      // Return true to bail out of the traversal, implying the Decl contains158      // the lambda.159      return getPrimaryTemplateOfGenericLambda(LE->getCallOperator()) !=160             CallOperator;161    }162    const FunctionDecl *CallOperator;163  };164 165  QualType Underlying =166      PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType();167 168  return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator))169              .TraverseType(Underlying);170}171 172// Add template arguments from a variable template instantiation.173Response174HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,175                      MultiLevelTemplateArgumentList &Result,176                      bool SkipForSpecialization) {177  // For a class-scope explicit specialization, there are no template arguments178  // at this level, but there may be enclosing template arguments.179  if (VarTemplSpec->isClassScopeExplicitSpecialization())180    return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);181 182  // We're done when we hit an explicit specialization.183  if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&184      !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec))185    return Response::Done();186 187  // If this variable template specialization was instantiated from a188  // specialized member that is a variable template, we're done.189  assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");190  llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>191      Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();192  if (VarTemplatePartialSpecializationDecl *Partial =193          dyn_cast<VarTemplatePartialSpecializationDecl *>(Specialized)) {194    if (!SkipForSpecialization)195      Result.addOuterTemplateArguments(196          Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),197          /*Final=*/false);198    if (Partial->isMemberSpecialization())199      return Response::Done();200  } else {201    VarTemplateDecl *Tmpl = cast<VarTemplateDecl *>(Specialized);202    if (!SkipForSpecialization)203      Result.addOuterTemplateArguments(204          Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),205          /*Final=*/false);206    if (Tmpl->isMemberSpecialization())207      return Response::Done();208  }209  return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);210}211 212// If we have a template template parameter with translation unit context,213// then we're performing substitution into a default template argument of214// this template template parameter before we've constructed the template215// that will own this template template parameter. In this case, we216// use empty template parameter lists for all of the outer templates217// to avoid performing any substitutions.218Response219HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,220                                      MultiLevelTemplateArgumentList &Result) {221  for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)222    Result.addOuterTemplateArguments(std::nullopt);223  return Response::Done();224}225 226Response HandlePartialClassTemplateSpec(227    const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,228    MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {229  if (!SkipForSpecialization)230    Result.addOuterRetainedLevels(PartialClassTemplSpec->getTemplateDepth());231  return Response::Done();232}233 234// Add template arguments from a class template instantiation.235Response236HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,237                        MultiLevelTemplateArgumentList &Result,238                        bool SkipForSpecialization) {239  if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {240    // We're done when we hit an explicit specialization.241    if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&242        !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec))243      return Response::Done();244 245    if (!SkipForSpecialization)246      Result.addOuterTemplateArguments(247          const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),248          ClassTemplSpec->getTemplateInstantiationArgs().asArray(),249          /*Final=*/false);250 251    // If this class template specialization was instantiated from a252    // specialized member that is a class template, we're done.253    assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");254    if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())255      return Response::Done();256 257    // If this was instantiated from a partial template specialization, we need258    // to get the next level of declaration context from the partial259    // specialization, as the ClassTemplateSpecializationDecl's260    // DeclContext/LexicalDeclContext will be for the primary template.261    if (auto *InstFromPartialTempl =262            ClassTemplSpec->getSpecializedTemplateOrPartial()263                .dyn_cast<ClassTemplatePartialSpecializationDecl *>())264      return Response::ChangeDecl(265          InstFromPartialTempl->getLexicalDeclContext());266  }267  return Response::UseNextDecl(ClassTemplSpec);268}269 270Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function,271                        MultiLevelTemplateArgumentList &Result,272                        const FunctionDecl *Pattern, bool RelativeToPrimary,273                        bool ForConstraintInstantiation,274                        bool ForDefaultArgumentSubstitution) {275  // Add template arguments from a function template specialization.276  if (!RelativeToPrimary &&277      Function->getTemplateSpecializationKindForInstantiation() ==278          TSK_ExplicitSpecialization)279    return Response::Done();280 281  if (!RelativeToPrimary &&282      Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {283    // This is an implicit instantiation of an explicit specialization. We284    // don't get any template arguments from this function but might get285    // some from an enclosing template.286    return Response::UseNextDecl(Function);287  } else if (const TemplateArgumentList *TemplateArgs =288                 Function->getTemplateSpecializationArgs()) {289    // Add the template arguments for this specialization.290    Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),291                                     TemplateArgs->asArray(),292                                     /*Final=*/false);293 294    if (RelativeToPrimary &&295        (Function->getTemplateSpecializationKind() ==296             TSK_ExplicitSpecialization ||297         (Function->getFriendObjectKind() &&298          !Function->getPrimaryTemplate()->getFriendObjectKind())))299      return Response::UseNextDecl(Function);300 301    // If this function was instantiated from a specialized member that is302    // a function template, we're done.303    assert(Function->getPrimaryTemplate() && "No function template?");304    if (!ForDefaultArgumentSubstitution &&305        Function->getPrimaryTemplate()->isMemberSpecialization())306      return Response::Done();307 308    // If this function is a generic lambda specialization, we are done.309    if (!ForConstraintInstantiation &&310        isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function))311      return Response::Done();312 313  } else if (auto *Template = Function->getDescribedFunctionTemplate()) {314    assert(315        (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&316        "Outer template not instantiated?");317    if (ForConstraintInstantiation) {318      for (auto &Inst : llvm::reverse(SemaRef.CodeSynthesisContexts)) {319        if (Inst.Kind == Sema::CodeSynthesisContext::ConstraintsCheck &&320            Inst.Entity == Template) {321          // After CWG2369, the outer templates are not instantiated when322          // checking its associated constraints. So add them back through the323          // synthesis context; this is useful for e.g. nested constraints324          // involving lambdas.325          Result.addOuterTemplateArguments(Template, Inst.template_arguments(),326                                           /*Final=*/false);327          break;328        }329      }330    }331  }332  // If this is a friend or local declaration and it declares an entity at333  // namespace scope, take arguments from its lexical parent334  // instead of its semantic parent, unless of course the pattern we're335  // instantiating actually comes from the file's context!336  if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&337      Function->getNonTransparentDeclContext()->isFileContext() &&338      (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {339    return Response::ChangeDecl(Function->getLexicalDeclContext());340  }341 342  if (ForConstraintInstantiation && Function->getFriendObjectKind())343    return Response::ChangeDecl(Function->getLexicalDeclContext());344  return Response::UseNextDecl(Function);345}346 347Response HandleFunctionTemplateDecl(Sema &SemaRef,348                                    const FunctionTemplateDecl *FTD,349                                    MultiLevelTemplateArgumentList &Result) {350  if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) {351    Result.addOuterTemplateArguments(352        const_cast<FunctionTemplateDecl *>(FTD),353        const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(354            SemaRef.Context),355        /*Final=*/false);356 357    NestedNameSpecifier NNS = FTD->getTemplatedDecl()->getQualifier();358 359    for (const Type *Ty = NNS.getKind() == NestedNameSpecifier::Kind::Type360                              ? NNS.getAsType()361                              : nullptr,362                    *NextTy = nullptr;363         Ty && Ty->isInstantiationDependentType();364         Ty = std::exchange(NextTy, nullptr)) {365      if (NestedNameSpecifier P = Ty->getPrefix();366          P.getKind() == NestedNameSpecifier::Kind::Type)367        NextTy = P.getAsType();368      const auto *TSTy = dyn_cast<TemplateSpecializationType>(Ty);369      if (!TSTy)370        continue;371 372      ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();373      // Prefer template arguments from the injected-class-type if possible.374      // For example,375      // ```cpp376      // template <class... Pack> struct S {377      //   template <class T> void foo();378      // };379      // template <class... Pack> template <class T>380      //           ^^^^^^^^^^^^^ InjectedTemplateArgs381      //           They're of kind TemplateArgument::Pack, not of382      //           TemplateArgument::Type.383      // void S<Pack...>::foo() {}384      //        ^^^^^^^385      //        TSTy->template_arguments() (which are of PackExpansionType)386      // ```387      // This meets the contract in388      // TreeTransform::TryExpandParameterPacks that the template arguments389      // for unexpanded parameters should be of a Pack kind.390      if (TSTy->isCurrentInstantiation()) {391        auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();392        if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())393          Arguments = CTD->getInjectedTemplateArgs(SemaRef.Context);394        else if (auto *Specialization =395                     dyn_cast<ClassTemplateSpecializationDecl>(RD))396          Arguments = Specialization->getTemplateInstantiationArgs().asArray();397      }398      Result.addOuterTemplateArguments(399          TSTy->getTemplateName().getAsTemplateDecl(), Arguments,400          /*Final=*/false);401    }402  }403 404  return Response::ChangeDecl(FTD->getLexicalDeclContext());405}406 407Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec,408                          MultiLevelTemplateArgumentList &Result,409                          ASTContext &Context,410                          bool ForConstraintInstantiation) {411  if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {412    assert(413        (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&414        "Outer template not instantiated?");415    if (ClassTemplate->isMemberSpecialization())416      return Response::Done();417    if (ForConstraintInstantiation)418      Result.addOuterTemplateArguments(419          const_cast<CXXRecordDecl *>(Rec),420          ClassTemplate->getInjectedTemplateArgs(SemaRef.Context),421          /*Final=*/false);422  }423 424  if (const MemberSpecializationInfo *MSInfo =425          Rec->getMemberSpecializationInfo())426    if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)427      return Response::Done();428 429  bool IsFriend = Rec->getFriendObjectKind() ||430                  (Rec->getDescribedClassTemplate() &&431                   Rec->getDescribedClassTemplate()->getFriendObjectKind());432  if (ForConstraintInstantiation && IsFriend &&433      Rec->getNonTransparentDeclContext()->isFileContext()) {434    return Response::ChangeDecl(Rec->getLexicalDeclContext());435  }436 437  // This is to make sure we pick up the VarTemplateSpecializationDecl or the438  // TypeAliasTemplateDecl that this lambda is defined inside of.439  if (Rec->isLambda()) {440    if (const Decl *LCD = Rec->getLambdaContextDecl())441      return Response::ChangeDecl(LCD);442    // Retrieve the template arguments for a using alias declaration.443    // This is necessary for constraint checking, since we always keep444    // constraints relative to the primary template.445    if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef);446        ForConstraintInstantiation && TypeAlias) {447      if (isLambdaEnclosedByTypeAliasDecl(Rec->getLambdaCallOperator(),448                                          TypeAlias.PrimaryTypeAliasDecl)) {449        Result.addOuterTemplateArguments(TypeAlias.Template,450                                         TypeAlias.AssociatedTemplateArguments,451                                         /*Final=*/false);452        // Visit the parent of the current type alias declaration rather than453        // the lambda thereof.454        // E.g., in the following example:455        // struct S {456        //  template <class> using T = decltype([]<Concept> {} ());457        // };458        // void foo() {459        //   S::T var;460        // }461        // The instantiated lambda expression (which we're visiting at 'var')462        // has a function DeclContext 'foo' rather than the Record DeclContext463        // S. This seems to be an oversight to me that we may want to set a464        // Sema Context from the CXXScopeSpec before substituting into T.465        return Response::ChangeDecl(TypeAlias.Template->getDeclContext());466      }467    }468  }469 470  return Response::UseNextDecl(Rec);471}472 473Response HandleImplicitConceptSpecializationDecl(474    const ImplicitConceptSpecializationDecl *CSD,475    MultiLevelTemplateArgumentList &Result) {476  Result.addOuterTemplateArguments(477      const_cast<ImplicitConceptSpecializationDecl *>(CSD),478      CSD->getTemplateArguments(),479      /*Final=*/false);480  return Response::UseNextDecl(CSD);481}482 483Response HandleGenericDeclContext(const Decl *CurDecl) {484  return Response::UseNextDecl(CurDecl);485}486} // namespace TemplateInstArgsHelpers487} // namespace488 489MultiLevelTemplateArgumentList Sema::getTemplateInstantiationArgs(490    const NamedDecl *ND, const DeclContext *DC, bool Final,491    std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,492    const FunctionDecl *Pattern, bool ForConstraintInstantiation,493    bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) {494  assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");495  // Accumulate the set of template argument lists in this structure.496  MultiLevelTemplateArgumentList Result;497 498  using namespace TemplateInstArgsHelpers;499  const Decl *CurDecl = ND;500 501  if (Innermost) {502    Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,503                                     Final);504    // Populate placeholder template arguments for TemplateTemplateParmDecls.505    // This is essential for the case e.g.506    //507    // template <class> concept Concept = false;508    // template <template <Concept C> class T> void foo(T<int>)509    //510    // where parameter C has a depth of 1 but the substituting argument `int`511    // has a depth of 0.512    if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))513      HandleDefaultTempArgIntoTempTempParam(TTP, Result);514    CurDecl = DC ? Decl::castFromDeclContext(DC)515                 : Response::UseNextDecl(CurDecl).NextDecl;516  } else if (!CurDecl)517    CurDecl = Decl::castFromDeclContext(DC);518 519  while (!CurDecl->isFileContextDecl()) {520    Response R;521    if (const auto *VarTemplSpec =522            dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {523      R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);524    } else if (const auto *PartialClassTemplSpec =525                   dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {526      R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,527                                         SkipForSpecialization);528    } else if (const auto *ClassTemplSpec =529                   dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {530      R = HandleClassTemplateSpec(ClassTemplSpec, Result,531                                  SkipForSpecialization);532    } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {533      R = HandleFunction(*this, Function, Result, Pattern, RelativeToPrimary,534                         ForConstraintInstantiation,535                         ForDefaultArgumentSubstitution);536    } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {537      R = HandleRecordDecl(*this, Rec, Result, Context,538                           ForConstraintInstantiation);539    } else if (const auto *CSD =540                   dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {541      R = HandleImplicitConceptSpecializationDecl(CSD, Result);542    } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {543      R = HandleFunctionTemplateDecl(*this, FTD, Result);544    } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) {545      R = Response::ChangeDecl(CTD->getLexicalDeclContext());546    } else if (!isa<DeclContext>(CurDecl)) {547      R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);548      if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {549        R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);550      }551    } else {552      R = HandleGenericDeclContext(CurDecl);553    }554 555    if (R.IsDone)556      return Result;557    if (R.ClearRelativeToPrimary)558      RelativeToPrimary = false;559    assert(R.NextDecl);560    CurDecl = R.NextDecl;561  }562  return Result;563}564 565bool Sema::CodeSynthesisContext::isInstantiationRecord() const {566  switch (Kind) {567  case TemplateInstantiation:568  case ExceptionSpecInstantiation:569  case DefaultTemplateArgumentInstantiation:570  case DefaultFunctionArgumentInstantiation:571  case ExplicitTemplateArgumentSubstitution:572  case DeducedTemplateArgumentSubstitution:573  case PriorTemplateArgumentSubstitution:574  case ConstraintsCheck:575  case NestedRequirementConstraintsCheck:576    return true;577 578  case RequirementInstantiation:579  case RequirementParameterInstantiation:580  case DefaultTemplateArgumentChecking:581  case DeclaringSpecialMember:582  case DeclaringImplicitEqualityComparison:583  case DefiningSynthesizedFunction:584  case ExceptionSpecEvaluation:585  case ConstraintSubstitution:586  case ParameterMappingSubstitution:587  case ConstraintNormalization:588  case RewritingOperatorAsSpaceship:589  case InitializingStructuredBinding:590  case MarkingClassDllexported:591  case BuildingBuiltinDumpStructCall:592  case LambdaExpressionSubstitution:593  case BuildingDeductionGuides:594  case TypeAliasTemplateInstantiation:595  case PartialOrderingTTP:596    return false;597 598  // This function should never be called when Kind's value is Memoization.599  case Memoization:600    break;601  }602 603  llvm_unreachable("Invalid SynthesisKind!");604}605 606Sema::InstantiatingTemplate::InstantiatingTemplate(607    Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,608    SourceLocation PointOfInstantiation, SourceRange InstantiationRange,609    Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs)610    : SemaRef(SemaRef) {611  // Don't allow further instantiation if a fatal error and an uncompilable612  // error have occurred. Any diagnostics we might have raised will not be613  // visible, and we do not need to construct a correct AST.614  if (SemaRef.Diags.hasFatalErrorOccurred() &&615      SemaRef.hasUncompilableErrorOccurred()) {616    Invalid = true;617    return;618  }619 620  CodeSynthesisContext Inst;621  Inst.Kind = Kind;622  Inst.PointOfInstantiation = PointOfInstantiation;623  Inst.Entity = Entity;624  Inst.Template = Template;625  Inst.TemplateArgs = TemplateArgs.data();626  Inst.NumTemplateArgs = TemplateArgs.size();627  Inst.InstantiationRange = InstantiationRange;628  Inst.InConstraintSubstitution =629      Inst.Kind == CodeSynthesisContext::ConstraintSubstitution;630  Inst.InParameterMappingSubstitution =631      Inst.Kind == CodeSynthesisContext::ParameterMappingSubstitution;632  if (!SemaRef.CodeSynthesisContexts.empty()) {633    Inst.InConstraintSubstitution |=634        SemaRef.CodeSynthesisContexts.back().InConstraintSubstitution;635    Inst.InParameterMappingSubstitution |=636        SemaRef.CodeSynthesisContexts.back().InParameterMappingSubstitution;637  }638 639  Invalid = SemaRef.pushCodeSynthesisContext(Inst);640  if (!Invalid)641    atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);642}643 644Sema::InstantiatingTemplate::InstantiatingTemplate(645    Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,646    SourceRange InstantiationRange)647    : InstantiatingTemplate(SemaRef,648                            CodeSynthesisContext::TemplateInstantiation,649                            PointOfInstantiation, InstantiationRange, Entity) {}650 651Sema::InstantiatingTemplate::InstantiatingTemplate(652    Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,653    ExceptionSpecification, SourceRange InstantiationRange)654    : InstantiatingTemplate(655          SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,656          PointOfInstantiation, InstantiationRange, Entity) {}657 658Sema::InstantiatingTemplate::InstantiatingTemplate(659    Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,660    TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,661    SourceRange InstantiationRange)662    : InstantiatingTemplate(663          SemaRef,664          CodeSynthesisContext::DefaultTemplateArgumentInstantiation,665          PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),666          Template, TemplateArgs) {}667 668Sema::InstantiatingTemplate::InstantiatingTemplate(669    Sema &SemaRef, SourceLocation PointOfInstantiation,670    FunctionTemplateDecl *FunctionTemplate,671    ArrayRef<TemplateArgument> TemplateArgs,672    CodeSynthesisContext::SynthesisKind Kind, SourceRange InstantiationRange)673    : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,674                            InstantiationRange, FunctionTemplate, nullptr,675                            TemplateArgs) {676  assert(Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||677         Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution ||678         Kind == CodeSynthesisContext::BuildingDeductionGuides);679}680 681Sema::InstantiatingTemplate::InstantiatingTemplate(682    Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,683    ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)684    : InstantiatingTemplate(685          SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution,686          PointOfInstantiation, InstantiationRange, Template, nullptr,687          TemplateArgs) {}688 689Sema::InstantiatingTemplate::InstantiatingTemplate(690    Sema &SemaRef, SourceLocation PointOfInstantiation,691    ClassTemplatePartialSpecializationDecl *PartialSpec,692    ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)693    : InstantiatingTemplate(694          SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution,695          PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,696          TemplateArgs) {}697 698Sema::InstantiatingTemplate::InstantiatingTemplate(699    Sema &SemaRef, SourceLocation PointOfInstantiation,700    VarTemplatePartialSpecializationDecl *PartialSpec,701    ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)702    : InstantiatingTemplate(703          SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution,704          PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,705          TemplateArgs) {}706 707Sema::InstantiatingTemplate::InstantiatingTemplate(708    Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,709    ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)710    : InstantiatingTemplate(711          SemaRef,712          CodeSynthesisContext::DefaultFunctionArgumentInstantiation,713          PointOfInstantiation, InstantiationRange, Param, nullptr,714          TemplateArgs) {}715 716Sema::InstantiatingTemplate::InstantiatingTemplate(717    Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,718    NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,719    SourceRange InstantiationRange)720    : InstantiatingTemplate(721          SemaRef,722          CodeSynthesisContext::PriorTemplateArgumentSubstitution,723          PointOfInstantiation, InstantiationRange, Param, Template,724          TemplateArgs) {}725 726Sema::InstantiatingTemplate::InstantiatingTemplate(727    Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,728    TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,729    SourceRange InstantiationRange)730    : InstantiatingTemplate(731          SemaRef,732          CodeSynthesisContext::PriorTemplateArgumentSubstitution,733          PointOfInstantiation, InstantiationRange, Param, Template,734          TemplateArgs) {}735 736Sema::InstantiatingTemplate::InstantiatingTemplate(737    Sema &SemaRef, SourceLocation PointOfInstantiation,738    TypeAliasTemplateDecl *Entity, ArrayRef<TemplateArgument> TemplateArgs,739    SourceRange InstantiationRange)740    : InstantiatingTemplate(741          SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,742          PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,743          /*Template=*/nullptr, TemplateArgs) {}744 745Sema::InstantiatingTemplate::InstantiatingTemplate(746    Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,747    NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,748    SourceRange InstantiationRange)749    : InstantiatingTemplate(750          SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,751          PointOfInstantiation, InstantiationRange, Param, Template,752          TemplateArgs) {}753 754Sema::InstantiatingTemplate::InstantiatingTemplate(755    Sema &SemaRef, SourceLocation PointOfInstantiation,756    concepts::Requirement *Req, SourceRange InstantiationRange)757    : InstantiatingTemplate(758          SemaRef, CodeSynthesisContext::RequirementInstantiation,759          PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,760          /*Template=*/nullptr, /*TemplateArgs=*/{}) {}761 762Sema::InstantiatingTemplate::InstantiatingTemplate(763    Sema &SemaRef, SourceLocation PointOfInstantiation,764    concepts::NestedRequirement *Req, ConstraintsCheck,765    SourceRange InstantiationRange)766    : InstantiatingTemplate(767          SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,768          PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,769          /*Template=*/nullptr, /*TemplateArgs=*/{}) {}770 771Sema::InstantiatingTemplate::InstantiatingTemplate(772    Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,773    SourceRange InstantiationRange)774    : InstantiatingTemplate(775          SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,776          PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,777          /*Template=*/nullptr, /*TemplateArgs=*/{}) {}778 779Sema::InstantiatingTemplate::InstantiatingTemplate(780    Sema &SemaRef, SourceLocation PointOfInstantiation,781    ConstraintsCheck, NamedDecl *Template,782    ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)783    : InstantiatingTemplate(784          SemaRef, CodeSynthesisContext::ConstraintsCheck,785          PointOfInstantiation, InstantiationRange, Template, nullptr,786          TemplateArgs) {}787 788Sema::InstantiatingTemplate::InstantiatingTemplate(789    Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution,790    NamedDecl *Template, SourceRange InstantiationRange)791    : InstantiatingTemplate(792          SemaRef, CodeSynthesisContext::ConstraintSubstitution,793          PointOfInstantiation, InstantiationRange, Template, nullptr, {}) {}794 795Sema::InstantiatingTemplate::InstantiatingTemplate(796    Sema &SemaRef, SourceLocation PointOfInstantiation,797    ConstraintNormalization, NamedDecl *Template,798    SourceRange InstantiationRange)799    : InstantiatingTemplate(800          SemaRef, CodeSynthesisContext::ConstraintNormalization,801          PointOfInstantiation, InstantiationRange, Template) {}802 803Sema::InstantiatingTemplate::InstantiatingTemplate(804    Sema &SemaRef, SourceLocation PointOfInstantiation,805    ParameterMappingSubstitution, NamedDecl *Template,806    SourceRange InstantiationRange)807    : InstantiatingTemplate(808          SemaRef, CodeSynthesisContext::ParameterMappingSubstitution,809          PointOfInstantiation, InstantiationRange, Template) {}810 811Sema::InstantiatingTemplate::InstantiatingTemplate(812    Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,813    BuildingDeductionGuidesTag, SourceRange InstantiationRange)814    : InstantiatingTemplate(815          SemaRef, CodeSynthesisContext::BuildingDeductionGuides,816          PointOfInstantiation, InstantiationRange, Entity) {}817 818Sema::InstantiatingTemplate::InstantiatingTemplate(819    Sema &SemaRef, SourceLocation ArgLoc, PartialOrderingTTP,820    TemplateDecl *PArg, SourceRange InstantiationRange)821    : InstantiatingTemplate(SemaRef, CodeSynthesisContext::PartialOrderingTTP,822                            ArgLoc, InstantiationRange, PArg) {}823 824bool Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {825  if (!Ctx.isInstantiationRecord()) {826    ++NonInstantiationEntries;827  } else {828    assert(SemaRef.NonInstantiationEntries <=829           SemaRef.CodeSynthesisContexts.size());830    if ((SemaRef.CodeSynthesisContexts.size() -831         SemaRef.NonInstantiationEntries) >832        SemaRef.getLangOpts().InstantiationDepth) {833      SemaRef.Diag(Ctx.PointOfInstantiation,834                   diag::err_template_recursion_depth_exceeded)835          << SemaRef.getLangOpts().InstantiationDepth << Ctx.InstantiationRange;836      SemaRef.Diag(Ctx.PointOfInstantiation,837                   diag::note_template_recursion_depth)838          << SemaRef.getLangOpts().InstantiationDepth;839      return true;840    }841  }842 843  CodeSynthesisContexts.push_back(Ctx);844 845  // Check to see if we're low on stack space. We can't do anything about this846  // from here, but we can at least warn the user.847  StackHandler.warnOnStackNearlyExhausted(Ctx.PointOfInstantiation);848  return false;849}850 851void Sema::popCodeSynthesisContext() {852  auto &Active = CodeSynthesisContexts.back();853  if (!Active.isInstantiationRecord()) {854    assert(NonInstantiationEntries > 0);855    --NonInstantiationEntries;856  }857 858  // Name lookup no longer looks in this template's defining module.859  assert(CodeSynthesisContexts.size() >=860             CodeSynthesisContextLookupModules.size() &&861         "forgot to remove a lookup module for a template instantiation");862  if (CodeSynthesisContexts.size() ==863      CodeSynthesisContextLookupModules.size()) {864    if (Module *M = CodeSynthesisContextLookupModules.back())865      LookupModulesCache.erase(M);866    CodeSynthesisContextLookupModules.pop_back();867  }868 869  // If we've left the code synthesis context for the current context stack,870  // stop remembering that we've emitted that stack.871  if (CodeSynthesisContexts.size() ==872      LastEmittedCodeSynthesisContextDepth)873    LastEmittedCodeSynthesisContextDepth = 0;874 875  CodeSynthesisContexts.pop_back();876}877 878void Sema::InstantiatingTemplate::Clear() {879  if (!Invalid) {880    atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,881                  SemaRef.CodeSynthesisContexts.back());882 883    SemaRef.popCodeSynthesisContext();884    Invalid = true;885  }886}887 888static std::string convertCallArgsToString(Sema &S,889                                           llvm::ArrayRef<const Expr *> Args) {890  std::string Result;891  llvm::raw_string_ostream OS(Result);892  llvm::ListSeparator Comma;893  for (const Expr *Arg : Args) {894    OS << Comma;895    Arg->IgnoreParens()->printPretty(OS, nullptr,896                                     S.Context.getPrintingPolicy());897  }898  return Result;899}900 901void Sema::PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc) {902  // Determine which template instantiations to skip, if any.903  unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;904  unsigned Limit = Diags.getTemplateBacktraceLimit();905  if (Limit && Limit < CodeSynthesisContexts.size()) {906    SkipStart = Limit / 2 + Limit % 2;907    SkipEnd = CodeSynthesisContexts.size() - Limit / 2;908  }909 910  // FIXME: In all of these cases, we need to show the template arguments911  unsigned InstantiationIdx = 0;912  for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator913         Active = CodeSynthesisContexts.rbegin(),914         ActiveEnd = CodeSynthesisContexts.rend();915       Active != ActiveEnd;916       ++Active, ++InstantiationIdx) {917    // Skip this instantiation?918    if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {919      if (InstantiationIdx == SkipStart) {920        // Note that we're skipping instantiations.921        DiagFunc(Active->PointOfInstantiation,922                 PDiag(diag::note_instantiation_contexts_suppressed)923                     << unsigned(CodeSynthesisContexts.size() - Limit));924      }925      continue;926    }927 928    switch (Active->Kind) {929    case CodeSynthesisContext::TemplateInstantiation: {930      Decl *D = Active->Entity;931      if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {932        unsigned DiagID = diag::note_template_member_class_here;933        if (isa<ClassTemplateSpecializationDecl>(Record))934          DiagID = diag::note_template_class_instantiation_here;935        DiagFunc(Active->PointOfInstantiation,936                 PDiag(DiagID) << Record << Active->InstantiationRange);937      } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {938        unsigned DiagID;939        if (Function->getPrimaryTemplate())940          DiagID = diag::note_function_template_spec_here;941        else942          DiagID = diag::note_template_member_function_here;943        DiagFunc(Active->PointOfInstantiation,944                 PDiag(DiagID) << Function << Active->InstantiationRange);945      } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {946        DiagFunc(Active->PointOfInstantiation,947                 PDiag(VD->isStaticDataMember()948                           ? diag::note_template_static_data_member_def_here949                           : diag::note_template_variable_def_here)950                     << VD << Active->InstantiationRange);951      } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {952        DiagFunc(Active->PointOfInstantiation,953                 PDiag(diag::note_template_enum_def_here)954                     << ED << Active->InstantiationRange);955      } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {956        DiagFunc(Active->PointOfInstantiation,957                 PDiag(diag::note_template_nsdmi_here)958                     << FD << Active->InstantiationRange);959      } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {960        DiagFunc(Active->PointOfInstantiation,961                 PDiag(diag::note_template_class_instantiation_here)962                     << CTD << Active->InstantiationRange);963      }964      break;965    }966 967    case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {968      TemplateDecl *Template = cast<TemplateDecl>(Active->Template);969      SmallString<128> TemplateArgsStr;970      llvm::raw_svector_ostream OS(TemplateArgsStr);971      Template->printName(OS, getPrintingPolicy());972      printTemplateArgumentList(OS, Active->template_arguments(),973                                getPrintingPolicy());974      DiagFunc(Active->PointOfInstantiation,975               PDiag(diag::note_default_arg_instantiation_here)976                   << OS.str() << Active->InstantiationRange);977      break;978    }979 980    case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {981      FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);982      DiagFunc(Active->PointOfInstantiation,983               PDiag(diag::note_explicit_template_arg_substitution_here)984                   << FnTmpl985                   << getTemplateArgumentBindingsText(986                          FnTmpl->getTemplateParameters(), Active->TemplateArgs,987                          Active->NumTemplateArgs)988                   << Active->InstantiationRange);989      break;990    }991 992    case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {993      if (FunctionTemplateDecl *FnTmpl =994              dyn_cast<FunctionTemplateDecl>(Active->Entity)) {995        DiagFunc(996            Active->PointOfInstantiation,997            PDiag(diag::note_function_template_deduction_instantiation_here)998                << FnTmpl999                << getTemplateArgumentBindingsText(1000                       FnTmpl->getTemplateParameters(), Active->TemplateArgs,1001                       Active->NumTemplateArgs)1002                << Active->InstantiationRange);1003      } else {1004        bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||1005                     isa<VarTemplateSpecializationDecl>(Active->Entity);1006        bool IsTemplate = false;1007        TemplateParameterList *Params;1008        if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {1009          IsTemplate = true;1010          Params = D->getTemplateParameters();1011        } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(1012                       Active->Entity)) {1013          Params = D->getTemplateParameters();1014        } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(1015                       Active->Entity)) {1016          Params = D->getTemplateParameters();1017        } else {1018          llvm_unreachable("unexpected template kind");1019        }1020 1021        DiagFunc(Active->PointOfInstantiation,1022                 PDiag(diag::note_deduced_template_arg_substitution_here)1023                     << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)1024                     << getTemplateArgumentBindingsText(Params,1025                                                        Active->TemplateArgs,1026                                                        Active->NumTemplateArgs)1027                     << Active->InstantiationRange);1028      }1029      break;1030    }1031 1032    case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {1033      ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);1034      FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());1035 1036      SmallString<128> TemplateArgsStr;1037      llvm::raw_svector_ostream OS(TemplateArgsStr);1038      FD->printName(OS, getPrintingPolicy());1039      printTemplateArgumentList(OS, Active->template_arguments(),1040                                getPrintingPolicy());1041      DiagFunc(Active->PointOfInstantiation,1042               PDiag(diag::note_default_function_arg_instantiation_here)1043                   << OS.str() << Active->InstantiationRange);1044      break;1045    }1046 1047    case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {1048      NamedDecl *Parm = cast<NamedDecl>(Active->Entity);1049      std::string Name;1050      if (!Parm->getName().empty())1051        Name = std::string(" '") + Parm->getName().str() + "'";1052 1053      TemplateParameterList *TemplateParams = nullptr;1054      if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))1055        TemplateParams = Template->getTemplateParameters();1056      else1057        TemplateParams =1058          cast<ClassTemplatePartialSpecializationDecl>(Active->Template)1059                                                      ->getTemplateParameters();1060      DiagFunc(Active->PointOfInstantiation,1061               PDiag(diag::note_prior_template_arg_substitution)1062                   << isa<TemplateTemplateParmDecl>(Parm) << Name1063                   << getTemplateArgumentBindingsText(TemplateParams,1064                                                      Active->TemplateArgs,1065                                                      Active->NumTemplateArgs)1066                   << Active->InstantiationRange);1067      break;1068    }1069 1070    case CodeSynthesisContext::DefaultTemplateArgumentChecking: {1071      TemplateParameterList *TemplateParams = nullptr;1072      if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))1073        TemplateParams = Template->getTemplateParameters();1074      else1075        TemplateParams =1076          cast<ClassTemplatePartialSpecializationDecl>(Active->Template)1077                                                      ->getTemplateParameters();1078 1079      DiagFunc(Active->PointOfInstantiation,1080               PDiag(diag::note_template_default_arg_checking)1081                   << getTemplateArgumentBindingsText(TemplateParams,1082                                                      Active->TemplateArgs,1083                                                      Active->NumTemplateArgs)1084                   << Active->InstantiationRange);1085      break;1086    }1087 1088    case CodeSynthesisContext::ExceptionSpecEvaluation:1089      DiagFunc(Active->PointOfInstantiation,1090               PDiag(diag::note_evaluating_exception_spec_here)1091                   << cast<FunctionDecl>(Active->Entity));1092      break;1093 1094    case CodeSynthesisContext::ExceptionSpecInstantiation:1095      DiagFunc(Active->PointOfInstantiation,1096               PDiag(diag::note_template_exception_spec_instantiation_here)1097                   << cast<FunctionDecl>(Active->Entity)1098                   << Active->InstantiationRange);1099      break;1100 1101    case CodeSynthesisContext::RequirementInstantiation:1102      DiagFunc(Active->PointOfInstantiation,1103               PDiag(diag::note_template_requirement_instantiation_here)1104                   << Active->InstantiationRange);1105      break;1106    case CodeSynthesisContext::RequirementParameterInstantiation:1107      DiagFunc(Active->PointOfInstantiation,1108               PDiag(diag::note_template_requirement_params_instantiation_here)1109                   << Active->InstantiationRange);1110      break;1111 1112    case CodeSynthesisContext::NestedRequirementConstraintsCheck:1113      DiagFunc(Active->PointOfInstantiation,1114               PDiag(diag::note_nested_requirement_here)1115                   << Active->InstantiationRange);1116      break;1117 1118    case CodeSynthesisContext::DeclaringSpecialMember:1119      DiagFunc(Active->PointOfInstantiation,1120               PDiag(diag::note_in_declaration_of_implicit_special_member)1121                   << cast<CXXRecordDecl>(Active->Entity)1122                   << Active->SpecialMember);1123      break;1124 1125    case CodeSynthesisContext::DeclaringImplicitEqualityComparison:1126      DiagFunc(1127          Active->Entity->getLocation(),1128          PDiag(diag::note_in_declaration_of_implicit_equality_comparison));1129      break;1130 1131    case CodeSynthesisContext::DefiningSynthesizedFunction: {1132      // FIXME: For synthesized functions that are not defaulted,1133      // produce a note.1134      auto *FD = dyn_cast<FunctionDecl>(Active->Entity);1135      // Note: if FD is nullptr currently setting DFK to DefaultedFunctionKind()1136      // will ensure that DFK.isComparison() is false. This is important because1137      // we will uncondtionally dereference FD in the else if.1138      DefaultedFunctionKind DFK =1139          FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind();1140      if (DFK.isSpecialMember()) {1141        auto *MD = cast<CXXMethodDecl>(FD);1142        DiagFunc(Active->PointOfInstantiation,1143                 PDiag(diag::note_member_synthesized_at)1144                     << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()1145                     << Context.getCanonicalTagType(MD->getParent()));1146      } else if (DFK.isComparison()) {1147        QualType RecordType = FD->getParamDecl(0)1148                                  ->getType()1149                                  .getNonReferenceType()1150                                  .getUnqualifiedType();1151        DiagFunc(Active->PointOfInstantiation,1152                 PDiag(diag::note_comparison_synthesized_at)1153                     << (int)DFK.asComparison() << RecordType);1154      }1155      break;1156    }1157 1158    case CodeSynthesisContext::RewritingOperatorAsSpaceship:1159      DiagFunc(Active->Entity->getLocation(),1160               PDiag(diag::note_rewriting_operator_as_spaceship));1161      break;1162 1163    case CodeSynthesisContext::InitializingStructuredBinding:1164      DiagFunc(Active->PointOfInstantiation,1165               PDiag(diag::note_in_binding_decl_init)1166                   << cast<BindingDecl>(Active->Entity));1167      break;1168 1169    case CodeSynthesisContext::MarkingClassDllexported:1170      DiagFunc(Active->PointOfInstantiation,1171               PDiag(diag::note_due_to_dllexported_class)1172                   << cast<CXXRecordDecl>(Active->Entity)1173                   << !getLangOpts().CPlusPlus11);1174      break;1175 1176    case CodeSynthesisContext::BuildingBuiltinDumpStructCall:1177      DiagFunc(Active->PointOfInstantiation,1178               PDiag(diag::note_building_builtin_dump_struct_call)1179                   << convertCallArgsToString(1180                          *this, llvm::ArrayRef(Active->CallArgs,1181                                                Active->NumCallArgs)));1182      break;1183 1184    case CodeSynthesisContext::Memoization:1185      break;1186 1187    case CodeSynthesisContext::LambdaExpressionSubstitution:1188      DiagFunc(Active->PointOfInstantiation,1189               PDiag(diag::note_lambda_substitution_here));1190      break;1191    case CodeSynthesisContext::ConstraintsCheck: {1192      unsigned DiagID = 0;1193      if (!Active->Entity) {1194        DiagFunc(Active->PointOfInstantiation,1195                 PDiag(diag::note_nested_requirement_here)1196                     << Active->InstantiationRange);1197        break;1198      }1199      if (isa<ConceptDecl>(Active->Entity))1200        DiagID = diag::note_concept_specialization_here;1201      else if (isa<TemplateDecl>(Active->Entity))1202        DiagID = diag::note_checking_constraints_for_template_id_here;1203      else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))1204        DiagID = diag::note_checking_constraints_for_var_spec_id_here;1205      else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))1206        DiagID = diag::note_checking_constraints_for_class_spec_id_here;1207      else {1208        assert(isa<FunctionDecl>(Active->Entity));1209        DiagID = diag::note_checking_constraints_for_function_here;1210      }1211      SmallString<128> TemplateArgsStr;1212      llvm::raw_svector_ostream OS(TemplateArgsStr);1213      cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());1214      if (!isa<FunctionDecl>(Active->Entity)) {1215        printTemplateArgumentList(OS, Active->template_arguments(),1216                                  getPrintingPolicy());1217      }1218      DiagFunc(Active->PointOfInstantiation,1219               PDiag(DiagID) << OS.str() << Active->InstantiationRange);1220      break;1221    }1222    case CodeSynthesisContext::ConstraintSubstitution:1223      DiagFunc(Active->PointOfInstantiation,1224               PDiag(diag::note_constraint_substitution_here)1225                   << Active->InstantiationRange);1226      break;1227    case CodeSynthesisContext::ConstraintNormalization:1228      DiagFunc(Active->PointOfInstantiation,1229               PDiag(diag::note_constraint_normalization_here)1230                   << cast<NamedDecl>(Active->Entity)1231                   << Active->InstantiationRange);1232      break;1233    case CodeSynthesisContext::ParameterMappingSubstitution:1234      DiagFunc(Active->PointOfInstantiation,1235               PDiag(diag::note_parameter_mapping_substitution_here)1236                   << Active->InstantiationRange);1237      break;1238    case CodeSynthesisContext::BuildingDeductionGuides:1239      DiagFunc(Active->PointOfInstantiation,1240               PDiag(diag::note_building_deduction_guide_here));1241      break;1242    case CodeSynthesisContext::TypeAliasTemplateInstantiation:1243      // Workaround for a workaround: don't produce a note if we are merely1244      // instantiating some other template which contains this alias template.1245      // This would be redundant either with the error itself, or some other1246      // context note attached to it.1247      if (Active->NumTemplateArgs == 0)1248        break;1249      DiagFunc(Active->PointOfInstantiation,1250               PDiag(diag::note_template_type_alias_instantiation_here)1251                   << cast<TypeAliasTemplateDecl>(Active->Entity)1252                   << Active->InstantiationRange);1253      break;1254    case CodeSynthesisContext::PartialOrderingTTP:1255      DiagFunc(Active->PointOfInstantiation,1256               PDiag(diag::note_template_arg_template_params_mismatch));1257      if (SourceLocation ParamLoc = Active->Entity->getLocation();1258          ParamLoc.isValid())1259        DiagFunc(ParamLoc, PDiag(diag::note_template_prev_declaration)1260                               << /*isTemplateTemplateParam=*/true1261                               << Active->InstantiationRange);1262      break;1263    }1264  }1265}1266 1267//===----------------------------------------------------------------------===/1268// Template Instantiation for Types1269//===----------------------------------------------------------------------===/1270namespace {1271 1272  class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {1273    const MultiLevelTemplateArgumentList &TemplateArgs;1274    SourceLocation Loc;1275    DeclarationName Entity;1276    // Whether to evaluate the C++20 constraints or simply substitute into them.1277    bool EvaluateConstraints = true;1278    // Whether Substitution was Incomplete, that is, we tried to substitute in1279    // any user provided template arguments which were null.1280    bool IsIncomplete = false;1281    // Whether an incomplete substituion should be treated as an error.1282    bool BailOutOnIncomplete;1283 1284    // Whether to rebuild pack expansion types; We don't do that when1285    // rebuilding the parameter mapping of a fold expression appearing1286    // in a constraint expression.1287    bool BuildPackExpansionTypes = true;1288 1289    // CWG2770: Function parameters should be instantiated when they are1290    // needed by a satisfaction check of an atomic constraint or1291    // (recursively) by another function parameter.1292    bool maybeInstantiateFunctionParameterToScope(ParmVarDecl *OldParm);1293 1294  public:1295    typedef TreeTransform<TemplateInstantiator> inherited;1296 1297    TemplateInstantiator(Sema &SemaRef,1298                         const MultiLevelTemplateArgumentList &TemplateArgs,1299                         SourceLocation Loc, DeclarationName Entity,1300                         bool BailOutOnIncomplete = false)1301        : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),1302          Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {}1303 1304    void setEvaluateConstraints(bool B) {1305      EvaluateConstraints = B;1306    }1307    bool getEvaluateConstraints() {1308      return EvaluateConstraints;1309    }1310 1311    inline static struct ForParameterMappingSubstitution_t {1312    } ForParameterMappingSubstitution;1313 1314    TemplateInstantiator(ForParameterMappingSubstitution_t, Sema &SemaRef,1315                         SourceLocation Loc,1316                         const MultiLevelTemplateArgumentList &TemplateArgs,1317                         bool BuildPackExpansionTypes)1318        : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),1319          BailOutOnIncomplete(false),1320          BuildPackExpansionTypes(BuildPackExpansionTypes) {}1321 1322    /// Determine whether the given type \p T has already been1323    /// transformed.1324    ///1325    /// For the purposes of template instantiation, a type has already been1326    /// transformed if it is NULL or if it is not dependent.1327    bool AlreadyTransformed(QualType T);1328 1329    /// Returns the location of the entity being instantiated, if known.1330    SourceLocation getBaseLocation() { return Loc; }1331 1332    /// Returns the name of the entity being instantiated, if any.1333    DeclarationName getBaseEntity() { return Entity; }1334 1335    /// Returns whether any substitution so far was incomplete.1336    bool getIsIncomplete() const { return IsIncomplete; }1337 1338    /// Sets the "base" location and entity when that1339    /// information is known based on another transformation.1340    void setBase(SourceLocation Loc, DeclarationName Entity) {1341      this->Loc = Loc;1342      this->Entity = Entity;1343    }1344 1345    unsigned TransformTemplateDepth(unsigned Depth) {1346      return TemplateArgs.getNewDepth(Depth);1347    }1348 1349    bool TryExpandParameterPacks(SourceLocation EllipsisLoc,1350                                 SourceRange PatternRange,1351                                 ArrayRef<UnexpandedParameterPack> Unexpanded,1352                                 bool FailOnPackProducingTemplates,1353                                 bool &ShouldExpand, bool &RetainExpansion,1354                                 UnsignedOrNone &NumExpansions) {1355      if (SemaRef.CurrentInstantiationScope &&1356          (SemaRef.inConstraintSubstitution() ||1357           SemaRef.inParameterMappingSubstitution())) {1358        for (UnexpandedParameterPack ParmPack : Unexpanded) {1359          NamedDecl *VD = ParmPack.first.dyn_cast<NamedDecl *>();1360          if (auto *PVD = dyn_cast_if_present<ParmVarDecl>(VD);1361              PVD && maybeInstantiateFunctionParameterToScope(PVD))1362            return true;1363        }1364      }1365 1366      return getSema().CheckParameterPacksForExpansion(1367          EllipsisLoc, PatternRange, Unexpanded, TemplateArgs,1368          FailOnPackProducingTemplates, ShouldExpand, RetainExpansion,1369          NumExpansions);1370    }1371 1372    void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {1373      SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);1374    }1375 1376    TemplateArgument ForgetPartiallySubstitutedPack() {1377      TemplateArgument Result;1378      if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope1379                                       ->getPartiallySubstitutedPack()) {1380        MultiLevelTemplateArgumentList &TemplateArgs =1381            const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);1382        unsigned Depth, Index;1383        std::tie(Depth, Index) = getDepthAndIndex(PartialPack);1384        if (TemplateArgs.hasTemplateArgument(Depth, Index)) {1385          Result = TemplateArgs(Depth, Index);1386          TemplateArgs.setArgument(Depth, Index, TemplateArgument());1387        } else {1388          IsIncomplete = true;1389          if (BailOutOnIncomplete)1390            return TemplateArgument();1391        }1392      }1393 1394      return Result;1395    }1396 1397    void RememberPartiallySubstitutedPack(TemplateArgument Arg) {1398      if (Arg.isNull())1399        return;1400 1401      if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope1402                                       ->getPartiallySubstitutedPack()) {1403        MultiLevelTemplateArgumentList &TemplateArgs =1404            const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);1405        unsigned Depth, Index;1406        std::tie(Depth, Index) = getDepthAndIndex(PartialPack);1407        TemplateArgs.setArgument(Depth, Index, Arg);1408      }1409    }1410 1411    MultiLevelTemplateArgumentList ForgetSubstitution() {1412      MultiLevelTemplateArgumentList New;1413      New.addOuterRetainedLevels(this->TemplateArgs.getNumLevels());1414 1415      MultiLevelTemplateArgumentList Old =1416          const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);1417      const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =1418          std::move(New);1419      return Old;1420    }1421 1422    void RememberSubstitution(MultiLevelTemplateArgumentList Old) {1423      const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) = Old;1424    }1425 1426    TemplateArgument1427    getTemplateArgumentPackPatternForRewrite(const TemplateArgument &TA) {1428      if (TA.getKind() != TemplateArgument::Pack)1429        return TA;1430      if (SemaRef.ArgPackSubstIndex)1431        return SemaRef.getPackSubstitutedTemplateArgument(TA);1432      assert(TA.pack_size() == 1 && TA.pack_begin()->isPackExpansion() &&1433             "unexpected pack arguments in template rewrite");1434      TemplateArgument Arg = *TA.pack_begin();1435      if (Arg.isPackExpansion())1436        Arg = Arg.getPackExpansionPattern();1437      return Arg;1438    }1439 1440    /// Transform the given declaration by instantiating a reference to1441    /// this declaration.1442    Decl *TransformDecl(SourceLocation Loc, Decl *D);1443 1444    void transformAttrs(Decl *Old, Decl *New) {1445      SemaRef.InstantiateAttrs(TemplateArgs, Old, New);1446    }1447 1448    void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {1449      if (Old->isParameterPack() &&1450          (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {1451        SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);1452        for (auto *New : NewDecls)1453          SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(1454              Old, cast<VarDecl>(New));1455        return;1456      }1457 1458      assert(NewDecls.size() == 1 &&1459             "should only have multiple expansions for a pack");1460      Decl *New = NewDecls.front();1461 1462      // If we've instantiated the call operator of a lambda or the call1463      // operator template of a generic lambda, update the "instantiation of"1464      // information.1465      auto *NewMD = dyn_cast<CXXMethodDecl>(New);1466      if (NewMD && isLambdaCallOperator(NewMD)) {1467        auto *OldMD = dyn_cast<CXXMethodDecl>(Old);1468        if (auto *NewTD = NewMD->getDescribedFunctionTemplate())1469          NewTD->setInstantiatedFromMemberTemplate(1470              OldMD->getDescribedFunctionTemplate());1471        else1472          NewMD->setInstantiationOfMemberFunction(OldMD,1473                                                  TSK_ImplicitInstantiation);1474      }1475 1476      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);1477 1478      // We recreated a local declaration, but not by instantiating it. There1479      // may be pending dependent diagnostics to produce.1480      if (auto *DC = dyn_cast<DeclContext>(Old);1481          DC && DC->isDependentContext() && DC->isFunctionOrMethod())1482        SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);1483    }1484 1485    /// Transform the definition of the given declaration by1486    /// instantiating it.1487    Decl *TransformDefinition(SourceLocation Loc, Decl *D);1488 1489    /// Transform the first qualifier within a scope by instantiating the1490    /// declaration.1491    NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);1492 1493    bool TransformExceptionSpec(SourceLocation Loc,1494                                FunctionProtoType::ExceptionSpecInfo &ESI,1495                                SmallVectorImpl<QualType> &Exceptions,1496                                bool &Changed);1497 1498    /// Rebuild the exception declaration and register the declaration1499    /// as an instantiated local.1500    VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,1501                                  TypeSourceInfo *Declarator,1502                                  SourceLocation StartLoc,1503                                  SourceLocation NameLoc,1504                                  IdentifierInfo *Name);1505 1506    /// Rebuild the Objective-C exception declaration and register the1507    /// declaration as an instantiated local.1508    VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,1509                                      TypeSourceInfo *TSInfo, QualType T);1510 1511    TemplateName1512    TransformTemplateName(NestedNameSpecifierLoc &QualifierLoc,1513                          SourceLocation TemplateKWLoc, TemplateName Name,1514                          SourceLocation NameLoc,1515                          QualType ObjectType = QualType(),1516                          NamedDecl *FirstQualifierInScope = nullptr,1517                          bool AllowInjectedClassName = false);1518 1519    const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);1520    const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);1521    const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);1522    const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,1523                                                  const Stmt *InstS,1524                                                  const NoInlineAttr *A);1525    const AlwaysInlineAttr *1526    TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,1527                                  const AlwaysInlineAttr *A);1528    const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);1529    const OpenACCRoutineDeclAttr *1530    TransformOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A);1531    ExprResult TransformPredefinedExpr(PredefinedExpr *E);1532    ExprResult TransformDeclRefExpr(DeclRefExpr *E);1533    ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);1534 1535    ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,1536                                            NonTypeTemplateParmDecl *D);1537 1538    /// Rebuild a DeclRefExpr for a VarDecl reference.1539    ExprResult RebuildVarDeclRefExpr(ValueDecl *PD, SourceLocation Loc);1540 1541    /// Transform a reference to a function or init-capture parameter pack.1542    ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, ValueDecl *PD);1543 1544    /// Transform a FunctionParmPackExpr which was built when we couldn't1545    /// expand a function parameter pack reference which refers to an expanded1546    /// pack.1547    ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);1548 1549    QualType TransformFunctionProtoType(TypeLocBuilder &TLB,1550                                        FunctionProtoTypeLoc TL) {1551      // Call the base version; it will forward to our overridden version below.1552      return inherited::TransformFunctionProtoType(TLB, TL);1553    }1554 1555    QualType TransformTagType(TypeLocBuilder &TLB, TagTypeLoc TL) {1556      auto Type = inherited::TransformTagType(TLB, TL);1557      if (!Type.isNull())1558        return Type;1559      // Special case for transforming a deduction guide, we return a1560      // transformed TemplateSpecializationType.1561      // FIXME: Why is this hack necessary?1562      if (const auto *ICNT = dyn_cast<InjectedClassNameType>(TL.getTypePtr());1563          ICNT && SemaRef.CodeSynthesisContexts.back().Kind ==1564                      Sema::CodeSynthesisContext::BuildingDeductionGuides) {1565        Type = inherited::TransformType(1566            ICNT->getDecl()->getCanonicalTemplateSpecializationType(1567                SemaRef.Context));1568        TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());1569      }1570      return Type;1571    }1572    // Override the default version to handle a rewrite-template-arg-pack case1573    // for building a deduction guide.1574    bool TransformTemplateArgument(const TemplateArgumentLoc &Input,1575                                   TemplateArgumentLoc &Output,1576                                   bool Uneval = false) {1577      const TemplateArgument &Arg = Input.getArgument();1578      std::vector<TemplateArgument> TArgs;1579      switch (Arg.getKind()) {1580      case TemplateArgument::Pack:1581        assert(SemaRef.CodeSynthesisContexts.empty() ||1582               SemaRef.CodeSynthesisContexts.back().Kind ==1583                   Sema::CodeSynthesisContext::BuildingDeductionGuides);1584        // Literally rewrite the template argument pack, instead of unpacking1585        // it.1586        for (auto &pack : Arg.getPackAsArray()) {1587          TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(1588              pack, QualType(), SourceLocation{});1589          TemplateArgumentLoc Output;1590          if (TransformTemplateArgument(Input, Output, Uneval))1591            return true; // fails1592          TArgs.push_back(Output.getArgument());1593        }1594        Output = SemaRef.getTrivialTemplateArgumentLoc(1595            TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),1596            QualType(), SourceLocation{});1597        return false;1598      default:1599        break;1600      }1601      return inherited::TransformTemplateArgument(Input, Output, Uneval);1602    }1603 1604    // This has to be here to allow its overload.1605    ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,1606                                    UnsignedOrNone NumExpansions) {1607      return inherited::RebuildPackExpansion(Pattern, EllipsisLoc,1608                                             NumExpansions);1609    }1610 1611    TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,1612                                             SourceLocation EllipsisLoc,1613                                             UnsignedOrNone NumExpansions) {1614      // We don't rewrite a PackExpansion type when we want to normalize a1615      // CXXFoldExpr constraint. We'll expand it when evaluating the constraint.1616      if (BuildPackExpansionTypes)1617        return inherited::RebuildPackExpansion(Pattern, EllipsisLoc,1618                                               NumExpansions);1619      return Pattern;1620    }1621 1622    using TreeTransform::TransformTemplateSpecializationType;1623    QualType1624    TransformTemplateSpecializationType(TypeLocBuilder &TLB,1625                                        TemplateSpecializationTypeLoc TL) {1626      auto *T = TL.getTypePtr();1627      if (!getSema().ArgPackSubstIndex || !T->isSugared() ||1628          !isPackProducingBuiltinTemplateName(T->getTemplateName()))1629        return TreeTransform::TransformTemplateSpecializationType(TLB, TL);1630      // Look through sugar to get to the SubstBuiltinTemplatePackType that we1631      // need to substitute into.1632 1633      // `TransformType` code below will handle picking the element from a pack1634      // with the index `ArgPackSubstIndex`.1635      // FIXME: add ability to represent sugarred type for N-th element of a1636      // builtin pack and produce the sugar here.1637      QualType R = TransformType(T->desugar());1638      TLB.pushTrivial(getSema().getASTContext(), R, TL.getBeginLoc());1639      return R;1640    }1641 1642    UnsignedOrNone ComputeSizeOfPackExprWithoutSubstitution(1643        ArrayRef<TemplateArgument> PackArgs) {1644      // Don't do this when rewriting template parameters for CTAD:1645      //   1) The heuristic needs the unpacked Subst* nodes to figure out the1646      //   expanded size, but this never applies since Subst* nodes are not1647      //   created in rewrite scenarios.1648      //1649      //   2) The heuristic substitutes into the pattern with pack expansion1650      //   suppressed, which does not meet the requirements for argument1651      //   rewriting when template arguments include a non-pack matching against1652      //   a pack, particularly when rewriting an alias CTAD.1653      if (TemplateArgs.isRewrite())1654        return std::nullopt;1655 1656      return inherited::ComputeSizeOfPackExprWithoutSubstitution(PackArgs);1657    }1658 1659    template<typename Fn>1660    QualType TransformFunctionProtoType(TypeLocBuilder &TLB,1661                                        FunctionProtoTypeLoc TL,1662                                        CXXRecordDecl *ThisContext,1663                                        Qualifiers ThisTypeQuals,1664                                        Fn TransformExceptionSpec);1665 1666    ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,1667                                            int indexAdjustment,1668                                            UnsignedOrNone NumExpansions,1669                                            bool ExpectParameterPack);1670 1671    using inherited::TransformTemplateTypeParmType;1672    /// Transforms a template type parameter type by performing1673    /// substitution of the corresponding template type argument.1674    QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,1675                                           TemplateTypeParmTypeLoc TL,1676                                           bool SuppressObjCLifetime);1677 1678    QualType BuildSubstTemplateTypeParmType(1679        TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,1680        Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,1681        TemplateArgument Arg, SourceLocation NameLoc);1682 1683    /// Transforms an already-substituted template type parameter pack1684    /// into either itself (if we aren't substituting into its pack expansion)1685    /// or the appropriate substituted argument.1686    using inherited::TransformSubstTemplateTypeParmPackType;1687    QualType1688    TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,1689                                           SubstTemplateTypeParmPackTypeLoc TL,1690                                           bool SuppressObjCLifetime);1691    QualType1692    TransformSubstBuiltinTemplatePackType(TypeLocBuilder &TLB,1693                                          SubstBuiltinTemplatePackTypeLoc TL);1694 1695    CXXRecordDecl::LambdaDependencyKind1696    ComputeLambdaDependency(LambdaScopeInfo *LSI) {1697      if (auto TypeAlias =1698              TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(1699                  getSema());1700          TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(1701                           LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {1702        unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();1703        if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())1704          return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;1705        for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)1706          if (TA.isDependent())1707            return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;1708      }1709      return inherited::ComputeLambdaDependency(LSI);1710    }1711 1712    ExprResult TransformLambdaExpr(LambdaExpr *E) {1713      // Do not rebuild lambdas to avoid creating a new type.1714      // Lambdas have already been processed inside their eval contexts.1715      if (SemaRef.RebuildingImmediateInvocation)1716        return E;1717      LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,1718                                    /*InstantiatingLambdaOrBlock=*/true);1719      Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this);1720 1721      return inherited::TransformLambdaExpr(E);1722    }1723 1724    ExprResult TransformBlockExpr(BlockExpr *E) {1725      LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,1726                                    /*InstantiatingLambdaOrBlock=*/true);1727      return inherited::TransformBlockExpr(E);1728    }1729 1730    ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,1731                                 LambdaScopeInfo *LSI) {1732      CXXMethodDecl *MD = LSI->CallOperator;1733      for (ParmVarDecl *PVD : MD->parameters()) {1734        assert(PVD && "null in a parameter list");1735        if (!PVD->hasDefaultArg())1736          continue;1737        Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();1738        // FIXME: Obtain the source location for the '=' token.1739        SourceLocation EqualLoc = UninstExpr->getBeginLoc();1740        if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {1741          // If substitution fails, the default argument is set to a1742          // RecoveryExpr that wraps the uninstantiated default argument so1743          // that downstream diagnostics are omitted.1744          ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(1745              UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr},1746              UninstExpr->getType());1747          if (ErrorResult.isUsable())1748            PVD->setDefaultArg(ErrorResult.get());1749        }1750      }1751      return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);1752    }1753 1754    StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {1755      // Currently, we instantiate the body when instantiating the lambda1756      // expression. However, `EvaluateConstraints` is disabled during the1757      // instantiation of the lambda expression, causing the instantiation1758      // failure of the return type requirement in the body. If p0588r1 is fully1759      // implemented, the body will be lazily instantiated, and this problem1760      // will not occur. Here, `EvaluateConstraints` is temporarily set to1761      // `true` to temporarily fix this issue.1762      // FIXME: This temporary fix can be removed after fully implementing1763      // p0588r1.1764      llvm::SaveAndRestore _(EvaluateConstraints, true);1765      return inherited::TransformLambdaBody(E, Body);1766    }1767 1768    ExprResult TransformRequiresExpr(RequiresExpr *E) {1769      LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);1770      ExprResult TransReq = inherited::TransformRequiresExpr(E);1771      if (TransReq.isInvalid())1772        return TransReq;1773      assert(TransReq.get() != E &&1774             "Do not change value of isSatisfied for the existing expression. "1775             "Create a new expression instead.");1776      if (E->getBody()->isDependentContext()) {1777        Sema::SFINAETrap Trap(SemaRef);1778        // We recreate the RequiresExpr body, but not by instantiating it.1779        // Produce pending diagnostics for dependent access check.1780        SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);1781        // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.1782        if (Trap.hasErrorOccurred())1783          TransReq.getAs<RequiresExpr>()->setSatisfied(false);1784      }1785      return TransReq;1786    }1787 1788    bool TransformRequiresExprRequirements(1789        ArrayRef<concepts::Requirement *> Reqs,1790        SmallVectorImpl<concepts::Requirement *> &Transformed) {1791      bool SatisfactionDetermined = false;1792      for (concepts::Requirement *Req : Reqs) {1793        concepts::Requirement *TransReq = nullptr;1794        if (!SatisfactionDetermined) {1795          if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))1796            TransReq = TransformTypeRequirement(TypeReq);1797          else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))1798            TransReq = TransformExprRequirement(ExprReq);1799          else1800            TransReq = TransformNestedRequirement(1801                cast<concepts::NestedRequirement>(Req));1802          if (!TransReq)1803            return true;1804          if (!TransReq->isDependent() && !TransReq->isSatisfied())1805            // [expr.prim.req]p61806            //   [...]  The substitution and semantic constraint checking1807            //   proceeds in lexical order and stops when a condition that1808            //   determines the result of the requires-expression is1809            //   encountered. [..]1810            SatisfactionDetermined = true;1811        } else1812          TransReq = Req;1813        Transformed.push_back(TransReq);1814      }1815      return false;1816    }1817 1818    TemplateParameterList *TransformTemplateParameterList(1819                              TemplateParameterList *OrigTPL)  {1820      if (!OrigTPL || !OrigTPL->size()) return OrigTPL;1821 1822      DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();1823      TemplateDeclInstantiator  DeclInstantiator(getSema(),1824                        /* DeclContext *Owner */ Owner, TemplateArgs);1825      DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);1826      return DeclInstantiator.SubstTemplateParams(OrigTPL);1827    }1828 1829    concepts::TypeRequirement *1830    TransformTypeRequirement(concepts::TypeRequirement *Req);1831    concepts::ExprRequirement *1832    TransformExprRequirement(concepts::ExprRequirement *Req);1833    concepts::NestedRequirement *1834    TransformNestedRequirement(concepts::NestedRequirement *Req);1835    ExprResult TransformRequiresTypeParams(1836        SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,1837        RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,1838        SmallVectorImpl<QualType> &PTypes,1839        SmallVectorImpl<ParmVarDecl *> &TransParams,1840        Sema::ExtParameterInfoBuilder &PInfos);1841  };1842}1843 1844bool TemplateInstantiator::AlreadyTransformed(QualType T) {1845  if (T.isNull())1846    return true;1847 1848  if (T->isInstantiationDependentType() || T->isVariablyModifiedType() ||1849      T->containsUnexpandedParameterPack())1850    return false;1851 1852  getSema().MarkDeclarationsReferencedInType(Loc, T);1853  return true;1854}1855 1856Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {1857  if (!D)1858    return nullptr;1859 1860  if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {1861    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {1862      // If the corresponding template argument is NULL or non-existent, it's1863      // because we are performing instantiation from explicitly-specified1864      // template arguments in a function template, but there were some1865      // arguments left unspecified.1866      if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),1867                                            TTP->getPosition())) {1868        IsIncomplete = true;1869        return BailOutOnIncomplete ? nullptr : D;1870      }1871 1872      TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());1873 1874      if (TTP->isParameterPack()) {1875        assert(Arg.getKind() == TemplateArgument::Pack &&1876               "Missing argument pack");1877        Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);1878      }1879 1880      TemplateName Template = Arg.getAsTemplate();1881      assert(!Template.isNull() && Template.getAsTemplateDecl() &&1882             "Wrong kind of template template argument");1883      return Template.getAsTemplateDecl();1884    }1885 1886    // Fall through to find the instantiated declaration for this template1887    // template parameter.1888  }1889 1890  if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D);1891      PVD && SemaRef.CurrentInstantiationScope &&1892      (SemaRef.inConstraintSubstitution() ||1893       SemaRef.inParameterMappingSubstitution()) &&1894      maybeInstantiateFunctionParameterToScope(PVD))1895    return nullptr;1896 1897  return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);1898}1899 1900bool TemplateInstantiator::maybeInstantiateFunctionParameterToScope(1901    ParmVarDecl *OldParm) {1902  if (SemaRef.CurrentInstantiationScope->getInstantiationOfIfExists(OldParm))1903    return false;1904 1905  if (!OldParm->isParameterPack())1906    return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,1907                                       /*NumExpansions=*/std::nullopt,1908                                       /*ExpectParameterPack=*/false);1909 1910  SmallVector<UnexpandedParameterPack, 2> Unexpanded;1911 1912  // Find the parameter packs that could be expanded.1913  TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();1914  PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();1915  TypeLoc Pattern = ExpansionTL.getPatternLoc();1916  SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);1917  assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");1918 1919  bool ShouldExpand = false;1920  bool RetainExpansion = false;1921  UnsignedOrNone OrigNumExpansions =1922      ExpansionTL.getTypePtr()->getNumExpansions();1923  UnsignedOrNone NumExpansions = OrigNumExpansions;1924  if (TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),1925                              Pattern.getSourceRange(), Unexpanded,1926                              /*FailOnPackProducingTemplates=*/true,1927                              ShouldExpand, RetainExpansion, NumExpansions))1928    return true;1929 1930  assert(ShouldExpand && !RetainExpansion &&1931         "Shouldn't preserve pack expansion when evaluating constraints");1932  ExpandingFunctionParameterPack(OldParm);1933  for (unsigned I = 0; I != *NumExpansions; ++I) {1934    Sema::ArgPackSubstIndexRAII SubstIndex(getSema(), I);1935    if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,1936                                    /*NumExpansions=*/OrigNumExpansions,1937                                    /*ExpectParameterPack=*/false))1938      return true;1939  }1940  return false;1941}1942 1943Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {1944  Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);1945  if (!Inst)1946    return nullptr;1947 1948  getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);1949  return Inst;1950}1951 1952bool TemplateInstantiator::TransformExceptionSpec(1953    SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,1954    SmallVectorImpl<QualType> &Exceptions, bool &Changed) {1955  if (ESI.Type == EST_Uninstantiated) {1956    ESI.instantiate();1957    Changed = true;1958  }1959  return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);1960}1961 1962NamedDecl *1963TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,1964                                                     SourceLocation Loc) {1965  // If the first part of the nested-name-specifier was a template type1966  // parameter, instantiate that type parameter down to a tag type.1967  if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {1968    const TemplateTypeParmType *TTP1969      = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));1970 1971    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {1972      // FIXME: This needs testing w/ member access expressions.1973      TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());1974 1975      if (TTP->isParameterPack()) {1976        assert(Arg.getKind() == TemplateArgument::Pack &&1977               "Missing argument pack");1978 1979        if (!getSema().ArgPackSubstIndex)1980          return nullptr;1981 1982        Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);1983      }1984 1985      QualType T = Arg.getAsType();1986      if (T.isNull())1987        return cast_or_null<NamedDecl>(TransformDecl(Loc, D));1988 1989      if (const TagType *Tag = T->getAs<TagType>())1990        return Tag->getDecl();1991 1992      // The resulting type is not a tag; complain.1993      getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;1994      return nullptr;1995    }1996  }1997 1998  return cast_or_null<NamedDecl>(TransformDecl(Loc, D));1999}2000 2001VarDecl *2002TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,2003                                           TypeSourceInfo *Declarator,2004                                           SourceLocation StartLoc,2005                                           SourceLocation NameLoc,2006                                           IdentifierInfo *Name) {2007  VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,2008                                                 StartLoc, NameLoc, Name);2009  if (Var)2010    getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);2011  return Var;2012}2013 2014VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,2015                                                        TypeSourceInfo *TSInfo,2016                                                        QualType T) {2017  VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);2018  if (Var)2019    getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);2020  return Var;2021}2022 2023TemplateName TemplateInstantiator::TransformTemplateName(2024    NestedNameSpecifierLoc &QualifierLoc, SourceLocation TemplateKWLoc,2025    TemplateName Name, SourceLocation NameLoc, QualType ObjectType,2026    NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName) {2027  if (Name.getKind() == TemplateName::Template) {2028    assert(!QualifierLoc && "Unexpected qualifier");2029    if (auto *TTP =2030            dyn_cast<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());2031        TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) {2032      // If the corresponding template argument is NULL or non-existent, it's2033      // because we are performing instantiation from explicitly-specified2034      // template arguments in a function template, but there were some2035      // arguments left unspecified.2036      if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),2037                                            TTP->getPosition())) {2038        IsIncomplete = true;2039        return BailOutOnIncomplete ? TemplateName() : Name;2040      }2041 2042      TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());2043 2044      if (TemplateArgs.isRewrite()) {2045        // We're rewriting the template parameter as a reference to another2046        // template parameter.2047        Arg = getTemplateArgumentPackPatternForRewrite(Arg);2048        assert(Arg.getKind() == TemplateArgument::Template &&2049               "unexpected nontype template argument kind in template rewrite");2050        return Arg.getAsTemplate();2051      }2052 2053      auto [AssociatedDecl, Final] =2054          TemplateArgs.getAssociatedDecl(TTP->getDepth());2055      UnsignedOrNone PackIndex = std::nullopt;2056      if (TTP->isParameterPack()) {2057        assert(Arg.getKind() == TemplateArgument::Pack &&2058               "Missing argument pack");2059 2060        if (!getSema().ArgPackSubstIndex) {2061          // We have the template argument pack to substitute, but we're not2062          // actually expanding the enclosing pack expansion yet. So, just2063          // keep the entire argument pack.2064          return getSema().Context.getSubstTemplateTemplateParmPack(2065              Arg, AssociatedDecl, TTP->getIndex(), Final);2066        }2067 2068        PackIndex = SemaRef.getPackIndex(Arg);2069        Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);2070      }2071 2072      TemplateName Template = Arg.getAsTemplate();2073      assert(!Template.isNull() && "Null template template argument");2074      return getSema().Context.getSubstTemplateTemplateParm(2075          Template, AssociatedDecl, TTP->getIndex(), PackIndex, Final);2076    }2077  }2078 2079  if (SubstTemplateTemplateParmPackStorage *SubstPack2080      = Name.getAsSubstTemplateTemplateParmPack()) {2081    if (!getSema().ArgPackSubstIndex)2082      return Name;2083 2084    TemplateArgument Pack = SubstPack->getArgumentPack();2085    TemplateName Template =2086        SemaRef.getPackSubstitutedTemplateArgument(Pack).getAsTemplate();2087    return getSema().Context.getSubstTemplateTemplateParm(2088        Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),2089        SemaRef.getPackIndex(Pack), SubstPack->getFinal());2090  }2091 2092  return inherited::TransformTemplateName(2093      QualifierLoc, TemplateKWLoc, Name, NameLoc, ObjectType,2094      FirstQualifierInScope, AllowInjectedClassName);2095}2096 2097ExprResult2098TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {2099  if (!E->isTypeDependent())2100    return E;2101 2102  return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());2103}2104 2105ExprResult2106TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,2107                                               NonTypeTemplateParmDecl *NTTP) {2108  // If the corresponding template argument is NULL or non-existent, it's2109  // because we are performing instantiation from explicitly-specified2110  // template arguments in a function template, but there were some2111  // arguments left unspecified.2112  if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),2113                                        NTTP->getPosition())) {2114    IsIncomplete = true;2115    return BailOutOnIncomplete ? ExprError() : E;2116  }2117 2118  TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());2119 2120  if (TemplateArgs.isRewrite()) {2121    // We're rewriting the template parameter as a reference to another2122    // template parameter.2123    Arg = getTemplateArgumentPackPatternForRewrite(Arg);2124    assert(Arg.getKind() == TemplateArgument::Expression &&2125           "unexpected nontype template argument kind in template rewrite");2126    // FIXME: This can lead to the same subexpression appearing multiple times2127    // in a complete expression.2128    return Arg.getAsExpr();2129  }2130 2131  auto [AssociatedDecl, Final] =2132      TemplateArgs.getAssociatedDecl(NTTP->getDepth());2133  UnsignedOrNone PackIndex = std::nullopt;2134  if (NTTP->isParameterPack()) {2135    assert(Arg.getKind() == TemplateArgument::Pack &&2136           "Missing argument pack");2137 2138    if (!getSema().ArgPackSubstIndex) {2139      // We have an argument pack, but we can't select a particular argument2140      // out of it yet. Therefore, we'll build an expression to hold on to that2141      // argument pack.2142      QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,2143                                              E->getLocation(),2144                                              NTTP->getDeclName());2145      if (TargetType.isNull())2146        return ExprError();2147 2148      QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);2149      if (TargetType->isRecordType())2150        ExprType.addConst();2151      return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(2152          ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,2153          E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition(), Final);2154    }2155    PackIndex = SemaRef.getPackIndex(Arg);2156    Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);2157  }2158  return SemaRef.BuildSubstNonTypeTemplateParmExpr(2159      AssociatedDecl, NTTP, E->getLocation(), Arg, PackIndex, Final);2160}2161 2162const AnnotateAttr *2163TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {2164  SmallVector<Expr *> Args;2165  for (Expr *Arg : AA->args()) {2166    ExprResult Res = getDerived().TransformExpr(Arg);2167    if (Res.isUsable())2168      Args.push_back(Res.get());2169  }2170  return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(),2171                                      Args.data(), Args.size(), AA->getRange());2172}2173 2174const CXXAssumeAttr *2175TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {2176  ExprResult Res = getDerived().TransformExpr(AA->getAssumption());2177  if (!Res.isUsable())2178    return AA;2179 2180  if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {2181    Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),2182                                       AA->getRange());2183    if (!Res.isUsable())2184      return AA;2185  }2186 2187  return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),2188                                       AA->getRange());2189}2190 2191const LoopHintAttr *2192TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {2193  Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();2194 2195  if (TransformedExpr == LH->getValue())2196    return LH;2197 2198  // Generate error if there is a problem with the value.2199  if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),2200                                  LH->getSemanticSpelling() ==2201                                      LoopHintAttr::Pragma_unroll))2202    return LH;2203 2204  LoopHintAttr::OptionType Option = LH->getOption();2205  LoopHintAttr::LoopHintState State = LH->getState();2206 2207  llvm::APSInt ValueAPS =2208      TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());2209  // The values of 0 and 1 block any unrolling of the loop.2210  if (ValueAPS.isZero() || ValueAPS.isOne()) {2211    Option = LoopHintAttr::Unroll;2212    State = LoopHintAttr::Disable;2213  }2214 2215  // Create new LoopHintValueAttr with integral expression in place of the2216  // non-type template parameter.2217  return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,2218                                      TransformedExpr, *LH);2219}2220const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(2221    const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {2222  if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))2223    return nullptr;2224 2225  return A;2226}2227const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(2228    const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {2229  if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))2230    return nullptr;2231 2232  return A;2233}2234 2235const CodeAlignAttr *2236TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {2237  Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();2238  return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);2239}2240const OpenACCRoutineDeclAttr *2241TemplateInstantiator::TransformOpenACCRoutineDeclAttr(2242    const OpenACCRoutineDeclAttr *A) {2243  llvm_unreachable("RoutineDecl should only be a declaration attribute, as it "2244                   "applies to a Function Decl (and a few places for VarDecl)");2245}2246 2247ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(ValueDecl *PD,2248                                                       SourceLocation Loc) {2249  DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);2250  return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);2251}2252 2253ExprResult2254TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {2255  if (getSema().ArgPackSubstIndex) {2256    // We can expand this parameter pack now.2257    ValueDecl *D = E->getExpansion(*getSema().ArgPackSubstIndex);2258    ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));2259    if (!VD)2260      return ExprError();2261    return RebuildVarDeclRefExpr(VD, E->getExprLoc());2262  }2263 2264  QualType T = TransformType(E->getType());2265  if (T.isNull())2266    return ExprError();2267 2268  // Transform each of the parameter expansions into the corresponding2269  // parameters in the instantiation of the function decl.2270  SmallVector<ValueDecl *, 8> Vars;2271  Vars.reserve(E->getNumExpansions());2272  for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();2273       I != End; ++I) {2274    ValueDecl *D = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), *I));2275    if (!D)2276      return ExprError();2277    Vars.push_back(D);2278  }2279 2280  auto *PackExpr =2281      FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),2282                                   E->getParameterPackLocation(), Vars);2283  getSema().MarkFunctionParmPackReferenced(PackExpr);2284  return PackExpr;2285}2286 2287ExprResult2288TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,2289                                                       ValueDecl *PD) {2290  typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;2291  llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found2292    = getSema().CurrentInstantiationScope->findInstantiationOf(PD);2293  assert(Found && "no instantiation for parameter pack");2294 2295  Decl *TransformedDecl;2296  if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(*Found)) {2297    // If this is a reference to a function parameter pack which we can2298    // substitute but can't yet expand, build a FunctionParmPackExpr for it.2299    if (!getSema().ArgPackSubstIndex) {2300      QualType T = TransformType(E->getType());2301      if (T.isNull())2302        return ExprError();2303      auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,2304                                                    E->getExprLoc(), *Pack);2305      getSema().MarkFunctionParmPackReferenced(PackExpr);2306      return PackExpr;2307    }2308 2309    TransformedDecl = (*Pack)[*getSema().ArgPackSubstIndex];2310  } else {2311    TransformedDecl = cast<Decl *>(*Found);2312  }2313 2314  // We have either an unexpanded pack or a specific expansion.2315  return RebuildVarDeclRefExpr(cast<ValueDecl>(TransformedDecl),2316                               E->getExprLoc());2317}2318 2319ExprResult2320TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {2321  NamedDecl *D = E->getDecl();2322 2323  // Handle references to non-type template parameters and non-type template2324  // parameter packs.2325  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {2326    if (NTTP->getDepth() < TemplateArgs.getNumLevels())2327      return TransformTemplateParmRefExpr(E, NTTP);2328 2329    // We have a non-type template parameter that isn't fully substituted;2330    // FindInstantiatedDecl will find it in the local instantiation scope.2331  }2332 2333  // Handle references to function parameter packs.2334  if (VarDecl *PD = dyn_cast<VarDecl>(D))2335    if (PD->isParameterPack())2336      return TransformFunctionParmPackRefExpr(E, PD);2337 2338  return inherited::TransformDeclRefExpr(E);2339}2340 2341ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(2342    CXXDefaultArgExpr *E) {2343  assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->2344             getDescribedFunctionTemplate() &&2345         "Default arg expressions are never formed in dependent cases.");2346  return SemaRef.BuildCXXDefaultArgExpr(2347      E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),2348      E->getParam());2349}2350 2351template<typename Fn>2352QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,2353                                 FunctionProtoTypeLoc TL,2354                                 CXXRecordDecl *ThisContext,2355                                 Qualifiers ThisTypeQuals,2356                                 Fn TransformExceptionSpec) {2357  // If this is a lambda or block, the transformation MUST be done in the2358  // CurrentInstantiationScope since it introduces a mapping of2359  // the original to the newly created transformed parameters.2360  //2361  // In that case, TemplateInstantiator::TransformLambdaExpr will2362  // have already pushed a scope for this prototype, so don't create2363  // a second one.2364  LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;2365  std::optional<LocalInstantiationScope> Scope;2366  if (!Current || !Current->isLambdaOrBlock())2367    Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true);2368 2369  return inherited::TransformFunctionProtoType(2370      TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);2371}2372 2373ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(2374    ParmVarDecl *OldParm, int indexAdjustment, UnsignedOrNone NumExpansions,2375    bool ExpectParameterPack) {2376  auto NewParm = SemaRef.SubstParmVarDecl(2377      OldParm, TemplateArgs, indexAdjustment, NumExpansions,2378      ExpectParameterPack, EvaluateConstraints);2379  if (NewParm && SemaRef.getLangOpts().OpenCL)2380    SemaRef.deduceOpenCLAddressSpace(NewParm);2381  return NewParm;2382}2383 2384QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(2385    TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,2386    Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,2387    TemplateArgument Arg, SourceLocation NameLoc) {2388  QualType Replacement = Arg.getAsType();2389 2390  // If the template parameter had ObjC lifetime qualifiers,2391  // then any such qualifiers on the replacement type are ignored.2392  if (SuppressObjCLifetime) {2393    Qualifiers RQs;2394    RQs = Replacement.getQualifiers();2395    RQs.removeObjCLifetime();2396    Replacement =2397        SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);2398  }2399 2400  // TODO: only do this uniquing once, at the start of instantiation.2401  QualType Result = getSema().Context.getSubstTemplateTypeParmType(2402      Replacement, AssociatedDecl, Index, PackIndex, Final);2403  SubstTemplateTypeParmTypeLoc NewTL =2404      TLB.push<SubstTemplateTypeParmTypeLoc>(Result);2405  NewTL.setNameLoc(NameLoc);2406  return Result;2407}2408 2409QualType2410TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,2411                                                    TemplateTypeParmTypeLoc TL,2412                                                    bool SuppressObjCLifetime) {2413  const TemplateTypeParmType *T = TL.getTypePtr();2414  if (T->getDepth() < TemplateArgs.getNumLevels()) {2415    // Replace the template type parameter with its corresponding2416    // template argument.2417 2418    // If the corresponding template argument is NULL or doesn't exist, it's2419    // because we are performing instantiation from explicitly-specified2420    // template arguments in a function template class, but there were some2421    // arguments left unspecified.2422    if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {2423      IsIncomplete = true;2424      if (BailOutOnIncomplete)2425        return QualType();2426 2427      TemplateTypeParmTypeLoc NewTL2428        = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());2429      NewTL.setNameLoc(TL.getNameLoc());2430      return TL.getType();2431    }2432 2433    TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());2434 2435    if (TemplateArgs.isRewrite()) {2436      // We're rewriting the template parameter as a reference to another2437      // template parameter.2438      Arg = getTemplateArgumentPackPatternForRewrite(Arg);2439      assert(Arg.getKind() == TemplateArgument::Type &&2440             "unexpected nontype template argument kind in template rewrite");2441      QualType NewT = Arg.getAsType();2442      TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());2443      return NewT;2444    }2445 2446    auto [AssociatedDecl, Final] =2447        TemplateArgs.getAssociatedDecl(T->getDepth());2448    UnsignedOrNone PackIndex = std::nullopt;2449    if (T->isParameterPack()) {2450      assert(Arg.getKind() == TemplateArgument::Pack &&2451             "Missing argument pack");2452 2453      if (!getSema().ArgPackSubstIndex) {2454        // We have the template argument pack, but we're not expanding the2455        // enclosing pack expansion yet. Just save the template argument2456        // pack for later substitution.2457        QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(2458            AssociatedDecl, T->getIndex(), Final, Arg);2459        SubstTemplateTypeParmPackTypeLoc NewTL2460          = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);2461        NewTL.setNameLoc(TL.getNameLoc());2462        return Result;2463      }2464 2465      // PackIndex starts from last element.2466      PackIndex = SemaRef.getPackIndex(Arg);2467      Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);2468    }2469 2470    assert(Arg.getKind() == TemplateArgument::Type &&2471           "Template argument kind mismatch");2472 2473    return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,2474                                          AssociatedDecl, T->getIndex(),2475                                          PackIndex, Arg, TL.getNameLoc());2476  }2477 2478  // The template type parameter comes from an inner template (e.g.,2479  // the template parameter list of a member template inside the2480  // template we are instantiating). Create a new template type2481  // parameter with the template "level" reduced by one.2482  TemplateTypeParmDecl *NewTTPDecl = nullptr;2483  if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())2484    NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(2485        TransformDecl(TL.getNameLoc(), OldTTPDecl));2486  QualType Result = getSema().Context.getTemplateTypeParmType(2487      T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),2488      T->isParameterPack(), NewTTPDecl);2489  TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);2490  NewTL.setNameLoc(TL.getNameLoc());2491  return Result;2492}2493 2494QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(2495    TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,2496    bool SuppressObjCLifetime) {2497  const SubstTemplateTypeParmPackType *T = TL.getTypePtr();2498 2499  Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());2500 2501  if (!getSema().ArgPackSubstIndex) {2502    // We aren't expanding the parameter pack, so just return ourselves.2503    QualType Result = TL.getType();2504    if (NewReplaced != T->getAssociatedDecl())2505      Result = getSema().Context.getSubstTemplateTypeParmPackType(2506          NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());2507    SubstTemplateTypeParmPackTypeLoc NewTL =2508        TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);2509    NewTL.setNameLoc(TL.getNameLoc());2510    return Result;2511  }2512 2513  TemplateArgument Pack = T->getArgumentPack();2514  TemplateArgument Arg = SemaRef.getPackSubstitutedTemplateArgument(Pack);2515  return BuildSubstTemplateTypeParmType(2516      TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),2517      SemaRef.getPackIndex(Pack), Arg, TL.getNameLoc());2518}2519 2520QualType TemplateInstantiator::TransformSubstBuiltinTemplatePackType(2521    TypeLocBuilder &TLB, SubstBuiltinTemplatePackTypeLoc TL) {2522  if (!getSema().ArgPackSubstIndex)2523    return TreeTransform::TransformSubstBuiltinTemplatePackType(TLB, TL);2524  TemplateArgument Result = SemaRef.getPackSubstitutedTemplateArgument(2525      TL.getTypePtr()->getArgumentPack());2526  TLB.pushTrivial(SemaRef.getASTContext(), Result.getAsType(),2527                  TL.getBeginLoc());2528  return Result.getAsType();2529}2530 2531static concepts::Requirement::SubstitutionDiagnostic *2532createSubstDiag(Sema &S, TemplateDeductionInfo &Info,2533                Sema::EntityPrinter Printer) {2534  SmallString<128> Message;2535  SourceLocation ErrorLoc;2536  if (Info.hasSFINAEDiagnostic()) {2537    PartialDiagnosticAt PDA(SourceLocation(),2538                            PartialDiagnostic::NullDiagnostic{});2539    Info.takeSFINAEDiagnostic(PDA);2540    PDA.second.EmitToString(S.getDiagnostics(), Message);2541    ErrorLoc = PDA.first;2542  } else {2543    ErrorLoc = Info.getLocation();2544  }2545  SmallString<128> Entity;2546  llvm::raw_svector_ostream OS(Entity);2547  Printer(OS);2548  const ASTContext &C = S.Context;2549  return new (C) concepts::Requirement::SubstitutionDiagnostic{2550      C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};2551}2552 2553concepts::Requirement::SubstitutionDiagnostic *2554Sema::createSubstDiagAt(SourceLocation Location, EntityPrinter Printer) {2555  SmallString<128> Entity;2556  llvm::raw_svector_ostream OS(Entity);2557  Printer(OS);2558  const ASTContext &C = Context;2559  return new (C) concepts::Requirement::SubstitutionDiagnostic{2560      /*SubstitutedEntity=*/C.backupStr(Entity),2561      /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};2562}2563 2564ExprResult TemplateInstantiator::TransformRequiresTypeParams(2565    SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,2566    RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,2567    SmallVectorImpl<QualType> &PTypes,2568    SmallVectorImpl<ParmVarDecl *> &TransParams,2569    Sema::ExtParameterInfoBuilder &PInfos) {2570 2571  TemplateDeductionInfo Info(KWLoc);2572  Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc, RE,2573                                       SourceRange{KWLoc, RBraceLoc});2574  Sema::SFINAETrap Trap(SemaRef, Info);2575 2576  unsigned ErrorIdx;2577  if (getDerived().TransformFunctionTypeParams(2578          KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,2579          &TransParams, PInfos, &ErrorIdx) ||2580      Trap.hasErrorOccurred()) {2581    SmallVector<concepts::Requirement *, 4> TransReqs;2582    ParmVarDecl *FailedDecl = Params[ErrorIdx];2583    // Add a 'failed' Requirement to contain the error that caused the failure2584    // here.2585    TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(2586        SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));2587    return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),2588                                            TransParams, RE->getRParenLoc(),2589                                            TransReqs, RBraceLoc);2590  }2591 2592  return ExprResult{};2593}2594 2595concepts::TypeRequirement *2596TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {2597  if (!Req->isDependent() && !AlwaysRebuild())2598    return Req;2599  if (Req->isSubstitutionFailure()) {2600    if (AlwaysRebuild())2601      return RebuildTypeRequirement(2602              Req->getSubstitutionDiagnostic());2603    return Req;2604  }2605 2606  TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());2607  Sema::SFINAETrap Trap(SemaRef, Info);2608  Sema::InstantiatingTemplate TypeInst(2609      SemaRef, Req->getType()->getTypeLoc().getBeginLoc(), Req,2610      Req->getType()->getTypeLoc().getSourceRange());2611  if (TypeInst.isInvalid())2612    return nullptr;2613  TypeSourceInfo *TransType = TransformType(Req->getType());2614  if (!TransType || Trap.hasErrorOccurred())2615    return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,2616        [&] (llvm::raw_ostream& OS) {2617            Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());2618        }));2619  return RebuildTypeRequirement(TransType);2620}2621 2622concepts::ExprRequirement *2623TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {2624  if (!Req->isDependent() && !AlwaysRebuild())2625    return Req;2626 2627  llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>2628      TransExpr;2629  if (Req->isExprSubstitutionFailure())2630    TransExpr = Req->getExprSubstitutionDiagnostic();2631  else {2632    Expr *E = Req->getExpr();2633    TemplateDeductionInfo Info(E->getBeginLoc());2634    Sema::SFINAETrap Trap(SemaRef, Info);2635    Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req,2636                                         E->getSourceRange());2637    if (ExprInst.isInvalid())2638      return nullptr;2639    ExprResult TransExprRes = TransformExpr(E);2640    if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&2641        TransExprRes.get()->hasPlaceholderType())2642      TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());2643    if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())2644      TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {2645        E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());2646      });2647    else2648      TransExpr = TransExprRes.get();2649  }2650 2651  std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;2652  const auto &RetReq = Req->getReturnTypeRequirement();2653  if (RetReq.isEmpty())2654    TransRetReq.emplace();2655  else if (RetReq.isSubstitutionFailure())2656    TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());2657  else if (RetReq.isTypeConstraint()) {2658    TemplateParameterList *OrigTPL =2659        RetReq.getTypeConstraintTemplateParameterList();2660    TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());2661    Sema::SFINAETrap Trap(SemaRef, Info);2662    Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(), Req,2663                                        OrigTPL->getSourceRange());2664    if (TPLInst.isInvalid())2665      return nullptr;2666    TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);2667    if (!TPL || Trap.hasErrorOccurred())2668      TransRetReq.emplace(createSubstDiag(SemaRef, Info,2669          [&] (llvm::raw_ostream& OS) {2670              RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()2671                  ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());2672          }));2673    else {2674      TPLInst.Clear();2675      TransRetReq.emplace(TPL);2676    }2677  }2678  assert(TransRetReq && "All code paths leading here must set TransRetReq");2679  if (Expr *E = TransExpr.dyn_cast<Expr *>())2680    return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),2681                                  std::move(*TransRetReq));2682  return RebuildExprRequirement(2683      cast<concepts::Requirement::SubstitutionDiagnostic *>(TransExpr),2684      Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));2685}2686 2687concepts::NestedRequirement *2688TemplateInstantiator::TransformNestedRequirement(2689    concepts::NestedRequirement *Req) {2690 2691  ASTContext &C = SemaRef.Context;2692 2693  Expr *Constraint = Req->getConstraintExpr();2694  ConstraintSatisfaction Satisfaction;2695 2696  auto NestedReqWithDiag = [&C, this](Expr *E,2697                                      ConstraintSatisfaction Satisfaction) {2698    Satisfaction.IsSatisfied = false;2699    SmallString<128> Entity;2700    llvm::raw_svector_ostream OS(Entity);2701    E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());2702    return new (C) concepts::NestedRequirement(2703        SemaRef.Context, C.backupStr(Entity), std::move(Satisfaction));2704  };2705 2706  if (Req->hasInvalidConstraint()) {2707    if (AlwaysRebuild())2708      return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),2709                                      Req->getConstraintSatisfaction());2710    return Req;2711  }2712 2713  if (!getEvaluateConstraints()) {2714    ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());2715    if (TransConstraint.isInvalid() || !TransConstraint.get())2716      return nullptr;2717    if (TransConstraint.get()->isInstantiationDependent())2718      return new (SemaRef.Context)2719          concepts::NestedRequirement(TransConstraint.get());2720    ConstraintSatisfaction Satisfaction;2721    return new (SemaRef.Context) concepts::NestedRequirement(2722        SemaRef.Context, TransConstraint.get(), Satisfaction);2723  }2724 2725  bool Success;2726  Expr *NewConstraint;2727  {2728    EnterExpressionEvaluationContext ContextRAII(2729        SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);2730    Sema::InstantiatingTemplate ConstrInst(2731        SemaRef, Constraint->getBeginLoc(), Req,2732        Sema::InstantiatingTemplate::ConstraintsCheck(),2733        Constraint->getSourceRange());2734 2735    if (ConstrInst.isInvalid())2736      return nullptr;2737 2738    Success = !SemaRef.CheckConstraintSatisfaction(2739        Req, AssociatedConstraint(Constraint, SemaRef.ArgPackSubstIndex),2740        TemplateArgs, Constraint->getSourceRange(), Satisfaction,2741        /*TopLevelConceptId=*/nullptr, &NewConstraint);2742  }2743 2744  if (!Success || Satisfaction.HasSubstitutionFailure())2745    return NestedReqWithDiag(Constraint, Satisfaction);2746 2747  // FIXME: const correctness2748  // MLTAL might be dependent.2749  if (!NewConstraint) {2750    if (!Satisfaction.IsSatisfied)2751      return NestedReqWithDiag(Constraint, Satisfaction);2752 2753    NewConstraint = Constraint;2754  }2755  return new (C) concepts::NestedRequirement(C, NewConstraint, Satisfaction);2756}2757 2758TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,2759                                const MultiLevelTemplateArgumentList &Args,2760                                SourceLocation Loc,2761                                DeclarationName Entity,2762                                bool AllowDeducedTST) {2763  assert(!CodeSynthesisContexts.empty() &&2764         "Cannot perform an instantiation without some context on the "2765         "instantiation stack");2766 2767  if (!T->getType()->isInstantiationDependentType() &&2768      !T->getType()->isVariablyModifiedType())2769    return T;2770 2771  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);2772  return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)2773                         : Instantiator.TransformType(T);2774}2775 2776TypeSourceInfo *Sema::SubstType(TypeLoc TL,2777                                const MultiLevelTemplateArgumentList &Args,2778                                SourceLocation Loc,2779                                DeclarationName Entity) {2780  assert(!CodeSynthesisContexts.empty() &&2781         "Cannot perform an instantiation without some context on the "2782         "instantiation stack");2783 2784  if (TL.getType().isNull())2785    return nullptr;2786 2787  if (!TL.getType()->isInstantiationDependentType() &&2788      !TL.getType()->isVariablyModifiedType()) {2789    // FIXME: Make a copy of the TypeLoc data here, so that we can2790    // return a new TypeSourceInfo. Inefficient!2791    TypeLocBuilder TLB;2792    TLB.pushFullCopy(TL);2793    return TLB.getTypeSourceInfo(Context, TL.getType());2794  }2795 2796  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);2797  TypeLocBuilder TLB;2798  TLB.reserve(TL.getFullDataSize());2799  QualType Result = Instantiator.TransformType(TLB, TL);2800  if (Result.isNull())2801    return nullptr;2802 2803  return TLB.getTypeSourceInfo(Context, Result);2804}2805 2806/// Deprecated form of the above.2807QualType Sema::SubstType(QualType T,2808                         const MultiLevelTemplateArgumentList &TemplateArgs,2809                         SourceLocation Loc, DeclarationName Entity,2810                         bool *IsIncompleteSubstitution) {2811  assert(!CodeSynthesisContexts.empty() &&2812         "Cannot perform an instantiation without some context on the "2813         "instantiation stack");2814 2815  // If T is not a dependent type or a variably-modified type, there2816  // is nothing to do.2817  if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())2818    return T;2819 2820  TemplateInstantiator Instantiator(2821      *this, TemplateArgs, Loc, Entity,2822      /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);2823  QualType QT = Instantiator.TransformType(T);2824  if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())2825    *IsIncompleteSubstitution = true;2826  return QT;2827}2828 2829static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {2830  if (T->getType()->isInstantiationDependentType() ||2831      T->getType()->isVariablyModifiedType())2832    return true;2833 2834  TypeLoc TL = T->getTypeLoc().IgnoreParens();2835  if (!TL.getAs<FunctionProtoTypeLoc>())2836    return false;2837 2838  FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();2839  for (ParmVarDecl *P : FP.getParams()) {2840    // This must be synthesized from a typedef.2841    if (!P) continue;2842 2843    // If there are any parameters, a new TypeSourceInfo that refers to the2844    // instantiated parameters must be built.2845    return true;2846  }2847 2848  return false;2849}2850 2851TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,2852                                const MultiLevelTemplateArgumentList &Args,2853                                SourceLocation Loc,2854                                DeclarationName Entity,2855                                CXXRecordDecl *ThisContext,2856                                Qualifiers ThisTypeQuals,2857                                bool EvaluateConstraints) {2858  assert(!CodeSynthesisContexts.empty() &&2859         "Cannot perform an instantiation without some context on the "2860         "instantiation stack");2861 2862  if (!NeedsInstantiationAsFunctionType(T))2863    return T;2864 2865  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);2866  Instantiator.setEvaluateConstraints(EvaluateConstraints);2867 2868  TypeLocBuilder TLB;2869 2870  TypeLoc TL = T->getTypeLoc();2871  TLB.reserve(TL.getFullDataSize());2872 2873  QualType Result;2874 2875  if (FunctionProtoTypeLoc Proto =2876          TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {2877    // Instantiate the type, other than its exception specification. The2878    // exception specification is instantiated in InitFunctionInstantiation2879    // once we've built the FunctionDecl.2880    // FIXME: Set the exception specification to EST_Uninstantiated here,2881    // instead of rebuilding the function type again later.2882    Result = Instantiator.TransformFunctionProtoType(2883        TLB, Proto, ThisContext, ThisTypeQuals,2884        [](FunctionProtoType::ExceptionSpecInfo &ESI,2885           bool &Changed) { return false; });2886  } else {2887    Result = Instantiator.TransformType(TLB, TL);2888  }2889  // When there are errors resolving types, clang may use IntTy as a fallback,2890  // breaking our assumption that function declarations have function types.2891  if (Result.isNull() || !Result->isFunctionType())2892    return nullptr;2893 2894  return TLB.getTypeSourceInfo(Context, Result);2895}2896 2897bool Sema::SubstExceptionSpec(SourceLocation Loc,2898                              FunctionProtoType::ExceptionSpecInfo &ESI,2899                              SmallVectorImpl<QualType> &ExceptionStorage,2900                              const MultiLevelTemplateArgumentList &Args) {2901  bool Changed = false;2902  TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());2903  return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,2904                                             Changed);2905}2906 2907void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,2908                              const MultiLevelTemplateArgumentList &Args) {2909  FunctionProtoType::ExceptionSpecInfo ESI =2910      Proto->getExtProtoInfo().ExceptionSpec;2911 2912  SmallVector<QualType, 4> ExceptionStorage;2913  if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),2914                         ESI, ExceptionStorage, Args))2915    // On error, recover by dropping the exception specification.2916    ESI.Type = EST_None;2917 2918  UpdateExceptionSpec(New, ESI);2919}2920 2921namespace {2922 2923  struct GetContainedInventedTypeParmVisitor :2924    public TypeVisitor<GetContainedInventedTypeParmVisitor,2925                       TemplateTypeParmDecl *> {2926    using TypeVisitor<GetContainedInventedTypeParmVisitor,2927                      TemplateTypeParmDecl *>::Visit;2928 2929    TemplateTypeParmDecl *Visit(QualType T) {2930      if (T.isNull())2931        return nullptr;2932      return Visit(T.getTypePtr());2933    }2934    // The deduced type itself.2935    TemplateTypeParmDecl *VisitTemplateTypeParmType(2936        const TemplateTypeParmType *T) {2937      if (!T->getDecl() || !T->getDecl()->isImplicit())2938        return nullptr;2939      return T->getDecl();2940    }2941 2942    // Only these types can contain 'auto' types, and subsequently be replaced2943    // by references to invented parameters.2944 2945    TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {2946      return Visit(T->getPointeeType());2947    }2948 2949    TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {2950      return Visit(T->getPointeeType());2951    }2952 2953    TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {2954      return Visit(T->getPointeeTypeAsWritten());2955    }2956 2957    TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {2958      return Visit(T->getPointeeType());2959    }2960 2961    TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {2962      return Visit(T->getElementType());2963    }2964 2965    TemplateTypeParmDecl *VisitDependentSizedExtVectorType(2966      const DependentSizedExtVectorType *T) {2967      return Visit(T->getElementType());2968    }2969 2970    TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {2971      return Visit(T->getElementType());2972    }2973 2974    TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {2975      return VisitFunctionType(T);2976    }2977 2978    TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {2979      return Visit(T->getReturnType());2980    }2981 2982    TemplateTypeParmDecl *VisitParenType(const ParenType *T) {2983      return Visit(T->getInnerType());2984    }2985 2986    TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {2987      return Visit(T->getModifiedType());2988    }2989 2990    TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {2991      return Visit(T->getUnderlyingType());2992    }2993 2994    TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {2995      return Visit(T->getOriginalType());2996    }2997 2998    TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {2999      return Visit(T->getPattern());3000    }3001  };3002 3003} // namespace3004 3005bool Sema::SubstTypeConstraint(3006    TemplateTypeParmDecl *Inst, const TypeConstraint *TC,3007    const MultiLevelTemplateArgumentList &TemplateArgs,3008    bool EvaluateConstraints) {3009  const ASTTemplateArgumentListInfo *TemplArgInfo =3010      TC->getTemplateArgsAsWritten();3011 3012  if (!EvaluateConstraints && !inParameterMappingSubstitution()) {3013    UnsignedOrNone Index = TC->getArgPackSubstIndex();3014    if (!Index)3015      Index = SemaRef.ArgPackSubstIndex;3016    Inst->setTypeConstraint(TC->getConceptReference(),3017                            TC->getImmediatelyDeclaredConstraint(), Index);3018    return false;3019  }3020 3021  TemplateArgumentListInfo InstArgs;3022 3023  if (TemplArgInfo) {3024    InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);3025    InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);3026    if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,3027                               InstArgs))3028      return true;3029  }3030  return AttachTypeConstraint(3031      TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),3032      TC->getNamedConcept(),3033      /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,3034      Inst->isParameterPack()3035          ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())3036                ->getEllipsisLoc()3037          : SourceLocation());3038}3039 3040ParmVarDecl *3041Sema::SubstParmVarDecl(ParmVarDecl *OldParm,3042                       const MultiLevelTemplateArgumentList &TemplateArgs,3043                       int indexAdjustment, UnsignedOrNone NumExpansions,3044                       bool ExpectParameterPack, bool EvaluateConstraint) {3045  TypeSourceInfo *OldTSI = OldParm->getTypeSourceInfo();3046  TypeSourceInfo *NewTSI = nullptr;3047 3048  TypeLoc OldTL = OldTSI->getTypeLoc();3049  if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {3050 3051    // We have a function parameter pack. Substitute into the pattern of the3052    // expansion.3053    NewTSI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,3054                       OldParm->getLocation(), OldParm->getDeclName());3055    if (!NewTSI)3056      return nullptr;3057 3058    if (NewTSI->getType()->containsUnexpandedParameterPack()) {3059      // We still have unexpanded parameter packs, which means that3060      // our function parameter is still a function parameter pack.3061      // Therefore, make its type a pack expansion type.3062      NewTSI = CheckPackExpansion(NewTSI, ExpansionTL.getEllipsisLoc(),3063                                  NumExpansions);3064    } else if (ExpectParameterPack) {3065      // We expected to get a parameter pack but didn't (because the type3066      // itself is not a pack expansion type), so complain. This can occur when3067      // the substitution goes through an alias template that "loses" the3068      // pack expansion.3069      Diag(OldParm->getLocation(),3070           diag::err_function_parameter_pack_without_parameter_packs)3071          << NewTSI->getType();3072      return nullptr;3073    }3074  } else {3075    NewTSI = SubstType(OldTSI, TemplateArgs, OldParm->getLocation(),3076                       OldParm->getDeclName());3077  }3078 3079  if (!NewTSI)3080    return nullptr;3081 3082  if (NewTSI->getType()->isVoidType()) {3083    Diag(OldParm->getLocation(), diag::err_param_with_void_type);3084    return nullptr;3085  }3086 3087  // In abbreviated templates, TemplateTypeParmDecls with possible3088  // TypeConstraints are created when the parameter list is originally parsed.3089  // The TypeConstraints can therefore reference other functions parameters in3090  // the abbreviated function template, which is why we must instantiate them3091  // here, when the instantiated versions of those referenced parameters are in3092  // scope.3093  if (TemplateTypeParmDecl *TTP =3094          GetContainedInventedTypeParmVisitor().Visit(OldTSI->getType())) {3095    if (const TypeConstraint *TC = TTP->getTypeConstraint()) {3096      auto *Inst = cast_or_null<TemplateTypeParmDecl>(3097          FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));3098      // We will first get here when instantiating the abbreviated function3099      // template's described function, but we might also get here later.3100      // Make sure we do not instantiate the TypeConstraint more than once.3101      if (Inst && !Inst->getTypeConstraint()) {3102        if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))3103          return nullptr;3104      }3105    }3106  }3107 3108  ParmVarDecl *NewParm = CheckParameter(3109      Context.getTranslationUnitDecl(), OldParm->getInnerLocStart(),3110      OldParm->getLocation(), OldParm->getIdentifier(), NewTSI->getType(),3111      NewTSI, OldParm->getStorageClass());3112  if (!NewParm)3113    return nullptr;3114 3115  // Mark the (new) default argument as uninstantiated (if any).3116  if (OldParm->hasUninstantiatedDefaultArg()) {3117    Expr *Arg = OldParm->getUninstantiatedDefaultArg();3118    NewParm->setUninstantiatedDefaultArg(Arg);3119  } else if (OldParm->hasUnparsedDefaultArg()) {3120    NewParm->setUnparsedDefaultArg();3121    UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);3122  } else if (Expr *Arg = OldParm->getDefaultArg()) {3123    // Default arguments cannot be substituted until the declaration context3124    // for the associated function or lambda capture class is available.3125    // This is necessary for cases like the following where construction of3126    // the lambda capture class for the outer lambda is dependent on the3127    // parameter types but where the default argument is dependent on the3128    // outer lambda's declaration context.3129    //   template <typename T>3130    //   auto f() {3131    //     return [](T = []{ return T{}; }()) { return 0; };3132    //   }3133    NewParm->setUninstantiatedDefaultArg(Arg);3134  }3135 3136  NewParm->setExplicitObjectParameterLoc(3137      OldParm->getExplicitObjectParamThisLoc());3138  NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());3139 3140  if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {3141    // Add the new parameter to the instantiated parameter pack.3142    CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);3143  } else {3144    // Introduce an Old -> New mapping3145    CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);3146  }3147 3148  // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext3149  // can be anything, is this right ?3150  NewParm->setDeclContext(CurContext);3151 3152  NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),3153                        OldParm->getFunctionScopeIndex() + indexAdjustment);3154 3155  InstantiateAttrs(TemplateArgs, OldParm, NewParm);3156 3157  return NewParm;3158}3159 3160bool Sema::SubstParmTypes(3161    SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,3162    const FunctionProtoType::ExtParameterInfo *ExtParamInfos,3163    const MultiLevelTemplateArgumentList &TemplateArgs,3164    SmallVectorImpl<QualType> &ParamTypes,3165    SmallVectorImpl<ParmVarDecl *> *OutParams,3166    ExtParameterInfoBuilder &ParamInfos) {3167  assert(!CodeSynthesisContexts.empty() &&3168         "Cannot perform an instantiation without some context on the "3169         "instantiation stack");3170 3171  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,3172                                    DeclarationName());3173  return Instantiator.TransformFunctionTypeParams(3174      Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);3175}3176 3177bool Sema::SubstDefaultArgument(3178    SourceLocation Loc,3179    ParmVarDecl *Param,3180    const MultiLevelTemplateArgumentList &TemplateArgs,3181    bool ForCallExpr) {3182  FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());3183  Expr *PatternExpr = Param->getUninstantiatedDefaultArg();3184 3185  RecursiveInstGuard AlreadyInstantiating(3186      *this, Param, RecursiveInstGuard::Kind::DefaultArgument);3187  if (AlreadyInstantiating) {3188    Param->setInvalidDecl();3189    return Diag(Param->getBeginLoc(), diag::err_recursive_default_argument)3190           << FD << PatternExpr->getSourceRange();3191  }3192 3193  EnterExpressionEvaluationContext EvalContext(3194      *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);3195  NonSFINAEContext _(*this);3196  InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());3197  if (Inst.isInvalid())3198    return true;3199 3200  ExprResult Result;3201  // C++ [dcl.fct.default]p5:3202  //   The names in the [default argument] expression are bound, and3203  //   the semantic constraints are checked, at the point where the3204  //   default argument expression appears.3205  ContextRAII SavedContext(*this, FD);3206  {3207    std::optional<LocalInstantiationScope> LIS;3208 3209    if (ForCallExpr) {3210      // When instantiating a default argument due to use in a call expression,3211      // an instantiation scope that includes the parameters of the callee is3212      // required to satisfy references from the default argument. For example:3213      //   template<typename T> void f(T a, int = decltype(a)());3214      //   void g() { f(0); }3215      LIS.emplace(*this);3216      FunctionDecl *PatternFD = FD->getTemplateInstantiationPattern(3217          /*ForDefinition*/ false);3218      if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))3219        return true;3220    }3221 3222    runWithSufficientStackSpace(Loc, [&] {3223      Result = SubstInitializer(PatternExpr, TemplateArgs,3224                                /*DirectInit*/ false);3225    });3226  }3227  if (Result.isInvalid())3228    return true;3229 3230  if (ForCallExpr) {3231    // Check the expression as an initializer for the parameter.3232    InitializedEntity Entity3233      = InitializedEntity::InitializeParameter(Context, Param);3234    InitializationKind Kind = InitializationKind::CreateCopy(3235        Param->getLocation(),3236        /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());3237    Expr *ResultE = Result.getAs<Expr>();3238 3239    InitializationSequence InitSeq(*this, Entity, Kind, ResultE);3240    Result = InitSeq.Perform(*this, Entity, Kind, ResultE);3241    if (Result.isInvalid())3242      return true;3243 3244    Result =3245        ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),3246                            /*DiscardedValue*/ false);3247  } else {3248    // FIXME: Obtain the source location for the '=' token.3249    SourceLocation EqualLoc = PatternExpr->getBeginLoc();3250    Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);3251  }3252  if (Result.isInvalid())3253      return true;3254 3255  // Remember the instantiated default argument.3256  Param->setDefaultArg(Result.getAs<Expr>());3257 3258  return false;3259}3260 3261// See TreeTransform::PreparePackForExpansion for the relevant comment.3262// This function implements the same concept for base specifiers.3263static bool3264PreparePackForExpansion(Sema &S, const CXXBaseSpecifier &Base,3265                        const MultiLevelTemplateArgumentList &TemplateArgs,3266                        TypeSourceInfo *&Out, UnexpandedInfo &Info) {3267  SourceRange BaseSourceRange = Base.getSourceRange();3268  SourceLocation BaseEllipsisLoc = Base.getEllipsisLoc();3269  Info.Ellipsis = Base.getEllipsisLoc();3270  auto ComputeInfo = [&S, &TemplateArgs, BaseSourceRange, BaseEllipsisLoc](3271                         TypeSourceInfo *BaseTypeInfo,3272                         bool IsLateExpansionAttempt, UnexpandedInfo &Info) {3273    // This is a pack expansion. See whether we should expand it now, or3274    // wait until later.3275    SmallVector<UnexpandedParameterPack, 2> Unexpanded;3276    S.collectUnexpandedParameterPacks(BaseTypeInfo->getTypeLoc(), Unexpanded);3277    if (IsLateExpansionAttempt) {3278      // Request expansion only when there is an opportunity to expand a pack3279      // that required a substituion first.3280      bool SawPackTypes =3281          llvm::any_of(Unexpanded, [](UnexpandedParameterPack P) {3282            return P.first.dyn_cast<const SubstBuiltinTemplatePackType *>();3283          });3284      if (!SawPackTypes) {3285        Info.Expand = false;3286        return false;3287      }3288    }3289 3290    // Determine whether the set of unexpanded parameter packs can and should be3291    // expanded.3292    Info.Expand = false;3293    Info.RetainExpansion = false;3294    Info.NumExpansions = std::nullopt;3295    return S.CheckParameterPacksForExpansion(3296        BaseEllipsisLoc, BaseSourceRange, Unexpanded, TemplateArgs,3297        /*FailOnPackProducingTemplates=*/false, Info.Expand,3298        Info.RetainExpansion, Info.NumExpansions);3299  };3300 3301  if (ComputeInfo(Base.getTypeSourceInfo(), false, Info))3302    return true;3303 3304  if (Info.Expand) {3305    Out = Base.getTypeSourceInfo();3306    return false;3307  }3308 3309  // The resulting base specifier will (still) be a pack expansion.3310  {3311    Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt);3312    Out = S.SubstType(Base.getTypeSourceInfo(), TemplateArgs,3313                      BaseSourceRange.getBegin(), DeclarationName());3314  }3315  if (!Out->getType()->containsUnexpandedParameterPack())3316    return false;3317 3318  // Some packs will learn their length after substitution.3319  // We may need to request their expansion.3320  if (ComputeInfo(Out, /*IsLateExpansionAttempt=*/true, Info))3321    return true;3322  if (Info.Expand)3323    Info.ExpandUnderForgetSubstitions = true;3324  return false;3325}3326 3327bool3328Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,3329                          CXXRecordDecl *Pattern,3330                          const MultiLevelTemplateArgumentList &TemplateArgs) {3331  bool Invalid = false;3332  SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;3333  for (const auto &Base : Pattern->bases()) {3334    if (!Base.getType()->isDependentType()) {3335      if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {3336        if (RD->isInvalidDecl())3337          Instantiation->setInvalidDecl();3338      }3339      InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));3340      continue;3341    }3342 3343    SourceLocation EllipsisLoc;3344    TypeSourceInfo *BaseTypeLoc = nullptr;3345    if (Base.isPackExpansion()) {3346      UnexpandedInfo Info;3347      if (PreparePackForExpansion(*this, Base, TemplateArgs, BaseTypeLoc,3348                                  Info)) {3349        Invalid = true;3350        continue;3351      }3352 3353      // If we should expand this pack expansion now, do so.3354      MultiLevelTemplateArgumentList EmptyList;3355      const MultiLevelTemplateArgumentList *ArgsForSubst = &TemplateArgs;3356      if (Info.ExpandUnderForgetSubstitions)3357        ArgsForSubst = &EmptyList;3358 3359      if (Info.Expand) {3360        for (unsigned I = 0; I != *Info.NumExpansions; ++I) {3361          Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);3362 3363          TypeSourceInfo *Expanded =3364              SubstType(BaseTypeLoc, *ArgsForSubst,3365                        Base.getSourceRange().getBegin(), DeclarationName());3366          if (!Expanded) {3367            Invalid = true;3368            continue;3369          }3370 3371          if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier(3372                  Instantiation, Base.getSourceRange(), Base.isVirtual(),3373                  Base.getAccessSpecifierAsWritten(), Expanded,3374                  SourceLocation()))3375            InstantiatedBases.push_back(InstantiatedBase);3376          else3377            Invalid = true;3378        }3379 3380        continue;3381      }3382 3383      // The resulting base specifier will (still) be a pack expansion.3384      EllipsisLoc = Base.getEllipsisLoc();3385      Sema::ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt);3386      BaseTypeLoc =3387          SubstType(BaseTypeLoc, *ArgsForSubst,3388                    Base.getSourceRange().getBegin(), DeclarationName());3389    } else {3390      BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),3391                              TemplateArgs,3392                              Base.getSourceRange().getBegin(),3393                              DeclarationName());3394    }3395 3396    if (!BaseTypeLoc) {3397      Invalid = true;3398      continue;3399    }3400 3401    if (CXXBaseSpecifier *InstantiatedBase3402          = CheckBaseSpecifier(Instantiation,3403                               Base.getSourceRange(),3404                               Base.isVirtual(),3405                               Base.getAccessSpecifierAsWritten(),3406                               BaseTypeLoc,3407                               EllipsisLoc))3408      InstantiatedBases.push_back(InstantiatedBase);3409    else3410      Invalid = true;3411  }3412 3413  if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))3414    Invalid = true;3415 3416  return Invalid;3417}3418 3419// Defined via #include from SemaTemplateInstantiateDecl.cpp3420namespace clang {3421  namespace sema {3422    Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,3423                            const MultiLevelTemplateArgumentList &TemplateArgs);3424    Attr *instantiateTemplateAttributeForDecl(3425        const Attr *At, ASTContext &C, Sema &S,3426        const MultiLevelTemplateArgumentList &TemplateArgs);3427  }3428}3429 3430bool Sema::InstantiateClass(SourceLocation PointOfInstantiation,3431                            CXXRecordDecl *Instantiation,3432                            CXXRecordDecl *Pattern,3433                            const MultiLevelTemplateArgumentList &TemplateArgs,3434                            TemplateSpecializationKind TSK, bool Complain) {3435#ifndef NDEBUG3436  RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,3437                                          RecursiveInstGuard::Kind::Template);3438  assert(!AlreadyInstantiating && "should have been caught by caller");3439#endif3440 3441  return InstantiateClassImpl(PointOfInstantiation, Instantiation, Pattern,3442                              TemplateArgs, TSK, Complain);3443}3444 3445bool Sema::InstantiateClassImpl(3446    SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation,3447    CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs,3448    TemplateSpecializationKind TSK, bool Complain) {3449 3450  CXXRecordDecl *PatternDef3451    = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());3452  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,3453                                Instantiation->getInstantiatedFromMemberClass(),3454                                     Pattern, PatternDef, TSK, Complain))3455    return true;3456 3457  llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {3458    llvm::TimeTraceMetadata M;3459    llvm::raw_string_ostream OS(M.Detail);3460    Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),3461                                        /*Qualified=*/true);3462    if (llvm::isTimeTraceVerbose()) {3463      auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());3464      M.File = SourceMgr.getFilename(Loc);3465      M.Line = SourceMgr.getExpansionLineNumber(Loc);3466    }3467    return M;3468  });3469 3470  Pattern = PatternDef;3471 3472  // Record the point of instantiation.3473  if (MemberSpecializationInfo *MSInfo3474        = Instantiation->getMemberSpecializationInfo()) {3475    MSInfo->setTemplateSpecializationKind(TSK);3476    MSInfo->setPointOfInstantiation(PointOfInstantiation);3477  } else if (ClassTemplateSpecializationDecl *Spec3478        = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {3479    Spec->setTemplateSpecializationKind(TSK);3480    Spec->setPointOfInstantiation(PointOfInstantiation);3481  }3482 3483  NonSFINAEContext _(*this);3484  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);3485  if (Inst.isInvalid())3486    return true;3487  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),3488                                      "instantiating class definition");3489 3490  // Enter the scope of this instantiation. We don't use3491  // PushDeclContext because we don't have a scope.3492  ContextRAII SavedContext(*this, Instantiation);3493  EnterExpressionEvaluationContext EvalContext(3494      *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);3495 3496  // If this is an instantiation of a local class, merge this local3497  // instantiation scope with the enclosing scope. Otherwise, every3498  // instantiation of a class has its own local instantiation scope.3499  bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();3500  LocalInstantiationScope Scope(*this, MergeWithParentScope);3501 3502  // Some class state isn't processed immediately but delayed till class3503  // instantiation completes. We may not be ready to handle any delayed state3504  // already on the stack as it might correspond to a different class, so save3505  // it now and put it back later.3506  SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);3507 3508  // Pull attributes from the pattern onto the instantiation.3509  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);3510 3511  // Start the definition of this instantiation.3512  Instantiation->startDefinition();3513 3514  // The instantiation is visible here, even if it was first declared in an3515  // unimported module.3516  Instantiation->setVisibleDespiteOwningModule();3517 3518  // FIXME: This loses the as-written tag kind for an explicit instantiation.3519  Instantiation->setTagKind(Pattern->getTagKind());3520 3521  // Do substitution on the base class specifiers.3522  if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))3523    Instantiation->setInvalidDecl();3524 3525  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);3526  Instantiator.setEvaluateConstraints(false);3527  SmallVector<Decl*, 4> Fields;3528  // Delay instantiation of late parsed attributes.3529  LateInstantiatedAttrVec LateAttrs;3530  Instantiator.enableLateAttributeInstantiation(&LateAttrs);3531 3532  bool MightHaveConstexprVirtualFunctions = false;3533  for (auto *Member : Pattern->decls()) {3534    // Don't instantiate members not belonging in this semantic context.3535    // e.g. for:3536    // @code3537    //    template <int i> class A {3538    //      class B *g;3539    //    };3540    // @endcode3541    // 'class B' has the template as lexical context but semantically it is3542    // introduced in namespace scope.3543    if (Member->getDeclContext() != Pattern)3544      continue;3545 3546    // BlockDecls can appear in a default-member-initializer. They must be the3547    // child of a BlockExpr, so we only know how to instantiate them from there.3548    // Similarly, lambda closure types are recreated when instantiating the3549    // corresponding LambdaExpr.3550    if (isa<BlockDecl>(Member) ||3551        (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))3552      continue;3553 3554    if (Member->isInvalidDecl()) {3555      Instantiation->setInvalidDecl();3556      continue;3557    }3558 3559    Decl *NewMember = Instantiator.Visit(Member);3560    if (NewMember) {3561      if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {3562        Fields.push_back(Field);3563      } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {3564        // C++11 [temp.inst]p1: The implicit instantiation of a class template3565        // specialization causes the implicit instantiation of the definitions3566        // of unscoped member enumerations.3567        // Record a point of instantiation for this implicit instantiation.3568        if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&3569            Enum->isCompleteDefinition()) {3570          MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();3571          assert(MSInfo && "no spec info for member enum specialization");3572          MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);3573          MSInfo->setPointOfInstantiation(PointOfInstantiation);3574        }3575      } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {3576        if (SA->isFailed()) {3577          // A static_assert failed. Bail out; instantiating this3578          // class is probably not meaningful.3579          Instantiation->setInvalidDecl();3580          break;3581        }3582      } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {3583        if (MD->isConstexpr() && !MD->getFriendObjectKind() &&3584            (MD->isVirtualAsWritten() || Instantiation->getNumBases()))3585          MightHaveConstexprVirtualFunctions = true;3586      }3587 3588      if (NewMember->isInvalidDecl())3589        Instantiation->setInvalidDecl();3590    } else {3591      // FIXME: Eventually, a NULL return will mean that one of the3592      // instantiations was a semantic disaster, and we'll want to mark the3593      // declaration invalid.3594      // For now, we expect to skip some members that we can't yet handle.3595    }3596  }3597 3598  // Finish checking fields.3599  ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,3600              SourceLocation(), SourceLocation(), ParsedAttributesView());3601  CheckCompletedCXXClass(nullptr, Instantiation);3602 3603  // Default arguments are parsed, if not instantiated. We can go instantiate3604  // default arg exprs for default constructors if necessary now. Unless we're3605  // parsing a class, in which case wait until that's finished.3606  if (ParsingClassDepth == 0)3607    ActOnFinishCXXNonNestedClass();3608 3609  // Instantiate late parsed attributes, and attach them to their decls.3610  // See Sema::InstantiateAttrs3611  for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),3612       E = LateAttrs.end(); I != E; ++I) {3613    assert(CurrentInstantiationScope == Instantiator.getStartingScope());3614    CurrentInstantiationScope = I->Scope;3615 3616    // Allow 'this' within late-parsed attributes.3617    auto *ND = cast<NamedDecl>(I->NewDecl);3618    auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());3619    CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),3620                               ND->isCXXInstanceMember());3621 3622    Attr *NewAttr =3623      instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);3624    if (NewAttr)3625      I->NewDecl->addAttr(NewAttr);3626    LocalInstantiationScope::deleteScopes(I->Scope,3627                                          Instantiator.getStartingScope());3628  }3629  Instantiator.disableLateAttributeInstantiation();3630  LateAttrs.clear();3631 3632  ActOnFinishDelayedMemberInitializers(Instantiation);3633 3634  // FIXME: We should do something similar for explicit instantiations so they3635  // end up in the right module.3636  if (TSK == TSK_ImplicitInstantiation) {3637    Instantiation->setLocation(Pattern->getLocation());3638    Instantiation->setLocStart(Pattern->getInnerLocStart());3639    Instantiation->setBraceRange(Pattern->getBraceRange());3640  }3641 3642  if (!Instantiation->isInvalidDecl()) {3643    // Perform any dependent diagnostics from the pattern.3644    if (Pattern->isDependentContext())3645      PerformDependentDiagnostics(Pattern, TemplateArgs);3646 3647    // Instantiate any out-of-line class template partial3648    // specializations now.3649    for (TemplateDeclInstantiator::delayed_partial_spec_iterator3650              P = Instantiator.delayed_partial_spec_begin(),3651           PEnd = Instantiator.delayed_partial_spec_end();3652         P != PEnd; ++P) {3653      if (!Instantiator.InstantiateClassTemplatePartialSpecialization(3654              P->first, P->second)) {3655        Instantiation->setInvalidDecl();3656        break;3657      }3658    }3659 3660    // Instantiate any out-of-line variable template partial3661    // specializations now.3662    for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator3663              P = Instantiator.delayed_var_partial_spec_begin(),3664           PEnd = Instantiator.delayed_var_partial_spec_end();3665         P != PEnd; ++P) {3666      if (!Instantiator.InstantiateVarTemplatePartialSpecialization(3667              P->first, P->second)) {3668        Instantiation->setInvalidDecl();3669        break;3670      }3671    }3672  }3673 3674  // Exit the scope of this instantiation.3675  SavedContext.pop();3676 3677  if (!Instantiation->isInvalidDecl()) {3678    // Always emit the vtable for an explicit instantiation definition3679    // of a polymorphic class template specialization. Otherwise, eagerly3680    // instantiate only constexpr virtual functions in preparation for their use3681    // in constant evaluation.3682    if (TSK == TSK_ExplicitInstantiationDefinition)3683      MarkVTableUsed(PointOfInstantiation, Instantiation, true);3684    else if (MightHaveConstexprVirtualFunctions)3685      MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,3686                                   /*ConstexprOnly*/ true);3687  }3688 3689  Consumer.HandleTagDeclDefinition(Instantiation);3690 3691  return Instantiation->isInvalidDecl();3692}3693 3694bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,3695                           EnumDecl *Instantiation, EnumDecl *Pattern,3696                           const MultiLevelTemplateArgumentList &TemplateArgs,3697                           TemplateSpecializationKind TSK) {3698#ifndef NDEBUG3699  RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,3700                                          RecursiveInstGuard::Kind::Template);3701  assert(!AlreadyInstantiating && "should have been caught by caller");3702#endif3703 3704  EnumDecl *PatternDef = Pattern->getDefinition();3705  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,3706                                 Instantiation->getInstantiatedFromMemberEnum(),3707                                     Pattern, PatternDef, TSK,/*Complain*/true))3708    return true;3709  Pattern = PatternDef;3710 3711  // Record the point of instantiation.3712  if (MemberSpecializationInfo *MSInfo3713        = Instantiation->getMemberSpecializationInfo()) {3714    MSInfo->setTemplateSpecializationKind(TSK);3715    MSInfo->setPointOfInstantiation(PointOfInstantiation);3716  }3717 3718  NonSFINAEContext _(*this);3719  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);3720  if (Inst.isInvalid())3721    return true;3722  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),3723                                      "instantiating enum definition");3724 3725  // The instantiation is visible here, even if it was first declared in an3726  // unimported module.3727  Instantiation->setVisibleDespiteOwningModule();3728 3729  // Enter the scope of this instantiation. We don't use3730  // PushDeclContext because we don't have a scope.3731  ContextRAII SavedContext(*this, Instantiation);3732  EnterExpressionEvaluationContext EvalContext(3733      *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);3734 3735  LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);3736 3737  // Pull attributes from the pattern onto the instantiation.3738  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);3739 3740  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);3741  Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);3742 3743  // Exit the scope of this instantiation.3744  SavedContext.pop();3745 3746  return Instantiation->isInvalidDecl();3747}3748 3749bool Sema::InstantiateInClassInitializer(3750    SourceLocation PointOfInstantiation, FieldDecl *Instantiation,3751    FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {3752  // If there is no initializer, we don't need to do anything.3753  if (!Pattern->hasInClassInitializer())3754    return false;3755 3756  assert(Instantiation->getInClassInitStyle() ==3757             Pattern->getInClassInitStyle() &&3758         "pattern and instantiation disagree about init style");3759 3760  RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,3761                                          RecursiveInstGuard::Kind::Template);3762  if (AlreadyInstantiating)3763    // Error out if we hit an instantiation cycle for this initializer.3764    return Diag(PointOfInstantiation,3765                diag::err_default_member_initializer_cycle)3766           << Instantiation;3767 3768  // Error out if we haven't parsed the initializer of the pattern yet because3769  // we are waiting for the closing brace of the outer class.3770  Expr *OldInit = Pattern->getInClassInitializer();3771  if (!OldInit) {3772    RecordDecl *PatternRD = Pattern->getParent();3773    RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();3774    Diag(PointOfInstantiation,3775         diag::err_default_member_initializer_not_yet_parsed)3776        << OutermostClass << Pattern;3777    Diag(Pattern->getEndLoc(),3778         diag::note_default_member_initializer_not_yet_parsed);3779    Instantiation->setInvalidDecl();3780    return true;3781  }3782 3783  NonSFINAEContext _(*this);3784  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);3785  if (Inst.isInvalid())3786    return true;3787  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),3788                                      "instantiating default member init");3789 3790  // Enter the scope of this instantiation. We don't use PushDeclContext because3791  // we don't have a scope.3792  ContextRAII SavedContext(*this, Instantiation->getParent());3793  EnterExpressionEvaluationContext EvalContext(3794      *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);3795  ExprEvalContexts.back().DelayedDefaultInitializationContext = {3796      PointOfInstantiation, Instantiation, CurContext};3797 3798  LocalInstantiationScope Scope(*this, true);3799 3800  // Instantiate the initializer.3801  ActOnStartCXXInClassMemberInitializer();3802  CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());3803 3804  ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,3805                                        /*CXXDirectInit=*/false);3806  Expr *Init = NewInit.get();3807  assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");3808  ActOnFinishCXXInClassMemberInitializer(3809      Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);3810 3811  if (auto *L = getASTMutationListener())3812    L->DefaultMemberInitializerInstantiated(Instantiation);3813 3814  // Return true if the in-class initializer is still missing.3815  return !Instantiation->getInClassInitializer();3816}3817 3818namespace {3819  /// A partial specialization whose template arguments have matched3820  /// a given template-id.3821  struct PartialSpecMatchResult {3822    ClassTemplatePartialSpecializationDecl *Partial;3823    TemplateArgumentList *Args;3824  };3825}3826 3827bool Sema::usesPartialOrExplicitSpecialization(3828    SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {3829  if (ClassTemplateSpec->getTemplateSpecializationKind() ==3830      TSK_ExplicitSpecialization)3831    return true;3832 3833  SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;3834  ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();3835  CTD->getPartialSpecializations(PartialSpecs);3836  for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {3837    // C++ [temp.spec.partial.member]p2:3838    //   If the primary member template is explicitly specialized for a given3839    //   (implicit) specialization of the enclosing class template, the partial3840    //   specializations of the member template are ignored for this3841    //   specialization of the enclosing class template. If a partial3842    //   specialization of the member template is explicitly specialized for a3843    //   given (implicit) specialization of the enclosing class template, the3844    //   primary member template and its other partial specializations are still3845    //   considered for this specialization of the enclosing class template.3846    if (CTD->getMostRecentDecl()->isMemberSpecialization() &&3847        !CTPSD->getMostRecentDecl()->isMemberSpecialization())3848      continue;3849 3850    TemplateDeductionInfo Info(Loc);3851    if (DeduceTemplateArguments(CTPSD,3852                                ClassTemplateSpec->getTemplateArgs().asArray(),3853                                Info) == TemplateDeductionResult::Success)3854      return true;3855  }3856 3857  return false;3858}3859 3860/// Get the instantiation pattern to use to instantiate the definition of a3861/// given ClassTemplateSpecializationDecl (either the pattern of the primary3862/// template or of a partial specialization).3863static ActionResult<CXXRecordDecl *> getPatternForClassTemplateSpecialization(3864    Sema &S, SourceLocation PointOfInstantiation,3865    ClassTemplateSpecializationDecl *ClassTemplateSpec,3866    TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) {3867  std::optional<Sema::NonSFINAEContext> NSC(S);3868  Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);3869  if (Inst.isInvalid())3870    return {/*Invalid=*/true};3871 3872  llvm::PointerUnion<ClassTemplateDecl *,3873                     ClassTemplatePartialSpecializationDecl *>3874      Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();3875  if (!isa<ClassTemplatePartialSpecializationDecl *>(Specialized)) {3876    // Find best matching specialization.3877    ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();3878 3879    // C++ [temp.class.spec.match]p1:3880    //   When a class template is used in a context that requires an3881    //   instantiation of the class, it is necessary to determine3882    //   whether the instantiation is to be generated using the primary3883    //   template or one of the partial specializations. This is done by3884    //   matching the template arguments of the class template3885    //   specialization with the template argument lists of the partial3886    //   specializations.3887    typedef PartialSpecMatchResult MatchResult;3888    SmallVector<MatchResult, 4> Matched, ExtraMatched;3889    SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;3890    Template->getPartialSpecializations(PartialSpecs);3891    TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);3892    for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {3893      // C++ [temp.spec.partial.member]p2:3894      //   If the primary member template is explicitly specialized for a given3895      //   (implicit) specialization of the enclosing class template, the3896      //   partial specializations of the member template are ignored for this3897      //   specialization of the enclosing class template. If a partial3898      //   specialization of the member template is explicitly specialized for a3899      //   given (implicit) specialization of the enclosing class template, the3900      //   primary member template and its other partial specializations are3901      //   still considered for this specialization of the enclosing class3902      //   template.3903      if (Template->getMostRecentDecl()->isMemberSpecialization() &&3904          !Partial->getMostRecentDecl()->isMemberSpecialization())3905        continue;3906 3907      TemplateDeductionInfo Info(FailedCandidates.getLocation());3908      if (TemplateDeductionResult Result = S.DeduceTemplateArguments(3909              Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);3910          Result != TemplateDeductionResult::Success) {3911        // Store the failed-deduction information for use in diagnostics, later.3912        // TODO: Actually use the failed-deduction info?3913        FailedCandidates.addCandidate().set(3914            DeclAccessPair::make(Template, AS_public), Partial,3915            MakeDeductionFailureInfo(S.Context, Result, Info));3916        (void)Result;3917      } else {3918        auto &List = Info.hasStrictPackMatch() ? ExtraMatched : Matched;3919        List.push_back(MatchResult{Partial, Info.takeCanonical()});3920      }3921    }3922    if (Matched.empty() && PrimaryStrictPackMatch)3923      Matched = std::move(ExtraMatched);3924 3925    // If we're dealing with a member template where the template parameters3926    // have been instantiated, this provides the original template parameters3927    // from which the member template's parameters were instantiated.3928 3929    if (Matched.size() >= 1) {3930      SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();3931      if (Matched.size() == 1) {3932        //   -- If exactly one matching specialization is found, the3933        //      instantiation is generated from that specialization.3934        // We don't need to do anything for this.3935      } else {3936        //   -- If more than one matching specialization is found, the3937        //      partial order rules (14.5.4.2) are used to determine3938        //      whether one of the specializations is more specialized3939        //      than the others. If none of the specializations is more3940        //      specialized than all of the other matching3941        //      specializations, then the use of the class template is3942        //      ambiguous and the program is ill-formed.3943        for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,3944                                                 PEnd = Matched.end();3945             P != PEnd; ++P) {3946          if (S.getMoreSpecializedPartialSpecialization(3947                  P->Partial, Best->Partial, PointOfInstantiation) ==3948              P->Partial)3949            Best = P;3950        }3951 3952        // Determine if the best partial specialization is more specialized than3953        // the others.3954        bool Ambiguous = false;3955        for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),3956                                                 PEnd = Matched.end();3957             P != PEnd; ++P) {3958          if (P != Best && S.getMoreSpecializedPartialSpecialization(3959                               P->Partial, Best->Partial,3960                               PointOfInstantiation) != Best->Partial) {3961            Ambiguous = true;3962            break;3963          }3964        }3965 3966        if (Ambiguous) {3967          // Partial ordering did not produce a clear winner. Complain.3968          Inst.Clear();3969          NSC.reset();3970          S.Diag(PointOfInstantiation,3971                 diag::err_partial_spec_ordering_ambiguous)3972              << ClassTemplateSpec;3973 3974          // Print the matching partial specializations.3975          for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),3976                                                   PEnd = Matched.end();3977               P != PEnd; ++P)3978            S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)3979                << S.getTemplateArgumentBindingsText(3980                       P->Partial->getTemplateParameters(), *P->Args);3981 3982          return {/*Invalid=*/true};3983        }3984      }3985 3986      ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);3987    } else {3988      //   -- If no matches are found, the instantiation is generated3989      //      from the primary template.3990    }3991  }3992 3993  CXXRecordDecl *Pattern = nullptr;3994  Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();3995  if (auto *PartialSpec =3996          Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {3997    // Instantiate using the best class template partial specialization.3998    while (PartialSpec->getInstantiatedFromMember()) {3999      // If we've found an explicit specialization of this class template,4000      // stop here and use that as the pattern.4001      if (PartialSpec->isMemberSpecialization())4002        break;4003 4004      PartialSpec = PartialSpec->getInstantiatedFromMember();4005    }4006    Pattern = PartialSpec;4007  } else {4008    ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();4009    while (Template->getInstantiatedFromMemberTemplate()) {4010      // If we've found an explicit specialization of this class template,4011      // stop here and use that as the pattern.4012      if (Template->isMemberSpecialization())4013        break;4014 4015      Template = Template->getInstantiatedFromMemberTemplate();4016    }4017    Pattern = Template->getTemplatedDecl();4018  }4019 4020  return Pattern;4021}4022 4023bool Sema::InstantiateClassTemplateSpecialization(4024    SourceLocation PointOfInstantiation,4025    ClassTemplateSpecializationDecl *ClassTemplateSpec,4026    TemplateSpecializationKind TSK, bool Complain,4027    bool PrimaryStrictPackMatch) {4028  // Perform the actual instantiation on the canonical declaration.4029  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(4030      ClassTemplateSpec->getCanonicalDecl());4031  if (ClassTemplateSpec->isInvalidDecl())4032    return true;4033 4034  Sema::RecursiveInstGuard AlreadyInstantiating(4035      *this, ClassTemplateSpec, Sema::RecursiveInstGuard::Kind::Template);4036  if (AlreadyInstantiating)4037    return false;4038 4039  bool HadAvaibilityWarning =4040      ShouldDiagnoseAvailabilityOfDecl(ClassTemplateSpec, nullptr, nullptr)4041          .first != AR_Available;4042 4043  ActionResult<CXXRecordDecl *> Pattern =4044      getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,4045                                               ClassTemplateSpec, TSK,4046                                               PrimaryStrictPackMatch);4047 4048  if (!Pattern.isUsable())4049    return Pattern.isInvalid();4050 4051  bool Err = InstantiateClassImpl(4052      PointOfInstantiation, ClassTemplateSpec, Pattern.get(),4053      getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);4054 4055  // If we haven't already warn on avaibility, consider the avaibility4056  // attributes of the partial specialization.4057  // Note that - because we need to have deduced the partial specialization -4058  // We can only emit these warnings when the specialization is instantiated.4059  if (!Err && !HadAvaibilityWarning) {4060    assert(ClassTemplateSpec->getTemplateSpecializationKind() !=4061           TSK_Undeclared);4062    DiagnoseAvailabilityOfDecl(ClassTemplateSpec, PointOfInstantiation);4063  }4064  return Err;4065}4066 4067void4068Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,4069                              CXXRecordDecl *Instantiation,4070                        const MultiLevelTemplateArgumentList &TemplateArgs,4071                              TemplateSpecializationKind TSK) {4072  // FIXME: We need to notify the ASTMutationListener that we did all of these4073  // things, in case we have an explicit instantiation definition in a PCM, a4074  // module, or preamble, and the declaration is in an imported AST.4075  assert(4076      (TSK == TSK_ExplicitInstantiationDefinition ||4077       TSK == TSK_ExplicitInstantiationDeclaration ||4078       (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&4079      "Unexpected template specialization kind!");4080  for (auto *D : Instantiation->decls()) {4081    bool SuppressNew = false;4082    if (auto *Function = dyn_cast<FunctionDecl>(D)) {4083      if (FunctionDecl *Pattern =4084              Function->getInstantiatedFromMemberFunction()) {4085 4086        if (Function->getTrailingRequiresClause()) {4087          ConstraintSatisfaction Satisfaction;4088          if (CheckFunctionConstraints(Function, Satisfaction) ||4089              !Satisfaction.IsSatisfied) {4090            continue;4091          }4092        }4093 4094        if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())4095          continue;4096 4097        TemplateSpecializationKind PrevTSK =4098            Function->getTemplateSpecializationKind();4099        if (PrevTSK == TSK_ExplicitSpecialization)4100          continue;4101 4102        if (CheckSpecializationInstantiationRedecl(4103                PointOfInstantiation, TSK, Function, PrevTSK,4104                Function->getPointOfInstantiation(), SuppressNew) ||4105            SuppressNew)4106          continue;4107 4108        // C++11 [temp.explicit]p8:4109        //   An explicit instantiation definition that names a class template4110        //   specialization explicitly instantiates the class template4111        //   specialization and is only an explicit instantiation definition4112        //   of members whose definition is visible at the point of4113        //   instantiation.4114        if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())4115          continue;4116 4117        Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);4118 4119        if (Function->isDefined()) {4120          // Let the ASTConsumer know that this function has been explicitly4121          // instantiated now, and its linkage might have changed.4122          Consumer.HandleTopLevelDecl(DeclGroupRef(Function));4123        } else if (TSK == TSK_ExplicitInstantiationDefinition) {4124          InstantiateFunctionDefinition(PointOfInstantiation, Function);4125        } else if (TSK == TSK_ImplicitInstantiation) {4126          PendingLocalImplicitInstantiations.push_back(4127              std::make_pair(Function, PointOfInstantiation));4128        }4129      }4130    } else if (auto *Var = dyn_cast<VarDecl>(D)) {4131      if (isa<VarTemplateSpecializationDecl>(Var))4132        continue;4133 4134      if (Var->isStaticDataMember()) {4135        if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())4136          continue;4137 4138        MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();4139        assert(MSInfo && "No member specialization information?");4140        if (MSInfo->getTemplateSpecializationKind()4141                                                 == TSK_ExplicitSpecialization)4142          continue;4143 4144        if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,4145                                                   Var,4146                                        MSInfo->getTemplateSpecializationKind(),4147                                              MSInfo->getPointOfInstantiation(),4148                                                   SuppressNew) ||4149            SuppressNew)4150          continue;4151 4152        if (TSK == TSK_ExplicitInstantiationDefinition) {4153          // C++0x [temp.explicit]p8:4154          //   An explicit instantiation definition that names a class template4155          //   specialization explicitly instantiates the class template4156          //   specialization and is only an explicit instantiation definition4157          //   of members whose definition is visible at the point of4158          //   instantiation.4159          if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())4160            continue;4161 4162          Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);4163          InstantiateVariableDefinition(PointOfInstantiation, Var);4164        } else {4165          Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);4166        }4167      }4168    } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {4169      if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())4170        continue;4171 4172      // Always skip the injected-class-name, along with any4173      // redeclarations of nested classes, since both would cause us4174      // to try to instantiate the members of a class twice.4175      // Skip closure types; they'll get instantiated when we instantiate4176      // the corresponding lambda-expression.4177      if (Record->isInjectedClassName() || Record->getPreviousDecl() ||4178          Record->isLambda())4179        continue;4180 4181      MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();4182      assert(MSInfo && "No member specialization information?");4183 4184      if (MSInfo->getTemplateSpecializationKind()4185                                                == TSK_ExplicitSpecialization)4186        continue;4187 4188      if (Context.getTargetInfo().getTriple().isOSWindows() &&4189          TSK == TSK_ExplicitInstantiationDeclaration) {4190        // On Windows, explicit instantiation decl of the outer class doesn't4191        // affect the inner class. Typically extern template declarations are4192        // used in combination with dll import/export annotations, but those4193        // are not propagated from the outer class templates to inner classes.4194        // Therefore, do not instantiate inner classes on this platform, so4195        // that users don't end up with undefined symbols during linking.4196        continue;4197      }4198 4199      if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,4200                                                 Record,4201                                        MSInfo->getTemplateSpecializationKind(),4202                                              MSInfo->getPointOfInstantiation(),4203                                                 SuppressNew) ||4204          SuppressNew)4205        continue;4206 4207      CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();4208      assert(Pattern && "Missing instantiated-from-template information");4209 4210      if (!Record->getDefinition()) {4211        if (!Pattern->getDefinition()) {4212          // C++0x [temp.explicit]p8:4213          //   An explicit instantiation definition that names a class template4214          //   specialization explicitly instantiates the class template4215          //   specialization and is only an explicit instantiation definition4216          //   of members whose definition is visible at the point of4217          //   instantiation.4218          if (TSK == TSK_ExplicitInstantiationDeclaration) {4219            MSInfo->setTemplateSpecializationKind(TSK);4220            MSInfo->setPointOfInstantiation(PointOfInstantiation);4221          }4222 4223          continue;4224        }4225 4226        InstantiateClass(PointOfInstantiation, Record, Pattern,4227                         TemplateArgs,4228                         TSK);4229      } else {4230        if (TSK == TSK_ExplicitInstantiationDefinition &&4231            Record->getTemplateSpecializationKind() ==4232                TSK_ExplicitInstantiationDeclaration) {4233          Record->setTemplateSpecializationKind(TSK);4234          MarkVTableUsed(PointOfInstantiation, Record, true);4235        }4236      }4237 4238      Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());4239      if (Pattern)4240        InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,4241                                TSK);4242    } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {4243      MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();4244      assert(MSInfo && "No member specialization information?");4245 4246      if (MSInfo->getTemplateSpecializationKind()4247            == TSK_ExplicitSpecialization)4248        continue;4249 4250      if (CheckSpecializationInstantiationRedecl(4251            PointOfInstantiation, TSK, Enum,4252            MSInfo->getTemplateSpecializationKind(),4253            MSInfo->getPointOfInstantiation(), SuppressNew) ||4254          SuppressNew)4255        continue;4256 4257      if (Enum->getDefinition())4258        continue;4259 4260      EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();4261      assert(Pattern && "Missing instantiated-from-template information");4262 4263      if (TSK == TSK_ExplicitInstantiationDefinition) {4264        if (!Pattern->getDefinition())4265          continue;4266 4267        InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);4268      } else {4269        MSInfo->setTemplateSpecializationKind(TSK);4270        MSInfo->setPointOfInstantiation(PointOfInstantiation);4271      }4272    } else if (auto *Field = dyn_cast<FieldDecl>(D)) {4273      // No need to instantiate in-class initializers during explicit4274      // instantiation.4275      if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {4276        // Handle local classes which could have substituted template params.4277        CXXRecordDecl *ClassPattern =4278            Instantiation->isLocalClass()4279                ? Instantiation->getInstantiatedFromMemberClass()4280                : Instantiation->getTemplateInstantiationPattern();4281 4282        DeclContext::lookup_result Lookup =4283            ClassPattern->lookup(Field->getDeclName());4284        FieldDecl *Pattern = Lookup.find_first<FieldDecl>();4285        assert(Pattern);4286        InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,4287                                      TemplateArgs);4288      }4289    }4290  }4291}4292 4293void4294Sema::InstantiateClassTemplateSpecializationMembers(4295                                           SourceLocation PointOfInstantiation,4296                            ClassTemplateSpecializationDecl *ClassTemplateSpec,4297                                               TemplateSpecializationKind TSK) {4298  // C++0x [temp.explicit]p7:4299  //   An explicit instantiation that names a class template4300  //   specialization is an explicit instantion of the same kind4301  //   (declaration or definition) of each of its members (not4302  //   including members inherited from base classes) that has not4303  //   been previously explicitly specialized in the translation unit4304  //   containing the explicit instantiation, except as described4305  //   below.4306  InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,4307                          getTemplateInstantiationArgs(ClassTemplateSpec),4308                          TSK);4309}4310 4311StmtResult4312Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {4313  if (!S)4314    return S;4315 4316  TemplateInstantiator Instantiator(*this, TemplateArgs,4317                                    SourceLocation(),4318                                    DeclarationName());4319  return Instantiator.TransformStmt(S);4320}4321 4322bool Sema::SubstTemplateArgument(4323    const TemplateArgumentLoc &Input,4324    const MultiLevelTemplateArgumentList &TemplateArgs,4325    TemplateArgumentLoc &Output, SourceLocation Loc,4326    const DeclarationName &Entity) {4327  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);4328  return Instantiator.TransformTemplateArgument(Input, Output);4329}4330 4331bool Sema::SubstTemplateArguments(4332    ArrayRef<TemplateArgumentLoc> Args,4333    const MultiLevelTemplateArgumentList &TemplateArgs,4334    TemplateArgumentListInfo &Out) {4335  TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),4336                                    DeclarationName());4337  return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);4338}4339 4340bool Sema::SubstTemplateArgumentsInParameterMapping(4341    ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,4342    const MultiLevelTemplateArgumentList &TemplateArgs,4343    TemplateArgumentListInfo &Out, bool BuildPackExpansionTypes) {4344  TemplateInstantiator Instantiator(4345      TemplateInstantiator::ForParameterMappingSubstitution, *this, BaseLoc,4346      TemplateArgs, BuildPackExpansionTypes);4347  return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);4348}4349 4350ExprResult4351Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {4352  if (!E)4353    return E;4354 4355  TemplateInstantiator Instantiator(*this, TemplateArgs,4356                                    SourceLocation(),4357                                    DeclarationName());4358  return Instantiator.TransformExpr(E);4359}4360 4361ExprResult4362Sema::SubstCXXIdExpr(Expr *E,4363                     const MultiLevelTemplateArgumentList &TemplateArgs) {4364  if (!E)4365    return E;4366 4367  TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),4368                                    DeclarationName());4369  return Instantiator.TransformAddressOfOperand(E);4370}4371 4372ExprResult4373Sema::SubstConstraintExpr(Expr *E,4374                          const MultiLevelTemplateArgumentList &TemplateArgs) {4375  // FIXME: should call SubstExpr directly if this function is equivalent or4376  //        should it be different?4377  return SubstExpr(E, TemplateArgs);4378}4379 4380ExprResult Sema::SubstConstraintExprWithoutSatisfaction(4381    Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {4382  if (!E)4383    return E;4384 4385  TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),4386                                    DeclarationName());4387  Instantiator.setEvaluateConstraints(false);4388  return Instantiator.TransformExpr(E);4389}4390 4391ExprResult Sema::SubstConceptTemplateArguments(4392    const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr,4393    const MultiLevelTemplateArgumentList &MLTAL) {4394  TemplateInstantiator Instantiator(*this, MLTAL, SourceLocation(),4395                                    DeclarationName());4396  const ASTTemplateArgumentListInfo *ArgsAsWritten =4397      CSE->getTemplateArgsAsWritten();4398  TemplateArgumentListInfo SubstArgs(ArgsAsWritten->getLAngleLoc(),4399                                     ArgsAsWritten->getRAngleLoc());4400 4401  NonSFINAEContext _(*this);4402  Sema::InstantiatingTemplate Inst(4403      *this, ArgsAsWritten->arguments().front().getSourceRange().getBegin(),4404      Sema::InstantiatingTemplate::ConstraintNormalization{},4405      CSE->getNamedConcept(),4406      ArgsAsWritten->arguments().front().getSourceRange());4407 4408  if (Inst.isInvalid())4409    return ExprError();4410 4411  if (Instantiator.TransformConceptTemplateArguments(4412          ArgsAsWritten->getTemplateArgs(),4413          ArgsAsWritten->getTemplateArgs() +4414              ArgsAsWritten->getNumTemplateArgs(),4415          SubstArgs))4416    return true;4417 4418  llvm::SmallVector<TemplateArgument, 4> NewArgList = llvm::map_to_vector(4419      SubstArgs.arguments(),4420      [](const TemplateArgumentLoc &Loc) { return Loc.getArgument(); });4421 4422  MultiLevelTemplateArgumentList MLTALForConstraint =4423      getTemplateInstantiationArgs(4424          CSE->getNamedConcept(),4425          CSE->getNamedConcept()->getLexicalDeclContext(),4426          /*Final=*/false,4427          /*Innermost=*/NewArgList,4428          /*RelativeToPrimary=*/true,4429          /*Pattern=*/nullptr,4430          /*ForConstraintInstantiation=*/true);4431 4432  // Rebuild a constraint, only substituting non-dependent concept names4433  // and nothing else.4434  // Given C<SomeType, SomeValue, SomeConceptName, SomeDependentConceptName>.4435  // only SomeConceptName is substituted, in the constraint expression of C.4436  struct ConstraintExprTransformer : TreeTransform<ConstraintExprTransformer> {4437    using Base = TreeTransform<ConstraintExprTransformer>;4438    MultiLevelTemplateArgumentList &MLTAL;4439 4440    ConstraintExprTransformer(Sema &SemaRef,4441                              MultiLevelTemplateArgumentList &MLTAL)4442        : TreeTransform(SemaRef), MLTAL(MLTAL) {}4443 4444    ExprResult TransformExpr(Expr *E) {4445      if (!E)4446        return E;4447      switch (E->getStmtClass()) {4448      case Stmt::BinaryOperatorClass:4449      case Stmt::ConceptSpecializationExprClass:4450      case Stmt::ParenExprClass:4451      case Stmt::UnresolvedLookupExprClass:4452        return Base::TransformExpr(E);4453      default:4454        break;4455      }4456      return E;4457    }4458 4459    // Rebuild both branches of a conjunction / disjunction4460    // even if there is a substitution failure in one of4461    // the branch.4462    ExprResult TransformBinaryOperator(BinaryOperator *E) {4463      if (!(E->getOpcode() == BinaryOperatorKind::BO_LAnd ||4464            E->getOpcode() == BinaryOperatorKind::BO_LOr))4465        return E;4466 4467      ExprResult LHS = TransformExpr(E->getLHS());4468      ExprResult RHS = TransformExpr(E->getRHS());4469 4470      if (LHS.get() == E->getLHS() && RHS.get() == E->getRHS())4471        return E;4472 4473      return BinaryOperator::Create(SemaRef.Context, LHS.get(), RHS.get(),4474                                    E->getOpcode(), SemaRef.Context.BoolTy,4475                                    VK_PRValue, OK_Ordinary,4476                                    E->getOperatorLoc(), FPOptionsOverride{});4477    }4478 4479    bool TransformTemplateArgument(const TemplateArgumentLoc &Input,4480                                   TemplateArgumentLoc &Output,4481                                   bool Uneval = false) {4482      if (Input.getArgument().isConceptOrConceptTemplateParameter())4483        return Base::TransformTemplateArgument(Input, Output, Uneval);4484 4485      Output = Input;4486      return false;4487    }4488 4489    ExprResult TransformUnresolvedLookupExpr(UnresolvedLookupExpr *E,4490                                             bool IsAddressOfOperand = false) {4491      if (E->isConceptReference()) {4492        ExprResult Res = SemaRef.SubstExpr(E, MLTAL);4493        return Res;4494      }4495      return E;4496    }4497  };4498 4499  ConstraintExprTransformer Transformer(*this, MLTALForConstraint);4500  ExprResult Res =4501      Transformer.TransformExpr(const_cast<Expr *>(ConstraintExpr));4502  return Res;4503}4504 4505ExprResult Sema::SubstInitializer(Expr *Init,4506                          const MultiLevelTemplateArgumentList &TemplateArgs,4507                          bool CXXDirectInit) {4508  TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),4509                                    DeclarationName());4510  return Instantiator.TransformInitializer(Init, CXXDirectInit);4511}4512 4513bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,4514                      const MultiLevelTemplateArgumentList &TemplateArgs,4515                      SmallVectorImpl<Expr *> &Outputs) {4516  if (Exprs.empty())4517    return false;4518 4519  TemplateInstantiator Instantiator(*this, TemplateArgs,4520                                    SourceLocation(),4521                                    DeclarationName());4522  return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),4523                                     IsCall, Outputs);4524}4525 4526NestedNameSpecifierLoc4527Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,4528                        const MultiLevelTemplateArgumentList &TemplateArgs) {4529  if (!NNS)4530    return NestedNameSpecifierLoc();4531 4532  TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),4533                                    DeclarationName());4534  return Instantiator.TransformNestedNameSpecifierLoc(NNS);4535}4536 4537DeclarationNameInfo4538Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,4539                         const MultiLevelTemplateArgumentList &TemplateArgs) {4540  TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),4541                                    NameInfo.getName());4542  return Instantiator.TransformDeclarationNameInfo(NameInfo);4543}4544 4545TemplateName4546Sema::SubstTemplateName(SourceLocation TemplateKWLoc,4547                        NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,4548                        SourceLocation NameLoc,4549                        const MultiLevelTemplateArgumentList &TemplateArgs) {4550  TemplateInstantiator Instantiator(*this, TemplateArgs, NameLoc,4551                                    DeclarationName());4552  return Instantiator.TransformTemplateName(QualifierLoc, TemplateKWLoc, Name,4553                                            NameLoc);4554}4555 4556static const Decl *getCanonicalParmVarDecl(const Decl *D) {4557  // When storing ParmVarDecls in the local instantiation scope, we always4558  // want to use the ParmVarDecl from the canonical function declaration,4559  // since the map is then valid for any redeclaration or definition of that4560  // function.4561  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {4562    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {4563      unsigned i = PV->getFunctionScopeIndex();4564      // This parameter might be from a freestanding function type within the4565      // function and isn't necessarily referring to one of FD's parameters.4566      if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)4567        return FD->getCanonicalDecl()->getParamDecl(i);4568    }4569  }4570  return D;4571}4572 4573llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *4574LocalInstantiationScope::getInstantiationOfIfExists(const Decl *D) {4575  D = getCanonicalParmVarDecl(D);4576  for (LocalInstantiationScope *Current = this; Current;4577       Current = Current->Outer) {4578 4579    // Check if we found something within this scope.4580    const Decl *CheckD = D;4581    do {4582      LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);4583      if (Found != Current->LocalDecls.end())4584        return &Found->second;4585 4586      // If this is a tag declaration, it's possible that we need to look for4587      // a previous declaration.4588      if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))4589        CheckD = Tag->getPreviousDecl();4590      else4591        CheckD = nullptr;4592    } while (CheckD);4593 4594    // If we aren't combined with our outer scope, we're done.4595    if (!Current->CombineWithOuterScope)4596      break;4597  }4598 4599  return nullptr;4600}4601 4602llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *4603LocalInstantiationScope::findInstantiationOf(const Decl *D) {4604  auto *Result = getInstantiationOfIfExists(D);4605  if (Result)4606    return Result;4607  // If we're performing a partial substitution during template argument4608  // deduction, we may not have values for template parameters yet.4609  if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||4610      isa<TemplateTemplateParmDecl>(D))4611    return nullptr;4612 4613  // Local types referenced prior to definition may require instantiation.4614  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))4615    if (RD->isLocalClass())4616      return nullptr;4617 4618  // Enumeration types referenced prior to definition may appear as a result of4619  // error recovery.4620  if (isa<EnumDecl>(D))4621    return nullptr;4622 4623  // Materialized typedefs/type alias for implicit deduction guides may require4624  // instantiation.4625  if (isa<TypedefNameDecl>(D) &&4626      isa<CXXDeductionGuideDecl>(D->getDeclContext()))4627    return nullptr;4628 4629  // If we didn't find the decl, then we either have a sema bug, or we have a4630  // forward reference to a label declaration.  Return null to indicate that4631  // we have an uninstantiated label.4632  assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");4633  return nullptr;4634}4635 4636void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {4637  D = getCanonicalParmVarDecl(D);4638  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];4639  if (Stored.isNull()) {4640#ifndef NDEBUG4641    // It should not be present in any surrounding scope either.4642    LocalInstantiationScope *Current = this;4643    while (Current->CombineWithOuterScope && Current->Outer) {4644      Current = Current->Outer;4645      assert(!Current->LocalDecls.contains(D) &&4646             "Instantiated local in inner and outer scopes");4647    }4648#endif4649    Stored = Inst;4650  } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Stored)) {4651    Pack->push_back(cast<ValueDecl>(Inst));4652  } else {4653    assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");4654  }4655}4656 4657void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,4658                                                       VarDecl *Inst) {4659  D = getCanonicalParmVarDecl(D);4660  DeclArgumentPack *Pack = cast<DeclArgumentPack *>(LocalDecls[D]);4661  Pack->push_back(Inst);4662}4663 4664void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {4665#ifndef NDEBUG4666  // This should be the first time we've been told about this decl.4667  for (LocalInstantiationScope *Current = this;4668       Current && Current->CombineWithOuterScope; Current = Current->Outer)4669    assert(!Current->LocalDecls.contains(D) &&4670           "Creating local pack after instantiation of local");4671#endif4672 4673  D = getCanonicalParmVarDecl(D);4674  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];4675  DeclArgumentPack *Pack = new DeclArgumentPack;4676  Stored = Pack;4677  ArgumentPacks.push_back(Pack);4678}4679 4680bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) {4681  for (DeclArgumentPack *Pack : ArgumentPacks)4682    if (llvm::is_contained(*Pack, D))4683      return true;4684  return false;4685}4686 4687void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,4688                                          const TemplateArgument *ExplicitArgs,4689                                                    unsigned NumExplicitArgs) {4690  assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&4691         "Already have a partially-substituted pack");4692  assert((!PartiallySubstitutedPack4693          || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&4694         "Wrong number of arguments in partially-substituted pack");4695  PartiallySubstitutedPack = Pack;4696  ArgsInPartiallySubstitutedPack = ExplicitArgs;4697  NumArgsInPartiallySubstitutedPack = NumExplicitArgs;4698}4699 4700NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(4701                                         const TemplateArgument **ExplicitArgs,4702                                              unsigned *NumExplicitArgs) const {4703  if (ExplicitArgs)4704    *ExplicitArgs = nullptr;4705  if (NumExplicitArgs)4706    *NumExplicitArgs = 0;4707 4708  for (const LocalInstantiationScope *Current = this; Current;4709       Current = Current->Outer) {4710    if (Current->PartiallySubstitutedPack) {4711      if (ExplicitArgs)4712        *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;4713      if (NumExplicitArgs)4714        *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;4715 4716      return Current->PartiallySubstitutedPack;4717    }4718 4719    if (!Current->CombineWithOuterScope)4720      break;4721  }4722 4723  return nullptr;4724}4725