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