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