clang API Documentation

SemaTemplateInstantiate.cpp
Go to the documentation of this file.
00001 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //===----------------------------------------------------------------------===/
00008 //
00009 //  This file implements C++ template instantiation.
00010 //
00011 //===----------------------------------------------------------------------===/
00012 
00013 #include "clang/Sema/SemaInternal.h"
00014 #include "TreeTransform.h"
00015 #include "clang/Sema/DeclSpec.h"
00016 #include "clang/Sema/Initialization.h"
00017 #include "clang/Sema/Lookup.h"
00018 #include "clang/Sema/Template.h"
00019 #include "clang/Sema/TemplateDeduction.h"
00020 #include "clang/AST/ASTConsumer.h"
00021 #include "clang/AST/ASTContext.h"
00022 #include "clang/AST/Expr.h"
00023 #include "clang/AST/DeclTemplate.h"
00024 #include "clang/Basic/LangOptions.h"
00025 
00026 using namespace clang;
00027 using namespace sema;
00028 
00029 //===----------------------------------------------------------------------===/
00030 // Template Instantiation Support
00031 //===----------------------------------------------------------------------===/
00032 
00033 /// \brief Retrieve the template argument list(s) that should be used to
00034 /// instantiate the definition of the given declaration.
00035 ///
00036 /// \param D the declaration for which we are computing template instantiation
00037 /// arguments.
00038 ///
00039 /// \param Innermost if non-NULL, the innermost template argument list.
00040 ///
00041 /// \param RelativeToPrimary true if we should get the template
00042 /// arguments relative to the primary template, even when we're
00043 /// dealing with a specialization. This is only relevant for function
00044 /// template specializations.
00045 ///
00046 /// \param Pattern If non-NULL, indicates the pattern from which we will be
00047 /// instantiating the definition of the given declaration, \p D. This is
00048 /// used to determine the proper set of template instantiation arguments for
00049 /// friend function template specializations.
00050 MultiLevelTemplateArgumentList
00051 Sema::getTemplateInstantiationArgs(NamedDecl *D, 
00052                                    const TemplateArgumentList *Innermost,
00053                                    bool RelativeToPrimary,
00054                                    const FunctionDecl *Pattern) {
00055   // Accumulate the set of template argument lists in this structure.
00056   MultiLevelTemplateArgumentList Result;
00057 
00058   if (Innermost)
00059     Result.addOuterTemplateArguments(Innermost);
00060   
00061   DeclContext *Ctx = dyn_cast<DeclContext>(D);
00062   if (!Ctx) {
00063     Ctx = D->getDeclContext();
00064     
00065     // If we have a template template parameter with translation unit context,
00066     // then we're performing substitution into a default template argument of
00067     // this template template parameter before we've constructed the template
00068     // that will own this template template parameter. In this case, we
00069     // use empty template parameter lists for all of the outer templates
00070     // to avoid performing any substitutions.
00071     if (Ctx->isTranslationUnit()) {
00072       if (TemplateTemplateParmDecl *TTP 
00073                                       = dyn_cast<TemplateTemplateParmDecl>(D)) {
00074         for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
00075           Result.addOuterTemplateArguments(0, 0);
00076         return Result;
00077       }
00078     }
00079   }
00080   
00081   while (!Ctx->isFileContext()) {
00082     // Add template arguments from a class template instantiation.
00083     if (ClassTemplateSpecializationDecl *Spec
00084           = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
00085       // We're done when we hit an explicit specialization.
00086       if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
00087           !isa<ClassTemplatePartialSpecializationDecl>(Spec))
00088         break;
00089 
00090       Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
00091       
00092       // If this class template specialization was instantiated from a 
00093       // specialized member that is a class template, we're done.
00094       assert(Spec->getSpecializedTemplate() && "No class template?");
00095       if (Spec->getSpecializedTemplate()->isMemberSpecialization())
00096         break;
00097     }
00098     // Add template arguments from a function template specialization.
00099     else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
00100       if (!RelativeToPrimary &&
00101           (Function->getTemplateSpecializationKind() == 
00102                                                   TSK_ExplicitSpecialization &&
00103            !Function->getClassScopeSpecializationPattern()))
00104         break;
00105           
00106       if (const TemplateArgumentList *TemplateArgs
00107             = Function->getTemplateSpecializationArgs()) {
00108         // Add the template arguments for this specialization.
00109         Result.addOuterTemplateArguments(TemplateArgs);
00110 
00111         // If this function was instantiated from a specialized member that is
00112         // a function template, we're done.
00113         assert(Function->getPrimaryTemplate() && "No function template?");
00114         if (Function->getPrimaryTemplate()->isMemberSpecialization())
00115           break;
00116       } else if (FunctionTemplateDecl *FunTmpl
00117                                    = Function->getDescribedFunctionTemplate()) {
00118         // Add the "injected" template arguments.
00119         std::pair<const TemplateArgument *, unsigned>
00120           Injected = FunTmpl->getInjectedTemplateArgs();
00121         Result.addOuterTemplateArguments(Injected.first, Injected.second);
00122       }
00123       
00124       // If this is a friend declaration and it declares an entity at
00125       // namespace scope, take arguments from its lexical parent
00126       // instead of its semantic parent, unless of course the pattern we're
00127       // instantiating actually comes from the file's context!
00128       if (Function->getFriendObjectKind() &&
00129           Function->getDeclContext()->isFileContext() &&
00130           (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
00131         Ctx = Function->getLexicalDeclContext();
00132         RelativeToPrimary = false;
00133         continue;
00134       }
00135     } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
00136       if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
00137         QualType T = ClassTemplate->getInjectedClassNameSpecialization();
00138         const TemplateSpecializationType *TST
00139           = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
00140         Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
00141         if (ClassTemplate->isMemberSpecialization())
00142           break;
00143       }
00144     }
00145 
00146     Ctx = Ctx->getParent();
00147     RelativeToPrimary = false;
00148   }
00149 
00150   return Result;
00151 }
00152 
00153 bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
00154   switch (Kind) {
00155   case TemplateInstantiation:
00156   case ExceptionSpecInstantiation:
00157   case DefaultTemplateArgumentInstantiation:
00158   case DefaultFunctionArgumentInstantiation:
00159     return true;
00160       
00161   case ExplicitTemplateArgumentSubstitution:
00162   case DeducedTemplateArgumentSubstitution:
00163   case PriorTemplateArgumentSubstitution:
00164   case DefaultTemplateArgumentChecking:
00165     return false;
00166   }
00167 
00168   llvm_unreachable("Invalid InstantiationKind!");
00169 }
00170 
00171 Sema::InstantiatingTemplate::
00172 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
00173                       Decl *Entity,
00174                       SourceRange InstantiationRange)
00175   : SemaRef(SemaRef),
00176     SavedInNonInstantiationSFINAEContext(
00177                                         SemaRef.InNonInstantiationSFINAEContext)
00178 {
00179   Invalid = CheckInstantiationDepth(PointOfInstantiation,
00180                                     InstantiationRange);
00181   if (!Invalid) {
00182     ActiveTemplateInstantiation Inst;
00183     Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
00184     Inst.PointOfInstantiation = PointOfInstantiation;
00185     Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
00186     Inst.TemplateArgs = 0;
00187     Inst.NumTemplateArgs = 0;
00188     Inst.InstantiationRange = InstantiationRange;
00189     SemaRef.InNonInstantiationSFINAEContext = false;
00190     SemaRef.ActiveTemplateInstantiations.push_back(Inst);
00191   }
00192 }
00193 
00194 Sema::InstantiatingTemplate::
00195 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
00196                       FunctionDecl *Entity, ExceptionSpecification,
00197                       SourceRange InstantiationRange)
00198   : SemaRef(SemaRef),
00199     SavedInNonInstantiationSFINAEContext(
00200                                         SemaRef.InNonInstantiationSFINAEContext)
00201 {
00202   Invalid = CheckInstantiationDepth(PointOfInstantiation,
00203                                     InstantiationRange);
00204   if (!Invalid) {
00205     ActiveTemplateInstantiation Inst;
00206     Inst.Kind = ActiveTemplateInstantiation::ExceptionSpecInstantiation;
00207     Inst.PointOfInstantiation = PointOfInstantiation;
00208     Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
00209     Inst.TemplateArgs = 0;
00210     Inst.NumTemplateArgs = 0;
00211     Inst.InstantiationRange = InstantiationRange;
00212     SemaRef.InNonInstantiationSFINAEContext = false;
00213     SemaRef.ActiveTemplateInstantiations.push_back(Inst);
00214   }
00215 }
00216 
00217 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
00218                                          SourceLocation PointOfInstantiation,
00219                                          TemplateDecl *Template,
00220                                          const TemplateArgument *TemplateArgs,
00221                                          unsigned NumTemplateArgs,
00222                                          SourceRange InstantiationRange)
00223   : SemaRef(SemaRef),
00224     SavedInNonInstantiationSFINAEContext(
00225                                      SemaRef.InNonInstantiationSFINAEContext)
00226 {
00227   Invalid = CheckInstantiationDepth(PointOfInstantiation,
00228                                     InstantiationRange);
00229   if (!Invalid) {
00230     ActiveTemplateInstantiation Inst;
00231     Inst.Kind
00232       = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
00233     Inst.PointOfInstantiation = PointOfInstantiation;
00234     Inst.Entity = reinterpret_cast<uintptr_t>(Template);
00235     Inst.TemplateArgs = TemplateArgs;
00236     Inst.NumTemplateArgs = NumTemplateArgs;
00237     Inst.InstantiationRange = InstantiationRange;
00238     SemaRef.InNonInstantiationSFINAEContext = false;
00239     SemaRef.ActiveTemplateInstantiations.push_back(Inst);
00240   }
00241 }
00242 
00243 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
00244                                          SourceLocation PointOfInstantiation,
00245                                       FunctionTemplateDecl *FunctionTemplate,
00246                                         const TemplateArgument *TemplateArgs,
00247                                                    unsigned NumTemplateArgs,
00248                          ActiveTemplateInstantiation::InstantiationKind Kind,
00249                                    sema::TemplateDeductionInfo &DeductionInfo,
00250                                               SourceRange InstantiationRange)
00251   : SemaRef(SemaRef),
00252     SavedInNonInstantiationSFINAEContext(
00253                                      SemaRef.InNonInstantiationSFINAEContext)
00254 {
00255   Invalid = CheckInstantiationDepth(PointOfInstantiation,
00256                                     InstantiationRange);
00257   if (!Invalid) {
00258     ActiveTemplateInstantiation Inst;
00259     Inst.Kind = Kind;
00260     Inst.PointOfInstantiation = PointOfInstantiation;
00261     Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
00262     Inst.TemplateArgs = TemplateArgs;
00263     Inst.NumTemplateArgs = NumTemplateArgs;
00264     Inst.DeductionInfo = &DeductionInfo;
00265     Inst.InstantiationRange = InstantiationRange;
00266     SemaRef.InNonInstantiationSFINAEContext = false;
00267     SemaRef.ActiveTemplateInstantiations.push_back(Inst);
00268     
00269     if (!Inst.isInstantiationRecord())
00270       ++SemaRef.NonInstantiationEntries;
00271   }
00272 }
00273 
00274 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
00275                                          SourceLocation PointOfInstantiation,
00276                           ClassTemplatePartialSpecializationDecl *PartialSpec,
00277                                          const TemplateArgument *TemplateArgs,
00278                                          unsigned NumTemplateArgs,
00279                                     sema::TemplateDeductionInfo &DeductionInfo,
00280                                          SourceRange InstantiationRange)
00281   : SemaRef(SemaRef),
00282     SavedInNonInstantiationSFINAEContext(
00283                                      SemaRef.InNonInstantiationSFINAEContext)
00284 {
00285   Invalid = false;
00286     
00287   ActiveTemplateInstantiation Inst;
00288   Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
00289   Inst.PointOfInstantiation = PointOfInstantiation;
00290   Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
00291   Inst.TemplateArgs = TemplateArgs;
00292   Inst.NumTemplateArgs = NumTemplateArgs;
00293   Inst.DeductionInfo = &DeductionInfo;
00294   Inst.InstantiationRange = InstantiationRange;
00295   SemaRef.InNonInstantiationSFINAEContext = false;
00296   SemaRef.ActiveTemplateInstantiations.push_back(Inst);
00297       
00298   assert(!Inst.isInstantiationRecord());
00299   ++SemaRef.NonInstantiationEntries;
00300 }
00301 
00302 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
00303                                           SourceLocation PointOfInstantiation,
00304                                           ParmVarDecl *Param,
00305                                           const TemplateArgument *TemplateArgs,
00306                                           unsigned NumTemplateArgs,
00307                                           SourceRange InstantiationRange)
00308   : SemaRef(SemaRef),
00309     SavedInNonInstantiationSFINAEContext(
00310                                      SemaRef.InNonInstantiationSFINAEContext)
00311 {
00312   Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
00313 
00314   if (!Invalid) {
00315     ActiveTemplateInstantiation Inst;
00316     Inst.Kind
00317       = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
00318     Inst.PointOfInstantiation = PointOfInstantiation;
00319     Inst.Entity = reinterpret_cast<uintptr_t>(Param);
00320     Inst.TemplateArgs = TemplateArgs;
00321     Inst.NumTemplateArgs = NumTemplateArgs;
00322     Inst.InstantiationRange = InstantiationRange;
00323     SemaRef.InNonInstantiationSFINAEContext = false;
00324     SemaRef.ActiveTemplateInstantiations.push_back(Inst);
00325   }
00326 }
00327 
00328 Sema::InstantiatingTemplate::
00329 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
00330                       NamedDecl *Template,
00331                       NonTypeTemplateParmDecl *Param,
00332                       const TemplateArgument *TemplateArgs,
00333                       unsigned NumTemplateArgs,
00334                       SourceRange InstantiationRange) 
00335   : SemaRef(SemaRef),
00336     SavedInNonInstantiationSFINAEContext(
00337                                      SemaRef.InNonInstantiationSFINAEContext)
00338 {
00339   Invalid = false;
00340   
00341   ActiveTemplateInstantiation Inst;
00342   Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
00343   Inst.PointOfInstantiation = PointOfInstantiation;
00344   Inst.Template = Template;
00345   Inst.Entity = reinterpret_cast<uintptr_t>(Param);
00346   Inst.TemplateArgs = TemplateArgs;
00347   Inst.NumTemplateArgs = NumTemplateArgs;
00348   Inst.InstantiationRange = InstantiationRange;
00349   SemaRef.InNonInstantiationSFINAEContext = false;
00350   SemaRef.ActiveTemplateInstantiations.push_back(Inst);
00351   
00352   assert(!Inst.isInstantiationRecord());
00353   ++SemaRef.NonInstantiationEntries;
00354 }
00355 
00356 Sema::InstantiatingTemplate::
00357 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
00358                       NamedDecl *Template,
00359                       TemplateTemplateParmDecl *Param,
00360                       const TemplateArgument *TemplateArgs,
00361                       unsigned NumTemplateArgs,
00362                       SourceRange InstantiationRange) 
00363   : SemaRef(SemaRef),
00364     SavedInNonInstantiationSFINAEContext(
00365                                      SemaRef.InNonInstantiationSFINAEContext)
00366 {
00367   Invalid = false;
00368   ActiveTemplateInstantiation Inst;
00369   Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
00370   Inst.PointOfInstantiation = PointOfInstantiation;
00371   Inst.Template = Template;
00372   Inst.Entity = reinterpret_cast<uintptr_t>(Param);
00373   Inst.TemplateArgs = TemplateArgs;
00374   Inst.NumTemplateArgs = NumTemplateArgs;
00375   Inst.InstantiationRange = InstantiationRange;
00376   SemaRef.InNonInstantiationSFINAEContext = false;
00377   SemaRef.ActiveTemplateInstantiations.push_back(Inst);
00378   
00379   assert(!Inst.isInstantiationRecord());
00380   ++SemaRef.NonInstantiationEntries;
00381 }
00382 
00383 Sema::InstantiatingTemplate::
00384 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
00385                       TemplateDecl *Template,
00386                       NamedDecl *Param,
00387                       const TemplateArgument *TemplateArgs,
00388                       unsigned NumTemplateArgs,
00389                       SourceRange InstantiationRange) 
00390   : SemaRef(SemaRef),
00391     SavedInNonInstantiationSFINAEContext(
00392                                      SemaRef.InNonInstantiationSFINAEContext)
00393 {
00394   Invalid = false;
00395   
00396   ActiveTemplateInstantiation Inst;
00397   Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
00398   Inst.PointOfInstantiation = PointOfInstantiation;
00399   Inst.Template = Template;
00400   Inst.Entity = reinterpret_cast<uintptr_t>(Param);
00401   Inst.TemplateArgs = TemplateArgs;
00402   Inst.NumTemplateArgs = NumTemplateArgs;
00403   Inst.InstantiationRange = InstantiationRange;
00404   SemaRef.InNonInstantiationSFINAEContext = false;
00405   SemaRef.ActiveTemplateInstantiations.push_back(Inst);
00406   
00407   assert(!Inst.isInstantiationRecord());
00408   ++SemaRef.NonInstantiationEntries;
00409 }
00410 
00411 void Sema::InstantiatingTemplate::Clear() {
00412   if (!Invalid) {
00413     if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
00414       assert(SemaRef.NonInstantiationEntries > 0);
00415       --SemaRef.NonInstantiationEntries;
00416     }
00417     SemaRef.InNonInstantiationSFINAEContext
00418       = SavedInNonInstantiationSFINAEContext;
00419     SemaRef.ActiveTemplateInstantiations.pop_back();
00420     Invalid = true;
00421   }
00422 }
00423 
00424 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
00425                                         SourceLocation PointOfInstantiation,
00426                                            SourceRange InstantiationRange) {
00427   assert(SemaRef.NonInstantiationEntries <=
00428                                    SemaRef.ActiveTemplateInstantiations.size());
00429   if ((SemaRef.ActiveTemplateInstantiations.size() - 
00430           SemaRef.NonInstantiationEntries)
00431         <= SemaRef.getLangOpts().InstantiationDepth)
00432     return false;
00433 
00434   SemaRef.Diag(PointOfInstantiation,
00435                diag::err_template_recursion_depth_exceeded)
00436     << SemaRef.getLangOpts().InstantiationDepth
00437     << InstantiationRange;
00438   SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
00439     << SemaRef.getLangOpts().InstantiationDepth;
00440   return true;
00441 }
00442 
00443 /// \brief Prints the current instantiation stack through a series of
00444 /// notes.
00445 void Sema::PrintInstantiationStack() {
00446   // Determine which template instantiations to skip, if any.
00447   unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
00448   unsigned Limit = Diags.getTemplateBacktraceLimit();
00449   if (Limit && Limit < ActiveTemplateInstantiations.size()) {
00450     SkipStart = Limit / 2 + Limit % 2;
00451     SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
00452   }
00453 
00454   // FIXME: In all of these cases, we need to show the template arguments
00455   unsigned InstantiationIdx = 0;
00456   for (SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
00457          Active = ActiveTemplateInstantiations.rbegin(),
00458          ActiveEnd = ActiveTemplateInstantiations.rend();
00459        Active != ActiveEnd;
00460        ++Active, ++InstantiationIdx) {
00461     // Skip this instantiation?
00462     if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
00463       if (InstantiationIdx == SkipStart) {
00464         // Note that we're skipping instantiations.
00465         Diags.Report(Active->PointOfInstantiation,
00466                      diag::note_instantiation_contexts_suppressed)
00467           << unsigned(ActiveTemplateInstantiations.size() - Limit);
00468       }
00469       continue;
00470     }
00471 
00472     switch (Active->Kind) {
00473     case ActiveTemplateInstantiation::TemplateInstantiation: {
00474       Decl *D = reinterpret_cast<Decl *>(Active->Entity);
00475       if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
00476         unsigned DiagID = diag::note_template_member_class_here;
00477         if (isa<ClassTemplateSpecializationDecl>(Record))
00478           DiagID = diag::note_template_class_instantiation_here;
00479         Diags.Report(Active->PointOfInstantiation, DiagID)
00480           << Context.getTypeDeclType(Record)
00481           << Active->InstantiationRange;
00482       } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
00483         unsigned DiagID;
00484         if (Function->getPrimaryTemplate())
00485           DiagID = diag::note_function_template_spec_here;
00486         else
00487           DiagID = diag::note_template_member_function_here;
00488         Diags.Report(Active->PointOfInstantiation, DiagID)
00489           << Function
00490           << Active->InstantiationRange;
00491       } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
00492         Diags.Report(Active->PointOfInstantiation,
00493                      diag::note_template_static_data_member_def_here)
00494           << VD
00495           << Active->InstantiationRange;
00496       } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
00497         Diags.Report(Active->PointOfInstantiation,
00498                      diag::note_template_enum_def_here)
00499           << ED
00500           << Active->InstantiationRange;
00501       } else {
00502         Diags.Report(Active->PointOfInstantiation,
00503                      diag::note_template_type_alias_instantiation_here)
00504           << cast<TypeAliasTemplateDecl>(D)
00505           << Active->InstantiationRange;
00506       }
00507       break;
00508     }
00509 
00510     case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
00511       TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
00512       std::string TemplateArgsStr
00513         = TemplateSpecializationType::PrintTemplateArgumentList(
00514                                                          Active->TemplateArgs,
00515                                                       Active->NumTemplateArgs,
00516                                                       getPrintingPolicy());
00517       Diags.Report(Active->PointOfInstantiation,
00518                    diag::note_default_arg_instantiation_here)
00519         << (Template->getNameAsString() + TemplateArgsStr)
00520         << Active->InstantiationRange;
00521       break;
00522     }
00523 
00524     case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
00525       FunctionTemplateDecl *FnTmpl
00526         = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
00527       Diags.Report(Active->PointOfInstantiation,
00528                    diag::note_explicit_template_arg_substitution_here)
00529         << FnTmpl 
00530         << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), 
00531                                            Active->TemplateArgs, 
00532                                            Active->NumTemplateArgs)
00533         << Active->InstantiationRange;
00534       break;
00535     }
00536 
00537     case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
00538       if (ClassTemplatePartialSpecializationDecl *PartialSpec
00539             = dyn_cast<ClassTemplatePartialSpecializationDecl>(
00540                                                     (Decl *)Active->Entity)) {
00541         Diags.Report(Active->PointOfInstantiation,
00542                      diag::note_partial_spec_deduct_instantiation_here)
00543           << Context.getTypeDeclType(PartialSpec)
00544           << getTemplateArgumentBindingsText(
00545                                          PartialSpec->getTemplateParameters(), 
00546                                              Active->TemplateArgs, 
00547                                              Active->NumTemplateArgs)
00548           << Active->InstantiationRange;
00549       } else {
00550         FunctionTemplateDecl *FnTmpl
00551           = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
00552         Diags.Report(Active->PointOfInstantiation,
00553                      diag::note_function_template_deduction_instantiation_here)
00554           << FnTmpl
00555           << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), 
00556                                              Active->TemplateArgs, 
00557                                              Active->NumTemplateArgs)
00558           << Active->InstantiationRange;
00559       }
00560       break;
00561 
00562     case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
00563       ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
00564       FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
00565 
00566       std::string TemplateArgsStr
00567         = TemplateSpecializationType::PrintTemplateArgumentList(
00568                                                          Active->TemplateArgs,
00569                                                       Active->NumTemplateArgs,
00570                                                       getPrintingPolicy());
00571       Diags.Report(Active->PointOfInstantiation,
00572                    diag::note_default_function_arg_instantiation_here)
00573         << (FD->getNameAsString() + TemplateArgsStr)
00574         << Active->InstantiationRange;
00575       break;
00576     }
00577 
00578     case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
00579       NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity);
00580       std::string Name;
00581       if (!Parm->getName().empty())
00582         Name = std::string(" '") + Parm->getName().str() + "'";
00583                     
00584       TemplateParameterList *TemplateParams = 0;
00585       if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
00586         TemplateParams = Template->getTemplateParameters();
00587       else
00588         TemplateParams =
00589           cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
00590                                                       ->getTemplateParameters();
00591       Diags.Report(Active->PointOfInstantiation,
00592                    diag::note_prior_template_arg_substitution)
00593         << isa<TemplateTemplateParmDecl>(Parm)
00594         << Name
00595         << getTemplateArgumentBindingsText(TemplateParams, 
00596                                            Active->TemplateArgs, 
00597                                            Active->NumTemplateArgs)
00598         << Active->InstantiationRange;
00599       break;
00600     }
00601 
00602     case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
00603       TemplateParameterList *TemplateParams = 0;
00604       if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
00605         TemplateParams = Template->getTemplateParameters();
00606       else
00607         TemplateParams =
00608           cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
00609                                                       ->getTemplateParameters();
00610 
00611       Diags.Report(Active->PointOfInstantiation,
00612                    diag::note_template_default_arg_checking)
00613         << getTemplateArgumentBindingsText(TemplateParams, 
00614                                            Active->TemplateArgs, 
00615                                            Active->NumTemplateArgs)
00616         << Active->InstantiationRange;
00617       break;
00618     }
00619 
00620     case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
00621       Diags.Report(Active->PointOfInstantiation,
00622                    diag::note_template_exception_spec_instantiation_here)
00623         << cast<FunctionDecl>((Decl *)Active->Entity)
00624         << Active->InstantiationRange;
00625       break;
00626     }
00627   }
00628 }
00629 
00630 llvm::Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
00631   if (InNonInstantiationSFINAEContext)
00632     return llvm::Optional<TemplateDeductionInfo *>(0);
00633 
00634   for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
00635          Active = ActiveTemplateInstantiations.rbegin(),
00636          ActiveEnd = ActiveTemplateInstantiations.rend();
00637        Active != ActiveEnd;
00638        ++Active) 
00639   {
00640     switch(Active->Kind) {
00641     case ActiveTemplateInstantiation::TemplateInstantiation:
00642       // An instantiation of an alias template may or may not be a SFINAE
00643       // context, depending on what else is on the stack.
00644       if (isa<TypeAliasTemplateDecl>(reinterpret_cast<Decl *>(Active->Entity)))
00645         break;
00646       // Fall through.
00647     case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
00648     case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
00649       // This is a template instantiation, so there is no SFINAE.
00650       return llvm::Optional<TemplateDeductionInfo *>();
00651 
00652     case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
00653     case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
00654     case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
00655       // A default template argument instantiation and substitution into
00656       // template parameters with arguments for prior parameters may or may 
00657       // not be a SFINAE context; look further up the stack.
00658       break;
00659 
00660     case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
00661     case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
00662       // We're either substitution explicitly-specified template arguments
00663       // or deduced template arguments, so SFINAE applies.
00664       assert(Active->DeductionInfo && "Missing deduction info pointer");
00665       return Active->DeductionInfo;
00666     }
00667   }
00668 
00669   return llvm::Optional<TemplateDeductionInfo *>();
00670 }
00671 
00672 /// \brief Retrieve the depth and index of a parameter pack.
00673 static std::pair<unsigned, unsigned> 
00674 getDepthAndIndex(NamedDecl *ND) {
00675   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
00676     return std::make_pair(TTP->getDepth(), TTP->getIndex());
00677   
00678   if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
00679     return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
00680   
00681   TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
00682   return std::make_pair(TTP->getDepth(), TTP->getIndex());
00683 }
00684 
00685 //===----------------------------------------------------------------------===/
00686 // Template Instantiation for Types
00687 //===----------------------------------------------------------------------===/
00688 namespace {
00689   class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
00690     const MultiLevelTemplateArgumentList &TemplateArgs;
00691     SourceLocation Loc;
00692     DeclarationName Entity;
00693 
00694   public:
00695     typedef TreeTransform<TemplateInstantiator> inherited;
00696 
00697     TemplateInstantiator(Sema &SemaRef,
00698                          const MultiLevelTemplateArgumentList &TemplateArgs,
00699                          SourceLocation Loc,
00700                          DeclarationName Entity)
00701       : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
00702         Entity(Entity) { }
00703 
00704     /// \brief Determine whether the given type \p T has already been
00705     /// transformed.
00706     ///
00707     /// For the purposes of template instantiation, a type has already been
00708     /// transformed if it is NULL or if it is not dependent.
00709     bool AlreadyTransformed(QualType T);
00710 
00711     /// \brief Returns the location of the entity being instantiated, if known.
00712     SourceLocation getBaseLocation() { return Loc; }
00713 
00714     /// \brief Returns the name of the entity being instantiated, if any.
00715     DeclarationName getBaseEntity() { return Entity; }
00716 
00717     /// \brief Sets the "base" location and entity when that
00718     /// information is known based on another transformation.
00719     void setBase(SourceLocation Loc, DeclarationName Entity) {
00720       this->Loc = Loc;
00721       this->Entity = Entity;
00722     }
00723 
00724     bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
00725                                  SourceRange PatternRange,
00726                              llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
00727                                  bool &ShouldExpand,
00728                                  bool &RetainExpansion,
00729                                  llvm::Optional<unsigned> &NumExpansions) {
00730       return getSema().CheckParameterPacksForExpansion(EllipsisLoc, 
00731                                                        PatternRange, Unexpanded,
00732                                                        TemplateArgs, 
00733                                                        ShouldExpand,
00734                                                        RetainExpansion,
00735                                                        NumExpansions);
00736     }
00737 
00738     void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { 
00739       SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
00740     }
00741     
00742     TemplateArgument ForgetPartiallySubstitutedPack() {
00743       TemplateArgument Result;
00744       if (NamedDecl *PartialPack
00745             = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
00746         MultiLevelTemplateArgumentList &TemplateArgs
00747           = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
00748         unsigned Depth, Index;
00749         llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
00750         if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
00751           Result = TemplateArgs(Depth, Index);
00752           TemplateArgs.setArgument(Depth, Index, TemplateArgument());
00753         }
00754       }
00755       
00756       return Result;
00757     }
00758     
00759     void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
00760       if (Arg.isNull())
00761         return;
00762       
00763       if (NamedDecl *PartialPack
00764             = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
00765         MultiLevelTemplateArgumentList &TemplateArgs
00766         = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
00767         unsigned Depth, Index;
00768         llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
00769         TemplateArgs.setArgument(Depth, Index, Arg);
00770       }
00771     }
00772 
00773     /// \brief Transform the given declaration by instantiating a reference to
00774     /// this declaration.
00775     Decl *TransformDecl(SourceLocation Loc, Decl *D);
00776 
00777     void transformAttrs(Decl *Old, Decl *New) { 
00778       SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
00779     }
00780 
00781     void transformedLocalDecl(Decl *Old, Decl *New) {
00782       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
00783     }
00784     
00785     /// \brief Transform the definition of the given declaration by
00786     /// instantiating it.
00787     Decl *TransformDefinition(SourceLocation Loc, Decl *D);
00788 
00789     /// \bried Transform the first qualifier within a scope by instantiating the
00790     /// declaration.
00791     NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
00792       
00793     /// \brief Rebuild the exception declaration and register the declaration
00794     /// as an instantiated local.
00795     VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, 
00796                                   TypeSourceInfo *Declarator,
00797                                   SourceLocation StartLoc,
00798                                   SourceLocation NameLoc,
00799                                   IdentifierInfo *Name);
00800 
00801     /// \brief Rebuild the Objective-C exception declaration and register the 
00802     /// declaration as an instantiated local.
00803     VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, 
00804                                       TypeSourceInfo *TSInfo, QualType T);
00805       
00806     /// \brief Check for tag mismatches when instantiating an
00807     /// elaborated type.
00808     QualType RebuildElaboratedType(SourceLocation KeywordLoc,
00809                                    ElaboratedTypeKeyword Keyword,
00810                                    NestedNameSpecifierLoc QualifierLoc,
00811                                    QualType T);
00812 
00813     TemplateName TransformTemplateName(CXXScopeSpec &SS,
00814                                        TemplateName Name,
00815                                        SourceLocation NameLoc,                                     
00816                                        QualType ObjectType = QualType(),
00817                                        NamedDecl *FirstQualifierInScope = 0);
00818 
00819     ExprResult TransformPredefinedExpr(PredefinedExpr *E);
00820     ExprResult TransformDeclRefExpr(DeclRefExpr *E);
00821     ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
00822     ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
00823                                             NonTypeTemplateParmDecl *D);
00824     ExprResult TransformSubstNonTypeTemplateParmPackExpr(
00825                                            SubstNonTypeTemplateParmPackExpr *E);
00826     
00827     QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
00828                                         FunctionProtoTypeLoc TL);
00829     QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
00830                                         FunctionProtoTypeLoc TL,
00831                                         CXXRecordDecl *ThisContext,
00832                                         unsigned ThisTypeQuals);
00833 
00834     ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
00835                                             int indexAdjustment,
00836                                         llvm::Optional<unsigned> NumExpansions,
00837                                             bool ExpectParameterPack);
00838 
00839     /// \brief Transforms a template type parameter type by performing
00840     /// substitution of the corresponding template type argument.
00841     QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
00842                                            TemplateTypeParmTypeLoc TL);
00843 
00844     /// \brief Transforms an already-substituted template type parameter pack
00845     /// into either itself (if we aren't substituting into its pack expansion)
00846     /// or the appropriate substituted argument.
00847     QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
00848                                            SubstTemplateTypeParmPackTypeLoc TL);
00849 
00850     ExprResult TransformCallExpr(CallExpr *CE) {
00851       getSema().CallsUndergoingInstantiation.push_back(CE);
00852       ExprResult Result =
00853           TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
00854       getSema().CallsUndergoingInstantiation.pop_back();
00855       return move(Result);
00856     }
00857 
00858   private:
00859     ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
00860                                                SourceLocation loc,
00861                                                const TemplateArgument &arg);
00862   };
00863 }
00864 
00865 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
00866   if (T.isNull())
00867     return true;
00868   
00869   if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
00870     return false;
00871   
00872   getSema().MarkDeclarationsReferencedInType(Loc, T);
00873   return true;
00874 }
00875 
00876 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
00877   if (!D)
00878     return 0;
00879 
00880   if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
00881     if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
00882       // If the corresponding template argument is NULL or non-existent, it's
00883       // because we are performing instantiation from explicitly-specified
00884       // template arguments in a function template, but there were some
00885       // arguments left unspecified.
00886       if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
00887                                             TTP->getPosition()))
00888         return D;
00889 
00890       TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
00891       
00892       if (TTP->isParameterPack()) {
00893         assert(Arg.getKind() == TemplateArgument::Pack && 
00894                "Missing argument pack");
00895         
00896         assert(getSema().ArgumentPackSubstitutionIndex >= 0);        
00897         assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
00898         Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
00899       }
00900 
00901       TemplateName Template = Arg.getAsTemplate();
00902       assert(!Template.isNull() && Template.getAsTemplateDecl() &&
00903              "Wrong kind of template template argument");
00904       return Template.getAsTemplateDecl();
00905     }
00906 
00907     // Fall through to find the instantiated declaration for this template
00908     // template parameter.
00909   }
00910 
00911   return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
00912 }
00913 
00914 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
00915   Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
00916   if (!Inst)
00917     return 0;
00918 
00919   getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
00920   return Inst;
00921 }
00922 
00923 NamedDecl *
00924 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, 
00925                                                      SourceLocation Loc) {
00926   // If the first part of the nested-name-specifier was a template type 
00927   // parameter, instantiate that type parameter down to a tag type.
00928   if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
00929     const TemplateTypeParmType *TTP 
00930       = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
00931     
00932     if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
00933       // FIXME: This needs testing w/ member access expressions.
00934       TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
00935       
00936       if (TTP->isParameterPack()) {
00937         assert(Arg.getKind() == TemplateArgument::Pack && 
00938                "Missing argument pack");
00939         
00940         if (getSema().ArgumentPackSubstitutionIndex == -1)
00941           return 0;
00942         
00943         assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
00944         Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
00945       }
00946 
00947       QualType T = Arg.getAsType();
00948       if (T.isNull())
00949         return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
00950       
00951       if (const TagType *Tag = T->getAs<TagType>())
00952         return Tag->getDecl();
00953       
00954       // The resulting type is not a tag; complain.
00955       getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
00956       return 0;
00957     }
00958   }
00959   
00960   return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
00961 }
00962 
00963 VarDecl *
00964 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
00965                                            TypeSourceInfo *Declarator,
00966                                            SourceLocation StartLoc,
00967                                            SourceLocation NameLoc,
00968                                            IdentifierInfo *Name) {
00969   VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
00970                                                  StartLoc, NameLoc, Name);
00971   if (Var)
00972     getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
00973   return Var;
00974 }
00975 
00976 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, 
00977                                                         TypeSourceInfo *TSInfo, 
00978                                                         QualType T) {
00979   VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
00980   if (Var)
00981     getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
00982   return Var;
00983 }
00984 
00985 QualType
00986 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
00987                                             ElaboratedTypeKeyword Keyword,
00988                                             NestedNameSpecifierLoc QualifierLoc,
00989                                             QualType T) {
00990   if (const TagType *TT = T->getAs<TagType>()) {
00991     TagDecl* TD = TT->getDecl();
00992 
00993     SourceLocation TagLocation = KeywordLoc;
00994 
00995     // FIXME: type might be anonymous.
00996     IdentifierInfo *Id = TD->getIdentifier();
00997 
00998     // TODO: should we even warn on struct/class mismatches for this?  Seems
00999     // like it's likely to produce a lot of spurious errors.
01000     if (Keyword != ETK_None && Keyword != ETK_Typename) {
01001       TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
01002       if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
01003                                                 TagLocation, *Id)) {
01004         SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
01005           << Id
01006           << FixItHint::CreateReplacement(SourceRange(TagLocation),
01007                                           TD->getKindName());
01008         SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
01009       }
01010     }
01011   }
01012 
01013   return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
01014                                                                     Keyword,
01015                                                                   QualifierLoc,
01016                                                                     T);
01017 }
01018 
01019 TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
01020                                                          TemplateName Name,
01021                                                          SourceLocation NameLoc,                                     
01022                                                          QualType ObjectType,
01023                                              NamedDecl *FirstQualifierInScope) {
01024   if (TemplateTemplateParmDecl *TTP
01025        = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
01026     if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
01027       // If the corresponding template argument is NULL or non-existent, it's
01028       // because we are performing instantiation from explicitly-specified
01029       // template arguments in a function template, but there were some
01030       // arguments left unspecified.
01031       if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
01032                                             TTP->getPosition()))
01033         return Name;
01034       
01035       TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
01036       
01037       if (TTP->isParameterPack()) {
01038         assert(Arg.getKind() == TemplateArgument::Pack && 
01039                "Missing argument pack");
01040         
01041         if (getSema().ArgumentPackSubstitutionIndex == -1) {
01042           // We have the template argument pack to substitute, but we're not
01043           // actually expanding the enclosing pack expansion yet. So, just
01044           // keep the entire argument pack.
01045           return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
01046         }
01047         
01048         assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
01049         Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
01050       }
01051       
01052       TemplateName Template = Arg.getAsTemplate();
01053       assert(!Template.isNull() && "Null template template argument");
01054 
01055       // We don't ever want to substitute for a qualified template name, since
01056       // the qualifier is handled separately. So, look through the qualified
01057       // template name to its underlying declaration.
01058       if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
01059         Template = TemplateName(QTN->getTemplateDecl());
01060 
01061       Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
01062       return Template;
01063     }
01064   }
01065   
01066   if (SubstTemplateTemplateParmPackStorage *SubstPack
01067       = Name.getAsSubstTemplateTemplateParmPack()) {
01068     if (getSema().ArgumentPackSubstitutionIndex == -1)
01069       return Name;
01070     
01071     const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
01072     assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
01073            "Pack substitution index out-of-range");
01074     return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
01075     .getAsTemplate();
01076   }
01077   
01078   return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType, 
01079                                           FirstQualifierInScope);  
01080 }
01081 
01082 ExprResult 
01083 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
01084   if (!E->isTypeDependent())
01085     return SemaRef.Owned(E);
01086 
01087   FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
01088   assert(currentDecl && "Must have current function declaration when "
01089                         "instantiating.");
01090 
01091   PredefinedExpr::IdentType IT = E->getIdentType();
01092 
01093   unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
01094 
01095   llvm::APInt LengthI(32, Length + 1);
01096   QualType ResTy = getSema().Context.CharTy.withConst();
01097   ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI, 
01098                                                  ArrayType::Normal, 0);
01099   PredefinedExpr *PE =
01100     new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
01101   return getSema().Owned(PE);
01102 }
01103 
01104 ExprResult
01105 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
01106                                                NonTypeTemplateParmDecl *NTTP) {
01107   // If the corresponding template argument is NULL or non-existent, it's
01108   // because we are performing instantiation from explicitly-specified
01109   // template arguments in a function template, but there were some
01110   // arguments left unspecified.
01111   if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
01112                                         NTTP->getPosition()))
01113     return SemaRef.Owned(E);
01114 
01115   TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
01116   if (NTTP->isParameterPack()) {
01117     assert(Arg.getKind() == TemplateArgument::Pack && 
01118            "Missing argument pack");
01119     
01120     if (getSema().ArgumentPackSubstitutionIndex == -1) {
01121       // We have an argument pack, but we can't select a particular argument
01122       // out of it yet. Therefore, we'll build an expression to hold on to that
01123       // argument pack.
01124       QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
01125                                               E->getLocation(), 
01126                                               NTTP->getDeclName());
01127       if (TargetType.isNull())
01128         return ExprError();
01129       
01130       return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
01131                                                                     NTTP, 
01132                                                               E->getLocation(),
01133                                                                     Arg);
01134     }
01135     
01136     assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
01137     Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
01138   }
01139 
01140   return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
01141 }
01142 
01143 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
01144                                                  NonTypeTemplateParmDecl *parm,
01145                                                  SourceLocation loc,
01146                                                  const TemplateArgument &arg) {
01147   ExprResult result;
01148   QualType type;
01149 
01150   // The template argument itself might be an expression, in which
01151   // case we just return that expression.
01152   if (arg.getKind() == TemplateArgument::Expression) {
01153     Expr *argExpr = arg.getAsExpr();
01154     result = SemaRef.Owned(argExpr);
01155     type = argExpr->getType();
01156 
01157   } else if (arg.getKind() == TemplateArgument::Declaration) {
01158     ValueDecl *VD;
01159     if (Decl *D = arg.getAsDecl()) {
01160       VD = cast<ValueDecl>(D);
01161 
01162       // Find the instantiation of the template argument.  This is
01163       // required for nested templates.
01164       VD = cast_or_null<ValueDecl>(
01165              getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
01166       if (!VD)
01167         return ExprError();
01168     } else {
01169       // Propagate NULL template argument.
01170       VD = 0;
01171     }
01172     
01173     // Derive the type we want the substituted decl to have.  This had
01174     // better be non-dependent, or these checks will have serious problems.
01175     if (parm->isExpandedParameterPack()) {
01176       type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
01177     } else if (parm->isParameterPack() && 
01178                isa<PackExpansionType>(parm->getType())) {
01179       type = SemaRef.SubstType(
01180                         cast<PackExpansionType>(parm->getType())->getPattern(),
01181                                      TemplateArgs, loc, parm->getDeclName());
01182     } else {
01183       type = SemaRef.SubstType(parm->getType(), TemplateArgs, 
01184                                loc, parm->getDeclName());
01185     }
01186     assert(!type.isNull() && "type substitution failed for param type");
01187     assert(!type->isDependentType() && "param type still dependent");
01188     result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
01189 
01190     if (!result.isInvalid()) type = result.get()->getType();
01191   } else {
01192     result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
01193 
01194     // Note that this type can be different from the type of 'result',
01195     // e.g. if it's an enum type.
01196     type = arg.getIntegralType();
01197   }
01198   if (result.isInvalid()) return ExprError();
01199 
01200   Expr *resultExpr = result.take();
01201   return SemaRef.Owned(new (SemaRef.Context)
01202                 SubstNonTypeTemplateParmExpr(type,
01203                                              resultExpr->getValueKind(),
01204                                              loc, parm, resultExpr));
01205 }
01206                                                    
01207 ExprResult 
01208 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
01209                                           SubstNonTypeTemplateParmPackExpr *E) {
01210   if (getSema().ArgumentPackSubstitutionIndex == -1) {
01211     // We aren't expanding the parameter pack, so just return ourselves.
01212     return getSema().Owned(E);
01213   }
01214   
01215   const TemplateArgument &ArgPack = E->getArgumentPack();
01216   unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
01217   assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
01218   
01219   const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
01220   return transformNonTypeTemplateParmRef(E->getParameterPack(),
01221                                          E->getParameterPackLocation(),
01222                                          Arg);
01223 }
01224 
01225 ExprResult
01226 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
01227   NamedDecl *D = E->getDecl();
01228   if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
01229     if (NTTP->getDepth() < TemplateArgs.getNumLevels())
01230       return TransformTemplateParmRefExpr(E, NTTP);
01231     
01232     // We have a non-type template parameter that isn't fully substituted;
01233     // FindInstantiatedDecl will find it in the local instantiation scope.
01234   }
01235 
01236   return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
01237 }
01238 
01239 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
01240     CXXDefaultArgExpr *E) {
01241   assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
01242              getDescribedFunctionTemplate() &&
01243          "Default arg expressions are never formed in dependent cases.");
01244   return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
01245                            cast<FunctionDecl>(E->getParam()->getDeclContext()), 
01246                                         E->getParam());
01247 }
01248 
01249 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
01250                                                       FunctionProtoTypeLoc TL) {
01251   // We need a local instantiation scope for this function prototype.
01252   LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
01253   return inherited::TransformFunctionProtoType(TLB, TL);
01254 }
01255 
01256 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
01257                                  FunctionProtoTypeLoc TL,
01258                                  CXXRecordDecl *ThisContext,
01259                                  unsigned ThisTypeQuals) {
01260   // We need a local instantiation scope for this function prototype.
01261   LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
01262   return inherited::TransformFunctionProtoType(TLB, TL, ThisContext, 
01263                                                ThisTypeQuals);  
01264 }
01265 
01266 ParmVarDecl *
01267 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
01268                                                  int indexAdjustment,
01269                                        llvm::Optional<unsigned> NumExpansions,
01270                                                  bool ExpectParameterPack) {
01271   return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
01272                                   NumExpansions, ExpectParameterPack);
01273 }
01274 
01275 QualType
01276 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
01277                                                 TemplateTypeParmTypeLoc TL) {
01278   const TemplateTypeParmType *T = TL.getTypePtr();
01279   if (T->getDepth() < TemplateArgs.getNumLevels()) {
01280     // Replace the template type parameter with its corresponding
01281     // template argument.
01282 
01283     // If the corresponding template argument is NULL or doesn't exist, it's
01284     // because we are performing instantiation from explicitly-specified
01285     // template arguments in a function template class, but there were some
01286     // arguments left unspecified.
01287     if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
01288       TemplateTypeParmTypeLoc NewTL
01289         = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
01290       NewTL.setNameLoc(TL.getNameLoc());
01291       return TL.getType();
01292     }
01293 
01294     TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
01295     
01296     if (T->isParameterPack()) {
01297       assert(Arg.getKind() == TemplateArgument::Pack && 
01298              "Missing argument pack");
01299       
01300       if (getSema().ArgumentPackSubstitutionIndex == -1) {
01301         // We have the template argument pack, but we're not expanding the
01302         // enclosing pack expansion yet. Just save the template argument
01303         // pack for later substitution.
01304         QualType Result
01305           = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
01306         SubstTemplateTypeParmPackTypeLoc NewTL
01307           = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
01308         NewTL.setNameLoc(TL.getNameLoc());
01309         return Result;
01310       }
01311       
01312       assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
01313       Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
01314     }
01315     
01316     assert(Arg.getKind() == TemplateArgument::Type &&
01317            "Template argument kind mismatch");
01318 
01319     QualType Replacement = Arg.getAsType();
01320 
01321     // TODO: only do this uniquing once, at the start of instantiation.
01322     QualType Result
01323       = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
01324     SubstTemplateTypeParmTypeLoc NewTL
01325       = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
01326     NewTL.setNameLoc(TL.getNameLoc());
01327     return Result;
01328   }
01329 
01330   // The template type parameter comes from an inner template (e.g.,
01331   // the template parameter list of a member template inside the
01332   // template we are instantiating). Create a new template type
01333   // parameter with the template "level" reduced by one.
01334   TemplateTypeParmDecl *NewTTPDecl = 0;
01335   if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
01336     NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
01337                                   TransformDecl(TL.getNameLoc(), OldTTPDecl));
01338 
01339   QualType Result
01340     = getSema().Context.getTemplateTypeParmType(T->getDepth()
01341                                                  - TemplateArgs.getNumLevels(),
01342                                                 T->getIndex(),
01343                                                 T->isParameterPack(),
01344                                                 NewTTPDecl);
01345   TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
01346   NewTL.setNameLoc(TL.getNameLoc());
01347   return Result;
01348 }
01349 
01350 QualType 
01351 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
01352                                                             TypeLocBuilder &TLB,
01353                                          SubstTemplateTypeParmPackTypeLoc TL) {
01354   if (getSema().ArgumentPackSubstitutionIndex == -1) {
01355     // We aren't expanding the parameter pack, so just return ourselves.
01356     SubstTemplateTypeParmPackTypeLoc NewTL
01357       = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
01358     NewTL.setNameLoc(TL.getNameLoc());
01359     return TL.getType();
01360   }
01361   
01362   const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
01363   unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
01364   assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
01365   
01366   QualType Result = ArgPack.pack_begin()[Index].getAsType();
01367   Result = getSema().Context.getSubstTemplateTypeParmType(
01368                                       TL.getTypePtr()->getReplacedParameter(),
01369                                                           Result);
01370   SubstTemplateTypeParmTypeLoc NewTL
01371     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
01372   NewTL.setNameLoc(TL.getNameLoc());
01373   return Result;
01374 }
01375 
01376 /// \brief Perform substitution on the type T with a given set of template
01377 /// arguments.
01378 ///
01379 /// This routine substitutes the given template arguments into the
01380 /// type T and produces the instantiated type.
01381 ///
01382 /// \param T the type into which the template arguments will be
01383 /// substituted. If this type is not dependent, it will be returned
01384 /// immediately.
01385 ///
01386 /// \param TemplateArgs the template arguments that will be
01387 /// substituted for the top-level template parameters within T.
01388 ///
01389 /// \param Loc the location in the source code where this substitution
01390 /// is being performed. It will typically be the location of the
01391 /// declarator (if we're instantiating the type of some declaration)
01392 /// or the location of the type in the source code (if, e.g., we're
01393 /// instantiating the type of a cast expression).
01394 ///
01395 /// \param Entity the name of the entity associated with a declaration
01396 /// being instantiated (if any). May be empty to indicate that there
01397 /// is no such entity (if, e.g., this is a type that occurs as part of
01398 /// a cast expression) or that the entity has no name (e.g., an
01399 /// unnamed function parameter).
01400 ///
01401 /// \returns If the instantiation succeeds, the instantiated
01402 /// type. Otherwise, produces diagnostics and returns a NULL type.
01403 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
01404                                 const MultiLevelTemplateArgumentList &Args,
01405                                 SourceLocation Loc,
01406                                 DeclarationName Entity) {
01407   assert(!ActiveTemplateInstantiations.empty() &&
01408          "Cannot perform an instantiation without some context on the "
01409          "instantiation stack");
01410   
01411   if (!T->getType()->isInstantiationDependentType() && 
01412       !T->getType()->isVariablyModifiedType())
01413     return T;
01414 
01415   TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
01416   return Instantiator.TransformType(T);
01417 }
01418 
01419 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
01420                                 const MultiLevelTemplateArgumentList &Args,
01421                                 SourceLocation Loc,
01422                                 DeclarationName Entity) {
01423   assert(!ActiveTemplateInstantiations.empty() &&
01424          "Cannot perform an instantiation without some context on the "
01425          "instantiation stack");
01426   
01427   if (TL.getType().isNull())
01428     return 0;
01429 
01430   if (!TL.getType()->isInstantiationDependentType() && 
01431       !TL.getType()->isVariablyModifiedType()) {
01432     // FIXME: Make a copy of the TypeLoc data here, so that we can
01433     // return a new TypeSourceInfo. Inefficient!
01434     TypeLocBuilder TLB;
01435     TLB.pushFullCopy(TL);
01436     return TLB.getTypeSourceInfo(Context, TL.getType());
01437   }
01438 
01439   TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
01440   TypeLocBuilder TLB;
01441   TLB.reserve(TL.getFullDataSize());
01442   QualType Result = Instantiator.TransformType(TLB, TL);
01443   if (Result.isNull())
01444     return 0;
01445 
01446   return TLB.getTypeSourceInfo(Context, Result);
01447 }
01448 
01449 /// Deprecated form of the above.
01450 QualType Sema::SubstType(QualType T,
01451                          const MultiLevelTemplateArgumentList &TemplateArgs,
01452                          SourceLocation Loc, DeclarationName Entity) {
01453   assert(!ActiveTemplateInstantiations.empty() &&
01454          "Cannot perform an instantiation without some context on the "
01455          "instantiation stack");
01456 
01457   // If T is not a dependent type or a variably-modified type, there
01458   // is nothing to do.
01459   if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
01460     return T;
01461 
01462   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
01463   return Instantiator.TransformType(T);
01464 }
01465 
01466 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
01467   if (T->getType()->isInstantiationDependentType() || 
01468       T->getType()->isVariablyModifiedType())
01469     return true;
01470 
01471   TypeLoc TL = T->getTypeLoc().IgnoreParens();
01472   if (!isa<FunctionProtoTypeLoc>(TL))
01473     return false;
01474 
01475   FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL);
01476   for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
01477     ParmVarDecl *P = FP.getArg(I);
01478 
01479     // The parameter's type as written might be dependent even if the
01480     // decayed type was not dependent.
01481     if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
01482       if (TSInfo->getType()->isInstantiationDependentType())
01483         return true;
01484 
01485     // TODO: currently we always rebuild expressions.  When we
01486     // properly get lazier about this, we should use the same
01487     // logic to avoid rebuilding prototypes here.
01488     if (P->hasDefaultArg())
01489       return true;
01490   }
01491 
01492   return false;
01493 }
01494 
01495 /// A form of SubstType intended specifically for instantiating the
01496 /// type of a FunctionDecl.  Its purpose is solely to force the
01497 /// instantiation of default-argument expressions.
01498 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
01499                                 const MultiLevelTemplateArgumentList &Args,
01500                                 SourceLocation Loc,
01501                                 DeclarationName Entity,
01502                                 CXXRecordDecl *ThisContext,
01503                                 unsigned ThisTypeQuals) {
01504   assert(!ActiveTemplateInstantiations.empty() &&
01505          "Cannot perform an instantiation without some context on the "
01506          "instantiation stack");
01507   
01508   if (!NeedsInstantiationAsFunctionType(T))
01509     return T;
01510 
01511   TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
01512 
01513   TypeLocBuilder TLB;
01514 
01515   TypeLoc TL = T->getTypeLoc();
01516   TLB.reserve(TL.getFullDataSize());
01517 
01518   QualType Result;
01519   
01520   if (FunctionProtoTypeLoc *Proto = dyn_cast<FunctionProtoTypeLoc>(&TL)) {
01521     Result = Instantiator.TransformFunctionProtoType(TLB, *Proto, ThisContext,
01522                                                      ThisTypeQuals);
01523   } else {
01524     Result = Instantiator.TransformType(TLB, TL);
01525   }
01526   if (Result.isNull())
01527     return 0;
01528 
01529   return TLB.getTypeSourceInfo(Context, Result);
01530 }
01531 
01532 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, 
01533                             const MultiLevelTemplateArgumentList &TemplateArgs,
01534                                     int indexAdjustment,
01535                                     llvm::Optional<unsigned> NumExpansions,
01536                                     bool ExpectParameterPack) {
01537   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
01538   TypeSourceInfo *NewDI = 0;
01539   
01540   TypeLoc OldTL = OldDI->getTypeLoc();
01541   if (isa<PackExpansionTypeLoc>(OldTL)) {    
01542     PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
01543     
01544     // We have a function parameter pack. Substitute into the pattern of the 
01545     // expansion.
01546     NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs, 
01547                       OldParm->getLocation(), OldParm->getDeclName());
01548     if (!NewDI)
01549       return 0;
01550         
01551     if (NewDI->getType()->containsUnexpandedParameterPack()) {
01552       // We still have unexpanded parameter packs, which means that
01553       // our function parameter is still a function parameter pack.
01554       // Therefore, make its type a pack expansion type.
01555       NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
01556                                  NumExpansions);
01557     } else if (ExpectParameterPack) {
01558       // We expected to get a parameter pack but didn't (because the type
01559       // itself is not a pack expansion type), so complain. This can occur when
01560       // the substitution goes through an alias template that "loses" the
01561       // pack expansion.
01562       Diag(OldParm->getLocation(), 
01563            diag::err_function_parameter_pack_without_parameter_packs)
01564         << NewDI->getType();
01565       return 0;
01566     } 
01567   } else {
01568     NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(), 
01569                       OldParm->getDeclName());
01570   }
01571   
01572   if (!NewDI)
01573     return 0;
01574 
01575   if (NewDI->getType()->isVoidType()) {
01576     Diag(OldParm->getLocation(), diag::err_param_with_void_type);
01577     return 0;
01578   }
01579 
01580   ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
01581                                         OldParm->getInnerLocStart(),
01582                                         OldParm->getLocation(),
01583                                         OldParm->getIdentifier(),
01584                                         NewDI->getType(), NewDI,
01585                                         OldParm->getStorageClass(),
01586                                         OldParm->getStorageClassAsWritten());
01587   if (!NewParm)
01588     return 0;
01589                                                 
01590   // Mark the (new) default argument as uninstantiated (if any).
01591   if (OldParm->hasUninstantiatedDefaultArg()) {
01592     Expr *Arg = OldParm->getUninstantiatedDefaultArg();
01593     NewParm->setUninstantiatedDefaultArg(Arg);
01594   } else if (OldParm->hasUnparsedDefaultArg()) {
01595     NewParm->setUnparsedDefaultArg();
01596     UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
01597   } else if (Expr *Arg = OldParm->getDefaultArg())
01598     // FIXME: if we non-lazily instantiated non-dependent default args for
01599     // non-dependent parameter types we could remove a bunch of duplicate
01600     // conversion warnings for such arguments.
01601     NewParm->setUninstantiatedDefaultArg(Arg);
01602 
01603   NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
01604   
01605   if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
01606     // Add the new parameter to the instantiated parameter pack.
01607     CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
01608   } else {
01609     // Introduce an Old -> New mapping
01610     CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);  
01611   }
01612   
01613   // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
01614   // can be anything, is this right ?
01615   NewParm->setDeclContext(CurContext);
01616 
01617   NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
01618                         OldParm->getFunctionScopeIndex() + indexAdjustment);
01619   
01620   return NewParm;  
01621 }
01622 
01623 /// \brief Substitute the given template arguments into the given set of
01624 /// parameters, producing the set of parameter types that would be generated
01625 /// from such a substitution.
01626 bool Sema::SubstParmTypes(SourceLocation Loc, 
01627                           ParmVarDecl **Params, unsigned NumParams,
01628                           const MultiLevelTemplateArgumentList &TemplateArgs,
01629                           SmallVectorImpl<QualType> &ParamTypes,
01630                           SmallVectorImpl<ParmVarDecl *> *OutParams) {
01631   assert(!ActiveTemplateInstantiations.empty() &&
01632          "Cannot perform an instantiation without some context on the "
01633          "instantiation stack");
01634   
01635   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, 
01636                                     DeclarationName());
01637   return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
01638                                                   ParamTypes, OutParams);
01639 }
01640 
01641 /// \brief Perform substitution on the base class specifiers of the
01642 /// given class template specialization.
01643 ///
01644 /// Produces a diagnostic and returns true on error, returns false and
01645 /// attaches the instantiated base classes to the class template
01646 /// specialization if successful.
01647 bool
01648 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
01649                           CXXRecordDecl *Pattern,
01650                           const MultiLevelTemplateArgumentList &TemplateArgs) {
01651   bool Invalid = false;
01652   SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
01653   for (ClassTemplateSpecializationDecl::base_class_iterator
01654          Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
01655        Base != BaseEnd; ++Base) {
01656     if (!Base->getType()->isDependentType()) {
01657       InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
01658       continue;
01659     }
01660 
01661     SourceLocation EllipsisLoc;
01662     TypeSourceInfo *BaseTypeLoc;
01663     if (Base->isPackExpansion()) {
01664       // This is a pack expansion. See whether we should expand it now, or
01665       // wait until later.
01666       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
01667       collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
01668                                       Unexpanded);
01669       bool ShouldExpand = false;
01670       bool RetainExpansion = false;
01671       llvm::Optional<unsigned> NumExpansions;
01672       if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(), 
01673                                           Base->getSourceRange(),
01674                                           Unexpanded,
01675                                           TemplateArgs, ShouldExpand, 
01676                                           RetainExpansion,
01677                                           NumExpansions)) {
01678         Invalid = true;
01679         continue;
01680       }
01681       
01682       // If we should expand this pack expansion now, do so.
01683       if (ShouldExpand) {
01684         for (unsigned I = 0; I != *NumExpansions; ++I) {
01685             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
01686           
01687           TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
01688                                                   TemplateArgs,
01689                                               Base->getSourceRange().getBegin(),
01690                                                   DeclarationName());
01691           if (!BaseTypeLoc) {
01692             Invalid = true;
01693             continue;
01694           }
01695           
01696           if (CXXBaseSpecifier *InstantiatedBase
01697                 = CheckBaseSpecifier(Instantiation,
01698                                      Base->getSourceRange(),
01699                                      Base->isVirtual(),
01700                                      Base->getAccessSpecifierAsWritten(),
01701                                      BaseTypeLoc,
01702                                      SourceLocation()))
01703             InstantiatedBases.push_back(InstantiatedBase);
01704           else
01705             Invalid = true;
01706         }
01707       
01708         continue;
01709       }
01710       
01711       // The resulting base specifier will (still) be a pack expansion.
01712       EllipsisLoc = Base->getEllipsisLoc();
01713       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
01714       BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
01715                               TemplateArgs,
01716                               Base->getSourceRange().getBegin(),
01717                               DeclarationName());
01718     } else {
01719       BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
01720                               TemplateArgs,
01721                               Base->getSourceRange().getBegin(),
01722                               DeclarationName());
01723     }
01724     
01725     if (!BaseTypeLoc) {
01726       Invalid = true;
01727       continue;
01728     }
01729 
01730     if (CXXBaseSpecifier *InstantiatedBase
01731           = CheckBaseSpecifier(Instantiation,
01732                                Base->getSourceRange(),
01733                                Base->isVirtual(),
01734                                Base->getAccessSpecifierAsWritten(),
01735                                BaseTypeLoc,
01736                                EllipsisLoc))
01737       InstantiatedBases.push_back(InstantiatedBase);
01738     else
01739       Invalid = true;
01740   }
01741 
01742   if (!Invalid &&
01743       AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
01744                            InstantiatedBases.size()))
01745     Invalid = true;
01746 
01747   return Invalid;
01748 }
01749 
01750 // Defined via #include from SemaTemplateInstantiateDecl.cpp
01751 namespace clang {
01752   namespace sema {
01753     Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
01754                             const MultiLevelTemplateArgumentList &TemplateArgs);
01755   }
01756 }
01757 
01758 /// Determine whether we would be unable to instantiate this template (because
01759 /// it either has no definition, or is in the process of being instantiated).
01760 static bool DiagnoseUninstantiableTemplate(Sema &S,
01761                                            SourceLocation PointOfInstantiation,
01762                                            TagDecl *Instantiation,
01763                                            bool InstantiatedFromMember,
01764                                            TagDecl *Pattern,
01765                                            TagDecl *PatternDef,
01766                                            TemplateSpecializationKind TSK,
01767                                            bool Complain = true) {
01768   if (PatternDef && !PatternDef->isBeingDefined())
01769     return false;
01770 
01771   if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
01772     // Say nothing
01773   } else if (PatternDef) {
01774     assert(PatternDef->isBeingDefined());
01775     S.Diag(PointOfInstantiation,
01776            diag::err_template_instantiate_within_definition)
01777       << (TSK != TSK_ImplicitInstantiation)
01778       << S.Context.getTypeDeclType(Instantiation);
01779     // Not much point in noting the template declaration here, since
01780     // we're lexically inside it.
01781     Instantiation->setInvalidDecl();
01782   } else if (InstantiatedFromMember) {
01783     S.Diag(PointOfInstantiation,
01784            diag::err_implicit_instantiate_member_undefined)
01785       << S.Context.getTypeDeclType(Instantiation);
01786     S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
01787   } else {
01788     S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
01789       << (TSK != TSK_ImplicitInstantiation)
01790       << S.Context.getTypeDeclType(Instantiation);
01791     S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
01792   }
01793 
01794   // In general, Instantiation isn't marked invalid to get more than one
01795   // error for multiple undefined instantiations. But the code that does
01796   // explicit declaration -> explicit definition conversion can't handle
01797   // invalid declarations, so mark as invalid in that case.
01798   if (TSK == TSK_ExplicitInstantiationDeclaration)
01799     Instantiation->setInvalidDecl();
01800   return true;
01801 }
01802 
01803 /// \brief Instantiate the definition of a class from a given pattern.
01804 ///
01805 /// \param PointOfInstantiation The point of instantiation within the
01806 /// source code.
01807 ///
01808 /// \param Instantiation is the declaration whose definition is being
01809 /// instantiated. This will be either a class template specialization
01810 /// or a member class of a class template specialization.
01811 ///
01812 /// \param Pattern is the pattern from which the instantiation
01813 /// occurs. This will be either the declaration of a class template or
01814 /// the declaration of a member class of a class template.
01815 ///
01816 /// \param TemplateArgs The template arguments to be substituted into
01817 /// the pattern.
01818 ///
01819 /// \param TSK the kind of implicit or explicit instantiation to perform.
01820 ///
01821 /// \param Complain whether to complain if the class cannot be instantiated due
01822 /// to the lack of a definition.
01823 ///
01824 /// \returns true if an error occurred, false otherwise.
01825 bool
01826 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
01827                        CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
01828                        const MultiLevelTemplateArgumentList &TemplateArgs,
01829                        TemplateSpecializationKind TSK,
01830                        bool Complain) {
01831   bool Invalid = false;
01832 
01833   CXXRecordDecl *PatternDef
01834     = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
01835   if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
01836                                 Instantiation->getInstantiatedFromMemberClass(),
01837                                      Pattern, PatternDef, TSK, Complain))
01838     return true;
01839   Pattern = PatternDef;
01840 
01841   // \brief Record the point of instantiation.
01842   if (MemberSpecializationInfo *MSInfo 
01843         = Instantiation->getMemberSpecializationInfo()) {
01844     MSInfo->setTemplateSpecializationKind(TSK);
01845     MSInfo->setPointOfInstantiation(PointOfInstantiation);
01846   } else if (ClassTemplateSpecializationDecl *Spec 
01847         = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
01848     Spec->setTemplateSpecializationKind(TSK);
01849     Spec->setPointOfInstantiation(PointOfInstantiation);
01850   }
01851   
01852   InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
01853   if (Inst)
01854     return true;
01855 
01856   // Enter the scope of this instantiation. We don't use
01857   // PushDeclContext because we don't have a scope.
01858   ContextRAII SavedContext(*this, Instantiation);
01859   EnterExpressionEvaluationContext EvalContext(*this, 
01860                                                Sema::PotentiallyEvaluated);
01861 
01862   // If this is an instantiation of a local class, merge this local
01863   // instantiation scope with the enclosing scope. Otherwise, every
01864   // instantiation of a class has its own local instantiation scope.
01865   bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
01866   LocalInstantiationScope Scope(*this, MergeWithParentScope);
01867 
01868   // Pull attributes from the pattern onto the instantiation.
01869   InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
01870 
01871   // Start the definition of this instantiation.
01872   Instantiation->startDefinition();
01873   
01874   Instantiation->setTagKind(Pattern->getTagKind());
01875 
01876   // Do substitution on the base class specifiers.
01877   if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
01878     Invalid = true;
01879 
01880   TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
01881   SmallVector<Decl*, 4> Fields;
01882   SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
01883     FieldsWithMemberInitializers;
01884   // Delay instantiation of late parsed attributes.
01885   LateInstantiatedAttrVec LateAttrs;
01886   Instantiator.enableLateAttributeInstantiation(&LateAttrs);
01887 
01888   for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
01889          MemberEnd = Pattern->decls_end();
01890        Member != MemberEnd; ++Member) {
01891     // Don't instantiate members not belonging in this semantic context.
01892     // e.g. for:
01893     // @code
01894     //    template <int i> class A {
01895     //      class B *g;
01896     //    };
01897     // @endcode
01898     // 'class B' has the template as lexical context but semantically it is
01899     // introduced in namespace scope.
01900     if ((*Member)->getDeclContext() != Pattern)
01901       continue;
01902 
01903     if ((*Member)->isInvalidDecl()) {
01904       Invalid = true; 
01905       continue;
01906     }
01907 
01908     Decl *NewMember = Instantiator.Visit(*Member);
01909     if (NewMember) {
01910       if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
01911         Fields.push_back(Field);
01912         FieldDecl *OldField = cast<FieldDecl>(*Member);
01913         if (OldField->getInClassInitializer())
01914           FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
01915                                                                 Field));
01916       } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
01917         // C++11 [temp.inst]p1: The implicit instantiation of a class template
01918         // specialization causes the implicit instantiation of the definitions
01919         // of unscoped member enumerations.
01920         // Record a point of instantiation for this implicit instantiation.
01921         if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
01922             Enum->isCompleteDefinition()) {
01923           MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
01924           assert(MSInfo && "no spec info for member enum specialization");
01925           MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
01926           MSInfo->setPointOfInstantiation(PointOfInstantiation);
01927         }
01928       }
01929 
01930       if (NewMember->isInvalidDecl())
01931         Invalid = true;
01932     } else {
01933       // FIXME: Eventually, a NULL return will mean that one of the
01934       // instantiations was a semantic disaster, and we'll want to set Invalid =
01935       // true. For now, we expect to skip some members that we can't yet handle.
01936     }
01937   }
01938 
01939   // Finish checking fields.
01940   ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields, 
01941               SourceLocation(), SourceLocation(), 0);
01942   CheckCompletedCXXClass(Instantiation);
01943 
01944   // Attach any in-class member initializers now the class is complete.
01945   if (!FieldsWithMemberInitializers.empty()) {
01946     // C++11 [expr.prim.general]p4:
01947     //   Otherwise, if a member-declarator declares a non-static data member 
01948     //  (9.2) of a class X, the expression this is a prvalue of type "pointer
01949     //  to X" within the optional brace-or-equal-initializer. It shall not 
01950     //  appear elsewhere in the member-declarator.
01951     CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
01952     
01953     for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
01954       FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
01955       FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
01956       Expr *OldInit = OldField->getInClassInitializer();
01957 
01958       ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
01959                                             /*CXXDirectInit=*/false);
01960       if (NewInit.isInvalid())
01961         NewField->setInvalidDecl();
01962       else {
01963         Expr *Init = NewInit.take();
01964         assert(Init && "no-argument initializer in class");
01965         assert(!isa<ParenListExpr>(Init) && "call-style init in class");
01966         ActOnCXXInClassMemberInitializer(NewField, 
01967                                          Init->getSourceRange().getBegin(), 
01968                                          Init);
01969       }
01970     }
01971   }
01972   // Instantiate late parsed attributes, and attach them to their decls.
01973   // See Sema::InstantiateAttrs
01974   for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
01975        E = LateAttrs.end(); I != E; ++I) {
01976     assert(CurrentInstantiationScope == Instantiator.getStartingScope());
01977     CurrentInstantiationScope = I->Scope;
01978     Attr *NewAttr =
01979       instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
01980     I->NewDecl->addAttr(NewAttr);
01981     LocalInstantiationScope::deleteScopes(I->Scope,
01982                                           Instantiator.getStartingScope());
01983   }
01984   Instantiator.disableLateAttributeInstantiation();
01985   LateAttrs.clear();
01986 
01987   if (!FieldsWithMemberInitializers.empty())
01988     ActOnFinishDelayedMemberInitializers(Instantiation);
01989 
01990   if (TSK == TSK_ImplicitInstantiation) {
01991     Instantiation->setLocation(Pattern->getLocation());
01992     Instantiation->setLocStart(Pattern->getInnerLocStart());
01993     Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
01994   }
01995 
01996   if (Instantiation->isInvalidDecl())
01997     Invalid = true;
01998   else {
01999     // Instantiate any out-of-line class template partial
02000     // specializations now.
02001     for (TemplateDeclInstantiator::delayed_partial_spec_iterator 
02002               P = Instantiator.delayed_partial_spec_begin(),
02003            PEnd = Instantiator.delayed_partial_spec_end();
02004          P != PEnd; ++P) {
02005       if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
02006                                                                 P->first,
02007                                                                 P->second)) {
02008         Invalid = true;
02009         break;
02010       }
02011     }
02012   }
02013 
02014   // Exit the scope of this instantiation.
02015   SavedContext.pop();
02016 
02017   if (!Invalid) {
02018     Consumer.HandleTagDeclDefinition(Instantiation);
02019 
02020     // Always emit the vtable for an explicit instantiation definition
02021     // of a polymorphic class template specialization.
02022     if (TSK == TSK_ExplicitInstantiationDefinition)
02023       MarkVTableUsed(PointOfInstantiation, Instantiation, true);
02024   }
02025 
02026   return Invalid;
02027 }
02028 
02029 /// \brief Instantiate the definition of an enum from a given pattern.
02030 ///
02031 /// \param PointOfInstantiation The point of instantiation within the
02032 ///        source code.
02033 /// \param Instantiation is the declaration whose definition is being
02034 ///        instantiated. This will be a member enumeration of a class
02035 ///        temploid specialization, or a local enumeration within a
02036 ///        function temploid specialization.
02037 /// \param Pattern The templated declaration from which the instantiation
02038 ///        occurs.
02039 /// \param TemplateArgs The template arguments to be substituted into
02040 ///        the pattern.
02041 /// \param TSK The kind of implicit or explicit instantiation to perform.
02042 ///
02043 /// \return \c true if an error occurred, \c false otherwise.
02044 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
02045                            EnumDecl *Instantiation, EnumDecl *Pattern,
02046                            const MultiLevelTemplateArgumentList &TemplateArgs,
02047                            TemplateSpecializationKind TSK) {
02048   EnumDecl *PatternDef = Pattern->getDefinition();
02049   if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
02050                                  Instantiation->getInstantiatedFromMemberEnum(),
02051                                      Pattern, PatternDef, TSK,/*Complain*/true))
02052     return true;
02053   Pattern = PatternDef;
02054 
02055   // Record the point of instantiation.
02056   if (MemberSpecializationInfo *MSInfo
02057         = Instantiation->getMemberSpecializationInfo()) {
02058     MSInfo->setTemplateSpecializationKind(TSK);
02059     MSInfo->setPointOfInstantiation(PointOfInstantiation);
02060   }
02061 
02062   InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
02063   if (Inst)
02064     return true;
02065 
02066   // Enter the scope of this instantiation. We don't use
02067   // PushDeclContext because we don't have a scope.
02068   ContextRAII SavedContext(*this, Instantiation);
02069   EnterExpressionEvaluationContext EvalContext(*this,
02070                                                Sema::PotentiallyEvaluated);
02071 
02072   LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
02073 
02074   // Pull attributes from the pattern onto the instantiation.
02075   InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
02076 
02077   TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
02078   Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
02079 
02080   // Exit the scope of this instantiation.
02081   SavedContext.pop();
02082 
02083   return Instantiation->isInvalidDecl();
02084 }
02085 
02086 namespace {
02087   /// \brief A partial specialization whose template arguments have matched
02088   /// a given template-id.
02089   struct PartialSpecMatchResult {
02090     ClassTemplatePartialSpecializationDecl *Partial;
02091     TemplateArgumentList *Args;
02092   };
02093 }
02094 
02095 bool
02096 Sema::InstantiateClassTemplateSpecialization(
02097                            SourceLocation PointOfInstantiation,
02098                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
02099                            TemplateSpecializationKind TSK,
02100                            bool Complain) {
02101   // Perform the actual instantiation on the canonical declaration.
02102   ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
02103                                          ClassTemplateSpec->getCanonicalDecl());
02104 
02105   // Check whether we have already instantiated or specialized this class
02106   // template specialization.
02107   if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
02108     if (ClassTemplateSpec->getSpecializationKind() == 
02109           TSK_ExplicitInstantiationDeclaration &&
02110         TSK == TSK_ExplicitInstantiationDefinition) {
02111       // An explicit instantiation definition follows an explicit instantiation
02112       // declaration (C++0x [temp.explicit]p10); go ahead and perform the
02113       // explicit instantiation.
02114       ClassTemplateSpec->setSpecializationKind(TSK);
02115       
02116       // If this is an explicit instantiation definition, mark the
02117       // vtable as used.
02118       if (TSK == TSK_ExplicitInstantiationDefinition &&
02119           !ClassTemplateSpec->isInvalidDecl())
02120         MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
02121 
02122       return false;
02123     }
02124     
02125     // We can only instantiate something that hasn't already been
02126     // instantiated or specialized. Fail without any diagnostics: our
02127     // caller will provide an error message.    
02128     return true;
02129   }
02130 
02131   if (ClassTemplateSpec->isInvalidDecl())
02132     return true;
02133   
02134   ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
02135   CXXRecordDecl *Pattern = 0;
02136 
02137   // C++ [temp.class.spec.match]p1:
02138   //   When a class template is used in a context that requires an
02139   //   instantiation of the class, it is necessary to determine
02140   //   whether the instantiation is to be generated using the primary
02141   //   template or one of the partial specializations. This is done by
02142   //   matching the template arguments of the class template
02143   //   specialization with the template argument lists of the partial
02144   //   specializations.
02145   typedef PartialSpecMatchResult MatchResult;
02146   SmallVector<MatchResult, 4> Matched;
02147   SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
02148   Template->getPartialSpecializations(PartialSpecs);
02149   for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
02150     ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
02151     TemplateDeductionInfo Info(Context, PointOfInstantiation);
02152     if (TemplateDeductionResult Result
02153           = DeduceTemplateArguments(Partial,
02154                                     ClassTemplateSpec->getTemplateArgs(),
02155                                     Info)) {
02156       // FIXME: Store the failed-deduction information for use in
02157       // diagnostics, later.
02158       (void)Result;
02159     } else {
02160       Matched.push_back(PartialSpecMatchResult());
02161       Matched.back().Partial = Partial;
02162       Matched.back().Args = Info.take();
02163     }
02164   }
02165 
02166   // If we're dealing with a member template where the template parameters
02167   // have been instantiated, this provides the original template parameters
02168   // from which the member template's parameters were instantiated.
02169   SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
02170   
02171   if (Matched.size() >= 1) {
02172     SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
02173     if (Matched.size() == 1) {
02174       //   -- If exactly one matching specialization is found, the
02175       //      instantiation is generated from that specialization.
02176       // We don't need to do anything for this.
02177     } else {
02178       //   -- If more than one matching specialization is found, the
02179       //      partial order rules (14.5.4.2) are used to determine
02180       //      whether one of the specializations is more specialized
02181       //      than the others. If none of the specializations is more
02182       //      specialized than all of the other matching
02183       //      specializations, then the use of the class template is
02184       //      ambiguous and the program is ill-formed.
02185       for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
02186                                                     PEnd = Matched.end();
02187            P != PEnd; ++P) {
02188         if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
02189                                                     PointOfInstantiation) 
02190               == P->Partial)
02191           Best = P;
02192       }
02193       
02194       // Determine if the best partial specialization is more specialized than
02195       // the others.
02196       bool Ambiguous = false;
02197       for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
02198                                                     PEnd = Matched.end();
02199            P != PEnd; ++P) {
02200         if (P != Best &&
02201             getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
02202                                                     PointOfInstantiation)
02203               != Best->Partial) {
02204           Ambiguous = true;
02205           break;
02206         }
02207       }
02208        
02209       if (Ambiguous) {
02210         // Partial ordering did not produce a clear winner. Complain.
02211         ClassTemplateSpec->setInvalidDecl();
02212         Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
02213           << ClassTemplateSpec;
02214         
02215         // Print the matching partial specializations.
02216         for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
02217                                                       PEnd = Matched.end();
02218              P != PEnd; ++P)
02219           Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
02220             << getTemplateArgumentBindingsText(
02221                                             P->Partial->getTemplateParameters(),
02222                                                *P->Args);
02223 
02224         return true;
02225       }
02226     }
02227     
02228     // Instantiate using the best class template partial specialization.
02229     ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
02230     while (OrigPartialSpec->getInstantiatedFromMember()) {
02231       // If we've found an explicit specialization of this class template,
02232       // stop here and use that as the pattern.
02233       if (OrigPartialSpec->isMemberSpecialization())
02234         break;
02235       
02236       OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
02237     }
02238     
02239     Pattern = OrigPartialSpec;
02240     ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
02241   } else {
02242     //   -- If no matches are found, the instantiation is generated
02243     //      from the primary template.
02244     ClassTemplateDecl *OrigTemplate = Template;
02245     while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
02246       // If we've found an explicit specialization of this class template,
02247       // stop here and use that as the pattern.
02248       if (OrigTemplate->isMemberSpecialization())
02249         break;
02250       
02251       OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
02252     }
02253     
02254     Pattern = OrigTemplate->getTemplatedDecl();
02255   }
02256 
02257   bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec, 
02258                                  Pattern,
02259                                 getTemplateInstantiationArgs(ClassTemplateSpec),
02260                                  TSK,
02261                                  Complain);
02262 
02263   return Result;
02264 }
02265 
02266 /// \brief Instantiates the definitions of all of the member
02267 /// of the given class, which is an instantiation of a class template
02268 /// or a member class of a template.
02269 void
02270 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
02271                               CXXRecordDecl *Instantiation,
02272                         const MultiLevelTemplateArgumentList &TemplateArgs,
02273                               TemplateSpecializationKind TSK) {
02274   for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
02275                                DEnd = Instantiation->decls_end();
02276        D != DEnd; ++D) {
02277     bool SuppressNew = false;
02278     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
02279       if (FunctionDecl *Pattern
02280             = Function->getInstantiatedFromMemberFunction()) {
02281         MemberSpecializationInfo *MSInfo 
02282           = Function->getMemberSpecializationInfo();
02283         assert(MSInfo && "No member specialization information?");
02284         if (MSInfo->getTemplateSpecializationKind()
02285                                                  == TSK_ExplicitSpecialization)
02286           continue;
02287         
02288         if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 
02289                                                    Function, 
02290                                         MSInfo->getTemplateSpecializationKind(),
02291                                               MSInfo->getPointOfInstantiation(),
02292                                                    SuppressNew) ||
02293             SuppressNew)
02294           continue;
02295         
02296         if (Function->isDefined())
02297           continue;
02298 
02299         if (TSK == TSK_ExplicitInstantiationDefinition) {
02300           // C++0x [temp.explicit]p8:
02301           //   An explicit instantiation definition that names a class template
02302           //   specialization explicitly instantiates the class template 
02303           //   specialization and is only an explicit instantiation definition 
02304           //   of members whose definition is visible at the point of 
02305           //   instantiation.
02306           if (!Pattern->isDefined())
02307             continue;
02308         
02309           Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
02310                       
02311           InstantiateFunctionDefinition(PointOfInstantiation, Function);
02312         } else {
02313           Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
02314         }
02315       }
02316     } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
02317       if (Var->isStaticDataMember()) {
02318         MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
02319         assert(MSInfo && "No member specialization information?");
02320         if (MSInfo->getTemplateSpecializationKind()
02321                                                  == TSK_ExplicitSpecialization)
02322           continue;
02323         
02324         if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 
02325                                                    Var, 
02326                                         MSInfo->getTemplateSpecializationKind(),
02327                                               MSInfo->getPointOfInstantiation(),
02328                                                    SuppressNew) ||
02329             SuppressNew)
02330           continue;
02331         
02332         if (TSK == TSK_ExplicitInstantiationDefinition) {
02333           // C++0x [temp.explicit]p8:
02334           //   An explicit instantiation definition that names a class template
02335           //   specialization explicitly instantiates the class template 
02336           //   specialization and is only an explicit instantiation definition 
02337           //   of members whose definition is visible at the point of 
02338           //   instantiation.
02339           if (!Var->getInstantiatedFromStaticDataMember()
02340                                                      ->getOutOfLineDefinition())
02341             continue;
02342           
02343           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
02344           InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
02345         } else {
02346           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
02347         }
02348       }      
02349     } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
02350       // Always skip the injected-class-name, along with any
02351       // redeclarations of nested classes, since both would cause us
02352       // to try to instantiate the members of a class twice.
02353       if (Record->isInjectedClassName() || Record->getPreviousDecl())
02354         continue;
02355       
02356       MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
02357       assert(MSInfo && "No member specialization information?");
02358       
02359       if (MSInfo->getTemplateSpecializationKind()
02360                                                 == TSK_ExplicitSpecialization)
02361         continue;
02362 
02363       if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 
02364                                                  Record, 
02365                                         MSInfo->getTemplateSpecializationKind(),
02366                                               MSInfo->getPointOfInstantiation(),
02367                                                  SuppressNew) ||
02368           SuppressNew)
02369         continue;
02370       
02371       CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
02372       assert(Pattern && "Missing instantiated-from-template information");
02373       
02374       if (!Record->getDefinition()) {
02375         if (!Pattern->getDefinition()) {
02376           // C++0x [temp.explicit]p8:
02377           //   An explicit instantiation definition that names a class template
02378           //   specialization explicitly instantiates the class template 
02379           //   specialization and is only an explicit instantiation definition 
02380           //   of members whose definition is visible at the point of 
02381           //   instantiation.
02382           if (TSK == TSK_ExplicitInstantiationDeclaration) {
02383             MSInfo->setTemplateSpecializationKind(TSK);
02384             MSInfo->setPointOfInstantiation(PointOfInstantiation);
02385           }
02386           
02387           continue;
02388         }
02389         
02390         InstantiateClass(PointOfInstantiation, Record, Pattern,
02391                          TemplateArgs,
02392                          TSK);
02393       } else {
02394         if (TSK == TSK_ExplicitInstantiationDefinition &&
02395             Record->getTemplateSpecializationKind() ==
02396                 TSK_ExplicitInstantiationDeclaration) {
02397           Record->setTemplateSpecializationKind(TSK);
02398           MarkVTableUsed(PointOfInstantiation, Record, true);
02399         }
02400       }
02401       
02402       Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
02403       if (Pattern)
02404         InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs, 
02405                                 TSK);
02406     } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
02407       MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
02408       assert(MSInfo && "No member specialization information?");
02409 
02410       if (MSInfo->getTemplateSpecializationKind()
02411             == TSK_ExplicitSpecialization)
02412         continue;
02413 
02414       if (CheckSpecializationInstantiationRedecl(
02415             PointOfInstantiation, TSK, Enum,
02416             MSInfo->getTemplateSpecializationKind(),
02417             MSInfo->getPointOfInstantiation(), SuppressNew) ||
02418           SuppressNew)
02419         continue;
02420 
02421       if (Enum->getDefinition())
02422         continue;
02423 
02424       EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
02425       assert(Pattern && "Missing instantiated-from-template information");
02426 
02427       if (TSK == TSK_ExplicitInstantiationDefinition) {
02428         if (!Pattern->getDefinition())
02429           continue;
02430 
02431         InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
02432       } else {
02433         MSInfo->setTemplateSpecializationKind(TSK);
02434         MSInfo->setPointOfInstantiation(PointOfInstantiation);
02435       }
02436     }
02437   }
02438 }
02439 
02440 /// \brief Instantiate the definitions of all of the members of the
02441 /// given class template specialization, which was named as part of an
02442 /// explicit instantiation.
02443 void
02444 Sema::InstantiateClassTemplateSpecializationMembers(
02445                                            SourceLocation PointOfInstantiation,
02446                             ClassTemplateSpecializationDecl *ClassTemplateSpec,
02447                                                TemplateSpecializationKind TSK) {
02448   // C++0x [temp.explicit]p7:
02449   //   An explicit instantiation that names a class template
02450   //   specialization is an explicit instantion of the same kind
02451   //   (declaration or definition) of each of its members (not
02452   //   including members inherited from base classes) that has not
02453   //   been previously explicitly specialized in the translation unit
02454   //   containing the explicit instantiation, except as described
02455   //   below.
02456   InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
02457                           getTemplateInstantiationArgs(ClassTemplateSpec),
02458                           TSK);
02459 }
02460 
02461 StmtResult
02462 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
02463   if (!S)
02464     return Owned(S);
02465 
02466   TemplateInstantiator Instantiator(*this, TemplateArgs,
02467                                     SourceLocation(),
02468                                     DeclarationName());
02469   return Instantiator.TransformStmt(S);
02470 }
02471 
02472 ExprResult
02473 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
02474   if (!E)
02475     return Owned(E);
02476 
02477   TemplateInstantiator Instantiator(*this, TemplateArgs,
02478                                     SourceLocation(),
02479                                     DeclarationName());
02480   return Instantiator.TransformExpr(E);
02481 }
02482 
02483 bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
02484                       const MultiLevelTemplateArgumentList &TemplateArgs,
02485                       SmallVectorImpl<Expr *> &Outputs) {
02486   if (NumExprs == 0)
02487     return false;
02488   
02489   TemplateInstantiator Instantiator(*this, TemplateArgs,
02490                                     SourceLocation(),
02491                                     DeclarationName());
02492   return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
02493 }
02494 
02495 NestedNameSpecifierLoc
02496 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
02497                         const MultiLevelTemplateArgumentList &TemplateArgs) {  
02498   if (!NNS)
02499     return NestedNameSpecifierLoc();
02500   
02501   TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
02502                                     DeclarationName());
02503   return Instantiator.TransformNestedNameSpecifierLoc(NNS);
02504 }
02505 
02506 /// \brief Do template substitution on declaration name info.
02507 DeclarationNameInfo
02508 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
02509                          const MultiLevelTemplateArgumentList &TemplateArgs) {
02510   TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
02511                                     NameInfo.getName());
02512   return Instantiator.TransformDeclarationNameInfo(NameInfo);
02513 }
02514 
02515 TemplateName
02516 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
02517                         TemplateName Name, SourceLocation Loc,
02518                         const MultiLevelTemplateArgumentList &TemplateArgs) {
02519   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
02520                                     DeclarationName());
02521   CXXScopeSpec SS;
02522   SS.Adopt(QualifierLoc);
02523   return Instantiator.TransformTemplateName(SS, Name, Loc);
02524 }
02525 
02526 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
02527                  TemplateArgumentListInfo &Result,
02528                  const MultiLevelTemplateArgumentList &TemplateArgs) {
02529   TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
02530                                     DeclarationName());
02531   
02532   return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
02533 }
02534 
02535 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
02536 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
02537   for (LocalInstantiationScope *Current = this; Current;
02538        Current = Current->Outer) {
02539 
02540     // Check if we found something within this scope.
02541     const Decl *CheckD = D;
02542     do {
02543       LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
02544       if (Found != Current->LocalDecls.end())
02545         return &Found->second;
02546       
02547       // If this is a tag declaration, it's possible that we need to look for
02548       // a previous declaration.
02549       if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
02550         CheckD = Tag->getPreviousDecl();
02551       else
02552         CheckD = 0;
02553     } while (CheckD);
02554     
02555     // If we aren't combined with our outer scope, we're done. 
02556     if (!Current->CombineWithOuterScope)
02557       break;
02558   }
02559 
02560   // If we didn't find the decl, then we either have a sema bug, or we have a
02561   // forward reference to a label declaration.  Return null to indicate that
02562   // we have an uninstantiated label.
02563   assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
02564   return 0;
02565 }
02566 
02567 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
02568   llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
02569   if (Stored.isNull())
02570     Stored = Inst;
02571   else if (Stored.is<Decl *>()) {
02572     assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
02573     Stored = Inst;
02574   } else
02575     LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst);
02576 }
02577 
02578 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D, 
02579                                                        Decl *Inst) {
02580   DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
02581   Pack->push_back(Inst);
02582 }
02583 
02584 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
02585   llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
02586   assert(Stored.isNull() && "Already instantiated this local");
02587   DeclArgumentPack *Pack = new DeclArgumentPack;
02588   Stored = Pack;
02589   ArgumentPacks.push_back(Pack);
02590 }
02591 
02592 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack, 
02593                                           const TemplateArgument *ExplicitArgs,
02594                                                     unsigned NumExplicitArgs) {
02595   assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
02596          "Already have a partially-substituted pack");
02597   assert((!PartiallySubstitutedPack 
02598           || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
02599          "Wrong number of arguments in partially-substituted pack");
02600   PartiallySubstitutedPack = Pack;
02601   ArgsInPartiallySubstitutedPack = ExplicitArgs;
02602   NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
02603 }
02604 
02605 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
02606                                          const TemplateArgument **ExplicitArgs,
02607                                               unsigned *NumExplicitArgs) const {
02608   if (ExplicitArgs)
02609     *ExplicitArgs = 0;
02610   if (NumExplicitArgs)
02611     *NumExplicitArgs = 0;
02612   
02613   for (const LocalInstantiationScope *Current = this; Current; 
02614        Current = Current->Outer) {
02615     if (Current->PartiallySubstitutedPack) {
02616       if (ExplicitArgs)
02617         *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
02618       if (NumExplicitArgs)
02619         *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
02620       
02621       return Current->PartiallySubstitutedPack;
02622     }
02623 
02624     if (!Current->CombineWithOuterScope)
02625       break;
02626   }
02627   
02628   return 0;
02629 }