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