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