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