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