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