clang API Documentation

SemaTemplateInstantiateDecl.cpp
Go to the documentation of this file.
00001 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl 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 for declarations.
00010 //
00011 //===----------------------------------------------------------------------===/
00012 #include "clang/Sema/SemaInternal.h"
00013 #include "clang/Sema/Lookup.h"
00014 #include "clang/Sema/PrettyDeclStackTrace.h"
00015 #include "clang/Sema/Template.h"
00016 #include "clang/AST/ASTConsumer.h"
00017 #include "clang/AST/ASTContext.h"
00018 #include "clang/AST/DeclTemplate.h"
00019 #include "clang/AST/DeclVisitor.h"
00020 #include "clang/AST/DependentDiagnostic.h"
00021 #include "clang/AST/Expr.h"
00022 #include "clang/AST/ExprCXX.h"
00023 #include "clang/AST/TypeLoc.h"
00024 #include "clang/Lex/Preprocessor.h"
00025 
00026 using namespace clang;
00027 
00028 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
00029                                               DeclaratorDecl *NewDecl) {
00030   if (!OldDecl->getQualifierLoc())
00031     return false;
00032 
00033   NestedNameSpecifierLoc NewQualifierLoc
00034     = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
00035                                           TemplateArgs);
00036 
00037   if (!NewQualifierLoc)
00038     return true;
00039 
00040   NewDecl->setQualifierInfo(NewQualifierLoc);
00041   return false;
00042 }
00043 
00044 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
00045                                               TagDecl *NewDecl) {
00046   if (!OldDecl->getQualifierLoc())
00047     return false;
00048 
00049   NestedNameSpecifierLoc NewQualifierLoc
00050   = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
00051                                         TemplateArgs);
00052 
00053   if (!NewQualifierLoc)
00054     return true;
00055 
00056   NewDecl->setQualifierInfo(NewQualifierLoc);
00057   return false;
00058 }
00059 
00060 // Include attribute instantiation code.
00061 #include "clang/Sema/AttrTemplateInstantiate.inc"
00062 
00063 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
00064                             const Decl *Tmpl, Decl *New,
00065                             LateInstantiatedAttrVec *LateAttrs,
00066                             LocalInstantiationScope *OuterMostScope) {
00067   for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
00068        i != e; ++i) {
00069     const Attr *TmplAttr = *i;
00070 
00071     // FIXME: This should be generalized to more than just the AlignedAttr.
00072     if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
00073       if (Aligned->isAlignmentDependent()) {
00074         if (Aligned->isAlignmentExpr()) {
00075           // The alignment expression is a constant expression.
00076           EnterExpressionEvaluationContext Unevaluated(*this,
00077                                                        Sema::ConstantEvaluated);
00078 
00079           ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
00080                                         TemplateArgs);
00081           if (!Result.isInvalid())
00082             AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>());
00083         } else {
00084           TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
00085                                              TemplateArgs,
00086                                              Aligned->getLocation(),
00087                                              DeclarationName());
00088           if (Result)
00089             AddAlignedAttr(Aligned->getLocation(), New, Result);
00090         }
00091         continue;
00092       }
00093     }
00094 
00095     if (TmplAttr->isLateParsed() && LateAttrs) {
00096       // Late parsed attributes must be instantiated and attached after the
00097       // enclosing class has been instantiated.  See Sema::InstantiateClass.
00098       LocalInstantiationScope *Saved = 0;
00099       if (CurrentInstantiationScope)
00100         Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
00101       LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
00102     } else {
00103       Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
00104                                                          *this, TemplateArgs);
00105       if (NewAttr)
00106         New->addAttr(NewAttr);
00107     }
00108   }
00109 }
00110 
00111 Decl *
00112 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
00113   llvm_unreachable("Translation units cannot be instantiated");
00114 }
00115 
00116 Decl *
00117 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
00118   LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
00119                                       D->getIdentifier());
00120   Owner->addDecl(Inst);
00121   return Inst;
00122 }
00123 
00124 Decl *
00125 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
00126   llvm_unreachable("Namespaces cannot be instantiated");
00127 }
00128 
00129 Decl *
00130 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
00131   NamespaceAliasDecl *Inst
00132     = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
00133                                  D->getNamespaceLoc(),
00134                                  D->getAliasLoc(),
00135                                  D->getIdentifier(),
00136                                  D->getQualifierLoc(),
00137                                  D->getTargetNameLoc(),
00138                                  D->getNamespace());
00139   Owner->addDecl(Inst);
00140   return Inst;
00141 }
00142 
00143 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
00144                                                            bool IsTypeAlias) {
00145   bool Invalid = false;
00146   TypeSourceInfo *DI = D->getTypeSourceInfo();
00147   if (DI->getType()->isInstantiationDependentType() ||
00148       DI->getType()->isVariablyModifiedType()) {
00149     DI = SemaRef.SubstType(DI, TemplateArgs,
00150                            D->getLocation(), D->getDeclName());
00151     if (!DI) {
00152       Invalid = true;
00153       DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
00154     }
00155   } else {
00156     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
00157   }
00158 
00159   // Create the new typedef
00160   TypedefNameDecl *Typedef;
00161   if (IsTypeAlias)
00162     Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
00163                                     D->getLocation(), D->getIdentifier(), DI);
00164   else
00165     Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
00166                                   D->getLocation(), D->getIdentifier(), DI);
00167   if (Invalid)
00168     Typedef->setInvalidDecl();
00169 
00170   // If the old typedef was the name for linkage purposes of an anonymous
00171   // tag decl, re-establish that relationship for the new typedef.
00172   if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
00173     TagDecl *oldTag = oldTagType->getDecl();
00174     if (oldTag->getTypedefNameForAnonDecl() == D) {
00175       TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
00176       assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
00177       newTag->setTypedefNameForAnonDecl(Typedef);
00178     }
00179   }
00180 
00181   if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
00182     NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
00183                                                        TemplateArgs);
00184     if (!InstPrev)
00185       return 0;
00186 
00187     TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
00188 
00189     // If the typedef types are not identical, reject them.
00190     SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
00191 
00192     Typedef->setPreviousDeclaration(InstPrevTypedef);
00193   }
00194 
00195   SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
00196 
00197   Typedef->setAccess(D->getAccess());
00198 
00199   return Typedef;
00200 }
00201 
00202 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
00203   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
00204   Owner->addDecl(Typedef);
00205   return Typedef;
00206 }
00207 
00208 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
00209   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
00210   Owner->addDecl(Typedef);
00211   return Typedef;
00212 }
00213 
00214 Decl *
00215 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
00216   // Create a local instantiation scope for this type alias template, which
00217   // will contain the instantiations of the template parameters.
00218   LocalInstantiationScope Scope(SemaRef);
00219 
00220   TemplateParameterList *TempParams = D->getTemplateParameters();
00221   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
00222   if (!InstParams)
00223     return 0;
00224 
00225   TypeAliasDecl *Pattern = D->getTemplatedDecl();
00226 
00227   TypeAliasTemplateDecl *PrevAliasTemplate = 0;
00228   if (Pattern->getPreviousDecl()) {
00229     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
00230     if (Found.first != Found.second) {
00231       PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first);
00232     }
00233   }
00234 
00235   TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
00236     InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
00237   if (!AliasInst)
00238     return 0;
00239 
00240   TypeAliasTemplateDecl *Inst
00241     = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
00242                                     D->getDeclName(), InstParams, AliasInst);
00243   if (PrevAliasTemplate)
00244     Inst->setPreviousDeclaration(PrevAliasTemplate);
00245 
00246   Inst->setAccess(D->getAccess());
00247 
00248   if (!PrevAliasTemplate)
00249     Inst->setInstantiatedFromMemberTemplate(D);
00250 
00251   Owner->addDecl(Inst);
00252 
00253   return Inst;
00254 }
00255 
00256 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
00257   // If this is the variable for an anonymous struct or union,
00258   // instantiate the anonymous struct/union type first.
00259   if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
00260     if (RecordTy->getDecl()->isAnonymousStructOrUnion())
00261       if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
00262         return 0;
00263 
00264   // Do substitution on the type of the declaration
00265   TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
00266                                          TemplateArgs,
00267                                          D->getTypeSpecStartLoc(),
00268                                          D->getDeclName());
00269   if (!DI)
00270     return 0;
00271 
00272   if (DI->getType()->isFunctionType()) {
00273     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
00274       << D->isStaticDataMember() << DI->getType();
00275     return 0;
00276   }
00277 
00278   // Build the instantiated declaration
00279   VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
00280                                  D->getInnerLocStart(),
00281                                  D->getLocation(), D->getIdentifier(),
00282                                  DI->getType(), DI,
00283                                  D->getStorageClass(),
00284                                  D->getStorageClassAsWritten());
00285   Var->setThreadSpecified(D->isThreadSpecified());
00286   Var->setInitStyle(D->getInitStyle());
00287   Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
00288   Var->setConstexpr(D->isConstexpr());
00289 
00290   // Substitute the nested name specifier, if any.
00291   if (SubstQualifier(D, Var))
00292     return 0;
00293 
00294   // If we are instantiating a static data member defined
00295   // out-of-line, the instantiation will have the same lexical
00296   // context (which will be a namespace scope) as the template.
00297   if (D->isOutOfLine())
00298     Var->setLexicalDeclContext(D->getLexicalDeclContext());
00299 
00300   Var->setAccess(D->getAccess());
00301 
00302   if (!D->isStaticDataMember()) {
00303     Var->setUsed(D->isUsed(false));
00304     Var->setReferenced(D->isReferenced());
00305   }
00306 
00307   // FIXME: In theory, we could have a previous declaration for variables that
00308   // are not static data members.
00309   // FIXME: having to fake up a LookupResult is dumb.
00310   LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
00311                         Sema::LookupOrdinaryName, Sema::ForRedeclaration);
00312   if (D->isStaticDataMember())
00313     SemaRef.LookupQualifiedName(Previous, Owner, false);
00314   
00315   // In ARC, infer 'retaining' for variables of retainable type.
00316   if (SemaRef.getLangOpts().ObjCAutoRefCount && 
00317       SemaRef.inferObjCARCLifetime(Var))
00318     Var->setInvalidDecl();
00319 
00320   SemaRef.CheckVariableDeclaration(Var, Previous);
00321 
00322   if (D->isOutOfLine()) {
00323     D->getLexicalDeclContext()->addDecl(Var);
00324     Owner->makeDeclVisibleInContext(Var);
00325   } else {
00326     Owner->addDecl(Var);
00327     if (Owner->isFunctionOrMethod())
00328       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
00329   }
00330   SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
00331 
00332   // Link instantiations of static data members back to the template from
00333   // which they were instantiated.
00334   if (Var->isStaticDataMember())
00335     SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
00336                                                      TSK_ImplicitInstantiation);
00337 
00338   if (Var->getAnyInitializer()) {
00339     // We already have an initializer in the class.
00340   } else if (D->getInit()) {
00341     if (Var->isStaticDataMember() && !D->isOutOfLine())
00342       SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated);
00343     else
00344       SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
00345 
00346     // Instantiate the initializer.
00347     ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
00348                                         D->getInitStyle() == VarDecl::CallInit);
00349     if (!Init.isInvalid()) {
00350       bool TypeMayContainAuto = true;
00351       if (Init.get()) {
00352         bool DirectInit = D->isDirectInit();
00353         SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
00354                                      TypeMayContainAuto);
00355       } else
00356         SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
00357     } else {
00358       // FIXME: Not too happy about invalidating the declaration
00359       // because of a bogus initializer.
00360       Var->setInvalidDecl();
00361     }
00362 
00363     SemaRef.PopExpressionEvaluationContext();
00364   } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
00365              !Var->isCXXForRangeDecl())
00366     SemaRef.ActOnUninitializedDecl(Var, false);
00367 
00368   // Diagnose unused local variables with dependent types, where the diagnostic
00369   // will have been deferred.
00370   if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
00371       D->getType()->isDependentType())
00372     SemaRef.DiagnoseUnusedDecl(Var);
00373 
00374   return Var;
00375 }
00376 
00377 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
00378   AccessSpecDecl* AD
00379     = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
00380                              D->getAccessSpecifierLoc(), D->getColonLoc());
00381   Owner->addHiddenDecl(AD);
00382   return AD;
00383 }
00384 
00385 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
00386   bool Invalid = false;
00387   TypeSourceInfo *DI = D->getTypeSourceInfo();
00388   if (DI->getType()->isInstantiationDependentType() ||
00389       DI->getType()->isVariablyModifiedType())  {
00390     DI = SemaRef.SubstType(DI, TemplateArgs,
00391                            D->getLocation(), D->getDeclName());
00392     if (!DI) {
00393       DI = D->getTypeSourceInfo();
00394       Invalid = true;
00395     } else if (DI->getType()->isFunctionType()) {
00396       // C++ [temp.arg.type]p3:
00397       //   If a declaration acquires a function type through a type
00398       //   dependent on a template-parameter and this causes a
00399       //   declaration that does not use the syntactic form of a
00400       //   function declarator to have function type, the program is
00401       //   ill-formed.
00402       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
00403         << DI->getType();
00404       Invalid = true;
00405     }
00406   } else {
00407     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
00408   }
00409 
00410   Expr *BitWidth = D->getBitWidth();
00411   if (Invalid)
00412     BitWidth = 0;
00413   else if (BitWidth) {
00414     // The bit-width expression is a constant expression.
00415     EnterExpressionEvaluationContext Unevaluated(SemaRef,
00416                                                  Sema::ConstantEvaluated);
00417 
00418     ExprResult InstantiatedBitWidth
00419       = SemaRef.SubstExpr(BitWidth, TemplateArgs);
00420     if (InstantiatedBitWidth.isInvalid()) {
00421       Invalid = true;
00422       BitWidth = 0;
00423     } else
00424       BitWidth = InstantiatedBitWidth.takeAs<Expr>();
00425   }
00426 
00427   FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
00428                                             DI->getType(), DI,
00429                                             cast<RecordDecl>(Owner),
00430                                             D->getLocation(),
00431                                             D->isMutable(),
00432                                             BitWidth,
00433                                             D->hasInClassInitializer(),
00434                                             D->getTypeSpecStartLoc(),
00435                                             D->getAccess(),
00436                                             0);
00437   if (!Field) {
00438     cast<Decl>(Owner)->setInvalidDecl();
00439     return 0;
00440   }
00441 
00442   SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
00443 
00444   if (Invalid)
00445     Field->setInvalidDecl();
00446 
00447   if (!Field->getDeclName()) {
00448     // Keep track of where this decl came from.
00449     SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
00450   }
00451   if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
00452     if (Parent->isAnonymousStructOrUnion() &&
00453         Parent->getRedeclContext()->isFunctionOrMethod())
00454       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
00455   }
00456 
00457   Field->setImplicit(D->isImplicit());
00458   Field->setAccess(D->getAccess());
00459   Owner->addDecl(Field);
00460 
00461   return Field;
00462 }
00463 
00464 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
00465   NamedDecl **NamedChain =
00466     new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
00467 
00468   int i = 0;
00469   for (IndirectFieldDecl::chain_iterator PI =
00470        D->chain_begin(), PE = D->chain_end();
00471        PI != PE; ++PI) {
00472     NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
00473                                               TemplateArgs);
00474     if (!Next)
00475       return 0;
00476 
00477     NamedChain[i++] = Next;
00478   }
00479 
00480   QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
00481   IndirectFieldDecl* IndirectField
00482     = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
00483                                 D->getIdentifier(), T,
00484                                 NamedChain, D->getChainingSize());
00485 
00486 
00487   IndirectField->setImplicit(D->isImplicit());
00488   IndirectField->setAccess(D->getAccess());
00489   Owner->addDecl(IndirectField);
00490   return IndirectField;
00491 }
00492 
00493 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
00494   // Handle friend type expressions by simply substituting template
00495   // parameters into the pattern type and checking the result.
00496   if (TypeSourceInfo *Ty = D->getFriendType()) {
00497     TypeSourceInfo *InstTy;
00498     // If this is an unsupported friend, don't bother substituting template
00499     // arguments into it. The actual type referred to won't be used by any
00500     // parts of Clang, and may not be valid for instantiating. Just use the
00501     // same info for the instantiated friend.
00502     if (D->isUnsupportedFriend()) {
00503       InstTy = Ty;
00504     } else {
00505       InstTy = SemaRef.SubstType(Ty, TemplateArgs,
00506                                  D->getLocation(), DeclarationName());
00507     }
00508     if (!InstTy)
00509       return 0;
00510 
00511     FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocation(),
00512                                                  D->getFriendLoc(), InstTy);
00513     if (!FD)
00514       return 0;
00515 
00516     FD->setAccess(AS_public);
00517     FD->setUnsupportedFriend(D->isUnsupportedFriend());
00518     Owner->addDecl(FD);
00519     return FD;
00520   }
00521 
00522   NamedDecl *ND = D->getFriendDecl();
00523   assert(ND && "friend decl must be a decl or a type!");
00524 
00525   // All of the Visit implementations for the various potential friend
00526   // declarations have to be carefully written to work for friend
00527   // objects, with the most important detail being that the target
00528   // decl should almost certainly not be placed in Owner.
00529   Decl *NewND = Visit(ND);
00530   if (!NewND) return 0;
00531 
00532   FriendDecl *FD =
00533     FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
00534                        cast<NamedDecl>(NewND), D->getFriendLoc());
00535   FD->setAccess(AS_public);
00536   FD->setUnsupportedFriend(D->isUnsupportedFriend());
00537   Owner->addDecl(FD);
00538   return FD;
00539 }
00540 
00541 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
00542   Expr *AssertExpr = D->getAssertExpr();
00543 
00544   // The expression in a static assertion is a constant expression.
00545   EnterExpressionEvaluationContext Unevaluated(SemaRef,
00546                                                Sema::ConstantEvaluated);
00547 
00548   ExprResult InstantiatedAssertExpr
00549     = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
00550   if (InstantiatedAssertExpr.isInvalid())
00551     return 0;
00552 
00553   ExprResult Message(D->getMessage());
00554   D->getMessage();
00555   return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
00556                                               InstantiatedAssertExpr.get(),
00557                                               Message.get(),
00558                                               D->getRParenLoc());
00559 }
00560 
00561 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
00562   EnumDecl *PrevDecl = 0;
00563   if (D->getPreviousDecl()) {
00564     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
00565                                                    D->getPreviousDecl(),
00566                                                    TemplateArgs);
00567     if (!Prev) return 0;
00568     PrevDecl = cast<EnumDecl>(Prev);
00569   }
00570 
00571   EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
00572                                     D->getLocation(), D->getIdentifier(),
00573                                     PrevDecl, D->isScoped(),
00574                                     D->isScopedUsingClassTag(), D->isFixed());
00575   if (D->isFixed()) {
00576     if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
00577       // If we have type source information for the underlying type, it means it
00578       // has been explicitly set by the user. Perform substitution on it before
00579       // moving on.
00580       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
00581       TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
00582                                                 DeclarationName());
00583       if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
00584         Enum->setIntegerType(SemaRef.Context.IntTy);
00585       else
00586         Enum->setIntegerTypeSourceInfo(NewTI);
00587     } else {
00588       assert(!D->getIntegerType()->isDependentType()
00589              && "Dependent type without type source info");
00590       Enum->setIntegerType(D->getIntegerType());
00591     }
00592   }
00593 
00594   SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
00595 
00596   Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
00597   Enum->setAccess(D->getAccess());
00598   if (SubstQualifier(D, Enum)) return 0;
00599   Owner->addDecl(Enum);
00600 
00601   EnumDecl *Def = D->getDefinition();
00602   if (Def && Def != D) {
00603     // If this is an out-of-line definition of an enum member template, check
00604     // that the underlying types match in the instantiation of both
00605     // declarations.
00606     if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
00607       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
00608       QualType DefnUnderlying =
00609         SemaRef.SubstType(TI->getType(), TemplateArgs,
00610                           UnderlyingLoc, DeclarationName());
00611       SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
00612                                      DefnUnderlying, Enum);
00613     }
00614   }
00615 
00616   if (D->getDeclContext()->isFunctionOrMethod())
00617     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
00618 
00619   // C++11 [temp.inst]p1: The implicit instantiation of a class template
00620   // specialization causes the implicit instantiation of the declarations, but
00621   // not the definitions of scoped member enumerations.
00622   // FIXME: There appears to be no wording for what happens for an enum defined
00623   // within a block scope, but we treat that much like a member template. Only
00624   // instantiate the definition when visiting the definition in that case, since
00625   // we will visit all redeclarations.
00626   if (!Enum->isScoped() && Def &&
00627       (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
00628     InstantiateEnumDefinition(Enum, Def);
00629 
00630   return Enum;
00631 }
00632 
00633 void TemplateDeclInstantiator::InstantiateEnumDefinition(
00634     EnumDecl *Enum, EnumDecl *Pattern) {
00635   Enum->startDefinition();
00636 
00637   // Update the location to refer to the definition.
00638   Enum->setLocation(Pattern->getLocation());
00639 
00640   SmallVector<Decl*, 4> Enumerators;
00641 
00642   EnumConstantDecl *LastEnumConst = 0;
00643   for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
00644          ECEnd = Pattern->enumerator_end();
00645        EC != ECEnd; ++EC) {
00646     // The specified value for the enumerator.
00647     ExprResult Value = SemaRef.Owned((Expr *)0);
00648     if (Expr *UninstValue = EC->getInitExpr()) {
00649       // The enumerator's value expression is a constant expression.
00650       EnterExpressionEvaluationContext Unevaluated(SemaRef,
00651                                                    Sema::ConstantEvaluated);
00652 
00653       Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
00654     }
00655 
00656     // Drop the initial value and continue.
00657     bool isInvalid = false;
00658     if (Value.isInvalid()) {
00659       Value = SemaRef.Owned((Expr *)0);
00660       isInvalid = true;
00661     }
00662 
00663     EnumConstantDecl *EnumConst
00664       = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
00665                                   EC->getLocation(), EC->getIdentifier(),
00666                                   Value.get());
00667 
00668     if (isInvalid) {
00669       if (EnumConst)
00670         EnumConst->setInvalidDecl();
00671       Enum->setInvalidDecl();
00672     }
00673 
00674     if (EnumConst) {
00675       SemaRef.InstantiateAttrs(TemplateArgs, &*EC, EnumConst);
00676 
00677       EnumConst->setAccess(Enum->getAccess());
00678       Enum->addDecl(EnumConst);
00679       Enumerators.push_back(EnumConst);
00680       LastEnumConst = EnumConst;
00681 
00682       if (Pattern->getDeclContext()->isFunctionOrMethod() &&
00683           !Enum->isScoped()) {
00684         // If the enumeration is within a function or method, record the enum
00685         // constant as a local.
00686         SemaRef.CurrentInstantiationScope->InstantiatedLocal(&*EC, EnumConst);
00687       }
00688     }
00689   }
00690 
00691   // FIXME: Fixup LBraceLoc
00692   SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
00693                         Enum->getRBraceLoc(), Enum,
00694                         Enumerators.data(), Enumerators.size(),
00695                         0, 0);
00696 }
00697 
00698 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
00699   llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
00700 }
00701 
00702 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
00703   bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
00704 
00705   // Create a local instantiation scope for this class template, which
00706   // will contain the instantiations of the template parameters.
00707   LocalInstantiationScope Scope(SemaRef);
00708   TemplateParameterList *TempParams = D->getTemplateParameters();
00709   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
00710   if (!InstParams)
00711     return NULL;
00712 
00713   CXXRecordDecl *Pattern = D->getTemplatedDecl();
00714 
00715   // Instantiate the qualifier.  We have to do this first in case
00716   // we're a friend declaration, because if we are then we need to put
00717   // the new declaration in the appropriate context.
00718   NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
00719   if (QualifierLoc) {
00720     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
00721                                                        TemplateArgs);
00722     if (!QualifierLoc)
00723       return 0;
00724   }
00725 
00726   CXXRecordDecl *PrevDecl = 0;
00727   ClassTemplateDecl *PrevClassTemplate = 0;
00728 
00729   if (!isFriend && Pattern->getPreviousDecl()) {
00730     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
00731     if (Found.first != Found.second) {
00732       PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
00733       if (PrevClassTemplate)
00734         PrevDecl = PrevClassTemplate->getTemplatedDecl();
00735     }
00736   }
00737 
00738   // If this isn't a friend, then it's a member template, in which
00739   // case we just want to build the instantiation in the
00740   // specialization.  If it is a friend, we want to build it in
00741   // the appropriate context.
00742   DeclContext *DC = Owner;
00743   if (isFriend) {
00744     if (QualifierLoc) {
00745       CXXScopeSpec SS;
00746       SS.Adopt(QualifierLoc);
00747       DC = SemaRef.computeDeclContext(SS);
00748       if (!DC) return 0;
00749     } else {
00750       DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
00751                                            Pattern->getDeclContext(),
00752                                            TemplateArgs);
00753     }
00754 
00755     // Look for a previous declaration of the template in the owning
00756     // context.
00757     LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
00758                    Sema::LookupOrdinaryName, Sema::ForRedeclaration);
00759     SemaRef.LookupQualifiedName(R, DC);
00760 
00761     if (R.isSingleResult()) {
00762       PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
00763       if (PrevClassTemplate)
00764         PrevDecl = PrevClassTemplate->getTemplatedDecl();
00765     }
00766 
00767     if (!PrevClassTemplate && QualifierLoc) {
00768       SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
00769         << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
00770         << QualifierLoc.getSourceRange();
00771       return 0;
00772     }
00773 
00774     bool AdoptedPreviousTemplateParams = false;
00775     if (PrevClassTemplate) {
00776       bool Complain = true;
00777 
00778       // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
00779       // template for struct std::tr1::__detail::_Map_base, where the
00780       // template parameters of the friend declaration don't match the
00781       // template parameters of the original declaration. In this one
00782       // case, we don't complain about the ill-formed friend
00783       // declaration.
00784       if (isFriend && Pattern->getIdentifier() &&
00785           Pattern->getIdentifier()->isStr("_Map_base") &&
00786           DC->isNamespace() &&
00787           cast<NamespaceDecl>(DC)->getIdentifier() &&
00788           cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
00789         DeclContext *DCParent = DC->getParent();
00790         if (DCParent->isNamespace() &&
00791             cast<NamespaceDecl>(DCParent)->getIdentifier() &&
00792             cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
00793           DeclContext *DCParent2 = DCParent->getParent();
00794           if (DCParent2->isNamespace() &&
00795               cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
00796               cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
00797               DCParent2->getParent()->isTranslationUnit())
00798             Complain = false;
00799         }
00800       }
00801 
00802       TemplateParameterList *PrevParams
00803         = PrevClassTemplate->getTemplateParameters();
00804 
00805       // Make sure the parameter lists match.
00806       if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
00807                                                   Complain,
00808                                                   Sema::TPL_TemplateMatch)) {
00809         if (Complain)
00810           return 0;
00811 
00812         AdoptedPreviousTemplateParams = true;
00813         InstParams = PrevParams;
00814       }
00815 
00816       // Do some additional validation, then merge default arguments
00817       // from the existing declarations.
00818       if (!AdoptedPreviousTemplateParams &&
00819           SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
00820                                              Sema::TPC_ClassTemplate))
00821         return 0;
00822     }
00823   }
00824 
00825   CXXRecordDecl *RecordInst
00826     = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
00827                             Pattern->getLocStart(), Pattern->getLocation(),
00828                             Pattern->getIdentifier(), PrevDecl,
00829                             /*DelayTypeCreation=*/true);
00830 
00831   if (QualifierLoc)
00832     RecordInst->setQualifierInfo(QualifierLoc);
00833 
00834   ClassTemplateDecl *Inst
00835     = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
00836                                 D->getIdentifier(), InstParams, RecordInst,
00837                                 PrevClassTemplate);
00838   RecordInst->setDescribedClassTemplate(Inst);
00839 
00840   if (isFriend) {
00841     if (PrevClassTemplate)
00842       Inst->setAccess(PrevClassTemplate->getAccess());
00843     else
00844       Inst->setAccess(D->getAccess());
00845 
00846     Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
00847     // TODO: do we want to track the instantiation progeny of this
00848     // friend target decl?
00849   } else {
00850     Inst->setAccess(D->getAccess());
00851     if (!PrevClassTemplate)
00852       Inst->setInstantiatedFromMemberTemplate(D);
00853   }
00854 
00855   // Trigger creation of the type for the instantiation.
00856   SemaRef.Context.getInjectedClassNameType(RecordInst,
00857                                     Inst->getInjectedClassNameSpecialization());
00858 
00859   // Finish handling of friends.
00860   if (isFriend) {
00861     DC->makeDeclVisibleInContext(Inst);
00862     Inst->setLexicalDeclContext(Owner);
00863     RecordInst->setLexicalDeclContext(Owner);
00864     return Inst;
00865   }
00866 
00867   if (D->isOutOfLine()) {
00868     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
00869     RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
00870   }
00871 
00872   Owner->addDecl(Inst);
00873 
00874   if (!PrevClassTemplate) {
00875     // Queue up any out-of-line partial specializations of this member
00876     // class template; the client will force their instantiation once
00877     // the enclosing class has been instantiated.
00878     SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
00879     D->getPartialSpecializations(PartialSpecs);
00880     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
00881       if (PartialSpecs[I]->isOutOfLine())
00882         OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
00883   }
00884 
00885   return Inst;
00886 }
00887 
00888 Decl *
00889 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
00890                                    ClassTemplatePartialSpecializationDecl *D) {
00891   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
00892 
00893   // Lookup the already-instantiated declaration in the instantiation
00894   // of the class template and return that.
00895   DeclContext::lookup_result Found
00896     = Owner->lookup(ClassTemplate->getDeclName());
00897   if (Found.first == Found.second)
00898     return 0;
00899 
00900   ClassTemplateDecl *InstClassTemplate
00901     = dyn_cast<ClassTemplateDecl>(*Found.first);
00902   if (!InstClassTemplate)
00903     return 0;
00904 
00905   if (ClassTemplatePartialSpecializationDecl *Result
00906         = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
00907     return Result;
00908 
00909   return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
00910 }
00911 
00912 Decl *
00913 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
00914   // Create a local instantiation scope for this function template, which
00915   // will contain the instantiations of the template parameters and then get
00916   // merged with the local instantiation scope for the function template
00917   // itself.
00918   LocalInstantiationScope Scope(SemaRef);
00919 
00920   TemplateParameterList *TempParams = D->getTemplateParameters();
00921   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
00922   if (!InstParams)
00923     return NULL;
00924 
00925   FunctionDecl *Instantiated = 0;
00926   if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
00927     Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
00928                                                                  InstParams));
00929   else
00930     Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
00931                                                           D->getTemplatedDecl(),
00932                                                                 InstParams));
00933 
00934   if (!Instantiated)
00935     return 0;
00936 
00937   Instantiated->setAccess(D->getAccess());
00938 
00939   // Link the instantiated function template declaration to the function
00940   // template from which it was instantiated.
00941   FunctionTemplateDecl *InstTemplate
00942     = Instantiated->getDescribedFunctionTemplate();
00943   InstTemplate->setAccess(D->getAccess());
00944   assert(InstTemplate &&
00945          "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
00946 
00947   bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
00948 
00949   // Link the instantiation back to the pattern *unless* this is a
00950   // non-definition friend declaration.
00951   if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
00952       !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
00953     InstTemplate->setInstantiatedFromMemberTemplate(D);
00954 
00955   // Make declarations visible in the appropriate context.
00956   if (!isFriend)
00957     Owner->addDecl(InstTemplate);
00958 
00959   return InstTemplate;
00960 }
00961 
00962 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
00963   CXXRecordDecl *PrevDecl = 0;
00964   if (D->isInjectedClassName())
00965     PrevDecl = cast<CXXRecordDecl>(Owner);
00966   else if (D->getPreviousDecl()) {
00967     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
00968                                                    D->getPreviousDecl(),
00969                                                    TemplateArgs);
00970     if (!Prev) return 0;
00971     PrevDecl = cast<CXXRecordDecl>(Prev);
00972   }
00973 
00974   CXXRecordDecl *Record
00975     = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
00976                             D->getLocStart(), D->getLocation(),
00977                             D->getIdentifier(), PrevDecl);
00978 
00979   // Substitute the nested name specifier, if any.
00980   if (SubstQualifier(D, Record))
00981     return 0;
00982 
00983   Record->setImplicit(D->isImplicit());
00984   // FIXME: Check against AS_none is an ugly hack to work around the issue that
00985   // the tag decls introduced by friend class declarations don't have an access
00986   // specifier. Remove once this area of the code gets sorted out.
00987   if (D->getAccess() != AS_none)
00988     Record->setAccess(D->getAccess());
00989   if (!D->isInjectedClassName())
00990     Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
00991 
00992   // If the original function was part of a friend declaration,
00993   // inherit its namespace state.
00994   if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
00995     Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
00996 
00997   // Make sure that anonymous structs and unions are recorded.
00998   if (D->isAnonymousStructOrUnion()) {
00999     Record->setAnonymousStructOrUnion(true);
01000     if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
01001       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
01002   }
01003 
01004   Owner->addDecl(Record);
01005   return Record;
01006 }
01007 
01008 /// Normal class members are of more specific types and therefore
01009 /// don't make it here.  This function serves two purposes:
01010 ///   1) instantiating function templates
01011 ///   2) substituting friend declarations
01012 /// FIXME: preserve function definitions in case #2
01013 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
01014                                        TemplateParameterList *TemplateParams) {
01015   // Check whether there is already a function template specialization for
01016   // this declaration.
01017   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
01018   if (FunctionTemplate && !TemplateParams) {
01019     std::pair<const TemplateArgument *, unsigned> Innermost
01020       = TemplateArgs.getInnermost();
01021 
01022     void *InsertPos = 0;
01023     FunctionDecl *SpecFunc
01024       = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
01025                                              InsertPos);
01026 
01027     // If we already have a function template specialization, return it.
01028     if (SpecFunc)
01029       return SpecFunc;
01030   }
01031 
01032   bool isFriend;
01033   if (FunctionTemplate)
01034     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
01035   else
01036     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
01037 
01038   bool MergeWithParentScope = (TemplateParams != 0) ||
01039     Owner->isFunctionOrMethod() ||
01040     !(isa<Decl>(Owner) &&
01041       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
01042   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
01043 
01044   SmallVector<ParmVarDecl *, 4> Params;
01045   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
01046   if (!TInfo)
01047     return 0;
01048   QualType T = TInfo->getType();
01049 
01050   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
01051   if (QualifierLoc) {
01052     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
01053                                                        TemplateArgs);
01054     if (!QualifierLoc)
01055       return 0;
01056   }
01057 
01058   // If we're instantiating a local function declaration, put the result
01059   // in the owner;  otherwise we need to find the instantiated context.
01060   DeclContext *DC;
01061   if (D->getDeclContext()->isFunctionOrMethod())
01062     DC = Owner;
01063   else if (isFriend && QualifierLoc) {
01064     CXXScopeSpec SS;
01065     SS.Adopt(QualifierLoc);
01066     DC = SemaRef.computeDeclContext(SS);
01067     if (!DC) return 0;
01068   } else {
01069     DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
01070                                          TemplateArgs);
01071   }
01072 
01073   FunctionDecl *Function =
01074       FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
01075                            D->getLocation(), D->getDeclName(), T, TInfo,
01076                            D->getStorageClass(), D->getStorageClassAsWritten(),
01077                            D->isInlineSpecified(), D->hasWrittenPrototype(),
01078                            D->isConstexpr());
01079 
01080   if (QualifierLoc)
01081     Function->setQualifierInfo(QualifierLoc);
01082 
01083   DeclContext *LexicalDC = Owner;
01084   if (!isFriend && D->isOutOfLine()) {
01085     assert(D->getDeclContext()->isFileContext());
01086     LexicalDC = D->getDeclContext();
01087   }
01088 
01089   Function->setLexicalDeclContext(LexicalDC);
01090 
01091   // Attach the parameters
01092   if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
01093     // Adopt the already-instantiated parameters into our own context.
01094     for (unsigned P = 0; P < Params.size(); ++P)
01095       if (Params[P])
01096         Params[P]->setOwningFunction(Function);
01097   } else {
01098     // Since we were instantiated via a typedef of a function type, create
01099     // new parameters.
01100     const FunctionProtoType *Proto
01101       = Function->getType()->getAs<FunctionProtoType>();
01102     assert(Proto && "No function prototype in template instantiation?");
01103     for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
01104          AE = Proto->arg_type_end(); AI != AE; ++AI) {
01105       ParmVarDecl *Param
01106         = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
01107                                              *AI);
01108       Param->setScopeInfo(0, Params.size());
01109       Params.push_back(Param);
01110     }
01111   }
01112   Function->setParams(Params);
01113 
01114   SourceLocation InstantiateAtPOI;
01115   if (TemplateParams) {
01116     // Our resulting instantiation is actually a function template, since we
01117     // are substituting only the outer template parameters. For example, given
01118     //
01119     //   template<typename T>
01120     //   struct X {
01121     //     template<typename U> friend void f(T, U);
01122     //   };
01123     //
01124     //   X<int> x;
01125     //
01126     // We are instantiating the friend function template "f" within X<int>,
01127     // which means substituting int for T, but leaving "f" as a friend function
01128     // template.
01129     // Build the function template itself.
01130     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
01131                                                     Function->getLocation(),
01132                                                     Function->getDeclName(),
01133                                                     TemplateParams, Function);
01134     Function->setDescribedFunctionTemplate(FunctionTemplate);
01135 
01136     FunctionTemplate->setLexicalDeclContext(LexicalDC);
01137 
01138     if (isFriend && D->isThisDeclarationADefinition()) {
01139       // TODO: should we remember this connection regardless of whether
01140       // the friend declaration provided a body?
01141       FunctionTemplate->setInstantiatedFromMemberTemplate(
01142                                            D->getDescribedFunctionTemplate());
01143     }
01144   } else if (FunctionTemplate) {
01145     // Record this function template specialization.
01146     std::pair<const TemplateArgument *, unsigned> Innermost
01147       = TemplateArgs.getInnermost();
01148     Function->setFunctionTemplateSpecialization(FunctionTemplate,
01149                             TemplateArgumentList::CreateCopy(SemaRef.Context,
01150                                                              Innermost.first,
01151                                                              Innermost.second),
01152                                                 /*InsertPos=*/0);
01153   } else if (isFriend) {
01154     // Note, we need this connection even if the friend doesn't have a body.
01155     // Its body may exist but not have been attached yet due to deferred
01156     // parsing.
01157     // FIXME: It might be cleaner to set this when attaching the body to the
01158     // friend function declaration, however that would require finding all the
01159     // instantiations and modifying them.
01160     Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
01161   }
01162 
01163   if (InitFunctionInstantiation(Function, D))
01164     Function->setInvalidDecl();
01165 
01166   bool isExplicitSpecialization = false;
01167 
01168   LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
01169                         Sema::LookupOrdinaryName, Sema::ForRedeclaration);
01170 
01171   if (DependentFunctionTemplateSpecializationInfo *Info
01172         = D->getDependentSpecializationInfo()) {
01173     assert(isFriend && "non-friend has dependent specialization info?");
01174 
01175     // This needs to be set now for future sanity.
01176     Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
01177 
01178     // Instantiate the explicit template arguments.
01179     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
01180                                           Info->getRAngleLoc());
01181     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
01182                       ExplicitArgs, TemplateArgs))
01183       return 0;
01184 
01185     // Map the candidate templates to their instantiations.
01186     for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
01187       Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
01188                                                 Info->getTemplate(I),
01189                                                 TemplateArgs);
01190       if (!Temp) return 0;
01191 
01192       Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
01193     }
01194 
01195     if (SemaRef.CheckFunctionTemplateSpecialization(Function,
01196                                                     &ExplicitArgs,
01197                                                     Previous))
01198       Function->setInvalidDecl();
01199 
01200     isExplicitSpecialization = true;
01201 
01202   } else if (TemplateParams || !FunctionTemplate) {
01203     // Look only into the namespace where the friend would be declared to
01204     // find a previous declaration. This is the innermost enclosing namespace,
01205     // as described in ActOnFriendFunctionDecl.
01206     SemaRef.LookupQualifiedName(Previous, DC);
01207 
01208     // In C++, the previous declaration we find might be a tag type
01209     // (class or enum). In this case, the new declaration will hide the
01210     // tag type. Note that this does does not apply if we're declaring a
01211     // typedef (C++ [dcl.typedef]p4).
01212     if (Previous.isSingleTagDecl())
01213       Previous.clear();
01214   }
01215 
01216   SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
01217                                    isExplicitSpecialization);
01218 
01219   NamedDecl *PrincipalDecl = (TemplateParams
01220                               ? cast<NamedDecl>(FunctionTemplate)
01221                               : Function);
01222 
01223   // If the original function was part of a friend declaration,
01224   // inherit its namespace state and add it to the owner.
01225   if (isFriend) {
01226     NamedDecl *PrevDecl;
01227     if (TemplateParams)
01228       PrevDecl = FunctionTemplate->getPreviousDecl();
01229     else
01230       PrevDecl = Function->getPreviousDecl();
01231 
01232     PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
01233     DC->makeDeclVisibleInContext(PrincipalDecl);
01234 
01235     bool queuedInstantiation = false;
01236 
01237     // C++98 [temp.friend]p5: When a function is defined in a friend function
01238     //   declaration in a class template, the function is defined at each
01239     //   instantiation of the class template. The function is defined even if it
01240     //   is never used.
01241     // C++11 [temp.friend]p4: When a function is defined in a friend function
01242     //   declaration in a class template, the function is instantiated when the
01243     //   function is odr-used.
01244     //
01245     // If -Wc++98-compat is enabled, we go through the motions of checking for a
01246     // redefinition, but don't instantiate the function.
01247     if ((!SemaRef.getLangOpts().CPlusPlus0x ||
01248          SemaRef.Diags.getDiagnosticLevel(
01249              diag::warn_cxx98_compat_friend_redefinition,
01250              Function->getLocation())
01251            != DiagnosticsEngine::Ignored) &&
01252         D->isThisDeclarationADefinition()) {
01253       // Check for a function body.
01254       const FunctionDecl *Definition = 0;
01255       if (Function->isDefined(Definition) &&
01256           Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
01257         SemaRef.Diag(Function->getLocation(),
01258                      SemaRef.getLangOpts().CPlusPlus0x ?
01259                        diag::warn_cxx98_compat_friend_redefinition :
01260                        diag::err_redefinition) << Function->getDeclName();
01261         SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
01262         if (!SemaRef.getLangOpts().CPlusPlus0x)
01263           Function->setInvalidDecl();
01264       }
01265       // Check for redefinitions due to other instantiations of this or
01266       // a similar friend function.
01267       else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
01268                                            REnd = Function->redecls_end();
01269                 R != REnd; ++R) {
01270         if (*R == Function)
01271           continue;
01272         switch (R->getFriendObjectKind()) {
01273         case Decl::FOK_None:
01274           if (!SemaRef.getLangOpts().CPlusPlus0x &&
01275               !queuedInstantiation && R->isUsed(false)) {
01276             if (MemberSpecializationInfo *MSInfo
01277                 = Function->getMemberSpecializationInfo()) {
01278               if (MSInfo->getPointOfInstantiation().isInvalid()) {
01279                 SourceLocation Loc = R->getLocation(); // FIXME
01280                 MSInfo->setPointOfInstantiation(Loc);
01281                 SemaRef.PendingLocalImplicitInstantiations.push_back(
01282                                                  std::make_pair(Function, Loc));
01283                 queuedInstantiation = true;
01284               }
01285             }
01286           }
01287           break;
01288         default:
01289           if (const FunctionDecl *RPattern
01290               = R->getTemplateInstantiationPattern())
01291             if (RPattern->isDefined(RPattern)) {
01292               SemaRef.Diag(Function->getLocation(),
01293                            SemaRef.getLangOpts().CPlusPlus0x ?
01294                              diag::warn_cxx98_compat_friend_redefinition :
01295                              diag::err_redefinition)
01296                 << Function->getDeclName();
01297               SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
01298               if (!SemaRef.getLangOpts().CPlusPlus0x)
01299                 Function->setInvalidDecl();
01300               break;
01301             }
01302         }
01303       }
01304     }
01305   }
01306 
01307   if (Function->isOverloadedOperator() && !DC->isRecord() &&
01308       PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
01309     PrincipalDecl->setNonMemberOperator();
01310 
01311   assert(!D->isDefaulted() && "only methods should be defaulted");
01312   return Function;
01313 }
01314 
01315 Decl *
01316 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
01317                                       TemplateParameterList *TemplateParams,
01318                                       bool IsClassScopeSpecialization) {
01319   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
01320   if (FunctionTemplate && !TemplateParams) {
01321     // We are creating a function template specialization from a function
01322     // template. Check whether there is already a function template
01323     // specialization for this particular set of template arguments.
01324     std::pair<const TemplateArgument *, unsigned> Innermost
01325       = TemplateArgs.getInnermost();
01326 
01327     void *InsertPos = 0;
01328     FunctionDecl *SpecFunc
01329       = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
01330                                              InsertPos);
01331 
01332     // If we already have a function template specialization, return it.
01333     if (SpecFunc)
01334       return SpecFunc;
01335   }
01336 
01337   bool isFriend;
01338   if (FunctionTemplate)
01339     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
01340   else
01341     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
01342 
01343   bool MergeWithParentScope = (TemplateParams != 0) ||
01344     !(isa<Decl>(Owner) &&
01345       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
01346   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
01347 
01348   // Instantiate enclosing template arguments for friends.
01349   SmallVector<TemplateParameterList *, 4> TempParamLists;
01350   unsigned NumTempParamLists = 0;
01351   if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
01352     TempParamLists.set_size(NumTempParamLists);
01353     for (unsigned I = 0; I != NumTempParamLists; ++I) {
01354       TemplateParameterList *TempParams = D->getTemplateParameterList(I);
01355       TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
01356       if (!InstParams)
01357         return NULL;
01358       TempParamLists[I] = InstParams;
01359     }
01360   }
01361 
01362   SmallVector<ParmVarDecl *, 4> Params;
01363   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
01364   if (!TInfo)
01365     return 0;
01366   QualType T = TInfo->getType();
01367 
01368   // \brief If the type of this function, after ignoring parentheses,
01369   // is not *directly* a function type, then we're instantiating a function
01370   // that was declared via a typedef, e.g.,
01371   //
01372   //   typedef int functype(int, int);
01373   //   functype func;
01374   //
01375   // In this case, we'll just go instantiate the ParmVarDecls that we
01376   // synthesized in the method declaration.
01377   if (!isa<FunctionProtoType>(T.IgnoreParens())) {
01378     assert(!Params.size() && "Instantiating type could not yield parameters");
01379     SmallVector<QualType, 4> ParamTypes;
01380     if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
01381                                D->getNumParams(), TemplateArgs, ParamTypes,
01382                                &Params))
01383       return 0;
01384   }
01385 
01386   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
01387   if (QualifierLoc) {
01388     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
01389                                                  TemplateArgs);
01390     if (!QualifierLoc)
01391       return 0;
01392   }
01393 
01394   DeclContext *DC = Owner;
01395   if (isFriend) {
01396     if (QualifierLoc) {
01397       CXXScopeSpec SS;
01398       SS.Adopt(QualifierLoc);
01399       DC = SemaRef.computeDeclContext(SS);
01400 
01401       if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
01402         return 0;
01403     } else {
01404       DC = SemaRef.FindInstantiatedContext(D->getLocation(),
01405                                            D->getDeclContext(),
01406                                            TemplateArgs);
01407     }
01408     if (!DC) return 0;
01409   }
01410 
01411   // Build the instantiated method declaration.
01412   CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
01413   CXXMethodDecl *Method = 0;
01414 
01415   SourceLocation StartLoc = D->getInnerLocStart();
01416   DeclarationNameInfo NameInfo
01417     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
01418   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
01419     Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
01420                                         StartLoc, NameInfo, T, TInfo,
01421                                         Constructor->isExplicit(),
01422                                         Constructor->isInlineSpecified(),
01423                                         false, Constructor->isConstexpr());
01424   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
01425     Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
01426                                        StartLoc, NameInfo, T, TInfo,
01427                                        Destructor->isInlineSpecified(),
01428                                        false);
01429   } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
01430     Method = CXXConversionDecl::Create(SemaRef.Context, Record,
01431                                        StartLoc, NameInfo, T, TInfo,
01432                                        Conversion->isInlineSpecified(),
01433                                        Conversion->isExplicit(),
01434                                        Conversion->isConstexpr(),
01435                                        Conversion->getLocEnd());
01436   } else {
01437     Method = CXXMethodDecl::Create(SemaRef.Context, Record,
01438                                    StartLoc, NameInfo, T, TInfo,
01439                                    D->isStatic(),
01440                                    D->getStorageClassAsWritten(),
01441                                    D->isInlineSpecified(),
01442                                    D->isConstexpr(), D->getLocEnd());
01443   }
01444 
01445   if (QualifierLoc)
01446     Method->setQualifierInfo(QualifierLoc);
01447 
01448   if (TemplateParams) {
01449     // Our resulting instantiation is actually a function template, since we
01450     // are substituting only the outer template parameters. For example, given
01451     //
01452     //   template<typename T>
01453     //   struct X {
01454     //     template<typename U> void f(T, U);
01455     //   };
01456     //
01457     //   X<int> x;
01458     //
01459     // We are instantiating the member template "f" within X<int>, which means
01460     // substituting int for T, but leaving "f" as a member function template.
01461     // Build the function template itself.
01462     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
01463                                                     Method->getLocation(),
01464                                                     Method->getDeclName(),
01465                                                     TemplateParams, Method);
01466     if (isFriend) {
01467       FunctionTemplate->setLexicalDeclContext(Owner);
01468       FunctionTemplate->setObjectOfFriendDecl(true);
01469     } else if (D->isOutOfLine())
01470       FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
01471     Method->setDescribedFunctionTemplate(FunctionTemplate);
01472   } else if (FunctionTemplate) {
01473     // Record this function template specialization.
01474     std::pair<const TemplateArgument *, unsigned> Innermost
01475       = TemplateArgs.getInnermost();
01476     Method->setFunctionTemplateSpecialization(FunctionTemplate,
01477                          TemplateArgumentList::CreateCopy(SemaRef.Context,
01478                                                           Innermost.first,
01479                                                           Innermost.second),
01480                                               /*InsertPos=*/0);
01481   } else if (!isFriend) {
01482     // Record that this is an instantiation of a member function.
01483     Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
01484   }
01485 
01486   // If we are instantiating a member function defined
01487   // out-of-line, the instantiation will have the same lexical
01488   // context (which will be a namespace scope) as the template.
01489   if (isFriend) {
01490     if (NumTempParamLists)
01491       Method->setTemplateParameterListsInfo(SemaRef.Context,
01492                                             NumTempParamLists,
01493                                             TempParamLists.data());
01494 
01495     Method->setLexicalDeclContext(Owner);
01496     Method->setObjectOfFriendDecl(true);
01497   } else if (D->isOutOfLine())
01498     Method->setLexicalDeclContext(D->getLexicalDeclContext());
01499 
01500   // Attach the parameters
01501   for (unsigned P = 0; P < Params.size(); ++P)
01502     Params[P]->setOwningFunction(Method);
01503   Method->setParams(Params);
01504 
01505   if (InitMethodInstantiation(Method, D))
01506     Method->setInvalidDecl();
01507 
01508   LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
01509                         Sema::ForRedeclaration);
01510 
01511   if (!FunctionTemplate || TemplateParams || isFriend) {
01512     SemaRef.LookupQualifiedName(Previous, Record);
01513 
01514     // In C++, the previous declaration we find might be a tag type
01515     // (class or enum). In this case, the new declaration will hide the
01516     // tag type. Note that this does does not apply if we're declaring a
01517     // typedef (C++ [dcl.typedef]p4).
01518     if (Previous.isSingleTagDecl())
01519       Previous.clear();
01520   }
01521 
01522   if (!IsClassScopeSpecialization)
01523     SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
01524 
01525   if (D->isPure())
01526     SemaRef.CheckPureMethod(Method, SourceRange());
01527 
01528   Method->setAccess(D->getAccess());
01529 
01530   SemaRef.CheckOverrideControl(Method);
01531 
01532   // If a function is defined as defaulted or deleted, mark it as such now.
01533   if (D->isDefaulted())
01534     Method->setDefaulted();
01535   if (D->isDeletedAsWritten())
01536     Method->setDeletedAsWritten();
01537 
01538   if (FunctionTemplate) {
01539     // If there's a function template, let our caller handle it.
01540   } else if (Method->isInvalidDecl() && !Previous.empty()) {
01541     // Don't hide a (potentially) valid declaration with an invalid one.
01542   } else {
01543     NamedDecl *DeclToAdd = (TemplateParams
01544                             ? cast<NamedDecl>(FunctionTemplate)
01545                             : Method);
01546     if (isFriend)
01547       Record->makeDeclVisibleInContext(DeclToAdd);
01548     else if (!IsClassScopeSpecialization)
01549       Owner->addDecl(DeclToAdd);
01550   }
01551 
01552   if (D->isExplicitlyDefaulted()) {
01553     SemaRef.SetDeclDefaulted(Method, Method->getLocation());
01554   } else {
01555     assert(!D->isDefaulted() &&
01556            "should not implicitly default uninstantiated function");
01557   }
01558 
01559   return Method;
01560 }
01561 
01562 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
01563   return VisitCXXMethodDecl(D);
01564 }
01565 
01566 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
01567   return VisitCXXMethodDecl(D);
01568 }
01569 
01570 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
01571   return VisitCXXMethodDecl(D);
01572 }
01573 
01574 ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
01575   return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
01576                                   llvm::Optional<unsigned>(),
01577                                   /*ExpectParameterPack=*/false);
01578 }
01579 
01580 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
01581                                                     TemplateTypeParmDecl *D) {
01582   // TODO: don't always clone when decls are refcounted.
01583   assert(D->getTypeForDecl()->isTemplateTypeParmType());
01584 
01585   TemplateTypeParmDecl *Inst =
01586     TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
01587                                  D->getLocStart(), D->getLocation(),
01588                                  D->getDepth() - TemplateArgs.getNumLevels(),
01589                                  D->getIndex(), D->getIdentifier(),
01590                                  D->wasDeclaredWithTypename(),
01591                                  D->isParameterPack());
01592   Inst->setAccess(AS_public);
01593 
01594   if (D->hasDefaultArgument())
01595     Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
01596 
01597   // Introduce this template parameter's instantiation into the instantiation
01598   // scope.
01599   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
01600 
01601   return Inst;
01602 }
01603 
01604 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
01605                                                  NonTypeTemplateParmDecl *D) {
01606   // Substitute into the type of the non-type template parameter.
01607   TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
01608   SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
01609   SmallVector<QualType, 4> ExpandedParameterPackTypes;
01610   bool IsExpandedParameterPack = false;
01611   TypeSourceInfo *DI;
01612   QualType T;
01613   bool Invalid = false;
01614 
01615   if (D->isExpandedParameterPack()) {
01616     // The non-type template parameter pack is an already-expanded pack
01617     // expansion of types. Substitute into each of the expanded types.
01618     ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
01619     ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
01620     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
01621       TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
01622                                                TemplateArgs,
01623                                                D->getLocation(),
01624                                                D->getDeclName());
01625       if (!NewDI)
01626         return 0;
01627 
01628       ExpandedParameterPackTypesAsWritten.push_back(NewDI);
01629       QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
01630                                                               D->getLocation());
01631       if (NewT.isNull())
01632         return 0;
01633       ExpandedParameterPackTypes.push_back(NewT);
01634     }
01635 
01636     IsExpandedParameterPack = true;
01637     DI = D->getTypeSourceInfo();
01638     T = DI->getType();
01639   } else if (isa<PackExpansionTypeLoc>(TL)) {
01640     // The non-type template parameter pack's type is a pack expansion of types.
01641     // Determine whether we need to expand this parameter pack into separate
01642     // types.
01643     PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
01644     TypeLoc Pattern = Expansion.getPatternLoc();
01645     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
01646     SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
01647 
01648     // Determine whether the set of unexpanded parameter packs can and should
01649     // be expanded.
01650     bool Expand = true;
01651     bool RetainExpansion = false;
01652     llvm::Optional<unsigned> OrigNumExpansions
01653       = Expansion.getTypePtr()->getNumExpansions();
01654     llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
01655     if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
01656                                                 Pattern.getSourceRange(),
01657                                                 Unexpanded,
01658                                                 TemplateArgs,
01659                                                 Expand, RetainExpansion,
01660                                                 NumExpansions))
01661       return 0;
01662 
01663     if (Expand) {
01664       for (unsigned I = 0; I != *NumExpansions; ++I) {
01665         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
01666         TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
01667                                                   D->getLocation(),
01668                                                   D->getDeclName());
01669         if (!NewDI)
01670           return 0;
01671 
01672         ExpandedParameterPackTypesAsWritten.push_back(NewDI);
01673         QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
01674                                                               NewDI->getType(),
01675                                                               D->getLocation());
01676         if (NewT.isNull())
01677           return 0;
01678         ExpandedParameterPackTypes.push_back(NewT);
01679       }
01680 
01681       // Note that we have an expanded parameter pack. The "type" of this
01682       // expanded parameter pack is the original expansion type, but callers
01683       // will end up using the expanded parameter pack types for type-checking.
01684       IsExpandedParameterPack = true;
01685       DI = D->getTypeSourceInfo();
01686       T = DI->getType();
01687     } else {
01688       // We cannot fully expand the pack expansion now, so substitute into the
01689       // pattern and create a new pack expansion type.
01690       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
01691       TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
01692                                                      D->getLocation(),
01693                                                      D->getDeclName());
01694       if (!NewPattern)
01695         return 0;
01696 
01697       DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
01698                                       NumExpansions);
01699       if (!DI)
01700         return 0;
01701 
01702       T = DI->getType();
01703     }
01704   } else {
01705     // Simple case: substitution into a parameter that is not a parameter pack.
01706     DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
01707                            D->getLocation(), D->getDeclName());
01708     if (!DI)
01709       return 0;
01710 
01711     // Check that this type is acceptable for a non-type template parameter.
01712     T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
01713                                                   D->getLocation());
01714     if (T.isNull()) {
01715       T = SemaRef.Context.IntTy;
01716       Invalid = true;
01717     }
01718   }
01719 
01720   NonTypeTemplateParmDecl *Param;
01721   if (IsExpandedParameterPack)
01722     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
01723                                             D->getInnerLocStart(),
01724                                             D->getLocation(),
01725                                     D->getDepth() - TemplateArgs.getNumLevels(),
01726                                             D->getPosition(),
01727                                             D->getIdentifier(), T,
01728                                             DI,
01729                                             ExpandedParameterPackTypes.data(),
01730                                             ExpandedParameterPackTypes.size(),
01731                                     ExpandedParameterPackTypesAsWritten.data());
01732   else
01733     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
01734                                             D->getInnerLocStart(),
01735                                             D->getLocation(),
01736                                     D->getDepth() - TemplateArgs.getNumLevels(),
01737                                             D->getPosition(),
01738                                             D->getIdentifier(), T,
01739                                             D->isParameterPack(), DI);
01740 
01741   Param->setAccess(AS_public);
01742   if (Invalid)
01743     Param->setInvalidDecl();
01744 
01745   Param->setDefaultArgument(D->getDefaultArgument(), false);
01746 
01747   // Introduce this template parameter's instantiation into the instantiation
01748   // scope.
01749   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
01750   return Param;
01751 }
01752 
01753 Decl *
01754 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
01755                                                   TemplateTemplateParmDecl *D) {
01756   // Instantiate the template parameter list of the template template parameter.
01757   TemplateParameterList *TempParams = D->getTemplateParameters();
01758   TemplateParameterList *InstParams;
01759   {
01760     // Perform the actual substitution of template parameters within a new,
01761     // local instantiation scope.
01762     LocalInstantiationScope Scope(SemaRef);
01763     InstParams = SubstTemplateParams(TempParams);
01764     if (!InstParams)
01765       return NULL;
01766   }
01767 
01768   // Build the template template parameter.
01769   TemplateTemplateParmDecl *Param
01770     = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
01771                                    D->getDepth() - TemplateArgs.getNumLevels(),
01772                                        D->getPosition(), D->isParameterPack(),
01773                                        D->getIdentifier(), InstParams);
01774   Param->setDefaultArgument(D->getDefaultArgument(), false);
01775   Param->setAccess(AS_public);
01776 
01777   // Introduce this template parameter's instantiation into the instantiation
01778   // scope.
01779   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
01780 
01781   return Param;
01782 }
01783 
01784 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
01785   // Using directives are never dependent (and never contain any types or
01786   // expressions), so they require no explicit instantiation work.
01787 
01788   UsingDirectiveDecl *Inst
01789     = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
01790                                  D->getNamespaceKeyLocation(),
01791                                  D->getQualifierLoc(),
01792                                  D->getIdentLocation(),
01793                                  D->getNominatedNamespace(),
01794                                  D->getCommonAncestor());
01795   Owner->addDecl(Inst);
01796   return Inst;
01797 }
01798 
01799 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
01800 
01801   // The nested name specifier may be dependent, for example
01802   //     template <typename T> struct t {
01803   //       struct s1 { T f1(); };
01804   //       struct s2 : s1 { using s1::f1; };
01805   //     };
01806   //     template struct t<int>;
01807   // Here, in using s1::f1, s1 refers to t<T>::s1;
01808   // we need to substitute for t<int>::s1.
01809   NestedNameSpecifierLoc QualifierLoc
01810     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
01811                                           TemplateArgs);
01812   if (!QualifierLoc)
01813     return 0;
01814 
01815   // The name info is non-dependent, so no transformation
01816   // is required.
01817   DeclarationNameInfo NameInfo = D->getNameInfo();
01818 
01819   // We only need to do redeclaration lookups if we're in a class
01820   // scope (in fact, it's not really even possible in non-class
01821   // scopes).
01822   bool CheckRedeclaration = Owner->isRecord();
01823 
01824   LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
01825                     Sema::ForRedeclaration);
01826 
01827   UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
01828                                        D->getUsingLocation(),
01829                                        QualifierLoc,
01830                                        NameInfo,
01831                                        D->isTypeName());
01832 
01833   CXXScopeSpec SS;
01834   SS.Adopt(QualifierLoc);
01835   if (CheckRedeclaration) {
01836     Prev.setHideTags(false);
01837     SemaRef.LookupQualifiedName(Prev, Owner);
01838 
01839     // Check for invalid redeclarations.
01840     if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
01841                                             D->isTypeName(), SS,
01842                                             D->getLocation(), Prev))
01843       NewUD->setInvalidDecl();
01844 
01845   }
01846 
01847   if (!NewUD->isInvalidDecl() &&
01848       SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
01849                                       D->getLocation()))
01850     NewUD->setInvalidDecl();
01851 
01852   SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
01853   NewUD->setAccess(D->getAccess());
01854   Owner->addDecl(NewUD);
01855 
01856   // Don't process the shadow decls for an invalid decl.
01857   if (NewUD->isInvalidDecl())
01858     return NewUD;
01859 
01860   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
01861     if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
01862       NewUD->setInvalidDecl();
01863     return NewUD;
01864   }
01865 
01866   bool isFunctionScope = Owner->isFunctionOrMethod();
01867 
01868   // Process the shadow decls.
01869   for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
01870          I != E; ++I) {
01871     UsingShadowDecl *Shadow = *I;
01872     NamedDecl *InstTarget =
01873       cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
01874                                                           Shadow->getLocation(),
01875                                                         Shadow->getTargetDecl(),
01876                                                            TemplateArgs));
01877     if (!InstTarget)
01878       return 0;
01879 
01880     if (CheckRedeclaration &&
01881         SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
01882       continue;
01883 
01884     UsingShadowDecl *InstShadow
01885       = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
01886     SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
01887 
01888     if (isFunctionScope)
01889       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
01890   }
01891 
01892   return NewUD;
01893 }
01894 
01895 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
01896   // Ignore these;  we handle them in bulk when processing the UsingDecl.
01897   return 0;
01898 }
01899 
01900 Decl * TemplateDeclInstantiator
01901     ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
01902   NestedNameSpecifierLoc QualifierLoc
01903     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
01904                                           TemplateArgs);
01905   if (!QualifierLoc)
01906     return 0;
01907 
01908   CXXScopeSpec SS;
01909   SS.Adopt(QualifierLoc);
01910 
01911   // Since NameInfo refers to a typename, it cannot be a C++ special name.
01912   // Hence, no tranformation is required for it.
01913   DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
01914   NamedDecl *UD =
01915     SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
01916                                   D->getUsingLoc(), SS, NameInfo, 0,
01917                                   /*instantiation*/ true,
01918                                   /*typename*/ true, D->getTypenameLoc());
01919   if (UD)
01920     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
01921 
01922   return UD;
01923 }
01924 
01925 Decl * TemplateDeclInstantiator
01926     ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
01927   NestedNameSpecifierLoc QualifierLoc
01928       = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
01929   if (!QualifierLoc)
01930     return 0;
01931 
01932   CXXScopeSpec SS;
01933   SS.Adopt(QualifierLoc);
01934 
01935   DeclarationNameInfo NameInfo
01936     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
01937 
01938   NamedDecl *UD =
01939     SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
01940                                   D->getUsingLoc(), SS, NameInfo, 0,
01941                                   /*instantiation*/ true,
01942                                   /*typename*/ false, SourceLocation());
01943   if (UD)
01944     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
01945 
01946   return UD;
01947 }
01948 
01949 
01950 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
01951                                      ClassScopeFunctionSpecializationDecl *Decl) {
01952   CXXMethodDecl *OldFD = Decl->getSpecialization();
01953   CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, 0, true));
01954 
01955   LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
01956                         Sema::ForRedeclaration);
01957 
01958   SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
01959   if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, 0, Previous)) {
01960     NewFD->setInvalidDecl();
01961     return NewFD;
01962   }
01963 
01964   // Associate the specialization with the pattern.
01965   FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
01966   assert(Specialization && "Class scope Specialization is null");
01967   SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
01968 
01969   return NewFD;
01970 }
01971 
01972 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
01973                       const MultiLevelTemplateArgumentList &TemplateArgs) {
01974   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
01975   if (D->isInvalidDecl())
01976     return 0;
01977 
01978   return Instantiator.Visit(D);
01979 }
01980 
01981 /// \brief Instantiates a nested template parameter list in the current
01982 /// instantiation context.
01983 ///
01984 /// \param L The parameter list to instantiate
01985 ///
01986 /// \returns NULL if there was an error
01987 TemplateParameterList *
01988 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
01989   // Get errors for all the parameters before bailing out.
01990   bool Invalid = false;
01991 
01992   unsigned N = L->size();
01993   typedef SmallVector<NamedDecl *, 8> ParamVector;
01994   ParamVector Params;
01995   Params.reserve(N);
01996   for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
01997        PI != PE; ++PI) {
01998     NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
01999     Params.push_back(D);
02000     Invalid = Invalid || !D || D->isInvalidDecl();
02001   }
02002 
02003   // Clean up if we had an error.
02004   if (Invalid)
02005     return NULL;
02006 
02007   TemplateParameterList *InstL
02008     = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
02009                                     L->getLAngleLoc(), &Params.front(), N,
02010                                     L->getRAngleLoc());
02011   return InstL;
02012 }
02013 
02014 /// \brief Instantiate the declaration of a class template partial
02015 /// specialization.
02016 ///
02017 /// \param ClassTemplate the (instantiated) class template that is partially
02018 // specialized by the instantiation of \p PartialSpec.
02019 ///
02020 /// \param PartialSpec the (uninstantiated) class template partial
02021 /// specialization that we are instantiating.
02022 ///
02023 /// \returns The instantiated partial specialization, if successful; otherwise,
02024 /// NULL to indicate an error.
02025 ClassTemplatePartialSpecializationDecl *
02026 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
02027                                             ClassTemplateDecl *ClassTemplate,
02028                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
02029   // Create a local instantiation scope for this class template partial
02030   // specialization, which will contain the instantiations of the template
02031   // parameters.
02032   LocalInstantiationScope Scope(SemaRef);
02033 
02034   // Substitute into the template parameters of the class template partial
02035   // specialization.
02036   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
02037   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
02038   if (!InstParams)
02039     return 0;
02040 
02041   // Substitute into the template arguments of the class template partial
02042   // specialization.
02043   TemplateArgumentListInfo InstTemplateArgs; // no angle locations
02044   if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
02045                     PartialSpec->getNumTemplateArgsAsWritten(),
02046                     InstTemplateArgs, TemplateArgs))
02047     return 0;
02048 
02049   // Check that the template argument list is well-formed for this
02050   // class template.
02051   SmallVector<TemplateArgument, 4> Converted;
02052   if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
02053                                         PartialSpec->getLocation(),
02054                                         InstTemplateArgs,
02055                                         false,
02056                                         Converted))
02057     return 0;
02058 
02059   // Figure out where to insert this class template partial specialization
02060   // in the member template's set of class template partial specializations.
02061   void *InsertPos = 0;
02062   ClassTemplateSpecializationDecl *PrevDecl
02063     = ClassTemplate->findPartialSpecialization(Converted.data(),
02064                                                Converted.size(), InsertPos);
02065 
02066   // Build the canonical type that describes the converted template
02067   // arguments of the class template partial specialization.
02068   QualType CanonType
02069     = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
02070                                                     Converted.data(),
02071                                                     Converted.size());
02072 
02073   // Build the fully-sugared type for this class template
02074   // specialization as the user wrote in the specialization
02075   // itself. This means that we'll pretty-print the type retrieved
02076   // from the specialization's declaration the way that the user
02077   // actually wrote the specialization, rather than formatting the
02078   // name based on the "canonical" representation used to store the
02079   // template arguments in the specialization.
02080   TypeSourceInfo *WrittenTy
02081     = SemaRef.Context.getTemplateSpecializationTypeInfo(
02082                                                     TemplateName(ClassTemplate),
02083                                                     PartialSpec->getLocation(),
02084                                                     InstTemplateArgs,
02085                                                     CanonType);
02086 
02087   if (PrevDecl) {
02088     // We've already seen a partial specialization with the same template
02089     // parameters and template arguments. This can happen, for example, when
02090     // substituting the outer template arguments ends up causing two
02091     // class template partial specializations of a member class template
02092     // to have identical forms, e.g.,
02093     //
02094     //   template<typename T, typename U>
02095     //   struct Outer {
02096     //     template<typename X, typename Y> struct Inner;
02097     //     template<typename Y> struct Inner<T, Y>;
02098     //     template<typename Y> struct Inner<U, Y>;
02099     //   };
02100     //
02101     //   Outer<int, int> outer; // error: the partial specializations of Inner
02102     //                          // have the same signature.
02103     SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
02104       << WrittenTy->getType();
02105     SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
02106       << SemaRef.Context.getTypeDeclType(PrevDecl);
02107     return 0;
02108   }
02109 
02110 
02111   // Create the class template partial specialization declaration.
02112   ClassTemplatePartialSpecializationDecl *InstPartialSpec
02113     = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
02114                                                      PartialSpec->getTagKind(),
02115                                                      Owner,
02116                                                      PartialSpec->getLocStart(),
02117                                                      PartialSpec->getLocation(),
02118                                                      InstParams,
02119                                                      ClassTemplate,
02120                                                      Converted.data(),
02121                                                      Converted.size(),
02122                                                      InstTemplateArgs,
02123                                                      CanonType,
02124                                                      0,
02125                              ClassTemplate->getNextPartialSpecSequenceNumber());
02126   // Substitute the nested name specifier, if any.
02127   if (SubstQualifier(PartialSpec, InstPartialSpec))
02128     return 0;
02129 
02130   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
02131   InstPartialSpec->setTypeAsWritten(WrittenTy);
02132 
02133   // Add this partial specialization to the set of class template partial
02134   // specializations.
02135   ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
02136   return InstPartialSpec;
02137 }
02138 
02139 TypeSourceInfo*
02140 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
02141                               SmallVectorImpl<ParmVarDecl *> &Params) {
02142   TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
02143   assert(OldTInfo && "substituting function without type source info");
02144   assert(Params.empty() && "parameter vector is non-empty at start");
02145   
02146   CXXRecordDecl *ThisContext = 0;
02147   unsigned ThisTypeQuals = 0;
02148   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
02149     ThisContext = Method->getParent();
02150     ThisTypeQuals = Method->getTypeQualifiers();
02151   }
02152   
02153   TypeSourceInfo *NewTInfo
02154     = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
02155                                     D->getTypeSpecStartLoc(),
02156                                     D->getDeclName(),
02157                                     ThisContext, ThisTypeQuals);
02158   if (!NewTInfo)
02159     return 0;
02160 
02161   if (NewTInfo != OldTInfo) {
02162     // Get parameters from the new type info.
02163     TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
02164     if (FunctionProtoTypeLoc *OldProtoLoc
02165                                   = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
02166       TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
02167       FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
02168       assert(NewProtoLoc && "Missing prototype?");
02169       unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
02170       for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
02171            OldIdx != NumOldParams; ++OldIdx) {
02172         ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
02173         if (!OldParam->isParameterPack() ||
02174             // FIXME: Is this right? OldParam could expand to an empty parameter
02175             // pack and the next parameter could be an unexpanded parameter pack
02176             (NewIdx < NumNewParams &&
02177              NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
02178           // Simple case: normal parameter, or a parameter pack that's
02179           // instantiated to a (still-dependent) parameter pack.
02180           ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
02181           Params.push_back(NewParam);
02182           SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
02183                                                                NewParam);
02184           continue;
02185         }
02186 
02187         // Parameter pack: make the instantiation an argument pack.
02188         SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
02189                                                                       OldParam);
02190         unsigned NumArgumentsInExpansion
02191           = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
02192                                                TemplateArgs);
02193         while (NumArgumentsInExpansion--) {
02194           ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
02195           Params.push_back(NewParam);
02196           SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
02197                                                                       NewParam);
02198         }
02199       }
02200     }
02201   } else {
02202     // The function type itself was not dependent and therefore no
02203     // substitution occurred. However, we still need to instantiate
02204     // the function parameters themselves.
02205     TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
02206     if (FunctionProtoTypeLoc *OldProtoLoc
02207                                     = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
02208       for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
02209         ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
02210         if (!Parm)
02211           return 0;
02212         Params.push_back(Parm);
02213       }
02214     }
02215   }
02216   return NewTInfo;
02217 }
02218 
02219 /// Introduce the instantiated function parameters into the local
02220 /// instantiation scope, and set the parameter names to those used
02221 /// in the template.
02222 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
02223                                              const FunctionDecl *PatternDecl,
02224                                              LocalInstantiationScope &Scope,
02225                            const MultiLevelTemplateArgumentList &TemplateArgs) {
02226   unsigned FParamIdx = 0;
02227   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
02228     const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
02229     if (!PatternParam->isParameterPack()) {
02230       // Simple case: not a parameter pack.
02231       assert(FParamIdx < Function->getNumParams());
02232       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
02233       FunctionParam->setDeclName(PatternParam->getDeclName());
02234       Scope.InstantiatedLocal(PatternParam, FunctionParam);
02235       ++FParamIdx;
02236       continue;
02237     }
02238 
02239     // Expand the parameter pack.
02240     Scope.MakeInstantiatedLocalArgPack(PatternParam);
02241     unsigned NumArgumentsInExpansion
02242       = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
02243     for (unsigned Arg = 0; Arg < NumArgumentsInExpansion; ++Arg) {
02244       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
02245       FunctionParam->setDeclName(PatternParam->getDeclName());
02246       Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
02247       ++FParamIdx;
02248     }
02249   }
02250 }
02251 
02252 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
02253                                      const FunctionProtoType *Proto,
02254                            const MultiLevelTemplateArgumentList &TemplateArgs) {
02255   assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
02256 
02257   // C++11 [expr.prim.general]p3:
02258   //   If a declaration declares a member function or member function 
02259   //   template of a class X, the expression this is a prvalue of type 
02260   //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
02261   //   and the end of the function-definition, member-declarator, or 
02262   //   declarator.    
02263   CXXRecordDecl *ThisContext = 0;
02264   unsigned ThisTypeQuals = 0;
02265   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
02266     ThisContext = Method->getParent();
02267     ThisTypeQuals = Method->getTypeQualifiers();
02268   }
02269   Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
02270                                    SemaRef.getLangOpts().CPlusPlus0x);
02271 
02272   // The function has an exception specification or a "noreturn"
02273   // attribute. Substitute into each of the exception types.
02274   SmallVector<QualType, 4> Exceptions;
02275   for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
02276     // FIXME: Poor location information!
02277     if (const PackExpansionType *PackExpansion
02278           = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
02279       // We have a pack expansion. Instantiate it.
02280       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
02281       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
02282                                               Unexpanded);
02283       assert(!Unexpanded.empty() &&
02284              "Pack expansion without parameter packs?");
02285 
02286       bool Expand = false;
02287       bool RetainExpansion = false;
02288       llvm::Optional<unsigned> NumExpansions
02289                                         = PackExpansion->getNumExpansions();
02290       if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
02291                                                   SourceRange(),
02292                                                   Unexpanded,
02293                                                   TemplateArgs,
02294                                                   Expand,
02295                                                   RetainExpansion,
02296                                                   NumExpansions))
02297         break;
02298 
02299       if (!Expand) {
02300         // We can't expand this pack expansion into separate arguments yet;
02301         // just substitute into the pattern and create a new pack expansion
02302         // type.
02303         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
02304         QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
02305                                        TemplateArgs,
02306                                      New->getLocation(), New->getDeclName());
02307         if (T.isNull())
02308           break;
02309 
02310         T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
02311         Exceptions.push_back(T);
02312         continue;
02313       }
02314 
02315       // Substitute into the pack expansion pattern for each template
02316       bool Invalid = false;
02317       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
02318         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
02319 
02320         QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
02321                                        TemplateArgs,
02322                                      New->getLocation(), New->getDeclName());
02323         if (T.isNull()) {
02324           Invalid = true;
02325           break;
02326         }
02327 
02328         Exceptions.push_back(T);
02329       }
02330 
02331       if (Invalid)
02332         break;
02333 
02334       continue;
02335     }
02336 
02337     QualType T
02338       = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
02339                           New->getLocation(), New->getDeclName());
02340     if (T.isNull() ||
02341         SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
02342       continue;
02343 
02344     Exceptions.push_back(T);
02345   }
02346   Expr *NoexceptExpr = 0;
02347   if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
02348     EnterExpressionEvaluationContext Unevaluated(SemaRef,
02349                                                  Sema::ConstantEvaluated);
02350     ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
02351     if (E.isUsable())
02352       E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
02353 
02354     if (E.isUsable()) {
02355       NoexceptExpr = E.take();
02356       if (!NoexceptExpr->isTypeDependent() &&
02357           !NoexceptExpr->isValueDependent())
02358         NoexceptExpr
02359           = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
02360               0, diag::err_noexcept_needs_constant_expression,
02361               /*AllowFold*/ false).take();
02362     }
02363   }
02364 
02365   // Rebuild the function type
02366   const FunctionProtoType *NewProto
02367     = New->getType()->getAs<FunctionProtoType>();
02368   assert(NewProto && "Template instantiation without function prototype?");
02369 
02370   FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
02371   EPI.ExceptionSpecType = Proto->getExceptionSpecType();
02372   EPI.NumExceptions = Exceptions.size();
02373   EPI.Exceptions = Exceptions.data();
02374   EPI.NoexceptExpr = NoexceptExpr;
02375 
02376   New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
02377                                                NewProto->arg_type_begin(),
02378                                                NewProto->getNumArgs(),
02379                                                EPI));
02380 }
02381 
02382 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
02383                                     FunctionDecl *Decl) {
02384   const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
02385   if (Proto->getExceptionSpecType() != EST_Uninstantiated)
02386     return;
02387 
02388   InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
02389                              InstantiatingTemplate::ExceptionSpecification());
02390   if (Inst)
02391     return;
02392 
02393   // Enter the scope of this instantiation. We don't use
02394   // PushDeclContext because we don't have a scope.
02395   Sema::ContextRAII savedContext(*this, Decl);
02396   LocalInstantiationScope Scope(*this);
02397 
02398   MultiLevelTemplateArgumentList TemplateArgs =
02399     getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
02400 
02401   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
02402   addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
02403 
02404   ::InstantiateExceptionSpec(*this, Decl,
02405                              Template->getType()->castAs<FunctionProtoType>(),
02406                              TemplateArgs);
02407 }
02408 
02409 /// \brief Initializes the common fields of an instantiation function
02410 /// declaration (New) from the corresponding fields of its template (Tmpl).
02411 ///
02412 /// \returns true if there was an error
02413 bool
02414 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
02415                                                     FunctionDecl *Tmpl) {
02416   if (Tmpl->isDeletedAsWritten())
02417     New->setDeletedAsWritten();
02418 
02419   // If we are performing substituting explicitly-specified template arguments
02420   // or deduced template arguments into a function template and we reach this
02421   // point, we are now past the point where SFINAE applies and have committed
02422   // to keeping the new function template specialization. We therefore
02423   // convert the active template instantiation for the function template
02424   // into a template instantiation for this specific function template
02425   // specialization, which is not a SFINAE context, so that we diagnose any
02426   // further errors in the declaration itself.
02427   typedef Sema::ActiveTemplateInstantiation ActiveInstType;
02428   ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
02429   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
02430       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
02431     if (FunctionTemplateDecl *FunTmpl
02432           = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
02433       assert(FunTmpl->getTemplatedDecl() == Tmpl &&
02434              "Deduction from the wrong function template?");
02435       (void) FunTmpl;
02436       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
02437       ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
02438       --SemaRef.NonInstantiationEntries;
02439     }
02440   }
02441 
02442   const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
02443   assert(Proto && "Function template without prototype?");
02444 
02445   if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
02446     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
02447 
02448     // DR1330: In C++11, defer instantiation of a non-trivial
02449     // exception specification.
02450     if (SemaRef.getLangOpts().CPlusPlus0x &&
02451         EPI.ExceptionSpecType != EST_None &&
02452         EPI.ExceptionSpecType != EST_DynamicNone &&
02453         EPI.ExceptionSpecType != EST_BasicNoexcept) {
02454       FunctionDecl *ExceptionSpecTemplate = Tmpl;
02455       if (EPI.ExceptionSpecType == EST_Uninstantiated)
02456         ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
02457 
02458       // Mark the function has having an uninstantiated exception specification.
02459       const FunctionProtoType *NewProto
02460         = New->getType()->getAs<FunctionProtoType>();
02461       assert(NewProto && "Template instantiation without function prototype?");
02462       EPI = NewProto->getExtProtoInfo();
02463       EPI.ExceptionSpecType = EST_Uninstantiated;
02464       EPI.ExceptionSpecDecl = New;
02465       EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
02466       New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
02467                                                    NewProto->arg_type_begin(),
02468                                                    NewProto->getNumArgs(),
02469                                                    EPI));
02470     } else {
02471       ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
02472     }
02473   }
02474 
02475   // Get the definition. Leaves the variable unchanged if undefined.
02476   const FunctionDecl *Definition = Tmpl;
02477   Tmpl->isDefined(Definition);
02478 
02479   SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
02480                            LateAttrs, StartingScope);
02481 
02482   return false;
02483 }
02484 
02485 /// \brief Initializes common fields of an instantiated method
02486 /// declaration (New) from the corresponding fields of its template
02487 /// (Tmpl).
02488 ///
02489 /// \returns true if there was an error
02490 bool
02491 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
02492                                                   CXXMethodDecl *Tmpl) {
02493   if (InitFunctionInstantiation(New, Tmpl))
02494     return true;
02495 
02496   New->setAccess(Tmpl->getAccess());
02497   if (Tmpl->isVirtualAsWritten())
02498     New->setVirtualAsWritten(true);
02499 
02500   // FIXME: attributes
02501   // FIXME: New needs a pointer to Tmpl
02502   return false;
02503 }
02504 
02505 /// \brief Instantiate the definition of the given function from its
02506 /// template.
02507 ///
02508 /// \param PointOfInstantiation the point at which the instantiation was
02509 /// required. Note that this is not precisely a "point of instantiation"
02510 /// for the function, but it's close.
02511 ///
02512 /// \param Function the already-instantiated declaration of a
02513 /// function template specialization or member function of a class template
02514 /// specialization.
02515 ///
02516 /// \param Recursive if true, recursively instantiates any functions that
02517 /// are required by this instantiation.
02518 ///
02519 /// \param DefinitionRequired if true, then we are performing an explicit
02520 /// instantiation where the body of the function is required. Complain if
02521 /// there is no such body.
02522 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
02523                                          FunctionDecl *Function,
02524                                          bool Recursive,
02525                                          bool DefinitionRequired) {
02526   if (Function->isInvalidDecl() || Function->isDefined())
02527     return;
02528 
02529   // Never instantiate an explicit specialization except if it is a class scope
02530   // explicit specialization.
02531   if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
02532       !Function->getClassScopeSpecializationPattern())
02533     return;
02534 
02535   // Find the function body that we'll be substituting.
02536   const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
02537   assert(PatternDecl && "instantiating a non-template");
02538 
02539   Stmt *Pattern = PatternDecl->getBody(PatternDecl);
02540   assert(PatternDecl && "template definition is not a template");
02541   if (!Pattern) {
02542     // Try to find a defaulted definition
02543     PatternDecl->isDefined(PatternDecl);
02544   }
02545   assert(PatternDecl && "template definition is not a template");
02546 
02547   // Postpone late parsed template instantiations.
02548   if (PatternDecl->isLateTemplateParsed() &&
02549       !LateTemplateParser) {
02550     PendingInstantiations.push_back(
02551       std::make_pair(Function, PointOfInstantiation));
02552     return;
02553   }
02554 
02555   // Call the LateTemplateParser callback if there a need to late parse
02556   // a templated function definition.
02557   if (!Pattern && PatternDecl->isLateTemplateParsed() &&
02558       LateTemplateParser) {
02559     LateTemplateParser(OpaqueParser, PatternDecl);
02560     Pattern = PatternDecl->getBody(PatternDecl);
02561   }
02562 
02563   if (!Pattern && !PatternDecl->isDefaulted()) {
02564     if (DefinitionRequired) {
02565       if (Function->getPrimaryTemplate())
02566         Diag(PointOfInstantiation,
02567              diag::err_explicit_instantiation_undefined_func_template)
02568           << Function->getPrimaryTemplate();
02569       else
02570         Diag(PointOfInstantiation,
02571              diag::err_explicit_instantiation_undefined_member)
02572           << 1 << Function->getDeclName() << Function->getDeclContext();
02573 
02574       if (PatternDecl)
02575         Diag(PatternDecl->getLocation(),
02576              diag::note_explicit_instantiation_here);
02577       Function->setInvalidDecl();
02578     } else if (Function->getTemplateSpecializationKind()
02579                  == TSK_ExplicitInstantiationDefinition) {
02580       PendingInstantiations.push_back(
02581         std::make_pair(Function, PointOfInstantiation));
02582     }
02583 
02584     return;
02585   }
02586 
02587   // C++0x [temp.explicit]p9:
02588   //   Except for inline functions, other explicit instantiation declarations
02589   //   have the effect of suppressing the implicit instantiation of the entity
02590   //   to which they refer.
02591   if (Function->getTemplateSpecializationKind()
02592         == TSK_ExplicitInstantiationDeclaration &&
02593       !PatternDecl->isInlined())
02594     return;
02595 
02596   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
02597   if (Inst)
02598     return;
02599 
02600   // Copy the inner loc start from the pattern.
02601   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
02602 
02603   // If we're performing recursive template instantiation, create our own
02604   // queue of pending implicit instantiations that we will instantiate later,
02605   // while we're still within our own instantiation context.
02606   SmallVector<VTableUse, 16> SavedVTableUses;
02607   std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
02608   if (Recursive) {
02609     VTableUses.swap(SavedVTableUses);
02610     PendingInstantiations.swap(SavedPendingInstantiations);
02611   }
02612 
02613   EnterExpressionEvaluationContext EvalContext(*this,
02614                                                Sema::PotentiallyEvaluated);
02615   ActOnStartOfFunctionDef(0, Function);
02616 
02617   // Introduce a new scope where local variable instantiations will be
02618   // recorded, unless we're actually a member function within a local
02619   // class, in which case we need to merge our results with the parent
02620   // scope (of the enclosing function).
02621   bool MergeWithParentScope = false;
02622   if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
02623     MergeWithParentScope = Rec->isLocalClass();
02624 
02625   LocalInstantiationScope Scope(*this, MergeWithParentScope);
02626 
02627   // Enter the scope of this instantiation. We don't use
02628   // PushDeclContext because we don't have a scope.
02629   Sema::ContextRAII savedContext(*this, Function);
02630 
02631   MultiLevelTemplateArgumentList TemplateArgs =
02632     getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
02633 
02634   addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
02635                                    TemplateArgs);
02636 
02637   if (PatternDecl->isDefaulted()) {
02638     ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true);
02639 
02640     SetDeclDefaulted(Function, PatternDecl->getLocation());
02641   } else {
02642     // If this is a constructor, instantiate the member initializers.
02643     if (const CXXConstructorDecl *Ctor =
02644           dyn_cast<CXXConstructorDecl>(PatternDecl)) {
02645       InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
02646                                  TemplateArgs);
02647     }
02648 
02649     // Instantiate the function body.
02650     StmtResult Body = SubstStmt(Pattern, TemplateArgs);
02651 
02652     if (Body.isInvalid())
02653       Function->setInvalidDecl();
02654 
02655     ActOnFinishFunctionBody(Function, Body.get(),
02656                             /*IsInstantiation=*/true);
02657   }
02658 
02659   PerformDependentDiagnostics(PatternDecl, TemplateArgs);
02660 
02661   savedContext.pop();
02662 
02663   DeclGroupRef DG(Function);
02664   Consumer.HandleTopLevelDecl(DG);
02665 
02666   // This class may have local implicit instantiations that need to be
02667   // instantiation within this scope.
02668   PerformPendingInstantiations(/*LocalOnly=*/true);
02669   Scope.Exit();
02670 
02671   if (Recursive) {
02672     // Define any pending vtables.
02673     DefineUsedVTables();
02674 
02675     // Instantiate any pending implicit instantiations found during the
02676     // instantiation of this template.
02677     PerformPendingInstantiations();
02678 
02679     // Restore the set of pending vtables.
02680     assert(VTableUses.empty() &&
02681            "VTableUses should be empty before it is discarded.");
02682     VTableUses.swap(SavedVTableUses);
02683 
02684     // Restore the set of pending implicit instantiations.
02685     assert(PendingInstantiations.empty() &&
02686            "PendingInstantiations should be empty before it is discarded.");
02687     PendingInstantiations.swap(SavedPendingInstantiations);
02688   }
02689 }
02690 
02691 /// \brief Instantiate the definition of the given variable from its
02692 /// template.
02693 ///
02694 /// \param PointOfInstantiation the point at which the instantiation was
02695 /// required. Note that this is not precisely a "point of instantiation"
02696 /// for the function, but it's close.
02697 ///
02698 /// \param Var the already-instantiated declaration of a static member
02699 /// variable of a class template specialization.
02700 ///
02701 /// \param Recursive if true, recursively instantiates any functions that
02702 /// are required by this instantiation.
02703 ///
02704 /// \param DefinitionRequired if true, then we are performing an explicit
02705 /// instantiation where an out-of-line definition of the member variable
02706 /// is required. Complain if there is no such definition.
02707 void Sema::InstantiateStaticDataMemberDefinition(
02708                                           SourceLocation PointOfInstantiation,
02709                                                  VarDecl *Var,
02710                                                  bool Recursive,
02711                                                  bool DefinitionRequired) {
02712   if (Var->isInvalidDecl())
02713     return;
02714 
02715   // Find the out-of-line definition of this static data member.
02716   VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
02717   assert(Def && "This data member was not instantiated from a template?");
02718   assert(Def->isStaticDataMember() && "Not a static data member?");
02719   Def = Def->getOutOfLineDefinition();
02720 
02721   if (!Def) {
02722     // We did not find an out-of-line definition of this static data member,
02723     // so we won't perform any instantiation. Rather, we rely on the user to
02724     // instantiate this definition (or provide a specialization for it) in
02725     // another translation unit.
02726     if (DefinitionRequired) {
02727       Def = Var->getInstantiatedFromStaticDataMember();
02728       Diag(PointOfInstantiation,
02729            diag::err_explicit_instantiation_undefined_member)
02730         << 2 << Var->getDeclName() << Var->getDeclContext();
02731       Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
02732     } else if (Var->getTemplateSpecializationKind()
02733                  == TSK_ExplicitInstantiationDefinition) {
02734       PendingInstantiations.push_back(
02735         std::make_pair(Var, PointOfInstantiation));
02736     }
02737 
02738     return;
02739   }
02740 
02741   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
02742 
02743   // Never instantiate an explicit specialization.
02744   if (TSK == TSK_ExplicitSpecialization)
02745     return;
02746 
02747   // C++0x [temp.explicit]p9:
02748   //   Except for inline functions, other explicit instantiation declarations
02749   //   have the effect of suppressing the implicit instantiation of the entity
02750   //   to which they refer.
02751   if (TSK == TSK_ExplicitInstantiationDeclaration)
02752     return;
02753 
02754   Consumer.HandleCXXStaticMemberVarInstantiation(Var);
02755 
02756   // If we already have a definition, we're done.
02757   if (VarDecl *Def = Var->getDefinition()) {
02758     // We may be explicitly instantiating something we've already implicitly
02759     // instantiated.
02760     Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
02761                                        PointOfInstantiation);
02762     return;
02763   }
02764 
02765   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
02766   if (Inst)
02767     return;
02768 
02769   // If we're performing recursive template instantiation, create our own
02770   // queue of pending implicit instantiations that we will instantiate later,
02771   // while we're still within our own instantiation context.
02772   SmallVector<VTableUse, 16> SavedVTableUses;
02773   std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
02774   if (Recursive) {
02775     VTableUses.swap(SavedVTableUses);
02776     PendingInstantiations.swap(SavedPendingInstantiations);
02777   }
02778 
02779   // Enter the scope of this instantiation. We don't use
02780   // PushDeclContext because we don't have a scope.
02781   ContextRAII previousContext(*this, Var->getDeclContext());
02782   LocalInstantiationScope Local(*this);
02783   
02784   VarDecl *OldVar = Var;
02785   Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
02786                                         getTemplateInstantiationArgs(Var)));
02787 
02788   previousContext.pop();
02789 
02790   if (Var) {
02791     MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
02792     assert(MSInfo && "Missing member specialization information?");
02793     Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
02794                                        MSInfo->getPointOfInstantiation());
02795     DeclGroupRef DG(Var);
02796     Consumer.HandleTopLevelDecl(DG);
02797   }
02798   Local.Exit();
02799   
02800   if (Recursive) {
02801     // Define any newly required vtables.
02802     DefineUsedVTables();
02803 
02804     // Instantiate any pending implicit instantiations found during the
02805     // instantiation of this template.
02806     PerformPendingInstantiations();
02807 
02808     // Restore the set of pending vtables.
02809     assert(VTableUses.empty() &&
02810            "VTableUses should be empty before it is discarded, "
02811            "while instantiating static data member.");
02812     VTableUses.swap(SavedVTableUses);
02813 
02814     // Restore the set of pending implicit instantiations.
02815     assert(PendingInstantiations.empty() &&
02816            "PendingInstantiations should be empty before it is discarded, "
02817            "while instantiating static data member.");
02818     PendingInstantiations.swap(SavedPendingInstantiations);
02819   }
02820 }
02821 
02822 void
02823 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
02824                                  const CXXConstructorDecl *Tmpl,
02825                            const MultiLevelTemplateArgumentList &TemplateArgs) {
02826 
02827   SmallVector<CXXCtorInitializer*, 4> NewInits;
02828   bool AnyErrors = false;
02829 
02830   // Instantiate all the initializers.
02831   for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
02832                                             InitsEnd = Tmpl->init_end();
02833        Inits != InitsEnd; ++Inits) {
02834     CXXCtorInitializer *Init = *Inits;
02835 
02836     // Only instantiate written initializers, let Sema re-construct implicit
02837     // ones.
02838     if (!Init->isWritten())
02839       continue;
02840 
02841     SourceLocation EllipsisLoc;
02842 
02843     if (Init->isPackExpansion()) {
02844       // This is a pack expansion. We should expand it now.
02845       TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
02846       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
02847       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
02848       bool ShouldExpand = false;
02849       bool RetainExpansion = false;
02850       llvm::Optional<unsigned> NumExpansions;
02851       if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
02852                                           BaseTL.getSourceRange(),
02853                                           Unexpanded,
02854                                           TemplateArgs, ShouldExpand,
02855                                           RetainExpansion,
02856                                           NumExpansions)) {
02857         AnyErrors = true;
02858         New->setInvalidDecl();
02859         continue;
02860       }
02861       assert(ShouldExpand && "Partial instantiation of base initializer?");
02862 
02863       // Loop over all of the arguments in the argument pack(s),
02864       for (unsigned I = 0; I != *NumExpansions; ++I) {
02865         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
02866 
02867         // Instantiate the initializer.
02868         ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
02869                                                /*CXXDirectInit=*/true);
02870         if (TempInit.isInvalid()) {
02871           AnyErrors = true;
02872           break;
02873         }
02874 
02875         // Instantiate the base type.
02876         TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
02877                                               TemplateArgs,
02878                                               Init->getSourceLocation(),
02879                                               New->getDeclName());
02880         if (!BaseTInfo) {
02881           AnyErrors = true;
02882           break;
02883         }
02884 
02885         // Build the initializer.
02886         MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
02887                                                      BaseTInfo, TempInit.take(),
02888                                                      New->getParent(),
02889                                                      SourceLocation());
02890         if (NewInit.isInvalid()) {
02891           AnyErrors = true;
02892           break;
02893         }
02894 
02895         NewInits.push_back(NewInit.get());
02896       }
02897 
02898       continue;
02899     }
02900 
02901     // Instantiate the initializer.
02902     ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
02903                                            /*CXXDirectInit=*/true);
02904     if (TempInit.isInvalid()) {
02905       AnyErrors = true;
02906       continue;
02907     }
02908 
02909     MemInitResult NewInit;
02910     if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
02911       TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
02912                                         TemplateArgs,
02913                                         Init->getSourceLocation(),
02914                                         New->getDeclName());
02915       if (!TInfo) {
02916         AnyErrors = true;
02917         New->setInvalidDecl();
02918         continue;
02919       }
02920 
02921       if (Init->isBaseInitializer())
02922         NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
02923                                        New->getParent(), EllipsisLoc);
02924       else
02925         NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
02926                                   cast<CXXRecordDecl>(CurContext->getParent()));
02927     } else if (Init->isMemberInitializer()) {
02928       FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
02929                                                      Init->getMemberLocation(),
02930                                                      Init->getMember(),
02931                                                      TemplateArgs));
02932       if (!Member) {
02933         AnyErrors = true;
02934         New->setInvalidDecl();
02935         continue;
02936       }
02937 
02938       NewInit = BuildMemberInitializer(Member, TempInit.take(),
02939                                        Init->getSourceLocation());
02940     } else if (Init->isIndirectMemberInitializer()) {
02941       IndirectFieldDecl *IndirectMember =
02942          cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
02943                                  Init->getMemberLocation(),
02944                                  Init->getIndirectMember(), TemplateArgs));
02945 
02946       if (!IndirectMember) {
02947         AnyErrors = true;
02948         New->setInvalidDecl();
02949         continue;
02950       }
02951 
02952       NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
02953                                        Init->getSourceLocation());
02954     }
02955 
02956     if (NewInit.isInvalid()) {
02957       AnyErrors = true;
02958       New->setInvalidDecl();
02959     } else {
02960       NewInits.push_back(NewInit.get());
02961     }
02962   }
02963 
02964   // Assign all the initializers to the new constructor.
02965   ActOnMemInitializers(New,
02966                        /*FIXME: ColonLoc */
02967                        SourceLocation(),
02968                        NewInits.data(), NewInits.size(),
02969                        AnyErrors);
02970 }
02971 
02972 ExprResult Sema::SubstInitializer(Expr *Init,
02973                           const MultiLevelTemplateArgumentList &TemplateArgs,
02974                           bool CXXDirectInit) {
02975   // Initializers are instantiated like expressions, except that various outer
02976   // layers are stripped.
02977   if (!Init)
02978     return Owned(Init);
02979 
02980   if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
02981     Init = ExprTemp->getSubExpr();
02982 
02983   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
02984     Init = Binder->getSubExpr();
02985 
02986   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
02987     Init = ICE->getSubExprAsWritten();
02988 
02989   // If this is a direct-initializer, we take apart CXXConstructExprs.
02990   // Everything else is passed through.
02991   CXXConstructExpr *Construct;
02992   if (!CXXDirectInit || !(Construct = dyn_cast<CXXConstructExpr>(Init)) ||
02993       isa<CXXTemporaryObjectExpr>(Construct))
02994     return SubstExpr(Init, TemplateArgs);
02995 
02996   ASTOwningVector<Expr*> NewArgs(*this);
02997   if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
02998                  TemplateArgs, NewArgs))
02999     return ExprError();
03000 
03001   // Treat an empty initializer like none.
03002   if (NewArgs.empty())
03003     return Owned((Expr*)0);
03004 
03005   // Build a ParenListExpr to represent anything else.
03006   // FIXME: Fake locations!
03007   SourceLocation Loc = PP.getLocForEndOfToken(Init->getLocStart());
03008   return ActOnParenListExpr(Loc, Loc, move_arg(NewArgs));
03009 }
03010 
03011 // TODO: this could be templated if the various decl types used the
03012 // same method name.
03013 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
03014                               ClassTemplateDecl *Instance) {
03015   Pattern = Pattern->getCanonicalDecl();
03016 
03017   do {
03018     Instance = Instance->getCanonicalDecl();
03019     if (Pattern == Instance) return true;
03020     Instance = Instance->getInstantiatedFromMemberTemplate();
03021   } while (Instance);
03022 
03023   return false;
03024 }
03025 
03026 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
03027                               FunctionTemplateDecl *Instance) {
03028   Pattern = Pattern->getCanonicalDecl();
03029 
03030   do {
03031     Instance = Instance->getCanonicalDecl();
03032     if (Pattern == Instance) return true;
03033     Instance = Instance->getInstantiatedFromMemberTemplate();
03034   } while (Instance);
03035 
03036   return false;
03037 }
03038 
03039 static bool
03040 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
03041                   ClassTemplatePartialSpecializationDecl *Instance) {
03042   Pattern
03043     = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
03044   do {
03045     Instance = cast<ClassTemplatePartialSpecializationDecl>(
03046                                                 Instance->getCanonicalDecl());
03047     if (Pattern == Instance)
03048       return true;
03049     Instance = Instance->getInstantiatedFromMember();
03050   } while (Instance);
03051 
03052   return false;
03053 }
03054 
03055 static bool isInstantiationOf(CXXRecordDecl *Pattern,
03056                               CXXRecordDecl *Instance) {
03057   Pattern = Pattern->getCanonicalDecl();
03058 
03059   do {
03060     Instance = Instance->getCanonicalDecl();
03061     if (Pattern == Instance) return true;
03062     Instance = Instance->getInstantiatedFromMemberClass();
03063   } while (Instance);
03064 
03065   return false;
03066 }
03067 
03068 static bool isInstantiationOf(FunctionDecl *Pattern,
03069                               FunctionDecl *Instance) {
03070   Pattern = Pattern->getCanonicalDecl();
03071 
03072   do {
03073     Instance = Instance->getCanonicalDecl();
03074     if (Pattern == Instance) return true;
03075     Instance = Instance->getInstantiatedFromMemberFunction();
03076   } while (Instance);
03077 
03078   return false;
03079 }
03080 
03081 static bool isInstantiationOf(EnumDecl *Pattern,
03082                               EnumDecl *Instance) {
03083   Pattern = Pattern->getCanonicalDecl();
03084 
03085   do {
03086     Instance = Instance->getCanonicalDecl();
03087     if (Pattern == Instance) return true;
03088     Instance = Instance->getInstantiatedFromMemberEnum();
03089   } while (Instance);
03090 
03091   return false;
03092 }
03093 
03094 static bool isInstantiationOf(UsingShadowDecl *Pattern,
03095                               UsingShadowDecl *Instance,
03096                               ASTContext &C) {
03097   return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
03098 }
03099 
03100 static bool isInstantiationOf(UsingDecl *Pattern,
03101                               UsingDecl *Instance,
03102                               ASTContext &C) {
03103   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
03104 }
03105 
03106 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
03107                               UsingDecl *Instance,
03108                               ASTContext &C) {
03109   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
03110 }
03111 
03112 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
03113                               UsingDecl *Instance,
03114                               ASTContext &C) {
03115   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
03116 }
03117 
03118 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
03119                                               VarDecl *Instance) {
03120   assert(Instance->isStaticDataMember());
03121 
03122   Pattern = Pattern->getCanonicalDecl();
03123 
03124   do {
03125     Instance = Instance->getCanonicalDecl();
03126     if (Pattern == Instance) return true;
03127     Instance = Instance->getInstantiatedFromStaticDataMember();
03128   } while (Instance);
03129 
03130   return false;
03131 }
03132 
03133 // Other is the prospective instantiation
03134 // D is the prospective pattern
03135 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
03136   if (D->getKind() != Other->getKind()) {
03137     if (UnresolvedUsingTypenameDecl *UUD
03138           = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
03139       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
03140         return isInstantiationOf(UUD, UD, Ctx);
03141       }
03142     }
03143 
03144     if (UnresolvedUsingValueDecl *UUD
03145           = dyn_cast<UnresolvedUsingValueDecl>(D)) {
03146       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
03147         return isInstantiationOf(UUD, UD, Ctx);
03148       }
03149     }
03150 
03151     return false;
03152   }
03153 
03154   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
03155     return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
03156 
03157   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
03158     return isInstantiationOf(cast<FunctionDecl>(D), Function);
03159 
03160   if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
03161     return isInstantiationOf(cast<EnumDecl>(D), Enum);
03162 
03163   if (VarDecl *Var = dyn_cast<VarDecl>(Other))
03164     if (Var->isStaticDataMember())
03165       return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
03166 
03167   if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
03168     return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
03169 
03170   if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
03171     return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
03172 
03173   if (ClassTemplatePartialSpecializationDecl *PartialSpec
03174         = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
03175     return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
03176                              PartialSpec);
03177 
03178   if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
03179     if (!Field->getDeclName()) {
03180       // This is an unnamed field.
03181       return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
03182         cast<FieldDecl>(D);
03183     }
03184   }
03185 
03186   if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
03187     return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
03188 
03189   if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
03190     return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
03191 
03192   return D->getDeclName() && isa<NamedDecl>(Other) &&
03193     D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
03194 }
03195 
03196 template<typename ForwardIterator>
03197 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
03198                                       NamedDecl *D,
03199                                       ForwardIterator first,
03200                                       ForwardIterator last) {
03201   for (; first != last; ++first)
03202     if (isInstantiationOf(Ctx, D, *first))
03203       return cast<NamedDecl>(*first);
03204 
03205   return 0;
03206 }
03207 
03208 /// \brief Finds the instantiation of the given declaration context
03209 /// within the current instantiation.
03210 ///
03211 /// \returns NULL if there was an error
03212 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
03213                           const MultiLevelTemplateArgumentList &TemplateArgs) {
03214   if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
03215     Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
03216     return cast_or_null<DeclContext>(ID);
03217   } else return DC;
03218 }
03219 
03220 /// \brief Find the instantiation of the given declaration within the
03221 /// current instantiation.
03222 ///
03223 /// This routine is intended to be used when \p D is a declaration
03224 /// referenced from within a template, that needs to mapped into the
03225 /// corresponding declaration within an instantiation. For example,
03226 /// given:
03227 ///
03228 /// \code
03229 /// template<typename T>
03230 /// struct X {
03231 ///   enum Kind {
03232 ///     KnownValue = sizeof(T)
03233 ///   };
03234 ///
03235 ///   bool getKind() const { return KnownValue; }
03236 /// };
03237 ///
03238 /// template struct X<int>;
03239 /// \endcode
03240 ///
03241 /// In the instantiation of X<int>::getKind(), we need to map the
03242 /// EnumConstantDecl for KnownValue (which refers to
03243 /// X<T>::<Kind>::KnownValue) to its instantiation
03244 /// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
03245 /// this mapping from within the instantiation of X<int>.
03246 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
03247                           const MultiLevelTemplateArgumentList &TemplateArgs) {
03248   DeclContext *ParentDC = D->getDeclContext();
03249   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
03250       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
03251       (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
03252       (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
03253     // D is a local of some kind. Look into the map of local
03254     // declarations to their instantiations.
03255     typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
03256     llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
03257       = CurrentInstantiationScope->findInstantiationOf(D);
03258 
03259     if (Found) {
03260       if (Decl *FD = Found->dyn_cast<Decl *>())
03261         return cast<NamedDecl>(FD);
03262 
03263       unsigned PackIdx = ArgumentPackSubstitutionIndex;
03264       return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
03265     }
03266 
03267     // If we didn't find the decl, then we must have a label decl that hasn't
03268     // been found yet.  Lazily instantiate it and return it now.
03269     assert(isa<LabelDecl>(D));
03270 
03271     Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
03272     assert(Inst && "Failed to instantiate label??");
03273 
03274     CurrentInstantiationScope->InstantiatedLocal(D, Inst);
03275     return cast<LabelDecl>(Inst);
03276   }
03277 
03278   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
03279     if (!Record->isDependentContext())
03280       return D;
03281 
03282     // Determine whether this record is the "templated" declaration describing
03283     // a class template or class template partial specialization.
03284     ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
03285     if (ClassTemplate)
03286       ClassTemplate = ClassTemplate->getCanonicalDecl();
03287     else if (ClassTemplatePartialSpecializationDecl *PartialSpec
03288                = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
03289       ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
03290     
03291     // Walk the current context to find either the record or an instantiation of
03292     // it.
03293     DeclContext *DC = CurContext;
03294     while (!DC->isFileContext()) {
03295       // If we're performing substitution while we're inside the template
03296       // definition, we'll find our own context. We're done.
03297       if (DC->Equals(Record))
03298         return Record;
03299       
03300       if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
03301         // Check whether we're in the process of instantiating a class template
03302         // specialization of the template we're mapping.
03303         if (ClassTemplateSpecializationDecl *InstSpec
03304                       = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
03305           ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
03306           if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
03307             return InstRecord;
03308         }
03309       
03310         // Check whether we're in the process of instantiating a member class.
03311         if (isInstantiationOf(Record, InstRecord))
03312           return InstRecord;
03313       }
03314       
03315       
03316       // Move to the outer template scope.
03317       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
03318         if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
03319           DC = FD->getLexicalDeclContext();
03320           continue;
03321         }
03322       }
03323       
03324       DC = DC->getParent();
03325     }
03326 
03327     // Fall through to deal with other dependent record types (e.g.,
03328     // anonymous unions in class templates).
03329   }
03330 
03331   if (!ParentDC->isDependentContext())
03332     return D;
03333 
03334   ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
03335   if (!ParentDC)
03336     return 0;
03337 
03338   if (ParentDC != D->getDeclContext()) {
03339     // We performed some kind of instantiation in the parent context,
03340     // so now we need to look into the instantiated parent context to
03341     // find the instantiation of the declaration D.
03342 
03343     // If our context used to be dependent, we may need to instantiate
03344     // it before performing lookup into that context.
03345     bool IsBeingInstantiated = false;
03346     if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
03347       if (!Spec->isDependentContext()) {
03348         QualType T = Context.getTypeDeclType(Spec);
03349         const RecordType *Tag = T->getAs<RecordType>();
03350         assert(Tag && "type of non-dependent record is not a RecordType");
03351         if (Tag->isBeingDefined())
03352           IsBeingInstantiated = true;
03353         if (!Tag->isBeingDefined() &&
03354             RequireCompleteType(Loc, T, diag::err_incomplete_type))
03355           return 0;
03356 
03357         ParentDC = Tag->getDecl();
03358       }
03359     }
03360 
03361     NamedDecl *Result = 0;
03362     if (D->getDeclName()) {
03363       DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
03364       Result = findInstantiationOf(Context, D, Found.first, Found.second);
03365     } else {
03366       // Since we don't have a name for the entity we're looking for,
03367       // our only option is to walk through all of the declarations to
03368       // find that name. This will occur in a few cases:
03369       //
03370       //   - anonymous struct/union within a template
03371       //   - unnamed class/struct/union/enum within a template
03372       //
03373       // FIXME: Find a better way to find these instantiations!
03374       Result = findInstantiationOf(Context, D,
03375                                    ParentDC->decls_begin(),
03376                                    ParentDC->decls_end());
03377     }
03378 
03379     if (!Result) {
03380       if (isa<UsingShadowDecl>(D)) {
03381         // UsingShadowDecls can instantiate to nothing because of using hiding.
03382       } else if (Diags.hasErrorOccurred()) {
03383         // We've already complained about something, so most likely this
03384         // declaration failed to instantiate. There's no point in complaining
03385         // further, since this is normal in invalid code.
03386       } else if (IsBeingInstantiated) {
03387         // The class in which this member exists is currently being
03388         // instantiated, and we haven't gotten around to instantiating this
03389         // member yet. This can happen when the code uses forward declarations
03390         // of member classes, and introduces ordering dependencies via
03391         // template instantiation.
03392         Diag(Loc, diag::err_member_not_yet_instantiated)
03393           << D->getDeclName()
03394           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
03395         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
03396       } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
03397         // This enumeration constant was found when the template was defined,
03398         // but can't be found in the instantiation. This can happen if an
03399         // unscoped enumeration member is explicitly specialized.
03400         EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
03401         EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
03402                                                              TemplateArgs));
03403         assert(Spec->getTemplateSpecializationKind() ==
03404                  TSK_ExplicitSpecialization);
03405         Diag(Loc, diag::err_enumerator_does_not_exist)
03406           << D->getDeclName()
03407           << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
03408         Diag(Spec->getLocation(), diag::note_enum_specialized_here)
03409           << Context.getTypeDeclType(Spec);
03410       } else {
03411         // We should have found something, but didn't.
03412         llvm_unreachable("Unable to find instantiation of declaration!");
03413       }
03414     }
03415 
03416     D = Result;
03417   }
03418 
03419   return D;
03420 }
03421 
03422 /// \brief Performs template instantiation for all implicit template
03423 /// instantiations we have seen until this point.
03424 void Sema::PerformPendingInstantiations(bool LocalOnly) {
03425   // Load pending instantiations from the external source.
03426   if (!LocalOnly && ExternalSource) {
03427     SmallVector<std::pair<ValueDecl *, SourceLocation>, 4> Pending;
03428     ExternalSource->ReadPendingInstantiations(Pending);
03429     PendingInstantiations.insert(PendingInstantiations.begin(),
03430                                  Pending.begin(), Pending.end());
03431   }
03432 
03433   while (!PendingLocalImplicitInstantiations.empty() ||
03434          (!LocalOnly && !PendingInstantiations.empty())) {
03435     PendingImplicitInstantiation Inst;
03436 
03437     if (PendingLocalImplicitInstantiations.empty()) {
03438       Inst = PendingInstantiations.front();
03439       PendingInstantiations.pop_front();
03440     } else {
03441       Inst = PendingLocalImplicitInstantiations.front();
03442       PendingLocalImplicitInstantiations.pop_front();
03443     }
03444 
03445     // Instantiate function definitions
03446     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
03447       PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
03448                                           "instantiating function definition");
03449       bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
03450                                 TSK_ExplicitInstantiationDefinition;
03451       InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
03452                                     DefinitionRequired);
03453       continue;
03454     }
03455 
03456     // Instantiate static data member definitions.
03457     VarDecl *Var = cast<VarDecl>(Inst.first);
03458     assert(Var->isStaticDataMember() && "Not a static data member?");
03459 
03460     // Don't try to instantiate declarations if the most recent redeclaration
03461     // is invalid.
03462     if (Var->getMostRecentDecl()->isInvalidDecl())
03463       continue;
03464 
03465     // Check if the most recent declaration has changed the specialization kind
03466     // and removed the need for implicit instantiation.
03467     switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
03468     case TSK_Undeclared:
03469       llvm_unreachable("Cannot instantitiate an undeclared specialization.");
03470     case TSK_ExplicitInstantiationDeclaration:
03471     case TSK_ExplicitSpecialization:
03472       continue;  // No longer need to instantiate this type.
03473     case TSK_ExplicitInstantiationDefinition:
03474       // We only need an instantiation if the pending instantiation *is* the
03475       // explicit instantiation.
03476       if (Var != Var->getMostRecentDecl()) continue;
03477     case TSK_ImplicitInstantiation:
03478       break;
03479     }
03480 
03481     PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
03482                                         "instantiating static data member "
03483                                         "definition");
03484 
03485     bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
03486                               TSK_ExplicitInstantiationDefinition;
03487     InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
03488                                           DefinitionRequired);
03489   }
03490 }
03491 
03492 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
03493                        const MultiLevelTemplateArgumentList &TemplateArgs) {
03494   for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
03495          E = Pattern->ddiag_end(); I != E; ++I) {
03496     DependentDiagnostic *DD = *I;
03497 
03498     switch (DD->getKind()) {
03499     case DependentDiagnostic::Access:
03500       HandleDependentAccessCheck(*DD, TemplateArgs);
03501       break;
03502     }
03503   }
03504 }