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