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