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