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