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