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