Home | History | Annotate | Download | only in Sema
      1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //===----------------------------------------------------------------------===/
      8 //
      9 //  This file implements C++ template instantiation for declarations.
     10 //
     11 //===----------------------------------------------------------------------===/
     12 #include "clang/Sema/SemaInternal.h"
     13 #include "clang/AST/ASTConsumer.h"
     14 #include "clang/AST/ASTContext.h"
     15 #include "clang/AST/DeclTemplate.h"
     16 #include "clang/AST/DeclVisitor.h"
     17 #include "clang/AST/DependentDiagnostic.h"
     18 #include "clang/AST/Expr.h"
     19 #include "clang/AST/ExprCXX.h"
     20 #include "clang/AST/TypeLoc.h"
     21 #include "clang/Lex/Preprocessor.h"
     22 #include "clang/Sema/Lookup.h"
     23 #include "clang/Sema/PrettyDeclStackTrace.h"
     24 #include "clang/Sema/Template.h"
     25 
     26 using namespace clang;
     27 
     28 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
     29                                               DeclaratorDecl *NewDecl) {
     30   if (!OldDecl->getQualifierLoc())
     31     return false;
     32 
     33   NestedNameSpecifierLoc NewQualifierLoc
     34     = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
     35                                           TemplateArgs);
     36 
     37   if (!NewQualifierLoc)
     38     return true;
     39 
     40   NewDecl->setQualifierInfo(NewQualifierLoc);
     41   return false;
     42 }
     43 
     44 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
     45                                               TagDecl *NewDecl) {
     46   if (!OldDecl->getQualifierLoc())
     47     return false;
     48 
     49   NestedNameSpecifierLoc NewQualifierLoc
     50   = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
     51                                         TemplateArgs);
     52 
     53   if (!NewQualifierLoc)
     54     return true;
     55 
     56   NewDecl->setQualifierInfo(NewQualifierLoc);
     57   return false;
     58 }
     59 
     60 // Include attribute instantiation code.
     61 #include "clang/Sema/AttrTemplateInstantiate.inc"
     62 
     63 static void instantiateDependentAlignedAttr(
     64     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
     65     const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
     66   if (Aligned->isAlignmentExpr()) {
     67     // The alignment expression is a constant expression.
     68     EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
     69     ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
     70     if (!Result.isInvalid())
     71       S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
     72                        Aligned->getSpellingListIndex(), IsPackExpansion);
     73   } else {
     74     TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
     75                                          TemplateArgs, Aligned->getLocation(),
     76                                          DeclarationName());
     77     if (Result)
     78       S.AddAlignedAttr(Aligned->getLocation(), New, Result,
     79                        Aligned->getSpellingListIndex(), IsPackExpansion);
     80   }
     81 }
     82 
     83 static void instantiateDependentAlignedAttr(
     84     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
     85     const AlignedAttr *Aligned, Decl *New) {
     86   if (!Aligned->isPackExpansion()) {
     87     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
     88     return;
     89   }
     90 
     91   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
     92   if (Aligned->isAlignmentExpr())
     93     S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
     94                                       Unexpanded);
     95   else
     96     S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
     97                                       Unexpanded);
     98   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
     99 
    100   // Determine whether we can expand this attribute pack yet.
    101   bool Expand = true, RetainExpansion = false;
    102   Optional<unsigned> NumExpansions;
    103   // FIXME: Use the actual location of the ellipsis.
    104   SourceLocation EllipsisLoc = Aligned->getLocation();
    105   if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
    106                                         Unexpanded, TemplateArgs, Expand,
    107                                         RetainExpansion, NumExpansions))
    108     return;
    109 
    110   if (!Expand) {
    111     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
    112     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
    113   } else {
    114     for (unsigned I = 0; I != *NumExpansions; ++I) {
    115       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
    116       instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
    117     }
    118   }
    119 }
    120 
    121 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
    122                             const Decl *Tmpl, Decl *New,
    123                             LateInstantiatedAttrVec *LateAttrs,
    124                             LocalInstantiationScope *OuterMostScope) {
    125   for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
    126        i != e; ++i) {
    127     const Attr *TmplAttr = *i;
    128 
    129     // FIXME: This should be generalized to more than just the AlignedAttr.
    130     const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
    131     if (Aligned && Aligned->isAlignmentDependent()) {
    132       instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
    133       continue;
    134     }
    135 
    136     assert(!TmplAttr->isPackExpansion());
    137     if (TmplAttr->isLateParsed() && LateAttrs) {
    138       // Late parsed attributes must be instantiated and attached after the
    139       // enclosing class has been instantiated.  See Sema::InstantiateClass.
    140       LocalInstantiationScope *Saved = 0;
    141       if (CurrentInstantiationScope)
    142         Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
    143       LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
    144     } else {
    145       // Allow 'this' within late-parsed attributes.
    146       NamedDecl *ND = dyn_cast<NamedDecl>(New);
    147       CXXRecordDecl *ThisContext =
    148           dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
    149       CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
    150                                  ND && ND->isCXXInstanceMember());
    151 
    152       Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
    153                                                          *this, TemplateArgs);
    154       if (NewAttr)
    155         New->addAttr(NewAttr);
    156     }
    157   }
    158 }
    159 
    160 Decl *
    161 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
    162   llvm_unreachable("Translation units cannot be instantiated");
    163 }
    164 
    165 Decl *
    166 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
    167   LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
    168                                       D->getIdentifier());
    169   Owner->addDecl(Inst);
    170   return Inst;
    171 }
    172 
    173 Decl *
    174 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
    175   llvm_unreachable("Namespaces cannot be instantiated");
    176 }
    177 
    178 Decl *
    179 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
    180   NamespaceAliasDecl *Inst
    181     = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
    182                                  D->getNamespaceLoc(),
    183                                  D->getAliasLoc(),
    184                                  D->getIdentifier(),
    185                                  D->getQualifierLoc(),
    186                                  D->getTargetNameLoc(),
    187                                  D->getNamespace());
    188   Owner->addDecl(Inst);
    189   return Inst;
    190 }
    191 
    192 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
    193                                                            bool IsTypeAlias) {
    194   bool Invalid = false;
    195   TypeSourceInfo *DI = D->getTypeSourceInfo();
    196   if (DI->getType()->isInstantiationDependentType() ||
    197       DI->getType()->isVariablyModifiedType()) {
    198     DI = SemaRef.SubstType(DI, TemplateArgs,
    199                            D->getLocation(), D->getDeclName());
    200     if (!DI) {
    201       Invalid = true;
    202       DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
    203     }
    204   } else {
    205     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
    206   }
    207 
    208   // HACK: g++ has a bug where it gets the value kind of ?: wrong.
    209   // libstdc++ relies upon this bug in its implementation of common_type.
    210   // If we happen to be processing that implementation, fake up the g++ ?:
    211   // semantics. See LWG issue 2141 for more information on the bug.
    212   const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
    213   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
    214   if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
    215       DT->isReferenceType() &&
    216       RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
    217       RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
    218       D->getIdentifier() && D->getIdentifier()->isStr("type") &&
    219       SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
    220     // Fold it to the (non-reference) type which g++ would have produced.
    221     DI = SemaRef.Context.getTrivialTypeSourceInfo(
    222       DI->getType().getNonReferenceType());
    223 
    224   // Create the new typedef
    225   TypedefNameDecl *Typedef;
    226   if (IsTypeAlias)
    227     Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
    228                                     D->getLocation(), D->getIdentifier(), DI);
    229   else
    230     Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
    231                                   D->getLocation(), D->getIdentifier(), DI);
    232   if (Invalid)
    233     Typedef->setInvalidDecl();
    234 
    235   // If the old typedef was the name for linkage purposes of an anonymous
    236   // tag decl, re-establish that relationship for the new typedef.
    237   if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
    238     TagDecl *oldTag = oldTagType->getDecl();
    239     if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
    240       TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
    241       assert(!newTag->hasNameForLinkage());
    242       newTag->setTypedefNameForAnonDecl(Typedef);
    243     }
    244   }
    245 
    246   if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
    247     NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
    248                                                        TemplateArgs);
    249     if (!InstPrev)
    250       return 0;
    251 
    252     TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
    253 
    254     // If the typedef types are not identical, reject them.
    255     SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
    256 
    257     Typedef->setPreviousDeclaration(InstPrevTypedef);
    258   }
    259 
    260   SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
    261 
    262   Typedef->setAccess(D->getAccess());
    263 
    264   return Typedef;
    265 }
    266 
    267 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
    268   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
    269   Owner->addDecl(Typedef);
    270   return Typedef;
    271 }
    272 
    273 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
    274   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
    275   Owner->addDecl(Typedef);
    276   return Typedef;
    277 }
    278 
    279 Decl *
    280 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
    281   // Create a local instantiation scope for this type alias template, which
    282   // will contain the instantiations of the template parameters.
    283   LocalInstantiationScope Scope(SemaRef);
    284 
    285   TemplateParameterList *TempParams = D->getTemplateParameters();
    286   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
    287   if (!InstParams)
    288     return 0;
    289 
    290   TypeAliasDecl *Pattern = D->getTemplatedDecl();
    291 
    292   TypeAliasTemplateDecl *PrevAliasTemplate = 0;
    293   if (Pattern->getPreviousDecl()) {
    294     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
    295     if (!Found.empty()) {
    296       PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
    297     }
    298   }
    299 
    300   TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
    301     InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
    302   if (!AliasInst)
    303     return 0;
    304 
    305   TypeAliasTemplateDecl *Inst
    306     = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
    307                                     D->getDeclName(), InstParams, AliasInst);
    308   if (PrevAliasTemplate)
    309     Inst->setPreviousDeclaration(PrevAliasTemplate);
    310 
    311   Inst->setAccess(D->getAccess());
    312 
    313   if (!PrevAliasTemplate)
    314     Inst->setInstantiatedFromMemberTemplate(D);
    315 
    316   Owner->addDecl(Inst);
    317 
    318   return Inst;
    319 }
    320 
    321 // FIXME: Revise for static member templates.
    322 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
    323   return VisitVarDecl(D, /*ForVarTemplate=*/false);
    324 }
    325 
    326 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D, bool ForVarTemplate) {
    327 
    328   // If this is the variable for an anonymous struct or union,
    329   // instantiate the anonymous struct/union type first.
    330   if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
    331     if (RecordTy->getDecl()->isAnonymousStructOrUnion())
    332       if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
    333         return 0;
    334 
    335   // Do substitution on the type of the declaration
    336   TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
    337                                          TemplateArgs,
    338                                          D->getTypeSpecStartLoc(),
    339                                          D->getDeclName());
    340   if (!DI)
    341     return 0;
    342 
    343   if (DI->getType()->isFunctionType()) {
    344     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
    345       << D->isStaticDataMember() << DI->getType();
    346     return 0;
    347   }
    348 
    349   // Build the instantiated declaration.
    350   VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, D->getInnerLocStart(),
    351                                  D->getLocation(), D->getIdentifier(),
    352                                  DI->getType(), DI, D->getStorageClass());
    353 
    354   // In ARC, infer 'retaining' for variables of retainable type.
    355   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
    356       SemaRef.inferObjCARCLifetime(Var))
    357     Var->setInvalidDecl();
    358 
    359   // Substitute the nested name specifier, if any.
    360   if (SubstQualifier(D, Var))
    361     return 0;
    362 
    363   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
    364                                      StartingScope, ForVarTemplate);
    365   return Var;
    366 }
    367 
    368 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
    369   AccessSpecDecl* AD
    370     = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
    371                              D->getAccessSpecifierLoc(), D->getColonLoc());
    372   Owner->addHiddenDecl(AD);
    373   return AD;
    374 }
    375 
    376 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
    377   bool Invalid = false;
    378   TypeSourceInfo *DI = D->getTypeSourceInfo();
    379   if (DI->getType()->isInstantiationDependentType() ||
    380       DI->getType()->isVariablyModifiedType())  {
    381     DI = SemaRef.SubstType(DI, TemplateArgs,
    382                            D->getLocation(), D->getDeclName());
    383     if (!DI) {
    384       DI = D->getTypeSourceInfo();
    385       Invalid = true;
    386     } else if (DI->getType()->isFunctionType()) {
    387       // C++ [temp.arg.type]p3:
    388       //   If a declaration acquires a function type through a type
    389       //   dependent on a template-parameter and this causes a
    390       //   declaration that does not use the syntactic form of a
    391       //   function declarator to have function type, the program is
    392       //   ill-formed.
    393       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
    394         << DI->getType();
    395       Invalid = true;
    396     }
    397   } else {
    398     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
    399   }
    400 
    401   Expr *BitWidth = D->getBitWidth();
    402   if (Invalid)
    403     BitWidth = 0;
    404   else if (BitWidth) {
    405     // The bit-width expression is a constant expression.
    406     EnterExpressionEvaluationContext Unevaluated(SemaRef,
    407                                                  Sema::ConstantEvaluated);
    408 
    409     ExprResult InstantiatedBitWidth
    410       = SemaRef.SubstExpr(BitWidth, TemplateArgs);
    411     if (InstantiatedBitWidth.isInvalid()) {
    412       Invalid = true;
    413       BitWidth = 0;
    414     } else
    415       BitWidth = InstantiatedBitWidth.takeAs<Expr>();
    416   }
    417 
    418   FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
    419                                             DI->getType(), DI,
    420                                             cast<RecordDecl>(Owner),
    421                                             D->getLocation(),
    422                                             D->isMutable(),
    423                                             BitWidth,
    424                                             D->getInClassInitStyle(),
    425                                             D->getInnerLocStart(),
    426                                             D->getAccess(),
    427                                             0);
    428   if (!Field) {
    429     cast<Decl>(Owner)->setInvalidDecl();
    430     return 0;
    431   }
    432 
    433   SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
    434 
    435   if (Field->hasAttrs())
    436     SemaRef.CheckAlignasUnderalignment(Field);
    437 
    438   if (Invalid)
    439     Field->setInvalidDecl();
    440 
    441   if (!Field->getDeclName()) {
    442     // Keep track of where this decl came from.
    443     SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
    444   }
    445   if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
    446     if (Parent->isAnonymousStructOrUnion() &&
    447         Parent->getRedeclContext()->isFunctionOrMethod())
    448       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
    449   }
    450 
    451   Field->setImplicit(D->isImplicit());
    452   Field->setAccess(D->getAccess());
    453   Owner->addDecl(Field);
    454 
    455   return Field;
    456 }
    457 
    458 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
    459   bool Invalid = false;
    460   TypeSourceInfo *DI = D->getTypeSourceInfo();
    461 
    462   if (DI->getType()->isVariablyModifiedType()) {
    463     SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
    464     << D->getName();
    465     Invalid = true;
    466   } else if (DI->getType()->isInstantiationDependentType())  {
    467     DI = SemaRef.SubstType(DI, TemplateArgs,
    468                            D->getLocation(), D->getDeclName());
    469     if (!DI) {
    470       DI = D->getTypeSourceInfo();
    471       Invalid = true;
    472     } else if (DI->getType()->isFunctionType()) {
    473       // C++ [temp.arg.type]p3:
    474       //   If a declaration acquires a function type through a type
    475       //   dependent on a template-parameter and this causes a
    476       //   declaration that does not use the syntactic form of a
    477       //   function declarator to have function type, the program is
    478       //   ill-formed.
    479       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
    480       << DI->getType();
    481       Invalid = true;
    482     }
    483   } else {
    484     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
    485   }
    486 
    487   MSPropertyDecl *Property = new (SemaRef.Context)
    488       MSPropertyDecl(Owner, D->getLocation(),
    489                      D->getDeclName(), DI->getType(), DI,
    490                      D->getLocStart(),
    491                      D->getGetterId(), D->getSetterId());
    492 
    493   SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
    494                            StartingScope);
    495 
    496   if (Invalid)
    497     Property->setInvalidDecl();
    498 
    499   Property->setAccess(D->getAccess());
    500   Owner->addDecl(Property);
    501 
    502   return Property;
    503 }
    504 
    505 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
    506   NamedDecl **NamedChain =
    507     new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
    508 
    509   int i = 0;
    510   for (IndirectFieldDecl::chain_iterator PI =
    511        D->chain_begin(), PE = D->chain_end();
    512        PI != PE; ++PI) {
    513     NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
    514                                               TemplateArgs);
    515     if (!Next)
    516       return 0;
    517 
    518     NamedChain[i++] = Next;
    519   }
    520 
    521   QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
    522   IndirectFieldDecl* IndirectField
    523     = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
    524                                 D->getIdentifier(), T,
    525                                 NamedChain, D->getChainingSize());
    526 
    527 
    528   IndirectField->setImplicit(D->isImplicit());
    529   IndirectField->setAccess(D->getAccess());
    530   Owner->addDecl(IndirectField);
    531   return IndirectField;
    532 }
    533 
    534 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
    535   // Handle friend type expressions by simply substituting template
    536   // parameters into the pattern type and checking the result.
    537   if (TypeSourceInfo *Ty = D->getFriendType()) {
    538     TypeSourceInfo *InstTy;
    539     // If this is an unsupported friend, don't bother substituting template
    540     // arguments into it. The actual type referred to won't be used by any
    541     // parts of Clang, and may not be valid for instantiating. Just use the
    542     // same info for the instantiated friend.
    543     if (D->isUnsupportedFriend()) {
    544       InstTy = Ty;
    545     } else {
    546       InstTy = SemaRef.SubstType(Ty, TemplateArgs,
    547                                  D->getLocation(), DeclarationName());
    548     }
    549     if (!InstTy)
    550       return 0;
    551 
    552     FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
    553                                                  D->getFriendLoc(), InstTy);
    554     if (!FD)
    555       return 0;
    556 
    557     FD->setAccess(AS_public);
    558     FD->setUnsupportedFriend(D->isUnsupportedFriend());
    559     Owner->addDecl(FD);
    560     return FD;
    561   }
    562 
    563   NamedDecl *ND = D->getFriendDecl();
    564   assert(ND && "friend decl must be a decl or a type!");
    565 
    566   // All of the Visit implementations for the various potential friend
    567   // declarations have to be carefully written to work for friend
    568   // objects, with the most important detail being that the target
    569   // decl should almost certainly not be placed in Owner.
    570   Decl *NewND = Visit(ND);
    571   if (!NewND) return 0;
    572 
    573   FriendDecl *FD =
    574     FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
    575                        cast<NamedDecl>(NewND), D->getFriendLoc());
    576   FD->setAccess(AS_public);
    577   FD->setUnsupportedFriend(D->isUnsupportedFriend());
    578   Owner->addDecl(FD);
    579   return FD;
    580 }
    581 
    582 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
    583   Expr *AssertExpr = D->getAssertExpr();
    584 
    585   // The expression in a static assertion is a constant expression.
    586   EnterExpressionEvaluationContext Unevaluated(SemaRef,
    587                                                Sema::ConstantEvaluated);
    588 
    589   ExprResult InstantiatedAssertExpr
    590     = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
    591   if (InstantiatedAssertExpr.isInvalid())
    592     return 0;
    593 
    594   return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
    595                                               InstantiatedAssertExpr.get(),
    596                                               D->getMessage(),
    597                                               D->getRParenLoc(),
    598                                               D->isFailed());
    599 }
    600 
    601 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
    602   EnumDecl *PrevDecl = 0;
    603   if (D->getPreviousDecl()) {
    604     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
    605                                                    D->getPreviousDecl(),
    606                                                    TemplateArgs);
    607     if (!Prev) return 0;
    608     PrevDecl = cast<EnumDecl>(Prev);
    609   }
    610 
    611   EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
    612                                     D->getLocation(), D->getIdentifier(),
    613                                     PrevDecl, D->isScoped(),
    614                                     D->isScopedUsingClassTag(), D->isFixed());
    615   if (D->isFixed()) {
    616     if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
    617       // If we have type source information for the underlying type, it means it
    618       // has been explicitly set by the user. Perform substitution on it before
    619       // moving on.
    620       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
    621       TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
    622                                                 DeclarationName());
    623       if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
    624         Enum->setIntegerType(SemaRef.Context.IntTy);
    625       else
    626         Enum->setIntegerTypeSourceInfo(NewTI);
    627     } else {
    628       assert(!D->getIntegerType()->isDependentType()
    629              && "Dependent type without type source info");
    630       Enum->setIntegerType(D->getIntegerType());
    631     }
    632   }
    633 
    634   SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
    635 
    636   Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
    637   Enum->setAccess(D->getAccess());
    638   if (SubstQualifier(D, Enum)) return 0;
    639   Owner->addDecl(Enum);
    640 
    641   EnumDecl *Def = D->getDefinition();
    642   if (Def && Def != D) {
    643     // If this is an out-of-line definition of an enum member template, check
    644     // that the underlying types match in the instantiation of both
    645     // declarations.
    646     if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
    647       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
    648       QualType DefnUnderlying =
    649         SemaRef.SubstType(TI->getType(), TemplateArgs,
    650                           UnderlyingLoc, DeclarationName());
    651       SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
    652                                      DefnUnderlying, Enum);
    653     }
    654   }
    655 
    656   if (D->getDeclContext()->isFunctionOrMethod())
    657     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
    658 
    659   // C++11 [temp.inst]p1: The implicit instantiation of a class template
    660   // specialization causes the implicit instantiation of the declarations, but
    661   // not the definitions of scoped member enumerations.
    662   // FIXME: There appears to be no wording for what happens for an enum defined
    663   // within a block scope, but we treat that much like a member template. Only
    664   // instantiate the definition when visiting the definition in that case, since
    665   // we will visit all redeclarations.
    666   if (!Enum->isScoped() && Def &&
    667       (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
    668     InstantiateEnumDefinition(Enum, Def);
    669 
    670   return Enum;
    671 }
    672 
    673 void TemplateDeclInstantiator::InstantiateEnumDefinition(
    674     EnumDecl *Enum, EnumDecl *Pattern) {
    675   Enum->startDefinition();
    676 
    677   // Update the location to refer to the definition.
    678   Enum->setLocation(Pattern->getLocation());
    679 
    680   SmallVector<Decl*, 4> Enumerators;
    681 
    682   EnumConstantDecl *LastEnumConst = 0;
    683   for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
    684          ECEnd = Pattern->enumerator_end();
    685        EC != ECEnd; ++EC) {
    686     // The specified value for the enumerator.
    687     ExprResult Value = SemaRef.Owned((Expr *)0);
    688     if (Expr *UninstValue = EC->getInitExpr()) {
    689       // The enumerator's value expression is a constant expression.
    690       EnterExpressionEvaluationContext Unevaluated(SemaRef,
    691                                                    Sema::ConstantEvaluated);
    692 
    693       Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
    694     }
    695 
    696     // Drop the initial value and continue.
    697     bool isInvalid = false;
    698     if (Value.isInvalid()) {
    699       Value = SemaRef.Owned((Expr *)0);
    700       isInvalid = true;
    701     }
    702 
    703     EnumConstantDecl *EnumConst
    704       = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
    705                                   EC->getLocation(), EC->getIdentifier(),
    706                                   Value.get());
    707 
    708     if (isInvalid) {
    709       if (EnumConst)
    710         EnumConst->setInvalidDecl();
    711       Enum->setInvalidDecl();
    712     }
    713 
    714     if (EnumConst) {
    715       SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
    716 
    717       EnumConst->setAccess(Enum->getAccess());
    718       Enum->addDecl(EnumConst);
    719       Enumerators.push_back(EnumConst);
    720       LastEnumConst = EnumConst;
    721 
    722       if (Pattern->getDeclContext()->isFunctionOrMethod() &&
    723           !Enum->isScoped()) {
    724         // If the enumeration is within a function or method, record the enum
    725         // constant as a local.
    726         SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
    727       }
    728     }
    729   }
    730 
    731   // FIXME: Fixup LBraceLoc
    732   SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
    733                         Enum->getRBraceLoc(), Enum,
    734                         Enumerators,
    735                         0, 0);
    736 }
    737 
    738 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
    739   llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
    740 }
    741 
    742 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
    743   bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
    744 
    745   // Create a local instantiation scope for this class template, which
    746   // will contain the instantiations of the template parameters.
    747   LocalInstantiationScope Scope(SemaRef);
    748   TemplateParameterList *TempParams = D->getTemplateParameters();
    749   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
    750   if (!InstParams)
    751     return NULL;
    752 
    753   CXXRecordDecl *Pattern = D->getTemplatedDecl();
    754 
    755   // Instantiate the qualifier.  We have to do this first in case
    756   // we're a friend declaration, because if we are then we need to put
    757   // the new declaration in the appropriate context.
    758   NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
    759   if (QualifierLoc) {
    760     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
    761                                                        TemplateArgs);
    762     if (!QualifierLoc)
    763       return 0;
    764   }
    765 
    766   CXXRecordDecl *PrevDecl = 0;
    767   ClassTemplateDecl *PrevClassTemplate = 0;
    768 
    769   if (!isFriend && Pattern->getPreviousDecl()) {
    770     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
    771     if (!Found.empty()) {
    772       PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
    773       if (PrevClassTemplate)
    774         PrevDecl = PrevClassTemplate->getTemplatedDecl();
    775     }
    776   }
    777 
    778   // If this isn't a friend, then it's a member template, in which
    779   // case we just want to build the instantiation in the
    780   // specialization.  If it is a friend, we want to build it in
    781   // the appropriate context.
    782   DeclContext *DC = Owner;
    783   if (isFriend) {
    784     if (QualifierLoc) {
    785       CXXScopeSpec SS;
    786       SS.Adopt(QualifierLoc);
    787       DC = SemaRef.computeDeclContext(SS);
    788       if (!DC) return 0;
    789     } else {
    790       DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
    791                                            Pattern->getDeclContext(),
    792                                            TemplateArgs);
    793     }
    794 
    795     // Look for a previous declaration of the template in the owning
    796     // context.
    797     LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
    798                    Sema::LookupOrdinaryName, Sema::ForRedeclaration);
    799     SemaRef.LookupQualifiedName(R, DC);
    800 
    801     if (R.isSingleResult()) {
    802       PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
    803       if (PrevClassTemplate)
    804         PrevDecl = PrevClassTemplate->getTemplatedDecl();
    805     }
    806 
    807     if (!PrevClassTemplate && QualifierLoc) {
    808       SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
    809         << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
    810         << QualifierLoc.getSourceRange();
    811       return 0;
    812     }
    813 
    814     bool AdoptedPreviousTemplateParams = false;
    815     if (PrevClassTemplate) {
    816       bool Complain = true;
    817 
    818       // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
    819       // template for struct std::tr1::__detail::_Map_base, where the
    820       // template parameters of the friend declaration don't match the
    821       // template parameters of the original declaration. In this one
    822       // case, we don't complain about the ill-formed friend
    823       // declaration.
    824       if (isFriend && Pattern->getIdentifier() &&
    825           Pattern->getIdentifier()->isStr("_Map_base") &&
    826           DC->isNamespace() &&
    827           cast<NamespaceDecl>(DC)->getIdentifier() &&
    828           cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
    829         DeclContext *DCParent = DC->getParent();
    830         if (DCParent->isNamespace() &&
    831             cast<NamespaceDecl>(DCParent)->getIdentifier() &&
    832             cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
    833           DeclContext *DCParent2 = DCParent->getParent();
    834           if (DCParent2->isNamespace() &&
    835               cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
    836               cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
    837               DCParent2->getParent()->isTranslationUnit())
    838             Complain = false;
    839         }
    840       }
    841 
    842       TemplateParameterList *PrevParams
    843         = PrevClassTemplate->getTemplateParameters();
    844 
    845       // Make sure the parameter lists match.
    846       if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
    847                                                   Complain,
    848                                                   Sema::TPL_TemplateMatch)) {
    849         if (Complain)
    850           return 0;
    851 
    852         AdoptedPreviousTemplateParams = true;
    853         InstParams = PrevParams;
    854       }
    855 
    856       // Do some additional validation, then merge default arguments
    857       // from the existing declarations.
    858       if (!AdoptedPreviousTemplateParams &&
    859           SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
    860                                              Sema::TPC_ClassTemplate))
    861         return 0;
    862     }
    863   }
    864 
    865   CXXRecordDecl *RecordInst
    866     = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
    867                             Pattern->getLocStart(), Pattern->getLocation(),
    868                             Pattern->getIdentifier(), PrevDecl,
    869                             /*DelayTypeCreation=*/true);
    870 
    871   if (QualifierLoc)
    872     RecordInst->setQualifierInfo(QualifierLoc);
    873 
    874   ClassTemplateDecl *Inst
    875     = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
    876                                 D->getIdentifier(), InstParams, RecordInst,
    877                                 PrevClassTemplate);
    878   RecordInst->setDescribedClassTemplate(Inst);
    879 
    880   if (isFriend) {
    881     if (PrevClassTemplate)
    882       Inst->setAccess(PrevClassTemplate->getAccess());
    883     else
    884       Inst->setAccess(D->getAccess());
    885 
    886     Inst->setObjectOfFriendDecl();
    887     // TODO: do we want to track the instantiation progeny of this
    888     // friend target decl?
    889   } else {
    890     Inst->setAccess(D->getAccess());
    891     if (!PrevClassTemplate)
    892       Inst->setInstantiatedFromMemberTemplate(D);
    893   }
    894 
    895   // Trigger creation of the type for the instantiation.
    896   SemaRef.Context.getInjectedClassNameType(RecordInst,
    897                                     Inst->getInjectedClassNameSpecialization());
    898 
    899   // Finish handling of friends.
    900   if (isFriend) {
    901     DC->makeDeclVisibleInContext(Inst);
    902     Inst->setLexicalDeclContext(Owner);
    903     RecordInst->setLexicalDeclContext(Owner);
    904     return Inst;
    905   }
    906 
    907   if (D->isOutOfLine()) {
    908     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
    909     RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
    910   }
    911 
    912   Owner->addDecl(Inst);
    913 
    914   if (!PrevClassTemplate) {
    915     // Queue up any out-of-line partial specializations of this member
    916     // class template; the client will force their instantiation once
    917     // the enclosing class has been instantiated.
    918     SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
    919     D->getPartialSpecializations(PartialSpecs);
    920     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
    921       if (PartialSpecs[I]->isOutOfLine())
    922         OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
    923   }
    924 
    925   return Inst;
    926 }
    927 
    928 Decl *
    929 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
    930                                    ClassTemplatePartialSpecializationDecl *D) {
    931   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
    932 
    933   // Lookup the already-instantiated declaration in the instantiation
    934   // of the class template and return that.
    935   DeclContext::lookup_result Found
    936     = Owner->lookup(ClassTemplate->getDeclName());
    937   if (Found.empty())
    938     return 0;
    939 
    940   ClassTemplateDecl *InstClassTemplate
    941     = dyn_cast<ClassTemplateDecl>(Found.front());
    942   if (!InstClassTemplate)
    943     return 0;
    944 
    945   if (ClassTemplatePartialSpecializationDecl *Result
    946         = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
    947     return Result;
    948 
    949   return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
    950 }
    951 
    952 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
    953   assert(D->getTemplatedDecl()->isStaticDataMember() &&
    954          "Only static data member templates are allowed.");
    955   // FIXME: Also only when instantiating a class?
    956 
    957   // Create a local instantiation scope for this variable template, which
    958   // will contain the instantiations of the template parameters.
    959   LocalInstantiationScope Scope(SemaRef);
    960   TemplateParameterList *TempParams = D->getTemplateParameters();
    961   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
    962   if (!InstParams)
    963     return NULL;
    964 
    965   VarDecl *Pattern = D->getTemplatedDecl();
    966   VarTemplateDecl *PrevVarTemplate = 0;
    967 
    968   if (Pattern->getPreviousDecl()) {
    969     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
    970     if (!Found.empty())
    971       PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
    972   }
    973 
    974   // FIXME: This, and ForVarTemplate, is a hack that is probably unnecessary.
    975   // We should use a simplified version of VisitVarDecl.
    976   VarDecl *VarInst = cast_or_null<VarDecl>(VisitVarDecl(Pattern, /*ForVarTemplate=*/true));
    977 
    978   DeclContext *DC = Owner;
    979 
    980   /* FIXME: This should be handled in VisitVarDecl, as used to produce
    981      VarInst above.
    982   // Instantiate the qualifier.
    983   NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
    984   if (QualifierLoc) {
    985     QualifierLoc =
    986         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
    987     if (!QualifierLoc)
    988       return 0;
    989   }
    990 
    991   if (QualifierLoc)
    992     VarInst->setQualifierInfo(QualifierLoc);
    993   */
    994 
    995   VarTemplateDecl *Inst = VarTemplateDecl::Create(
    996       SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
    997       VarInst, PrevVarTemplate);
    998   VarInst->setDescribedVarTemplate(Inst);
    999 
   1000   Inst->setAccess(D->getAccess());
   1001   if (!PrevVarTemplate)
   1002     Inst->setInstantiatedFromMemberTemplate(D);
   1003 
   1004   if (D->isOutOfLine()) {
   1005     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
   1006     VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
   1007   }
   1008 
   1009   Owner->addDecl(Inst);
   1010 
   1011   if (!PrevVarTemplate) {
   1012     // Queue up any out-of-line partial specializations of this member
   1013     // variable template; the client will force their instantiation once
   1014     // the enclosing class has been instantiated.
   1015     SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
   1016     D->getPartialSpecializations(PartialSpecs);
   1017     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
   1018       if (PartialSpecs[I]->isOutOfLine())
   1019         OutOfLineVarPartialSpecs.push_back(
   1020             std::make_pair(Inst, PartialSpecs[I]));
   1021   }
   1022 
   1023   return Inst;
   1024 }
   1025 
   1026 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
   1027     VarTemplatePartialSpecializationDecl *D) {
   1028   assert(D->isStaticDataMember() &&
   1029          "Only static data member templates are allowed.");
   1030   // FIXME: Also only when instantiating a class?
   1031 
   1032   VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
   1033 
   1034   // Lookup the already-instantiated declaration and return that.
   1035   DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
   1036   assert(!Found.empty() && "Instantiation found nothing?");
   1037 
   1038   VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
   1039   assert(InstVarTemplate && "Instantiation did not find a variable template?");
   1040 
   1041   if (VarTemplatePartialSpecializationDecl *Result =
   1042           InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
   1043     return Result;
   1044 
   1045   return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
   1046 }
   1047 
   1048 Decl *
   1049 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
   1050   // Create a local instantiation scope for this function template, which
   1051   // will contain the instantiations of the template parameters and then get
   1052   // merged with the local instantiation scope for the function template
   1053   // itself.
   1054   LocalInstantiationScope Scope(SemaRef);
   1055 
   1056   TemplateParameterList *TempParams = D->getTemplateParameters();
   1057   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
   1058   if (!InstParams)
   1059     return NULL;
   1060 
   1061   FunctionDecl *Instantiated = 0;
   1062   if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
   1063     Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
   1064                                                                  InstParams));
   1065   else
   1066     Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
   1067                                                           D->getTemplatedDecl(),
   1068                                                                 InstParams));
   1069 
   1070   if (!Instantiated)
   1071     return 0;
   1072 
   1073   // Link the instantiated function template declaration to the function
   1074   // template from which it was instantiated.
   1075   FunctionTemplateDecl *InstTemplate
   1076     = Instantiated->getDescribedFunctionTemplate();
   1077   InstTemplate->setAccess(D->getAccess());
   1078   assert(InstTemplate &&
   1079          "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
   1080 
   1081   bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
   1082 
   1083   // Link the instantiation back to the pattern *unless* this is a
   1084   // non-definition friend declaration.
   1085   if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
   1086       !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
   1087     InstTemplate->setInstantiatedFromMemberTemplate(D);
   1088 
   1089   // Make declarations visible in the appropriate context.
   1090   if (!isFriend) {
   1091     Owner->addDecl(InstTemplate);
   1092   } else if (InstTemplate->getDeclContext()->isRecord() &&
   1093              !D->getPreviousDecl()) {
   1094     SemaRef.CheckFriendAccess(InstTemplate);
   1095   }
   1096 
   1097   return InstTemplate;
   1098 }
   1099 
   1100 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
   1101   CXXRecordDecl *PrevDecl = 0;
   1102   if (D->isInjectedClassName())
   1103     PrevDecl = cast<CXXRecordDecl>(Owner);
   1104   else if (D->getPreviousDecl()) {
   1105     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
   1106                                                    D->getPreviousDecl(),
   1107                                                    TemplateArgs);
   1108     if (!Prev) return 0;
   1109     PrevDecl = cast<CXXRecordDecl>(Prev);
   1110   }
   1111 
   1112   CXXRecordDecl *Record
   1113     = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
   1114                             D->getLocStart(), D->getLocation(),
   1115                             D->getIdentifier(), PrevDecl);
   1116 
   1117   // Substitute the nested name specifier, if any.
   1118   if (SubstQualifier(D, Record))
   1119     return 0;
   1120 
   1121   Record->setImplicit(D->isImplicit());
   1122   // FIXME: Check against AS_none is an ugly hack to work around the issue that
   1123   // the tag decls introduced by friend class declarations don't have an access
   1124   // specifier. Remove once this area of the code gets sorted out.
   1125   if (D->getAccess() != AS_none)
   1126     Record->setAccess(D->getAccess());
   1127   if (!D->isInjectedClassName())
   1128     Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
   1129 
   1130   // If the original function was part of a friend declaration,
   1131   // inherit its namespace state.
   1132   if (D->getFriendObjectKind())
   1133     Record->setObjectOfFriendDecl();
   1134 
   1135   // Make sure that anonymous structs and unions are recorded.
   1136   if (D->isAnonymousStructOrUnion()) {
   1137     Record->setAnonymousStructOrUnion(true);
   1138     if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
   1139       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
   1140   }
   1141 
   1142   Owner->addDecl(Record);
   1143   return Record;
   1144 }
   1145 
   1146 /// \brief Adjust the given function type for an instantiation of the
   1147 /// given declaration, to cope with modifications to the function's type that
   1148 /// aren't reflected in the type-source information.
   1149 ///
   1150 /// \param D The declaration we're instantiating.
   1151 /// \param TInfo The already-instantiated type.
   1152 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
   1153                                                    FunctionDecl *D,
   1154                                                    TypeSourceInfo *TInfo) {
   1155   const FunctionProtoType *OrigFunc
   1156     = D->getType()->castAs<FunctionProtoType>();
   1157   const FunctionProtoType *NewFunc
   1158     = TInfo->getType()->castAs<FunctionProtoType>();
   1159   if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
   1160     return TInfo->getType();
   1161 
   1162   FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
   1163   NewEPI.ExtInfo = OrigFunc->getExtInfo();
   1164   return Context.getFunctionType(NewFunc->getResultType(),
   1165                                  NewFunc->getArgTypes(), NewEPI);
   1166 }
   1167 
   1168 /// Normal class members are of more specific types and therefore
   1169 /// don't make it here.  This function serves two purposes:
   1170 ///   1) instantiating function templates
   1171 ///   2) substituting friend declarations
   1172 /// FIXME: preserve function definitions in case #2
   1173 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
   1174                                        TemplateParameterList *TemplateParams) {
   1175   // Check whether there is already a function template specialization for
   1176   // this declaration.
   1177   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
   1178   if (FunctionTemplate && !TemplateParams) {
   1179     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
   1180 
   1181     void *InsertPos = 0;
   1182     FunctionDecl *SpecFunc
   1183       = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
   1184                                              InsertPos);
   1185 
   1186     // If we already have a function template specialization, return it.
   1187     if (SpecFunc)
   1188       return SpecFunc;
   1189   }
   1190 
   1191   bool isFriend;
   1192   if (FunctionTemplate)
   1193     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
   1194   else
   1195     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
   1196 
   1197   bool MergeWithParentScope = (TemplateParams != 0) ||
   1198     Owner->isFunctionOrMethod() ||
   1199     !(isa<Decl>(Owner) &&
   1200       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
   1201   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
   1202 
   1203   SmallVector<ParmVarDecl *, 4> Params;
   1204   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
   1205   if (!TInfo)
   1206     return 0;
   1207   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
   1208 
   1209   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
   1210   if (QualifierLoc) {
   1211     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
   1212                                                        TemplateArgs);
   1213     if (!QualifierLoc)
   1214       return 0;
   1215   }
   1216 
   1217   // If we're instantiating a local function declaration, put the result
   1218   // in the owner;  otherwise we need to find the instantiated context.
   1219   DeclContext *DC;
   1220   if (D->getDeclContext()->isFunctionOrMethod())
   1221     DC = Owner;
   1222   else if (isFriend && QualifierLoc) {
   1223     CXXScopeSpec SS;
   1224     SS.Adopt(QualifierLoc);
   1225     DC = SemaRef.computeDeclContext(SS);
   1226     if (!DC) return 0;
   1227   } else {
   1228     DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
   1229                                          TemplateArgs);
   1230   }
   1231 
   1232   FunctionDecl *Function =
   1233       FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
   1234                            D->getNameInfo(), T, TInfo,
   1235                            D->getCanonicalDecl()->getStorageClass(),
   1236                            D->isInlineSpecified(), D->hasWrittenPrototype(),
   1237                            D->isConstexpr());
   1238   Function->setRangeEnd(D->getSourceRange().getEnd());
   1239 
   1240   if (D->isInlined())
   1241     Function->setImplicitlyInline();
   1242 
   1243   if (QualifierLoc)
   1244     Function->setQualifierInfo(QualifierLoc);
   1245 
   1246   DeclContext *LexicalDC = Owner;
   1247   if (!isFriend && D->isOutOfLine()) {
   1248     assert(D->getDeclContext()->isFileContext());
   1249     LexicalDC = D->getDeclContext();
   1250   }
   1251 
   1252   Function->setLexicalDeclContext(LexicalDC);
   1253 
   1254   // Attach the parameters
   1255   for (unsigned P = 0; P < Params.size(); ++P)
   1256     if (Params[P])
   1257       Params[P]->setOwningFunction(Function);
   1258   Function->setParams(Params);
   1259 
   1260   SourceLocation InstantiateAtPOI;
   1261   if (TemplateParams) {
   1262     // Our resulting instantiation is actually a function template, since we
   1263     // are substituting only the outer template parameters. For example, given
   1264     //
   1265     //   template<typename T>
   1266     //   struct X {
   1267     //     template<typename U> friend void f(T, U);
   1268     //   };
   1269     //
   1270     //   X<int> x;
   1271     //
   1272     // We are instantiating the friend function template "f" within X<int>,
   1273     // which means substituting int for T, but leaving "f" as a friend function
   1274     // template.
   1275     // Build the function template itself.
   1276     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
   1277                                                     Function->getLocation(),
   1278                                                     Function->getDeclName(),
   1279                                                     TemplateParams, Function);
   1280     Function->setDescribedFunctionTemplate(FunctionTemplate);
   1281 
   1282     FunctionTemplate->setLexicalDeclContext(LexicalDC);
   1283 
   1284     if (isFriend && D->isThisDeclarationADefinition()) {
   1285       // TODO: should we remember this connection regardless of whether
   1286       // the friend declaration provided a body?
   1287       FunctionTemplate->setInstantiatedFromMemberTemplate(
   1288                                            D->getDescribedFunctionTemplate());
   1289     }
   1290   } else if (FunctionTemplate) {
   1291     // Record this function template specialization.
   1292     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
   1293     Function->setFunctionTemplateSpecialization(FunctionTemplate,
   1294                             TemplateArgumentList::CreateCopy(SemaRef.Context,
   1295                                                              Innermost.begin(),
   1296                                                              Innermost.size()),
   1297                                                 /*InsertPos=*/0);
   1298   } else if (isFriend) {
   1299     // Note, we need this connection even if the friend doesn't have a body.
   1300     // Its body may exist but not have been attached yet due to deferred
   1301     // parsing.
   1302     // FIXME: It might be cleaner to set this when attaching the body to the
   1303     // friend function declaration, however that would require finding all the
   1304     // instantiations and modifying them.
   1305     Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
   1306   }
   1307 
   1308   if (InitFunctionInstantiation(Function, D))
   1309     Function->setInvalidDecl();
   1310 
   1311   bool isExplicitSpecialization = false;
   1312 
   1313   LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
   1314                         Sema::LookupOrdinaryName, Sema::ForRedeclaration);
   1315 
   1316   if (DependentFunctionTemplateSpecializationInfo *Info
   1317         = D->getDependentSpecializationInfo()) {
   1318     assert(isFriend && "non-friend has dependent specialization info?");
   1319 
   1320     // This needs to be set now for future sanity.
   1321     Function->setObjectOfFriendDecl();
   1322 
   1323     // Instantiate the explicit template arguments.
   1324     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
   1325                                           Info->getRAngleLoc());
   1326     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
   1327                       ExplicitArgs, TemplateArgs))
   1328       return 0;
   1329 
   1330     // Map the candidate templates to their instantiations.
   1331     for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
   1332       Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
   1333                                                 Info->getTemplate(I),
   1334                                                 TemplateArgs);
   1335       if (!Temp) return 0;
   1336 
   1337       Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
   1338     }
   1339 
   1340     if (SemaRef.CheckFunctionTemplateSpecialization(Function,
   1341                                                     &ExplicitArgs,
   1342                                                     Previous))
   1343       Function->setInvalidDecl();
   1344 
   1345     isExplicitSpecialization = true;
   1346 
   1347   } else if (TemplateParams || !FunctionTemplate) {
   1348     // Look only into the namespace where the friend would be declared to
   1349     // find a previous declaration. This is the innermost enclosing namespace,
   1350     // as described in ActOnFriendFunctionDecl.
   1351     SemaRef.LookupQualifiedName(Previous, DC);
   1352 
   1353     // In C++, the previous declaration we find might be a tag type
   1354     // (class or enum). In this case, the new declaration will hide the
   1355     // tag type. Note that this does does not apply if we're declaring a
   1356     // typedef (C++ [dcl.typedef]p4).
   1357     if (Previous.isSingleTagDecl())
   1358       Previous.clear();
   1359   }
   1360 
   1361   SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
   1362                                    isExplicitSpecialization);
   1363 
   1364   NamedDecl *PrincipalDecl = (TemplateParams
   1365                               ? cast<NamedDecl>(FunctionTemplate)
   1366                               : Function);
   1367 
   1368   // If the original function was part of a friend declaration,
   1369   // inherit its namespace state and add it to the owner.
   1370   if (isFriend) {
   1371     PrincipalDecl->setObjectOfFriendDecl();
   1372     DC->makeDeclVisibleInContext(PrincipalDecl);
   1373 
   1374     bool queuedInstantiation = false;
   1375 
   1376     // C++98 [temp.friend]p5: When a function is defined in a friend function
   1377     //   declaration in a class template, the function is defined at each
   1378     //   instantiation of the class template. The function is defined even if it
   1379     //   is never used.
   1380     // C++11 [temp.friend]p4: When a function is defined in a friend function
   1381     //   declaration in a class template, the function is instantiated when the
   1382     //   function is odr-used.
   1383     //
   1384     // If -Wc++98-compat is enabled, we go through the motions of checking for a
   1385     // redefinition, but don't instantiate the function.
   1386     if ((!SemaRef.getLangOpts().CPlusPlus11 ||
   1387          SemaRef.Diags.getDiagnosticLevel(
   1388              diag::warn_cxx98_compat_friend_redefinition,
   1389              Function->getLocation())
   1390            != DiagnosticsEngine::Ignored) &&
   1391         D->isThisDeclarationADefinition()) {
   1392       // Check for a function body.
   1393       const FunctionDecl *Definition = 0;
   1394       if (Function->isDefined(Definition) &&
   1395           Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
   1396         SemaRef.Diag(Function->getLocation(),
   1397                      SemaRef.getLangOpts().CPlusPlus11 ?
   1398                        diag::warn_cxx98_compat_friend_redefinition :
   1399                        diag::err_redefinition) << Function->getDeclName();
   1400         SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
   1401         if (!SemaRef.getLangOpts().CPlusPlus11)
   1402           Function->setInvalidDecl();
   1403       }
   1404       // Check for redefinitions due to other instantiations of this or
   1405       // a similar friend function.
   1406       else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
   1407                                            REnd = Function->redecls_end();
   1408                 R != REnd; ++R) {
   1409         if (*R == Function)
   1410           continue;
   1411         switch (R->getFriendObjectKind()) {
   1412         case Decl::FOK_None:
   1413           if (!SemaRef.getLangOpts().CPlusPlus11 &&
   1414               !queuedInstantiation && R->isUsed(false)) {
   1415             if (MemberSpecializationInfo *MSInfo
   1416                 = Function->getMemberSpecializationInfo()) {
   1417               if (MSInfo->getPointOfInstantiation().isInvalid()) {
   1418                 SourceLocation Loc = R->getLocation(); // FIXME
   1419                 MSInfo->setPointOfInstantiation(Loc);
   1420                 SemaRef.PendingLocalImplicitInstantiations.push_back(
   1421                                                  std::make_pair(Function, Loc));
   1422                 queuedInstantiation = true;
   1423               }
   1424             }
   1425           }
   1426           break;
   1427         default:
   1428           if (const FunctionDecl *RPattern
   1429               = R->getTemplateInstantiationPattern())
   1430             if (RPattern->isDefined(RPattern)) {
   1431               SemaRef.Diag(Function->getLocation(),
   1432                            SemaRef.getLangOpts().CPlusPlus11 ?
   1433                              diag::warn_cxx98_compat_friend_redefinition :
   1434                              diag::err_redefinition)
   1435                 << Function->getDeclName();
   1436               SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
   1437               if (!SemaRef.getLangOpts().CPlusPlus11)
   1438                 Function->setInvalidDecl();
   1439               break;
   1440             }
   1441         }
   1442       }
   1443     }
   1444   }
   1445 
   1446   if (Function->isOverloadedOperator() && !DC->isRecord() &&
   1447       PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
   1448     PrincipalDecl->setNonMemberOperator();
   1449 
   1450   assert(!D->isDefaulted() && "only methods should be defaulted");
   1451   return Function;
   1452 }
   1453 
   1454 Decl *
   1455 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
   1456                                       TemplateParameterList *TemplateParams,
   1457                                       bool IsClassScopeSpecialization) {
   1458   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
   1459   if (FunctionTemplate && !TemplateParams) {
   1460     // We are creating a function template specialization from a function
   1461     // template. Check whether there is already a function template
   1462     // specialization for this particular set of template arguments.
   1463     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
   1464 
   1465     void *InsertPos = 0;
   1466     FunctionDecl *SpecFunc
   1467       = FunctionTemplate->findSpecialization(Innermost.begin(),
   1468                                              Innermost.size(),
   1469                                              InsertPos);
   1470 
   1471     // If we already have a function template specialization, return it.
   1472     if (SpecFunc)
   1473       return SpecFunc;
   1474   }
   1475 
   1476   bool isFriend;
   1477   if (FunctionTemplate)
   1478     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
   1479   else
   1480     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
   1481 
   1482   bool MergeWithParentScope = (TemplateParams != 0) ||
   1483     !(isa<Decl>(Owner) &&
   1484       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
   1485   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
   1486 
   1487   // Instantiate enclosing template arguments for friends.
   1488   SmallVector<TemplateParameterList *, 4> TempParamLists;
   1489   unsigned NumTempParamLists = 0;
   1490   if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
   1491     TempParamLists.set_size(NumTempParamLists);
   1492     for (unsigned I = 0; I != NumTempParamLists; ++I) {
   1493       TemplateParameterList *TempParams = D->getTemplateParameterList(I);
   1494       TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
   1495       if (!InstParams)
   1496         return NULL;
   1497       TempParamLists[I] = InstParams;
   1498     }
   1499   }
   1500 
   1501   SmallVector<ParmVarDecl *, 4> Params;
   1502   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
   1503   if (!TInfo)
   1504     return 0;
   1505   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
   1506 
   1507   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
   1508   if (QualifierLoc) {
   1509     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
   1510                                                  TemplateArgs);
   1511     if (!QualifierLoc)
   1512       return 0;
   1513   }
   1514 
   1515   DeclContext *DC = Owner;
   1516   if (isFriend) {
   1517     if (QualifierLoc) {
   1518       CXXScopeSpec SS;
   1519       SS.Adopt(QualifierLoc);
   1520       DC = SemaRef.computeDeclContext(SS);
   1521 
   1522       if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
   1523         return 0;
   1524     } else {
   1525       DC = SemaRef.FindInstantiatedContext(D->getLocation(),
   1526                                            D->getDeclContext(),
   1527                                            TemplateArgs);
   1528     }
   1529     if (!DC) return 0;
   1530   }
   1531 
   1532   // Build the instantiated method declaration.
   1533   CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
   1534   CXXMethodDecl *Method = 0;
   1535 
   1536   SourceLocation StartLoc = D->getInnerLocStart();
   1537   DeclarationNameInfo NameInfo
   1538     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
   1539   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
   1540     Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
   1541                                         StartLoc, NameInfo, T, TInfo,
   1542                                         Constructor->isExplicit(),
   1543                                         Constructor->isInlineSpecified(),
   1544                                         false, Constructor->isConstexpr());
   1545 
   1546     // Claim that the instantiation of a constructor or constructor template
   1547     // inherits the same constructor that the template does.
   1548     if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
   1549             Constructor->getInheritedConstructor())) {
   1550       // If we're instantiating a specialization of a function template, our
   1551       // "inherited constructor" will actually itself be a function template.
   1552       // Instantiate a declaration of it, too.
   1553       if (FunctionTemplate) {
   1554         assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
   1555                !Inh->getParent()->isDependentContext() &&
   1556                "inheriting constructor template in dependent context?");
   1557         Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
   1558                                          Inh);
   1559         if (Inst)
   1560           return 0;
   1561         Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
   1562         LocalInstantiationScope LocalScope(SemaRef);
   1563 
   1564         // Use the same template arguments that we deduced for the inheriting
   1565         // constructor. There's no way they could be deduced differently.
   1566         MultiLevelTemplateArgumentList InheritedArgs;
   1567         InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
   1568         Inh = cast_or_null<CXXConstructorDecl>(
   1569             SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
   1570         if (!Inh)
   1571           return 0;
   1572       }
   1573       cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
   1574     }
   1575   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
   1576     Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
   1577                                        StartLoc, NameInfo, T, TInfo,
   1578                                        Destructor->isInlineSpecified(),
   1579                                        false);
   1580   } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
   1581     Method = CXXConversionDecl::Create(SemaRef.Context, Record,
   1582                                        StartLoc, NameInfo, T, TInfo,
   1583                                        Conversion->isInlineSpecified(),
   1584                                        Conversion->isExplicit(),
   1585                                        Conversion->isConstexpr(),
   1586                                        Conversion->getLocEnd());
   1587   } else {
   1588     StorageClass SC = D->isStatic() ? SC_Static : SC_None;
   1589     Method = CXXMethodDecl::Create(SemaRef.Context, Record,
   1590                                    StartLoc, NameInfo, T, TInfo,
   1591                                    SC, D->isInlineSpecified(),
   1592                                    D->isConstexpr(), D->getLocEnd());
   1593   }
   1594 
   1595   if (D->isInlined())
   1596     Method->setImplicitlyInline();
   1597 
   1598   if (QualifierLoc)
   1599     Method->setQualifierInfo(QualifierLoc);
   1600 
   1601   if (TemplateParams) {
   1602     // Our resulting instantiation is actually a function template, since we
   1603     // are substituting only the outer template parameters. For example, given
   1604     //
   1605     //   template<typename T>
   1606     //   struct X {
   1607     //     template<typename U> void f(T, U);
   1608     //   };
   1609     //
   1610     //   X<int> x;
   1611     //
   1612     // We are instantiating the member template "f" within X<int>, which means
   1613     // substituting int for T, but leaving "f" as a member function template.
   1614     // Build the function template itself.
   1615     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
   1616                                                     Method->getLocation(),
   1617                                                     Method->getDeclName(),
   1618                                                     TemplateParams, Method);
   1619     if (isFriend) {
   1620       FunctionTemplate->setLexicalDeclContext(Owner);
   1621       FunctionTemplate->setObjectOfFriendDecl();
   1622     } else if (D->isOutOfLine())
   1623       FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
   1624     Method->setDescribedFunctionTemplate(FunctionTemplate);
   1625   } else if (FunctionTemplate) {
   1626     // Record this function template specialization.
   1627     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
   1628     Method->setFunctionTemplateSpecialization(FunctionTemplate,
   1629                          TemplateArgumentList::CreateCopy(SemaRef.Context,
   1630                                                           Innermost.begin(),
   1631                                                           Innermost.size()),
   1632                                               /*InsertPos=*/0);
   1633   } else if (!isFriend) {
   1634     // Record that this is an instantiation of a member function.
   1635     Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
   1636   }
   1637 
   1638   // If we are instantiating a member function defined
   1639   // out-of-line, the instantiation will have the same lexical
   1640   // context (which will be a namespace scope) as the template.
   1641   if (isFriend) {
   1642     if (NumTempParamLists)
   1643       Method->setTemplateParameterListsInfo(SemaRef.Context,
   1644                                             NumTempParamLists,
   1645                                             TempParamLists.data());
   1646 
   1647     Method->setLexicalDeclContext(Owner);
   1648     Method->setObjectOfFriendDecl();
   1649   } else if (D->isOutOfLine())
   1650     Method->setLexicalDeclContext(D->getLexicalDeclContext());
   1651 
   1652   // Attach the parameters
   1653   for (unsigned P = 0; P < Params.size(); ++P)
   1654     Params[P]->setOwningFunction(Method);
   1655   Method->setParams(Params);
   1656 
   1657   if (InitMethodInstantiation(Method, D))
   1658     Method->setInvalidDecl();
   1659 
   1660   LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
   1661                         Sema::ForRedeclaration);
   1662 
   1663   if (!FunctionTemplate || TemplateParams || isFriend) {
   1664     SemaRef.LookupQualifiedName(Previous, Record);
   1665 
   1666     // In C++, the previous declaration we find might be a tag type
   1667     // (class or enum). In this case, the new declaration will hide the
   1668     // tag type. Note that this does does not apply if we're declaring a
   1669     // typedef (C++ [dcl.typedef]p4).
   1670     if (Previous.isSingleTagDecl())
   1671       Previous.clear();
   1672   }
   1673 
   1674   if (!IsClassScopeSpecialization)
   1675     SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
   1676 
   1677   if (D->isPure())
   1678     SemaRef.CheckPureMethod(Method, SourceRange());
   1679 
   1680   // Propagate access.  For a non-friend declaration, the access is
   1681   // whatever we're propagating from.  For a friend, it should be the
   1682   // previous declaration we just found.
   1683   if (isFriend && Method->getPreviousDecl())
   1684     Method->setAccess(Method->getPreviousDecl()->getAccess());
   1685   else
   1686     Method->setAccess(D->getAccess());
   1687   if (FunctionTemplate)
   1688     FunctionTemplate->setAccess(Method->getAccess());
   1689 
   1690   SemaRef.CheckOverrideControl(Method);
   1691 
   1692   // If a function is defined as defaulted or deleted, mark it as such now.
   1693   if (D->isExplicitlyDefaulted())
   1694     SemaRef.SetDeclDefaulted(Method, Method->getLocation());
   1695   if (D->isDeletedAsWritten())
   1696     SemaRef.SetDeclDeleted(Method, Method->getLocation());
   1697 
   1698   // If there's a function template, let our caller handle it.
   1699   if (FunctionTemplate) {
   1700     // do nothing
   1701 
   1702   // Don't hide a (potentially) valid declaration with an invalid one.
   1703   } else if (Method->isInvalidDecl() && !Previous.empty()) {
   1704     // do nothing
   1705 
   1706   // Otherwise, check access to friends and make them visible.
   1707   } else if (isFriend) {
   1708     // We only need to re-check access for methods which we didn't
   1709     // manage to match during parsing.
   1710     if (!D->getPreviousDecl())
   1711       SemaRef.CheckFriendAccess(Method);
   1712 
   1713     Record->makeDeclVisibleInContext(Method);
   1714 
   1715   // Otherwise, add the declaration.  We don't need to do this for
   1716   // class-scope specializations because we'll have matched them with
   1717   // the appropriate template.
   1718   } else if (!IsClassScopeSpecialization) {
   1719     Owner->addDecl(Method);
   1720   }
   1721 
   1722   return Method;
   1723 }
   1724 
   1725 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
   1726   return VisitCXXMethodDecl(D);
   1727 }
   1728 
   1729 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
   1730   return VisitCXXMethodDecl(D);
   1731 }
   1732 
   1733 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
   1734   return VisitCXXMethodDecl(D);
   1735 }
   1736 
   1737 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
   1738   return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
   1739                                   /*ExpectParameterPack=*/ false);
   1740 }
   1741 
   1742 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
   1743                                                     TemplateTypeParmDecl *D) {
   1744   // TODO: don't always clone when decls are refcounted.
   1745   assert(D->getTypeForDecl()->isTemplateTypeParmType());
   1746 
   1747   TemplateTypeParmDecl *Inst =
   1748     TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
   1749                                  D->getLocStart(), D->getLocation(),
   1750                                  D->getDepth() - TemplateArgs.getNumLevels(),
   1751                                  D->getIndex(), D->getIdentifier(),
   1752                                  D->wasDeclaredWithTypename(),
   1753                                  D->isParameterPack());
   1754   Inst->setAccess(AS_public);
   1755 
   1756   if (D->hasDefaultArgument())
   1757     Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
   1758 
   1759   // Introduce this template parameter's instantiation into the instantiation
   1760   // scope.
   1761   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
   1762 
   1763   return Inst;
   1764 }
   1765 
   1766 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
   1767                                                  NonTypeTemplateParmDecl *D) {
   1768   // Substitute into the type of the non-type template parameter.
   1769   TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
   1770   SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
   1771   SmallVector<QualType, 4> ExpandedParameterPackTypes;
   1772   bool IsExpandedParameterPack = false;
   1773   TypeSourceInfo *DI;
   1774   QualType T;
   1775   bool Invalid = false;
   1776 
   1777   if (D->isExpandedParameterPack()) {
   1778     // The non-type template parameter pack is an already-expanded pack
   1779     // expansion of types. Substitute into each of the expanded types.
   1780     ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
   1781     ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
   1782     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
   1783       TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
   1784                                                TemplateArgs,
   1785                                                D->getLocation(),
   1786                                                D->getDeclName());
   1787       if (!NewDI)
   1788         return 0;
   1789 
   1790       ExpandedParameterPackTypesAsWritten.push_back(NewDI);
   1791       QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
   1792                                                               D->getLocation());
   1793       if (NewT.isNull())
   1794         return 0;
   1795       ExpandedParameterPackTypes.push_back(NewT);
   1796     }
   1797 
   1798     IsExpandedParameterPack = true;
   1799     DI = D->getTypeSourceInfo();
   1800     T = DI->getType();
   1801   } else if (D->isPackExpansion()) {
   1802     // The non-type template parameter pack's type is a pack expansion of types.
   1803     // Determine whether we need to expand this parameter pack into separate
   1804     // types.
   1805     PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
   1806     TypeLoc Pattern = Expansion.getPatternLoc();
   1807     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   1808     SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
   1809 
   1810     // Determine whether the set of unexpanded parameter packs can and should
   1811     // be expanded.
   1812     bool Expand = true;
   1813     bool RetainExpansion = false;
   1814     Optional<unsigned> OrigNumExpansions
   1815       = Expansion.getTypePtr()->getNumExpansions();
   1816     Optional<unsigned> NumExpansions = OrigNumExpansions;
   1817     if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
   1818                                                 Pattern.getSourceRange(),
   1819                                                 Unexpanded,
   1820                                                 TemplateArgs,
   1821                                                 Expand, RetainExpansion,
   1822                                                 NumExpansions))
   1823       return 0;
   1824 
   1825     if (Expand) {
   1826       for (unsigned I = 0; I != *NumExpansions; ++I) {
   1827         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
   1828         TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
   1829                                                   D->getLocation(),
   1830                                                   D->getDeclName());
   1831         if (!NewDI)
   1832           return 0;
   1833 
   1834         ExpandedParameterPackTypesAsWritten.push_back(NewDI);
   1835         QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
   1836                                                               NewDI->getType(),
   1837                                                               D->getLocation());
   1838         if (NewT.isNull())
   1839           return 0;
   1840         ExpandedParameterPackTypes.push_back(NewT);
   1841       }
   1842 
   1843       // Note that we have an expanded parameter pack. The "type" of this
   1844       // expanded parameter pack is the original expansion type, but callers
   1845       // will end up using the expanded parameter pack types for type-checking.
   1846       IsExpandedParameterPack = true;
   1847       DI = D->getTypeSourceInfo();
   1848       T = DI->getType();
   1849     } else {
   1850       // We cannot fully expand the pack expansion now, so substitute into the
   1851       // pattern and create a new pack expansion type.
   1852       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
   1853       TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
   1854                                                      D->getLocation(),
   1855                                                      D->getDeclName());
   1856       if (!NewPattern)
   1857         return 0;
   1858 
   1859       DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
   1860                                       NumExpansions);
   1861       if (!DI)
   1862         return 0;
   1863 
   1864       T = DI->getType();
   1865     }
   1866   } else {
   1867     // Simple case: substitution into a parameter that is not a parameter pack.
   1868     DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
   1869                            D->getLocation(), D->getDeclName());
   1870     if (!DI)
   1871       return 0;
   1872 
   1873     // Check that this type is acceptable for a non-type template parameter.
   1874     T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
   1875                                                   D->getLocation());
   1876     if (T.isNull()) {
   1877       T = SemaRef.Context.IntTy;
   1878       Invalid = true;
   1879     }
   1880   }
   1881 
   1882   NonTypeTemplateParmDecl *Param;
   1883   if (IsExpandedParameterPack)
   1884     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
   1885                                             D->getInnerLocStart(),
   1886                                             D->getLocation(),
   1887                                     D->getDepth() - TemplateArgs.getNumLevels(),
   1888                                             D->getPosition(),
   1889                                             D->getIdentifier(), T,
   1890                                             DI,
   1891                                             ExpandedParameterPackTypes.data(),
   1892                                             ExpandedParameterPackTypes.size(),
   1893                                     ExpandedParameterPackTypesAsWritten.data());
   1894   else
   1895     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
   1896                                             D->getInnerLocStart(),
   1897                                             D->getLocation(),
   1898                                     D->getDepth() - TemplateArgs.getNumLevels(),
   1899                                             D->getPosition(),
   1900                                             D->getIdentifier(), T,
   1901                                             D->isParameterPack(), DI);
   1902 
   1903   Param->setAccess(AS_public);
   1904   if (Invalid)
   1905     Param->setInvalidDecl();
   1906 
   1907   Param->setDefaultArgument(D->getDefaultArgument(), false);
   1908 
   1909   // Introduce this template parameter's instantiation into the instantiation
   1910   // scope.
   1911   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
   1912   return Param;
   1913 }
   1914 
   1915 static void collectUnexpandedParameterPacks(
   1916     Sema &S,
   1917     TemplateParameterList *Params,
   1918     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
   1919   for (TemplateParameterList::const_iterator I = Params->begin(),
   1920                                              E = Params->end(); I != E; ++I) {
   1921     if ((*I)->isTemplateParameterPack())
   1922       continue;
   1923     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
   1924       S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
   1925                                         Unexpanded);
   1926     if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
   1927       collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
   1928                                       Unexpanded);
   1929   }
   1930 }
   1931 
   1932 Decl *
   1933 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
   1934                                                   TemplateTemplateParmDecl *D) {
   1935   // Instantiate the template parameter list of the template template parameter.
   1936   TemplateParameterList *TempParams = D->getTemplateParameters();
   1937   TemplateParameterList *InstParams;
   1938   SmallVector<TemplateParameterList*, 8> ExpandedParams;
   1939 
   1940   bool IsExpandedParameterPack = false;
   1941 
   1942   if (D->isExpandedParameterPack()) {
   1943     // The template template parameter pack is an already-expanded pack
   1944     // expansion of template parameters. Substitute into each of the expanded
   1945     // parameters.
   1946     ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
   1947     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
   1948          I != N; ++I) {
   1949       LocalInstantiationScope Scope(SemaRef);
   1950       TemplateParameterList *Expansion =
   1951         SubstTemplateParams(D->getExpansionTemplateParameters(I));
   1952       if (!Expansion)
   1953         return 0;
   1954       ExpandedParams.push_back(Expansion);
   1955     }
   1956 
   1957     IsExpandedParameterPack = true;
   1958     InstParams = TempParams;
   1959   } else if (D->isPackExpansion()) {
   1960     // The template template parameter pack expands to a pack of template
   1961     // template parameters. Determine whether we need to expand this parameter
   1962     // pack into separate parameters.
   1963     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   1964     collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
   1965                                     Unexpanded);
   1966 
   1967     // Determine whether the set of unexpanded parameter packs can and should
   1968     // be expanded.
   1969     bool Expand = true;
   1970     bool RetainExpansion = false;
   1971     Optional<unsigned> NumExpansions;
   1972     if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
   1973                                                 TempParams->getSourceRange(),
   1974                                                 Unexpanded,
   1975                                                 TemplateArgs,
   1976                                                 Expand, RetainExpansion,
   1977                                                 NumExpansions))
   1978       return 0;
   1979 
   1980     if (Expand) {
   1981       for (unsigned I = 0; I != *NumExpansions; ++I) {
   1982         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
   1983         LocalInstantiationScope Scope(SemaRef);
   1984         TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
   1985         if (!Expansion)
   1986           return 0;
   1987         ExpandedParams.push_back(Expansion);
   1988       }
   1989 
   1990       // Note that we have an expanded parameter pack. The "type" of this
   1991       // expanded parameter pack is the original expansion type, but callers
   1992       // will end up using the expanded parameter pack types for type-checking.
   1993       IsExpandedParameterPack = true;
   1994       InstParams = TempParams;
   1995     } else {
   1996       // We cannot fully expand the pack expansion now, so just substitute
   1997       // into the pattern.
   1998       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
   1999 
   2000       LocalInstantiationScope Scope(SemaRef);
   2001       InstParams = SubstTemplateParams(TempParams);
   2002       if (!InstParams)
   2003         return 0;
   2004     }
   2005   } else {
   2006     // Perform the actual substitution of template parameters within a new,
   2007     // local instantiation scope.
   2008     LocalInstantiationScope Scope(SemaRef);
   2009     InstParams = SubstTemplateParams(TempParams);
   2010     if (!InstParams)
   2011       return 0;
   2012   }
   2013 
   2014   // Build the template template parameter.
   2015   TemplateTemplateParmDecl *Param;
   2016   if (IsExpandedParameterPack)
   2017     Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
   2018                                              D->getLocation(),
   2019                                    D->getDepth() - TemplateArgs.getNumLevels(),
   2020                                              D->getPosition(),
   2021                                              D->getIdentifier(), InstParams,
   2022                                              ExpandedParams);
   2023   else
   2024     Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
   2025                                              D->getLocation(),
   2026                                    D->getDepth() - TemplateArgs.getNumLevels(),
   2027                                              D->getPosition(),
   2028                                              D->isParameterPack(),
   2029                                              D->getIdentifier(), InstParams);
   2030   Param->setDefaultArgument(D->getDefaultArgument(), false);
   2031   Param->setAccess(AS_public);
   2032 
   2033   // Introduce this template parameter's instantiation into the instantiation
   2034   // scope.
   2035   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
   2036 
   2037   return Param;
   2038 }
   2039 
   2040 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
   2041   // Using directives are never dependent (and never contain any types or
   2042   // expressions), so they require no explicit instantiation work.
   2043 
   2044   UsingDirectiveDecl *Inst
   2045     = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
   2046                                  D->getNamespaceKeyLocation(),
   2047                                  D->getQualifierLoc(),
   2048                                  D->getIdentLocation(),
   2049                                  D->getNominatedNamespace(),
   2050                                  D->getCommonAncestor());
   2051 
   2052   // Add the using directive to its declaration context
   2053   // only if this is not a function or method.
   2054   if (!Owner->isFunctionOrMethod())
   2055     Owner->addDecl(Inst);
   2056 
   2057   return Inst;
   2058 }
   2059 
   2060 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
   2061 
   2062   // The nested name specifier may be dependent, for example
   2063   //     template <typename T> struct t {
   2064   //       struct s1 { T f1(); };
   2065   //       struct s2 : s1 { using s1::f1; };
   2066   //     };
   2067   //     template struct t<int>;
   2068   // Here, in using s1::f1, s1 refers to t<T>::s1;
   2069   // we need to substitute for t<int>::s1.
   2070   NestedNameSpecifierLoc QualifierLoc
   2071     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
   2072                                           TemplateArgs);
   2073   if (!QualifierLoc)
   2074     return 0;
   2075 
   2076   // The name info is non-dependent, so no transformation
   2077   // is required.
   2078   DeclarationNameInfo NameInfo = D->getNameInfo();
   2079 
   2080   // We only need to do redeclaration lookups if we're in a class
   2081   // scope (in fact, it's not really even possible in non-class
   2082   // scopes).
   2083   bool CheckRedeclaration = Owner->isRecord();
   2084 
   2085   LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
   2086                     Sema::ForRedeclaration);
   2087 
   2088   UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
   2089                                        D->getUsingLoc(),
   2090                                        QualifierLoc,
   2091                                        NameInfo,
   2092                                        D->hasTypename());
   2093 
   2094   CXXScopeSpec SS;
   2095   SS.Adopt(QualifierLoc);
   2096   if (CheckRedeclaration) {
   2097     Prev.setHideTags(false);
   2098     SemaRef.LookupQualifiedName(Prev, Owner);
   2099 
   2100     // Check for invalid redeclarations.
   2101     if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
   2102                                             D->hasTypename(), SS,
   2103                                             D->getLocation(), Prev))
   2104       NewUD->setInvalidDecl();
   2105 
   2106   }
   2107 
   2108   if (!NewUD->isInvalidDecl() &&
   2109       SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS,
   2110                                       D->getLocation()))
   2111     NewUD->setInvalidDecl();
   2112 
   2113   SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
   2114   NewUD->setAccess(D->getAccess());
   2115   Owner->addDecl(NewUD);
   2116 
   2117   // Don't process the shadow decls for an invalid decl.
   2118   if (NewUD->isInvalidDecl())
   2119     return NewUD;
   2120 
   2121   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
   2122     if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
   2123       NewUD->setInvalidDecl();
   2124     return NewUD;
   2125   }
   2126 
   2127   bool isFunctionScope = Owner->isFunctionOrMethod();
   2128 
   2129   // Process the shadow decls.
   2130   for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
   2131          I != E; ++I) {
   2132     UsingShadowDecl *Shadow = *I;
   2133     NamedDecl *InstTarget =
   2134       cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
   2135                                                           Shadow->getLocation(),
   2136                                                         Shadow->getTargetDecl(),
   2137                                                            TemplateArgs));
   2138     if (!InstTarget)
   2139       return 0;
   2140 
   2141     if (CheckRedeclaration &&
   2142         SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
   2143       continue;
   2144 
   2145     UsingShadowDecl *InstShadow
   2146       = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
   2147     SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
   2148 
   2149     if (isFunctionScope)
   2150       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
   2151   }
   2152 
   2153   return NewUD;
   2154 }
   2155 
   2156 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
   2157   // Ignore these;  we handle them in bulk when processing the UsingDecl.
   2158   return 0;
   2159 }
   2160 
   2161 Decl * TemplateDeclInstantiator
   2162     ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
   2163   NestedNameSpecifierLoc QualifierLoc
   2164     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
   2165                                           TemplateArgs);
   2166   if (!QualifierLoc)
   2167     return 0;
   2168 
   2169   CXXScopeSpec SS;
   2170   SS.Adopt(QualifierLoc);
   2171 
   2172   // Since NameInfo refers to a typename, it cannot be a C++ special name.
   2173   // Hence, no transformation is required for it.
   2174   DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
   2175   NamedDecl *UD =
   2176     SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
   2177                                   D->getUsingLoc(), SS, NameInfo, 0,
   2178                                   /*instantiation*/ true,
   2179                                   /*typename*/ true, D->getTypenameLoc());
   2180   if (UD)
   2181     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
   2182 
   2183   return UD;
   2184 }
   2185 
   2186 Decl * TemplateDeclInstantiator
   2187     ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
   2188   NestedNameSpecifierLoc QualifierLoc
   2189       = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
   2190   if (!QualifierLoc)
   2191     return 0;
   2192 
   2193   CXXScopeSpec SS;
   2194   SS.Adopt(QualifierLoc);
   2195 
   2196   DeclarationNameInfo NameInfo
   2197     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
   2198 
   2199   NamedDecl *UD =
   2200     SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
   2201                                   D->getUsingLoc(), SS, NameInfo, 0,
   2202                                   /*instantiation*/ true,
   2203                                   /*typename*/ false, SourceLocation());
   2204   if (UD)
   2205     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
   2206 
   2207   return UD;
   2208 }
   2209 
   2210 
   2211 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
   2212                                      ClassScopeFunctionSpecializationDecl *Decl) {
   2213   CXXMethodDecl *OldFD = Decl->getSpecialization();
   2214   CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
   2215                                                                 0, true));
   2216 
   2217   LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
   2218                         Sema::ForRedeclaration);
   2219 
   2220   TemplateArgumentListInfo TemplateArgs;
   2221   TemplateArgumentListInfo* TemplateArgsPtr = 0;
   2222   if (Decl->hasExplicitTemplateArgs()) {
   2223     TemplateArgs = Decl->templateArgs();
   2224     TemplateArgsPtr = &TemplateArgs;
   2225   }
   2226 
   2227   SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
   2228   if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
   2229                                                   Previous)) {
   2230     NewFD->setInvalidDecl();
   2231     return NewFD;
   2232   }
   2233 
   2234   // Associate the specialization with the pattern.
   2235   FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
   2236   assert(Specialization && "Class scope Specialization is null");
   2237   SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
   2238 
   2239   return NewFD;
   2240 }
   2241 
   2242 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
   2243                                      OMPThreadPrivateDecl *D) {
   2244   SmallVector<Expr *, 5> Vars;
   2245   for (ArrayRef<Expr *>::iterator I = D->varlist_begin(),
   2246                                   E = D->varlist_end();
   2247        I != E; ++I) {
   2248     Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
   2249     assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
   2250     Vars.push_back(Var);
   2251   }
   2252 
   2253   OMPThreadPrivateDecl *TD =
   2254     SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
   2255 
   2256   return TD;
   2257 }
   2258 
   2259 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
   2260   return VisitFunctionDecl(D, 0);
   2261 }
   2262 
   2263 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
   2264   return VisitCXXMethodDecl(D, 0);
   2265 }
   2266 
   2267 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
   2268   llvm_unreachable("There are only CXXRecordDecls in C++");
   2269 }
   2270 
   2271 Decl *
   2272 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
   2273     ClassTemplateSpecializationDecl *D) {
   2274   llvm_unreachable("Only ClassTemplatePartialSpecializationDecls occur"
   2275                    "inside templates");
   2276 }
   2277 
   2278 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
   2279     VarTemplateSpecializationDecl *D) {
   2280 
   2281   TemplateArgumentListInfo VarTemplateArgsInfo;
   2282   VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
   2283   assert(VarTemplate &&
   2284          "A template specialization without specialized template?");
   2285 
   2286   // Substitute the current template arguments.
   2287   const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
   2288   VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
   2289   VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
   2290 
   2291   if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
   2292                     TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
   2293     return 0;
   2294 
   2295   // Check that the template argument list is well-formed for this template.
   2296   SmallVector<TemplateArgument, 4> Converted;
   2297   bool ExpansionIntoFixedList = false;
   2298   if (SemaRef.CheckTemplateArgumentList(
   2299           VarTemplate, VarTemplate->getLocStart(),
   2300           const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
   2301           Converted, &ExpansionIntoFixedList))
   2302     return 0;
   2303 
   2304   // Find the variable template specialization declaration that
   2305   // corresponds to these arguments.
   2306   void *InsertPos = 0;
   2307   if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
   2308           Converted.data(), Converted.size(), InsertPos))
   2309     // If we already have a variable template specialization, return it.
   2310     return VarSpec;
   2311 
   2312   return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
   2313                                             VarTemplateArgsInfo, Converted);
   2314 }
   2315 
   2316 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
   2317     VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
   2318     const TemplateArgumentListInfo &TemplateArgsInfo,
   2319     SmallVectorImpl<TemplateArgument> &Converted) {
   2320 
   2321   // If this is the variable for an anonymous struct or union,
   2322   // instantiate the anonymous struct/union type first.
   2323   if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
   2324     if (RecordTy->getDecl()->isAnonymousStructOrUnion())
   2325       if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
   2326         return 0;
   2327 
   2328   // Do substitution on the type of the declaration
   2329   TypeSourceInfo *DI =
   2330       SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
   2331                         D->getTypeSpecStartLoc(), D->getDeclName());
   2332   if (!DI)
   2333     return 0;
   2334 
   2335   if (DI->getType()->isFunctionType()) {
   2336     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
   2337         << D->isStaticDataMember() << DI->getType();
   2338     return 0;
   2339   }
   2340 
   2341   // Build the instantiated declaration
   2342   VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
   2343       SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
   2344       VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
   2345       Converted.size());
   2346   Var->setTemplateArgsInfo(TemplateArgsInfo);
   2347   VarTemplate->AddSpecialization(Var, InsertPos);
   2348 
   2349   // Substitute the nested name specifier, if any.
   2350   if (SubstQualifier(D, Var))
   2351     return 0;
   2352 
   2353   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
   2354                                      StartingScope);
   2355 
   2356   return Var;
   2357 }
   2358 
   2359 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
   2360   llvm_unreachable("@defs is not supported in Objective-C++");
   2361 }
   2362 
   2363 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
   2364   // FIXME: We need to be able to instantiate FriendTemplateDecls.
   2365   unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
   2366                                                DiagnosticsEngine::Error,
   2367                                                "cannot instantiate %0 yet");
   2368   SemaRef.Diag(D->getLocation(), DiagID)
   2369     << D->getDeclKindName();
   2370 
   2371   return 0;
   2372 }
   2373 
   2374 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
   2375   llvm_unreachable("Unexpected decl");
   2376 }
   2377 
   2378 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
   2379                       const MultiLevelTemplateArgumentList &TemplateArgs) {
   2380   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
   2381   if (D->isInvalidDecl())
   2382     return 0;
   2383 
   2384   return Instantiator.Visit(D);
   2385 }
   2386 
   2387 /// \brief Instantiates a nested template parameter list in the current
   2388 /// instantiation context.
   2389 ///
   2390 /// \param L The parameter list to instantiate
   2391 ///
   2392 /// \returns NULL if there was an error
   2393 TemplateParameterList *
   2394 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
   2395   // Get errors for all the parameters before bailing out.
   2396   bool Invalid = false;
   2397 
   2398   unsigned N = L->size();
   2399   typedef SmallVector<NamedDecl *, 8> ParamVector;
   2400   ParamVector Params;
   2401   Params.reserve(N);
   2402   for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
   2403        PI != PE; ++PI) {
   2404     NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
   2405     Params.push_back(D);
   2406     Invalid = Invalid || !D || D->isInvalidDecl();
   2407   }
   2408 
   2409   // Clean up if we had an error.
   2410   if (Invalid)
   2411     return NULL;
   2412 
   2413   TemplateParameterList *InstL
   2414     = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
   2415                                     L->getLAngleLoc(), &Params.front(), N,
   2416                                     L->getRAngleLoc());
   2417   return InstL;
   2418 }
   2419 
   2420 /// \brief Instantiate the declaration of a class template partial
   2421 /// specialization.
   2422 ///
   2423 /// \param ClassTemplate the (instantiated) class template that is partially
   2424 // specialized by the instantiation of \p PartialSpec.
   2425 ///
   2426 /// \param PartialSpec the (uninstantiated) class template partial
   2427 /// specialization that we are instantiating.
   2428 ///
   2429 /// \returns The instantiated partial specialization, if successful; otherwise,
   2430 /// NULL to indicate an error.
   2431 ClassTemplatePartialSpecializationDecl *
   2432 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
   2433                                             ClassTemplateDecl *ClassTemplate,
   2434                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
   2435   // Create a local instantiation scope for this class template partial
   2436   // specialization, which will contain the instantiations of the template
   2437   // parameters.
   2438   LocalInstantiationScope Scope(SemaRef);
   2439 
   2440   // Substitute into the template parameters of the class template partial
   2441   // specialization.
   2442   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
   2443   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
   2444   if (!InstParams)
   2445     return 0;
   2446 
   2447   // Substitute into the template arguments of the class template partial
   2448   // specialization.
   2449   TemplateArgumentListInfo InstTemplateArgs; // no angle locations
   2450   if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
   2451                     PartialSpec->getNumTemplateArgsAsWritten(),
   2452                     InstTemplateArgs, TemplateArgs))
   2453     return 0;
   2454 
   2455   // Check that the template argument list is well-formed for this
   2456   // class template.
   2457   SmallVector<TemplateArgument, 4> Converted;
   2458   if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
   2459                                         PartialSpec->getLocation(),
   2460                                         InstTemplateArgs,
   2461                                         false,
   2462                                         Converted))
   2463     return 0;
   2464 
   2465   // Figure out where to insert this class template partial specialization
   2466   // in the member template's set of class template partial specializations.
   2467   void *InsertPos = 0;
   2468   ClassTemplateSpecializationDecl *PrevDecl
   2469     = ClassTemplate->findPartialSpecialization(Converted.data(),
   2470                                                Converted.size(), InsertPos);
   2471 
   2472   // Build the canonical type that describes the converted template
   2473   // arguments of the class template partial specialization.
   2474   QualType CanonType
   2475     = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
   2476                                                     Converted.data(),
   2477                                                     Converted.size());
   2478 
   2479   // Build the fully-sugared type for this class template
   2480   // specialization as the user wrote in the specialization
   2481   // itself. This means that we'll pretty-print the type retrieved
   2482   // from the specialization's declaration the way that the user
   2483   // actually wrote the specialization, rather than formatting the
   2484   // name based on the "canonical" representation used to store the
   2485   // template arguments in the specialization.
   2486   TypeSourceInfo *WrittenTy
   2487     = SemaRef.Context.getTemplateSpecializationTypeInfo(
   2488                                                     TemplateName(ClassTemplate),
   2489                                                     PartialSpec->getLocation(),
   2490                                                     InstTemplateArgs,
   2491                                                     CanonType);
   2492 
   2493   if (PrevDecl) {
   2494     // We've already seen a partial specialization with the same template
   2495     // parameters and template arguments. This can happen, for example, when
   2496     // substituting the outer template arguments ends up causing two
   2497     // class template partial specializations of a member class template
   2498     // to have identical forms, e.g.,
   2499     //
   2500     //   template<typename T, typename U>
   2501     //   struct Outer {
   2502     //     template<typename X, typename Y> struct Inner;
   2503     //     template<typename Y> struct Inner<T, Y>;
   2504     //     template<typename Y> struct Inner<U, Y>;
   2505     //   };
   2506     //
   2507     //   Outer<int, int> outer; // error: the partial specializations of Inner
   2508     //                          // have the same signature.
   2509     SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
   2510       << WrittenTy->getType();
   2511     SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
   2512       << SemaRef.Context.getTypeDeclType(PrevDecl);
   2513     return 0;
   2514   }
   2515 
   2516 
   2517   // Create the class template partial specialization declaration.
   2518   ClassTemplatePartialSpecializationDecl *InstPartialSpec
   2519     = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
   2520                                                      PartialSpec->getTagKind(),
   2521                                                      Owner,
   2522                                                      PartialSpec->getLocStart(),
   2523                                                      PartialSpec->getLocation(),
   2524                                                      InstParams,
   2525                                                      ClassTemplate,
   2526                                                      Converted.data(),
   2527                                                      Converted.size(),
   2528                                                      InstTemplateArgs,
   2529                                                      CanonType,
   2530                                                      0,
   2531                              ClassTemplate->getNextPartialSpecSequenceNumber());
   2532   // Substitute the nested name specifier, if any.
   2533   if (SubstQualifier(PartialSpec, InstPartialSpec))
   2534     return 0;
   2535 
   2536   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
   2537   InstPartialSpec->setTypeAsWritten(WrittenTy);
   2538 
   2539   // Add this partial specialization to the set of class template partial
   2540   // specializations.
   2541   ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
   2542   return InstPartialSpec;
   2543 }
   2544 
   2545 /// \brief Instantiate the declaration of a variable template partial
   2546 /// specialization.
   2547 ///
   2548 /// \param VarTemplate the (instantiated) variable template that is partially
   2549 /// specialized by the instantiation of \p PartialSpec.
   2550 ///
   2551 /// \param PartialSpec the (uninstantiated) variable template partial
   2552 /// specialization that we are instantiating.
   2553 ///
   2554 /// \returns The instantiated partial specialization, if successful; otherwise,
   2555 /// NULL to indicate an error.
   2556 VarTemplatePartialSpecializationDecl *
   2557 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
   2558     VarTemplateDecl *VarTemplate,
   2559     VarTemplatePartialSpecializationDecl *PartialSpec) {
   2560   // Create a local instantiation scope for this variable template partial
   2561   // specialization, which will contain the instantiations of the template
   2562   // parameters.
   2563   LocalInstantiationScope Scope(SemaRef);
   2564 
   2565   // Substitute into the template parameters of the variable template partial
   2566   // specialization.
   2567   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
   2568   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
   2569   if (!InstParams)
   2570     return 0;
   2571 
   2572   // Substitute into the template arguments of the variable template partial
   2573   // specialization.
   2574   TemplateArgumentListInfo InstTemplateArgs; // no angle locations
   2575   if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
   2576                     PartialSpec->getNumTemplateArgsAsWritten(),
   2577                     InstTemplateArgs, TemplateArgs))
   2578     return 0;
   2579 
   2580   // Check that the template argument list is well-formed for this
   2581   // class template.
   2582   SmallVector<TemplateArgument, 4> Converted;
   2583   if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
   2584                                         InstTemplateArgs, false, Converted))
   2585     return 0;
   2586 
   2587   // Figure out where to insert this variable template partial specialization
   2588   // in the member template's set of variable template partial specializations.
   2589   void *InsertPos = 0;
   2590   VarTemplateSpecializationDecl *PrevDecl =
   2591       VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
   2592                                              InsertPos);
   2593 
   2594   // Build the canonical type that describes the converted template
   2595   // arguments of the variable template partial specialization.
   2596   QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
   2597       TemplateName(VarTemplate), Converted.data(), Converted.size());
   2598 
   2599   // Build the fully-sugared type for this variable template
   2600   // specialization as the user wrote in the specialization
   2601   // itself. This means that we'll pretty-print the type retrieved
   2602   // from the specialization's declaration the way that the user
   2603   // actually wrote the specialization, rather than formatting the
   2604   // name based on the "canonical" representation used to store the
   2605   // template arguments in the specialization.
   2606   TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
   2607       TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
   2608       CanonType);
   2609 
   2610   if (PrevDecl) {
   2611     // We've already seen a partial specialization with the same template
   2612     // parameters and template arguments. This can happen, for example, when
   2613     // substituting the outer template arguments ends up causing two
   2614     // variable template partial specializations of a member variable template
   2615     // to have identical forms, e.g.,
   2616     //
   2617     //   template<typename T, typename U>
   2618     //   struct Outer {
   2619     //     template<typename X, typename Y> pair<X,Y> p;
   2620     //     template<typename Y> pair<T, Y> p;
   2621     //     template<typename Y> pair<U, Y> p;
   2622     //   };
   2623     //
   2624     //   Outer<int, int> outer; // error: the partial specializations of Inner
   2625     //                          // have the same signature.
   2626     SemaRef.Diag(PartialSpec->getLocation(),
   2627                  diag::err_var_partial_spec_redeclared)
   2628         << WrittenTy->getType();
   2629     SemaRef.Diag(PrevDecl->getLocation(),
   2630                  diag::note_var_prev_partial_spec_here);
   2631     return 0;
   2632   }
   2633 
   2634   // Do substitution on the type of the declaration
   2635   TypeSourceInfo *DI = SemaRef.SubstType(
   2636       PartialSpec->getTypeSourceInfo(), TemplateArgs,
   2637       PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
   2638   if (!DI)
   2639     return 0;
   2640 
   2641   if (DI->getType()->isFunctionType()) {
   2642     SemaRef.Diag(PartialSpec->getLocation(),
   2643                  diag::err_variable_instantiates_to_function)
   2644         << PartialSpec->isStaticDataMember() << DI->getType();
   2645     return 0;
   2646   }
   2647 
   2648   // Create the variable template partial specialization declaration.
   2649   VarTemplatePartialSpecializationDecl *InstPartialSpec =
   2650       VarTemplatePartialSpecializationDecl::Create(
   2651           SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
   2652           PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
   2653           DI, PartialSpec->getStorageClass(), Converted.data(),
   2654           Converted.size(), InstTemplateArgs,
   2655           VarTemplate->getNextPartialSpecSequenceNumber());
   2656 
   2657   // Substitute the nested name specifier, if any.
   2658   if (SubstQualifier(PartialSpec, InstPartialSpec))
   2659     return 0;
   2660 
   2661   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
   2662   InstPartialSpec->setTypeAsWritten(WrittenTy);
   2663 
   2664   InstPartialSpec->setAccess(PartialSpec->getAccess());
   2665   // FIXME: How much of BuildVariableInstantiation() should go in here?
   2666 
   2667   // Add this partial specialization to the set of variable template partial
   2668   // specializations. The instantiation of the initializer is not necessary.
   2669   VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
   2670   return InstPartialSpec;
   2671 }
   2672 
   2673 TypeSourceInfo*
   2674 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
   2675                               SmallVectorImpl<ParmVarDecl *> &Params) {
   2676   TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
   2677   assert(OldTInfo && "substituting function without type source info");
   2678   assert(Params.empty() && "parameter vector is non-empty at start");
   2679 
   2680   CXXRecordDecl *ThisContext = 0;
   2681   unsigned ThisTypeQuals = 0;
   2682   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
   2683     ThisContext = cast<CXXRecordDecl>(Owner);
   2684     ThisTypeQuals = Method->getTypeQualifiers();
   2685   }
   2686 
   2687   TypeSourceInfo *NewTInfo
   2688     = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
   2689                                     D->getTypeSpecStartLoc(),
   2690                                     D->getDeclName(),
   2691                                     ThisContext, ThisTypeQuals);
   2692   if (!NewTInfo)
   2693     return 0;
   2694 
   2695   TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
   2696   if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
   2697     if (NewTInfo != OldTInfo) {
   2698       // Get parameters from the new type info.
   2699       TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
   2700       FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
   2701       unsigned NewIdx = 0;
   2702       for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
   2703            OldIdx != NumOldParams; ++OldIdx) {
   2704         ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
   2705         LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
   2706 
   2707         Optional<unsigned> NumArgumentsInExpansion;
   2708         if (OldParam->isParameterPack())
   2709           NumArgumentsInExpansion =
   2710               SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
   2711                                                  TemplateArgs);
   2712         if (!NumArgumentsInExpansion) {
   2713           // Simple case: normal parameter, or a parameter pack that's
   2714           // instantiated to a (still-dependent) parameter pack.
   2715           ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
   2716           Params.push_back(NewParam);
   2717           Scope->InstantiatedLocal(OldParam, NewParam);
   2718         } else {
   2719           // Parameter pack expansion: make the instantiation an argument pack.
   2720           Scope->MakeInstantiatedLocalArgPack(OldParam);
   2721           for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
   2722             ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
   2723             Params.push_back(NewParam);
   2724             Scope->InstantiatedLocalPackArg(OldParam, NewParam);
   2725           }
   2726         }
   2727       }
   2728     } else {
   2729       // The function type itself was not dependent and therefore no
   2730       // substitution occurred. However, we still need to instantiate
   2731       // the function parameters themselves.
   2732       const FunctionProtoType *OldProto =
   2733           cast<FunctionProtoType>(OldProtoLoc.getType());
   2734       for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
   2735         ParmVarDecl *OldParam = OldProtoLoc.getArg(i);
   2736         if (!OldParam) {
   2737           Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
   2738               D, D->getLocation(), OldProto->getArgType(i)));
   2739           continue;
   2740         }
   2741 
   2742         ParmVarDecl *Parm =
   2743             cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
   2744         if (!Parm)
   2745           return 0;
   2746         Params.push_back(Parm);
   2747       }
   2748     }
   2749   } else {
   2750     // If the type of this function, after ignoring parentheses, is not
   2751     // *directly* a function type, then we're instantiating a function that
   2752     // was declared via a typedef or with attributes, e.g.,
   2753     //
   2754     //   typedef int functype(int, int);
   2755     //   functype func;
   2756     //   int __cdecl meth(int, int);
   2757     //
   2758     // In this case, we'll just go instantiate the ParmVarDecls that we
   2759     // synthesized in the method declaration.
   2760     SmallVector<QualType, 4> ParamTypes;
   2761     if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
   2762                                D->getNumParams(), TemplateArgs, ParamTypes,
   2763                                &Params))
   2764       return 0;
   2765   }
   2766 
   2767   return NewTInfo;
   2768 }
   2769 
   2770 /// Introduce the instantiated function parameters into the local
   2771 /// instantiation scope, and set the parameter names to those used
   2772 /// in the template.
   2773 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
   2774                                              const FunctionDecl *PatternDecl,
   2775                                              LocalInstantiationScope &Scope,
   2776                            const MultiLevelTemplateArgumentList &TemplateArgs) {
   2777   unsigned FParamIdx = 0;
   2778   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
   2779     const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
   2780     if (!PatternParam->isParameterPack()) {
   2781       // Simple case: not a parameter pack.
   2782       assert(FParamIdx < Function->getNumParams());
   2783       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
   2784       FunctionParam->setDeclName(PatternParam->getDeclName());
   2785       Scope.InstantiatedLocal(PatternParam, FunctionParam);
   2786       ++FParamIdx;
   2787       continue;
   2788     }
   2789 
   2790     // Expand the parameter pack.
   2791     Scope.MakeInstantiatedLocalArgPack(PatternParam);
   2792     Optional<unsigned> NumArgumentsInExpansion
   2793       = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
   2794     assert(NumArgumentsInExpansion &&
   2795            "should only be called when all template arguments are known");
   2796     for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
   2797       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
   2798       FunctionParam->setDeclName(PatternParam->getDeclName());
   2799       Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
   2800       ++FParamIdx;
   2801     }
   2802   }
   2803 }
   2804 
   2805 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
   2806                                      const FunctionProtoType *Proto,
   2807                            const MultiLevelTemplateArgumentList &TemplateArgs) {
   2808   assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
   2809 
   2810   // C++11 [expr.prim.general]p3:
   2811   //   If a declaration declares a member function or member function
   2812   //   template of a class X, the expression this is a prvalue of type
   2813   //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
   2814   //   and the end of the function-definition, member-declarator, or
   2815   //   declarator.
   2816   CXXRecordDecl *ThisContext = 0;
   2817   unsigned ThisTypeQuals = 0;
   2818   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
   2819     ThisContext = Method->getParent();
   2820     ThisTypeQuals = Method->getTypeQualifiers();
   2821   }
   2822   Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
   2823                                    SemaRef.getLangOpts().CPlusPlus11);
   2824 
   2825   // The function has an exception specification or a "noreturn"
   2826   // attribute. Substitute into each of the exception types.
   2827   SmallVector<QualType, 4> Exceptions;
   2828   for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
   2829     // FIXME: Poor location information!
   2830     if (const PackExpansionType *PackExpansion
   2831           = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
   2832       // We have a pack expansion. Instantiate it.
   2833       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   2834       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
   2835                                               Unexpanded);
   2836       assert(!Unexpanded.empty() &&
   2837              "Pack expansion without parameter packs?");
   2838 
   2839       bool Expand = false;
   2840       bool RetainExpansion = false;
   2841       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
   2842       if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
   2843                                                   SourceRange(),
   2844                                                   Unexpanded,
   2845                                                   TemplateArgs,
   2846                                                   Expand,
   2847                                                   RetainExpansion,
   2848                                                   NumExpansions))
   2849         break;
   2850 
   2851       if (!Expand) {
   2852         // We can't expand this pack expansion into separate arguments yet;
   2853         // just substitute into the pattern and create a new pack expansion
   2854         // type.
   2855         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
   2856         QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
   2857                                        TemplateArgs,
   2858                                      New->getLocation(), New->getDeclName());
   2859         if (T.isNull())
   2860           break;
   2861 
   2862         T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
   2863         Exceptions.push_back(T);
   2864         continue;
   2865       }
   2866 
   2867       // Substitute into the pack expansion pattern for each template
   2868       bool Invalid = false;
   2869       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
   2870         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
   2871 
   2872         QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
   2873                                        TemplateArgs,
   2874                                      New->getLocation(), New->getDeclName());
   2875         if (T.isNull()) {
   2876           Invalid = true;
   2877           break;
   2878         }
   2879 
   2880         Exceptions.push_back(T);
   2881       }
   2882 
   2883       if (Invalid)
   2884         break;
   2885 
   2886       continue;
   2887     }
   2888 
   2889     QualType T
   2890       = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
   2891                           New->getLocation(), New->getDeclName());
   2892     if (T.isNull() ||
   2893         SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
   2894       continue;
   2895 
   2896     Exceptions.push_back(T);
   2897   }
   2898   Expr *NoexceptExpr = 0;
   2899   if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
   2900     EnterExpressionEvaluationContext Unevaluated(SemaRef,
   2901                                                  Sema::ConstantEvaluated);
   2902     ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
   2903     if (E.isUsable())
   2904       E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
   2905 
   2906     if (E.isUsable()) {
   2907       NoexceptExpr = E.take();
   2908       if (!NoexceptExpr->isTypeDependent() &&
   2909           !NoexceptExpr->isValueDependent())
   2910         NoexceptExpr
   2911           = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
   2912               0, diag::err_noexcept_needs_constant_expression,
   2913               /*AllowFold*/ false).take();
   2914     }
   2915   }
   2916 
   2917   // Rebuild the function type
   2918   const FunctionProtoType *NewProto
   2919     = New->getType()->getAs<FunctionProtoType>();
   2920   assert(NewProto && "Template instantiation without function prototype?");
   2921 
   2922   FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
   2923   EPI.ExceptionSpecType = Proto->getExceptionSpecType();
   2924   EPI.NumExceptions = Exceptions.size();
   2925   EPI.Exceptions = Exceptions.data();
   2926   EPI.NoexceptExpr = NoexceptExpr;
   2927 
   2928   New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
   2929                                                NewProto->getArgTypes(), EPI));
   2930 }
   2931 
   2932 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
   2933                                     FunctionDecl *Decl) {
   2934   const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
   2935   if (Proto->getExceptionSpecType() != EST_Uninstantiated)
   2936     return;
   2937 
   2938   InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
   2939                              InstantiatingTemplate::ExceptionSpecification());
   2940   if (Inst) {
   2941     // We hit the instantiation depth limit. Clear the exception specification
   2942     // so that our callers don't have to cope with EST_Uninstantiated.
   2943     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
   2944     EPI.ExceptionSpecType = EST_None;
   2945     Decl->setType(Context.getFunctionType(Proto->getResultType(),
   2946                                           Proto->getArgTypes(), EPI));
   2947     return;
   2948   }
   2949 
   2950   // Enter the scope of this instantiation. We don't use
   2951   // PushDeclContext because we don't have a scope.
   2952   Sema::ContextRAII savedContext(*this, Decl);
   2953   LocalInstantiationScope Scope(*this);
   2954 
   2955   MultiLevelTemplateArgumentList TemplateArgs =
   2956     getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
   2957 
   2958   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
   2959   addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
   2960 
   2961   ::InstantiateExceptionSpec(*this, Decl,
   2962                              Template->getType()->castAs<FunctionProtoType>(),
   2963                              TemplateArgs);
   2964 }
   2965 
   2966 /// \brief Initializes the common fields of an instantiation function
   2967 /// declaration (New) from the corresponding fields of its template (Tmpl).
   2968 ///
   2969 /// \returns true if there was an error
   2970 bool
   2971 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
   2972                                                     FunctionDecl *Tmpl) {
   2973   if (Tmpl->isDeleted())
   2974     New->setDeletedAsWritten();
   2975 
   2976   // If we are performing substituting explicitly-specified template arguments
   2977   // or deduced template arguments into a function template and we reach this
   2978   // point, we are now past the point where SFINAE applies and have committed
   2979   // to keeping the new function template specialization. We therefore
   2980   // convert the active template instantiation for the function template
   2981   // into a template instantiation for this specific function template
   2982   // specialization, which is not a SFINAE context, so that we diagnose any
   2983   // further errors in the declaration itself.
   2984   typedef Sema::ActiveTemplateInstantiation ActiveInstType;
   2985   ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
   2986   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
   2987       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
   2988     if (FunctionTemplateDecl *FunTmpl
   2989           = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
   2990       assert(FunTmpl->getTemplatedDecl() == Tmpl &&
   2991              "Deduction from the wrong function template?");
   2992       (void) FunTmpl;
   2993       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
   2994       ActiveInst.Entity = New;
   2995     }
   2996   }
   2997 
   2998   const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
   2999   assert(Proto && "Function template without prototype?");
   3000 
   3001   if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
   3002     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
   3003 
   3004     // DR1330: In C++11, defer instantiation of a non-trivial
   3005     // exception specification.
   3006     if (SemaRef.getLangOpts().CPlusPlus11 &&
   3007         EPI.ExceptionSpecType != EST_None &&
   3008         EPI.ExceptionSpecType != EST_DynamicNone &&
   3009         EPI.ExceptionSpecType != EST_BasicNoexcept) {
   3010       FunctionDecl *ExceptionSpecTemplate = Tmpl;
   3011       if (EPI.ExceptionSpecType == EST_Uninstantiated)
   3012         ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
   3013       ExceptionSpecificationType NewEST = EST_Uninstantiated;
   3014       if (EPI.ExceptionSpecType == EST_Unevaluated)
   3015         NewEST = EST_Unevaluated;
   3016 
   3017       // Mark the function has having an uninstantiated exception specification.
   3018       const FunctionProtoType *NewProto
   3019         = New->getType()->getAs<FunctionProtoType>();
   3020       assert(NewProto && "Template instantiation without function prototype?");
   3021       EPI = NewProto->getExtProtoInfo();
   3022       EPI.ExceptionSpecType = NewEST;
   3023       EPI.ExceptionSpecDecl = New;
   3024       EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
   3025       New->setType(SemaRef.Context.getFunctionType(
   3026           NewProto->getResultType(), NewProto->getArgTypes(), EPI));
   3027     } else {
   3028       ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
   3029     }
   3030   }
   3031 
   3032   // Get the definition. Leaves the variable unchanged if undefined.
   3033   const FunctionDecl *Definition = Tmpl;
   3034   Tmpl->isDefined(Definition);
   3035 
   3036   SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
   3037                            LateAttrs, StartingScope);
   3038 
   3039   return false;
   3040 }
   3041 
   3042 /// \brief Initializes common fields of an instantiated method
   3043 /// declaration (New) from the corresponding fields of its template
   3044 /// (Tmpl).
   3045 ///
   3046 /// \returns true if there was an error
   3047 bool
   3048 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
   3049                                                   CXXMethodDecl *Tmpl) {
   3050   if (InitFunctionInstantiation(New, Tmpl))
   3051     return true;
   3052 
   3053   New->setAccess(Tmpl->getAccess());
   3054   if (Tmpl->isVirtualAsWritten())
   3055     New->setVirtualAsWritten(true);
   3056 
   3057   // FIXME: New needs a pointer to Tmpl
   3058   return false;
   3059 }
   3060 
   3061 /// \brief Instantiate the definition of the given function from its
   3062 /// template.
   3063 ///
   3064 /// \param PointOfInstantiation the point at which the instantiation was
   3065 /// required. Note that this is not precisely a "point of instantiation"
   3066 /// for the function, but it's close.
   3067 ///
   3068 /// \param Function the already-instantiated declaration of a
   3069 /// function template specialization or member function of a class template
   3070 /// specialization.
   3071 ///
   3072 /// \param Recursive if true, recursively instantiates any functions that
   3073 /// are required by this instantiation.
   3074 ///
   3075 /// \param DefinitionRequired if true, then we are performing an explicit
   3076 /// instantiation where the body of the function is required. Complain if
   3077 /// there is no such body.
   3078 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
   3079                                          FunctionDecl *Function,
   3080                                          bool Recursive,
   3081                                          bool DefinitionRequired) {
   3082   if (Function->isInvalidDecl() || Function->isDefined())
   3083     return;
   3084 
   3085   // Never instantiate an explicit specialization except if it is a class scope
   3086   // explicit specialization.
   3087   if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
   3088       !Function->getClassScopeSpecializationPattern())
   3089     return;
   3090 
   3091   // Find the function body that we'll be substituting.
   3092   const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
   3093   assert(PatternDecl && "instantiating a non-template");
   3094 
   3095   Stmt *Pattern = PatternDecl->getBody(PatternDecl);
   3096   assert(PatternDecl && "template definition is not a template");
   3097   if (!Pattern) {
   3098     // Try to find a defaulted definition
   3099     PatternDecl->isDefined(PatternDecl);
   3100   }
   3101   assert(PatternDecl && "template definition is not a template");
   3102 
   3103   // Postpone late parsed template instantiations.
   3104   if (PatternDecl->isLateTemplateParsed() &&
   3105       !LateTemplateParser) {
   3106     PendingInstantiations.push_back(
   3107       std::make_pair(Function, PointOfInstantiation));
   3108     return;
   3109   }
   3110 
   3111   // Call the LateTemplateParser callback if there a need to late parse
   3112   // a templated function definition.
   3113   if (!Pattern && PatternDecl->isLateTemplateParsed() &&
   3114       LateTemplateParser) {
   3115     LateTemplateParser(OpaqueParser, PatternDecl);
   3116     Pattern = PatternDecl->getBody(PatternDecl);
   3117   }
   3118 
   3119   if (!Pattern && !PatternDecl->isDefaulted()) {
   3120     if (DefinitionRequired) {
   3121       if (Function->getPrimaryTemplate())
   3122         Diag(PointOfInstantiation,
   3123              diag::err_explicit_instantiation_undefined_func_template)
   3124           << Function->getPrimaryTemplate();
   3125       else
   3126         Diag(PointOfInstantiation,
   3127              diag::err_explicit_instantiation_undefined_member)
   3128           << 1 << Function->getDeclName() << Function->getDeclContext();
   3129 
   3130       if (PatternDecl)
   3131         Diag(PatternDecl->getLocation(),
   3132              diag::note_explicit_instantiation_here);
   3133       Function->setInvalidDecl();
   3134     } else if (Function->getTemplateSpecializationKind()
   3135                  == TSK_ExplicitInstantiationDefinition) {
   3136       PendingInstantiations.push_back(
   3137         std::make_pair(Function, PointOfInstantiation));
   3138     }
   3139 
   3140     return;
   3141   }
   3142 
   3143   // C++1y [temp.explicit]p10:
   3144   //   Except for inline functions, declarations with types deduced from their
   3145   //   initializer or return value, and class template specializations, other
   3146   //   explicit instantiation declarations have the effect of suppressing the
   3147   //   implicit instantiation of the entity to which they refer.
   3148   if (Function->getTemplateSpecializationKind()
   3149         == TSK_ExplicitInstantiationDeclaration &&
   3150       !PatternDecl->isInlined() &&
   3151       !PatternDecl->getResultType()->isUndeducedType())
   3152     return;
   3153 
   3154   if (PatternDecl->isInlined())
   3155     Function->setImplicitlyInline();
   3156 
   3157   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
   3158   if (Inst)
   3159     return;
   3160 
   3161   // Copy the inner loc start from the pattern.
   3162   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
   3163 
   3164   // If we're performing recursive template instantiation, create our own
   3165   // queue of pending implicit instantiations that we will instantiate later,
   3166   // while we're still within our own instantiation context.
   3167   SmallVector<VTableUse, 16> SavedVTableUses;
   3168   std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
   3169   std::deque<PendingImplicitInstantiation>
   3170                               SavedPendingLocalImplicitInstantiations;
   3171   SavedPendingLocalImplicitInstantiations.swap(
   3172                                   PendingLocalImplicitInstantiations);
   3173   if (Recursive) {
   3174     VTableUses.swap(SavedVTableUses);
   3175     PendingInstantiations.swap(SavedPendingInstantiations);
   3176   }
   3177 
   3178   EnterExpressionEvaluationContext EvalContext(*this,
   3179                                                Sema::PotentiallyEvaluated);
   3180 
   3181   // Introduce a new scope where local variable instantiations will be
   3182   // recorded, unless we're actually a member function within a local
   3183   // class, in which case we need to merge our results with the parent
   3184   // scope (of the enclosing function).
   3185   bool MergeWithParentScope = false;
   3186   if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
   3187     MergeWithParentScope = Rec->isLocalClass();
   3188 
   3189   LocalInstantiationScope Scope(*this, MergeWithParentScope);
   3190 
   3191   if (PatternDecl->isDefaulted())
   3192     SetDeclDefaulted(Function, PatternDecl->getLocation());
   3193   else {
   3194     ActOnStartOfFunctionDef(0, Function);
   3195 
   3196     // Enter the scope of this instantiation. We don't use
   3197     // PushDeclContext because we don't have a scope.
   3198     Sema::ContextRAII savedContext(*this, Function);
   3199 
   3200     MultiLevelTemplateArgumentList TemplateArgs =
   3201       getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
   3202 
   3203     addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
   3204                                      TemplateArgs);
   3205 
   3206     // If this is a constructor, instantiate the member initializers.
   3207     if (const CXXConstructorDecl *Ctor =
   3208           dyn_cast<CXXConstructorDecl>(PatternDecl)) {
   3209       InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
   3210                                  TemplateArgs);
   3211     }
   3212 
   3213     // Instantiate the function body.
   3214     StmtResult Body = SubstStmt(Pattern, TemplateArgs);
   3215 
   3216     if (Body.isInvalid())
   3217       Function->setInvalidDecl();
   3218 
   3219     ActOnFinishFunctionBody(Function, Body.get(),
   3220                             /*IsInstantiation=*/true);
   3221 
   3222     PerformDependentDiagnostics(PatternDecl, TemplateArgs);
   3223 
   3224     savedContext.pop();
   3225   }
   3226 
   3227   DeclGroupRef DG(Function);
   3228   Consumer.HandleTopLevelDecl(DG);
   3229 
   3230   // This class may have local implicit instantiations that need to be
   3231   // instantiation within this scope.
   3232   PerformPendingInstantiations(/*LocalOnly=*/true);
   3233   Scope.Exit();
   3234 
   3235   if (Recursive) {
   3236     // Define any pending vtables.
   3237     DefineUsedVTables();
   3238 
   3239     // Instantiate any pending implicit instantiations found during the
   3240     // instantiation of this template.
   3241     PerformPendingInstantiations();
   3242 
   3243     // Restore the set of pending vtables.
   3244     assert(VTableUses.empty() &&
   3245            "VTableUses should be empty before it is discarded.");
   3246     VTableUses.swap(SavedVTableUses);
   3247 
   3248     // Restore the set of pending implicit instantiations.
   3249     assert(PendingInstantiations.empty() &&
   3250            "PendingInstantiations should be empty before it is discarded.");
   3251     PendingInstantiations.swap(SavedPendingInstantiations);
   3252   }
   3253   SavedPendingLocalImplicitInstantiations.swap(
   3254                             PendingLocalImplicitInstantiations);
   3255 }
   3256 
   3257 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
   3258     VarTemplateDecl *VarTemplate, VarDecl *FromVar,
   3259     const TemplateArgumentList &TemplateArgList,
   3260     const TemplateArgumentListInfo &TemplateArgsInfo,
   3261     SmallVectorImpl<TemplateArgument> &Converted,
   3262     SourceLocation PointOfInstantiation, void *InsertPos,
   3263     LateInstantiatedAttrVec *LateAttrs,
   3264     LocalInstantiationScope *StartingScope) {
   3265   if (FromVar->isInvalidDecl())
   3266     return 0;
   3267 
   3268   InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
   3269   if (Inst)
   3270     return 0;
   3271 
   3272   MultiLevelTemplateArgumentList TemplateArgLists;
   3273   TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
   3274 
   3275   TemplateDeclInstantiator Instantiator(
   3276       *this, VarTemplate->getDeclContext(),
   3277       MultiLevelTemplateArgumentList(TemplateArgList));
   3278 
   3279   // TODO: Set LateAttrs and StartingScope ...
   3280 
   3281   return cast_or_null<VarTemplateSpecializationDecl>(
   3282       Instantiator.VisitVarTemplateSpecializationDecl(
   3283           VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
   3284 }
   3285 
   3286 /// \brief Instantiates a variable template specialization by completing it
   3287 /// with appropriate type information and initializer.
   3288 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
   3289     VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
   3290     const MultiLevelTemplateArgumentList &TemplateArgs) {
   3291 
   3292   // Do substitution on the type of the declaration
   3293   TypeSourceInfo *DI =
   3294       SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
   3295                 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
   3296   if (!DI)
   3297     return 0;
   3298 
   3299   // Update the type of this variable template specialization.
   3300   VarSpec->setType(DI->getType());
   3301 
   3302   // Instantiate the initializer.
   3303   InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
   3304 
   3305   return VarSpec;
   3306 }
   3307 
   3308 /// BuildVariableInstantiation - Used after a new variable has been created.
   3309 /// Sets basic variable data and decides whether to postpone the
   3310 /// variable instantiation.
   3311 void Sema::BuildVariableInstantiation(
   3312     VarDecl *NewVar, VarDecl *OldVar,
   3313     const MultiLevelTemplateArgumentList &TemplateArgs,
   3314     LateInstantiatedAttrVec *LateAttrs,
   3315     LocalInstantiationScope *StartingScope,
   3316     bool ForVarTemplate) {
   3317 
   3318   // If we are instantiating a static data member defined
   3319   // out-of-line, the instantiation will have the same lexical
   3320   // context (which will be a namespace scope) as the template.
   3321   if (OldVar->isOutOfLine())
   3322     NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
   3323   NewVar->setTSCSpec(OldVar->getTSCSpec());
   3324   NewVar->setInitStyle(OldVar->getInitStyle());
   3325   NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
   3326   NewVar->setConstexpr(OldVar->isConstexpr());
   3327   NewVar->setAccess(OldVar->getAccess());
   3328 
   3329   if (!OldVar->isStaticDataMember()) {
   3330     NewVar->setUsed(OldVar->isUsed(false));
   3331     NewVar->setReferenced(OldVar->isReferenced());
   3332   }
   3333 
   3334   InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
   3335 
   3336   if (NewVar->hasAttrs())
   3337     CheckAlignasUnderalignment(NewVar);
   3338 
   3339   // FIXME: In theory, we could have a previous declaration for variables that
   3340   // are not static data members.
   3341   // FIXME: having to fake up a LookupResult is dumb.
   3342   LookupResult Previous(*this, NewVar->getDeclName(), NewVar->getLocation(),
   3343                         Sema::LookupOrdinaryName, Sema::ForRedeclaration);
   3344 
   3345   if (!isa<VarTemplateSpecializationDecl>(NewVar))
   3346     LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
   3347 
   3348   CheckVariableDeclaration(NewVar, Previous);
   3349 
   3350   if (OldVar->isOutOfLine()) {
   3351     OldVar->getLexicalDeclContext()->addDecl(NewVar);
   3352     if (!ForVarTemplate)
   3353       NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
   3354   } else {
   3355     if (!ForVarTemplate)
   3356       NewVar->getDeclContext()->addDecl(NewVar);
   3357     if (NewVar->getDeclContext()->isFunctionOrMethod())
   3358       CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
   3359   }
   3360 
   3361   // Link instantiations of static data members back to the template from
   3362   // which they were instantiated.
   3363   if (NewVar->isStaticDataMember() && !ForVarTemplate)
   3364     NewVar->setInstantiationOfStaticDataMember(OldVar,
   3365                                                TSK_ImplicitInstantiation);
   3366 
   3367   if (isa<VarTemplateSpecializationDecl>(NewVar)) {
   3368     // Do not instantiate the variable just yet.
   3369   } else
   3370     InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
   3371 
   3372   // Diagnose unused local variables with dependent types, where the diagnostic
   3373   // will have been deferred.
   3374   if (!NewVar->isInvalidDecl() &&
   3375       NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
   3376       OldVar->getType()->isDependentType())
   3377     DiagnoseUnusedDecl(NewVar);
   3378 }
   3379 
   3380 /// \brief Instantiate the initializer of a variable.
   3381 void Sema::InstantiateVariableInitializer(
   3382     VarDecl *Var, VarDecl *OldVar,
   3383     const MultiLevelTemplateArgumentList &TemplateArgs) {
   3384 
   3385   if (Var->getAnyInitializer())
   3386     // We already have an initializer in the class.
   3387     return;
   3388 
   3389   if (OldVar->getInit()) {
   3390     if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
   3391       PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
   3392     else
   3393       PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
   3394 
   3395     // Instantiate the initializer.
   3396     ExprResult Init =
   3397         SubstInitializer(OldVar->getInit(), TemplateArgs,
   3398                          OldVar->getInitStyle() == VarDecl::CallInit);
   3399     if (!Init.isInvalid()) {
   3400       bool TypeMayContainAuto = true;
   3401       if (Init.get()) {
   3402         bool DirectInit = OldVar->isDirectInit();
   3403         AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
   3404       } else
   3405         ActOnUninitializedDecl(Var, TypeMayContainAuto);
   3406     } else {
   3407       // FIXME: Not too happy about invalidating the declaration
   3408       // because of a bogus initializer.
   3409       Var->setInvalidDecl();
   3410     }
   3411 
   3412     PopExpressionEvaluationContext();
   3413   } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
   3414              !Var->isCXXForRangeDecl())
   3415     ActOnUninitializedDecl(Var, false);
   3416 }
   3417 
   3418 /// \brief Instantiate the definition of the given variable from its
   3419 /// template.
   3420 ///
   3421 /// \param PointOfInstantiation the point at which the instantiation was
   3422 /// required. Note that this is not precisely a "point of instantiation"
   3423 /// for the function, but it's close.
   3424 ///
   3425 /// \param Var the already-instantiated declaration of a static member
   3426 /// variable of a class template specialization.
   3427 ///
   3428 /// \param Recursive if true, recursively instantiates any functions that
   3429 /// are required by this instantiation.
   3430 ///
   3431 /// \param DefinitionRequired if true, then we are performing an explicit
   3432 /// instantiation where an out-of-line definition of the member variable
   3433 /// is required. Complain if there is no such definition.
   3434 void Sema::InstantiateStaticDataMemberDefinition(
   3435                                           SourceLocation PointOfInstantiation,
   3436                                                  VarDecl *Var,
   3437                                                  bool Recursive,
   3438                                                  bool DefinitionRequired) {
   3439   InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
   3440                                 DefinitionRequired);
   3441 }
   3442 
   3443 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
   3444                                          VarDecl *Var, bool Recursive,
   3445                                          bool DefinitionRequired) {
   3446 
   3447   if (Var->isInvalidDecl())
   3448     return;
   3449 
   3450   VarTemplateSpecializationDecl *VarSpec =
   3451       dyn_cast<VarTemplateSpecializationDecl>(Var);
   3452   assert((VarSpec || Var->isStaticDataMember()) &&
   3453          "Not a static data member, nor a variable template specialization?");
   3454   VarDecl *PatternDecl = 0;
   3455 
   3456   // If this is a variable template specialization, make sure that it is
   3457   // non-dependent, then find its instantiation pattern.
   3458   if (VarSpec) {
   3459     bool InstantiationDependent = false;
   3460     assert(!TemplateSpecializationType::anyDependentTemplateArguments(
   3461                VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
   3462            "Only instantiate variable template specializations that are "
   3463            "not type-dependent");
   3464     (void)InstantiationDependent;
   3465 
   3466     // Find the variable initialization that we'll be substituting.
   3467     assert(VarSpec->getSpecializedTemplate() &&
   3468            "Specialization without specialized template?");
   3469     llvm::PointerUnion<VarTemplateDecl *,
   3470                        VarTemplatePartialSpecializationDecl *> PatternPtr =
   3471         VarSpec->getSpecializedTemplateOrPartial();
   3472     if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>())
   3473       PatternDecl = cast<VarDecl>(
   3474           PatternPtr.get<VarTemplatePartialSpecializationDecl *>());
   3475     else
   3476       PatternDecl = (PatternPtr.get<VarTemplateDecl *>())->getTemplatedDecl();
   3477     assert(PatternDecl && "instantiating a non-template");
   3478   }
   3479 
   3480   // If this is a static data member, find its out-of-line definition.
   3481   VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
   3482   if (Var->isStaticDataMember()) {
   3483     assert(Def && "This data member was not instantiated from a template?");
   3484     assert(Def->isStaticDataMember() && "Not a static data member?");
   3485     Def = Def->getOutOfLineDefinition();
   3486   }
   3487 
   3488   // If the instantiation pattern does not have an initializer, or if an
   3489   // out-of-line definition is not found, we won't perform any instantiation.
   3490   // Rather, we rely on the user to instantiate this definition (or provide
   3491   // a specialization for it) in another translation unit.
   3492   if ((VarSpec && !PatternDecl->getInit()) ||
   3493       (!VarSpec && Var->isStaticDataMember() && !Def)) {
   3494     if (DefinitionRequired) {
   3495       if (!Var->isStaticDataMember()) {
   3496         Diag(PointOfInstantiation,
   3497              diag::err_explicit_instantiation_undefined_var_template)
   3498             << PatternDecl;
   3499         Diag(PatternDecl->getLocation(),
   3500              diag::note_explicit_instantiation_here);
   3501       } else {
   3502         Def = Var->getInstantiatedFromStaticDataMember();
   3503         Diag(PointOfInstantiation,
   3504              diag::err_explicit_instantiation_undefined_member)
   3505             << 3 << Var->getDeclName() << Var->getDeclContext();
   3506         Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
   3507       }
   3508       if (VarSpec)
   3509         Var->setInvalidDecl();
   3510     } else if (Var->getTemplateSpecializationKind()
   3511                  == TSK_ExplicitInstantiationDefinition) {
   3512       PendingInstantiations.push_back(
   3513         std::make_pair(Var, PointOfInstantiation));
   3514     }
   3515 
   3516     return;
   3517   }
   3518 
   3519   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
   3520 
   3521   // Never instantiate an explicit specialization.
   3522   if (TSK == TSK_ExplicitSpecialization)
   3523     return;
   3524 
   3525   // C++0x [temp.explicit]p9:
   3526   //   Except for inline functions, other explicit instantiation declarations
   3527   //   have the effect of suppressing the implicit instantiation of the entity
   3528   //   to which they refer.
   3529   //
   3530   // C++11 [temp.explicit]p10:
   3531   //   Except for inline functions, [...] explicit instantiation declarations
   3532   //   have the effect of suppressing the implicit instantiation of the entity
   3533   //   to which they refer.
   3534   if (TSK == TSK_ExplicitInstantiationDeclaration)
   3535     return;
   3536 
   3537   // Make sure to pass the instantiated variable to the consumer at the end.
   3538   struct PassToConsumerRAII {
   3539     ASTConsumer &Consumer;
   3540     VarDecl *Var;
   3541 
   3542     PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
   3543       : Consumer(Consumer), Var(Var) { }
   3544 
   3545     ~PassToConsumerRAII() {
   3546       if (Var->isStaticDataMember())
   3547         Consumer.HandleCXXStaticMemberVarInstantiation(Var);
   3548       else {
   3549         DeclGroupRef DG(Var);
   3550         Consumer.HandleTopLevelDecl(DG);
   3551       }
   3552     }
   3553   } PassToConsumerRAII(Consumer, Var);
   3554 
   3555   if (!VarSpec) {
   3556     // If we already have a definition, we're done.
   3557     if (VarDecl *Def = Var->getDefinition()) {
   3558       // We may be explicitly instantiating something we've already implicitly
   3559       // instantiated.
   3560       Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
   3561                                          PointOfInstantiation);
   3562       return;
   3563     }
   3564   }
   3565 
   3566   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
   3567   if (Inst)
   3568     return;
   3569 
   3570   // If we're performing recursive template instantiation, create our own
   3571   // queue of pending implicit instantiations that we will instantiate later,
   3572   // while we're still within our own instantiation context.
   3573   SmallVector<VTableUse, 16> SavedVTableUses;
   3574   std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
   3575   if (Recursive) {
   3576     VTableUses.swap(SavedVTableUses);
   3577     PendingInstantiations.swap(SavedPendingInstantiations);
   3578   }
   3579 
   3580   // Enter the scope of this instantiation. We don't use
   3581   // PushDeclContext because we don't have a scope.
   3582   ContextRAII PreviousContext(*this, Var->getDeclContext());
   3583   LocalInstantiationScope Local(*this);
   3584 
   3585   VarDecl *OldVar = Var;
   3586   if (!VarSpec)
   3587     Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
   3588                                           getTemplateInstantiationArgs(Var)));
   3589   else
   3590     // Construct a VarTemplateSpecializationDecl to avoid name clashing with
   3591     // the primary template. (Note that unlike function declarations, variable
   3592     // declarations cannot be overloaded.)
   3593     // In fact, there is no need to construct a new declaration from scratch.
   3594     // Thus, simply complete its definition with an appropriately substituted
   3595     // type and initializer.
   3596     Var = CompleteVarTemplateSpecializationDecl(
   3597         VarSpec, PatternDecl, getTemplateInstantiationArgs(Var));
   3598 
   3599   PreviousContext.pop();
   3600 
   3601   if (Var) {
   3602     MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
   3603     if (!VarSpec)
   3604       assert(MSInfo && "Missing member specialization information?");
   3605 
   3606     PassToConsumerRAII.Var = Var;
   3607     if (MSInfo)
   3608       Var->setTemplateSpecializationKind(
   3609           MSInfo->getTemplateSpecializationKind(),
   3610           MSInfo->getPointOfInstantiation());
   3611   }
   3612 
   3613   // This variable may have local implicit instantiations that need to be
   3614   // instantiated within this scope.
   3615   PerformPendingInstantiations(/*LocalOnly=*/true);
   3616 
   3617   Local.Exit();
   3618 
   3619   if (Recursive) {
   3620     // Define any newly required vtables.
   3621     DefineUsedVTables();
   3622 
   3623     // Instantiate any pending implicit instantiations found during the
   3624     // instantiation of this template.
   3625     PerformPendingInstantiations();
   3626 
   3627     // Restore the set of pending vtables.
   3628     assert(VTableUses.empty() &&
   3629            "VTableUses should be empty before it is discarded.");
   3630     VTableUses.swap(SavedVTableUses);
   3631 
   3632     // Restore the set of pending implicit instantiations.
   3633     assert(PendingInstantiations.empty() &&
   3634            "PendingInstantiations should be empty before it is discarded.");
   3635     PendingInstantiations.swap(SavedPendingInstantiations);
   3636   }
   3637 }
   3638 
   3639 void
   3640 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
   3641                                  const CXXConstructorDecl *Tmpl,
   3642                            const MultiLevelTemplateArgumentList &TemplateArgs) {
   3643 
   3644   SmallVector<CXXCtorInitializer*, 4> NewInits;
   3645   bool AnyErrors = Tmpl->isInvalidDecl();
   3646 
   3647   // Instantiate all the initializers.
   3648   for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
   3649                                             InitsEnd = Tmpl->init_end();
   3650        Inits != InitsEnd; ++Inits) {
   3651     CXXCtorInitializer *Init = *Inits;
   3652 
   3653     // Only instantiate written initializers, let Sema re-construct implicit
   3654     // ones.
   3655     if (!Init->isWritten())
   3656       continue;
   3657 
   3658     SourceLocation EllipsisLoc;
   3659 
   3660     if (Init->isPackExpansion()) {
   3661       // This is a pack expansion. We should expand it now.
   3662       TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
   3663       SmallVector<UnexpandedParameterPack, 4> Unexpanded;
   3664       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
   3665       collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
   3666       bool ShouldExpand = false;
   3667       bool RetainExpansion = false;
   3668       Optional<unsigned> NumExpansions;
   3669       if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
   3670                                           BaseTL.getSourceRange(),
   3671                                           Unexpanded,
   3672                                           TemplateArgs, ShouldExpand,
   3673                                           RetainExpansion,
   3674                                           NumExpansions)) {
   3675         AnyErrors = true;
   3676         New->setInvalidDecl();
   3677         continue;
   3678       }
   3679       assert(ShouldExpand && "Partial instantiation of base initializer?");
   3680 
   3681       // Loop over all of the arguments in the argument pack(s),
   3682       for (unsigned I = 0; I != *NumExpansions; ++I) {
   3683         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
   3684 
   3685         // Instantiate the initializer.
   3686         ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
   3687                                                /*CXXDirectInit=*/true);
   3688         if (TempInit.isInvalid()) {
   3689           AnyErrors = true;
   3690           break;
   3691         }
   3692 
   3693         // Instantiate the base type.
   3694         TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
   3695                                               TemplateArgs,
   3696                                               Init->getSourceLocation(),
   3697                                               New->getDeclName());
   3698         if (!BaseTInfo) {
   3699           AnyErrors = true;
   3700           break;
   3701         }
   3702 
   3703         // Build the initializer.
   3704         MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
   3705                                                      BaseTInfo, TempInit.take(),
   3706                                                      New->getParent(),
   3707                                                      SourceLocation());
   3708         if (NewInit.isInvalid()) {
   3709           AnyErrors = true;
   3710           break;
   3711         }
   3712 
   3713         NewInits.push_back(NewInit.get());
   3714       }
   3715 
   3716       continue;
   3717     }
   3718 
   3719     // Instantiate the initializer.
   3720     ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
   3721                                            /*CXXDirectInit=*/true);
   3722     if (TempInit.isInvalid()) {
   3723       AnyErrors = true;
   3724       continue;
   3725     }
   3726 
   3727     MemInitResult NewInit;
   3728     if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
   3729       TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
   3730                                         TemplateArgs,
   3731                                         Init->getSourceLocation(),
   3732                                         New->getDeclName());
   3733       if (!TInfo) {
   3734         AnyErrors = true;
   3735         New->setInvalidDecl();
   3736         continue;
   3737       }
   3738 
   3739       if (Init->isBaseInitializer())
   3740         NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
   3741                                        New->getParent(), EllipsisLoc);
   3742       else
   3743         NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
   3744                                   cast<CXXRecordDecl>(CurContext->getParent()));
   3745     } else if (Init->isMemberInitializer()) {
   3746       FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
   3747                                                      Init->getMemberLocation(),
   3748                                                      Init->getMember(),
   3749                                                      TemplateArgs));
   3750       if (!Member) {
   3751         AnyErrors = true;
   3752         New->setInvalidDecl();
   3753         continue;
   3754       }
   3755 
   3756       NewInit = BuildMemberInitializer(Member, TempInit.take(),
   3757                                        Init->getSourceLocation());
   3758     } else if (Init->isIndirectMemberInitializer()) {
   3759       IndirectFieldDecl *IndirectMember =
   3760          cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
   3761                                  Init->getMemberLocation(),
   3762                                  Init->getIndirectMember(), TemplateArgs));
   3763 
   3764       if (!IndirectMember) {
   3765         AnyErrors = true;
   3766         New->setInvalidDecl();
   3767         continue;
   3768       }
   3769 
   3770       NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
   3771                                        Init->getSourceLocation());
   3772     }
   3773 
   3774     if (NewInit.isInvalid()) {
   3775       AnyErrors = true;
   3776       New->setInvalidDecl();
   3777     } else {
   3778       NewInits.push_back(NewInit.get());
   3779     }
   3780   }
   3781 
   3782   // Assign all the initializers to the new constructor.
   3783   ActOnMemInitializers(New,
   3784                        /*FIXME: ColonLoc */
   3785                        SourceLocation(),
   3786                        NewInits,
   3787                        AnyErrors);
   3788 }
   3789 
   3790 // TODO: this could be templated if the various decl types used the
   3791 // same method name.
   3792 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
   3793                               ClassTemplateDecl *Instance) {
   3794   Pattern = Pattern->getCanonicalDecl();
   3795 
   3796   do {
   3797     Instance = Instance->getCanonicalDecl();
   3798     if (Pattern == Instance) return true;
   3799     Instance = Instance->getInstantiatedFromMemberTemplate();
   3800   } while (Instance);
   3801 
   3802   return false;
   3803 }
   3804 
   3805 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
   3806                               FunctionTemplateDecl *Instance) {
   3807   Pattern = Pattern->getCanonicalDecl();
   3808 
   3809   do {
   3810     Instance = Instance->getCanonicalDecl();
   3811     if (Pattern == Instance) return true;
   3812     Instance = Instance->getInstantiatedFromMemberTemplate();
   3813   } while (Instance);
   3814 
   3815   return false;
   3816 }
   3817 
   3818 static bool
   3819 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
   3820                   ClassTemplatePartialSpecializationDecl *Instance) {
   3821   Pattern
   3822     = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
   3823   do {
   3824     Instance = cast<ClassTemplatePartialSpecializationDecl>(
   3825                                                 Instance->getCanonicalDecl());
   3826     if (Pattern == Instance)
   3827       return true;
   3828     Instance = Instance->getInstantiatedFromMember();
   3829   } while (Instance);
   3830 
   3831   return false;
   3832 }
   3833 
   3834 static bool isInstantiationOf(CXXRecordDecl *Pattern,
   3835                               CXXRecordDecl *Instance) {
   3836   Pattern = Pattern->getCanonicalDecl();
   3837 
   3838   do {
   3839     Instance = Instance->getCanonicalDecl();
   3840     if (Pattern == Instance) return true;
   3841     Instance = Instance->getInstantiatedFromMemberClass();
   3842   } while (Instance);
   3843 
   3844   return false;
   3845 }
   3846 
   3847 static bool isInstantiationOf(FunctionDecl *Pattern,
   3848                               FunctionDecl *Instance) {
   3849   Pattern = Pattern->getCanonicalDecl();
   3850 
   3851   do {
   3852     Instance = Instance->getCanonicalDecl();
   3853     if (Pattern == Instance) return true;
   3854     Instance = Instance->getInstantiatedFromMemberFunction();
   3855   } while (Instance);
   3856 
   3857   return false;
   3858 }
   3859 
   3860 static bool isInstantiationOf(EnumDecl *Pattern,
   3861                               EnumDecl *Instance) {
   3862   Pattern = Pattern->getCanonicalDecl();
   3863 
   3864   do {
   3865     Instance = Instance->getCanonicalDecl();
   3866     if (Pattern == Instance) return true;
   3867     Instance = Instance->getInstantiatedFromMemberEnum();
   3868   } while (Instance);
   3869 
   3870   return false;
   3871 }
   3872 
   3873 static bool isInstantiationOf(UsingShadowDecl *Pattern,
   3874                               UsingShadowDecl *Instance,
   3875                               ASTContext &C) {
   3876   return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
   3877 }
   3878 
   3879 static bool isInstantiationOf(UsingDecl *Pattern,
   3880                               UsingDecl *Instance,
   3881                               ASTContext &C) {
   3882   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
   3883 }
   3884 
   3885 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
   3886                               UsingDecl *Instance,
   3887                               ASTContext &C) {
   3888   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
   3889 }
   3890 
   3891 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
   3892                               UsingDecl *Instance,
   3893                               ASTContext &C) {
   3894   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
   3895 }
   3896 
   3897 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
   3898                                               VarDecl *Instance) {
   3899   assert(Instance->isStaticDataMember());
   3900 
   3901   Pattern = Pattern->getCanonicalDecl();
   3902 
   3903   do {
   3904     Instance = Instance->getCanonicalDecl();
   3905     if (Pattern == Instance) return true;
   3906     Instance = Instance->getInstantiatedFromStaticDataMember();
   3907   } while (Instance);
   3908 
   3909   return false;
   3910 }
   3911 
   3912 // Other is the prospective instantiation
   3913 // D is the prospective pattern
   3914 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
   3915   if (D->getKind() != Other->getKind()) {
   3916     if (UnresolvedUsingTypenameDecl *UUD
   3917           = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
   3918       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
   3919         return isInstantiationOf(UUD, UD, Ctx);
   3920       }
   3921     }
   3922 
   3923     if (UnresolvedUsingValueDecl *UUD
   3924           = dyn_cast<UnresolvedUsingValueDecl>(D)) {
   3925       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
   3926         return isInstantiationOf(UUD, UD, Ctx);
   3927       }
   3928     }
   3929 
   3930     return false;
   3931   }
   3932 
   3933   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
   3934     return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
   3935 
   3936   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
   3937     return isInstantiationOf(cast<FunctionDecl>(D), Function);
   3938 
   3939   if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
   3940     return isInstantiationOf(cast<EnumDecl>(D), Enum);
   3941 
   3942   if (VarDecl *Var = dyn_cast<VarDecl>(Other))
   3943     if (Var->isStaticDataMember())
   3944       return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
   3945 
   3946   if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
   3947     return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
   3948 
   3949   if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
   3950     return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
   3951 
   3952   if (ClassTemplatePartialSpecializationDecl *PartialSpec
   3953         = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
   3954     return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
   3955                              PartialSpec);
   3956 
   3957   if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
   3958     if (!Field->getDeclName()) {
   3959       // This is an unnamed field.
   3960       return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
   3961         cast<FieldDecl>(D);
   3962     }
   3963   }
   3964 
   3965   if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
   3966     return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
   3967 
   3968   if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
   3969     return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
   3970 
   3971   return D->getDeclName() && isa<NamedDecl>(Other) &&
   3972     D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
   3973 }
   3974 
   3975 template<typename ForwardIterator>
   3976 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
   3977                                       NamedDecl *D,
   3978                                       ForwardIterator first,
   3979                                       ForwardIterator last) {
   3980   for (; first != last; ++first)
   3981     if (isInstantiationOf(Ctx, D, *first))
   3982       return cast<NamedDecl>(*first);
   3983 
   3984   return 0;
   3985 }
   3986 
   3987 /// \brief Finds the instantiation of the given declaration context
   3988 /// within the current instantiation.
   3989 ///
   3990 /// \returns NULL if there was an error
   3991 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
   3992                           const MultiLevelTemplateArgumentList &TemplateArgs) {
   3993   if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
   3994     Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
   3995     return cast_or_null<DeclContext>(ID);
   3996   } else return DC;
   3997 }
   3998 
   3999 /// \brief Find the instantiation of the given declaration within the
   4000 /// current instantiation.
   4001 ///
   4002 /// This routine is intended to be used when \p D is a declaration
   4003 /// referenced from within a template, that needs to mapped into the
   4004 /// corresponding declaration within an instantiation. For example,
   4005 /// given:
   4006 ///
   4007 /// \code
   4008 /// template<typename T>
   4009 /// struct X {
   4010 ///   enum Kind {
   4011 ///     KnownValue = sizeof(T)
   4012 ///   };
   4013 ///
   4014 ///   bool getKind() const { return KnownValue; }
   4015 /// };
   4016 ///
   4017 /// template struct X<int>;
   4018 /// \endcode
   4019 ///
   4020 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
   4021 /// \p EnumConstantDecl for \p KnownValue (which refers to
   4022 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
   4023 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
   4024 /// this mapping from within the instantiation of <tt>X<int></tt>.
   4025 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
   4026                           const MultiLevelTemplateArgumentList &TemplateArgs) {
   4027   DeclContext *ParentDC = D->getDeclContext();
   4028   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
   4029       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
   4030       (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
   4031       (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
   4032     // D is a local of some kind. Look into the map of local
   4033     // declarations to their instantiations.
   4034     typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
   4035     llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
   4036       = CurrentInstantiationScope->findInstantiationOf(D);
   4037 
   4038     if (Found) {
   4039       if (Decl *FD = Found->dyn_cast<Decl *>())
   4040         return cast<NamedDecl>(FD);
   4041 
   4042       int PackIdx = ArgumentPackSubstitutionIndex;
   4043       assert(PackIdx != -1 && "found declaration pack but not pack expanding");
   4044       return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
   4045     }
   4046 
   4047     // If we're performing a partial substitution during template argument
   4048     // deduction, we may not have values for template parameters yet. They
   4049     // just map to themselves.
   4050     if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
   4051         isa<TemplateTemplateParmDecl>(D))
   4052       return D;
   4053 
   4054     // If we didn't find the decl, then we must have a label decl that hasn't
   4055     // been found yet.  Lazily instantiate it and return it now.
   4056     assert(isa<LabelDecl>(D));
   4057 
   4058     Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
   4059     assert(Inst && "Failed to instantiate label??");
   4060 
   4061     CurrentInstantiationScope->InstantiatedLocal(D, Inst);
   4062     return cast<LabelDecl>(Inst);
   4063   }
   4064 
   4065   // For variable template specializations, update those that are still
   4066   // type-dependent.
   4067   if (VarTemplateSpecializationDecl *VarSpec =
   4068           dyn_cast<VarTemplateSpecializationDecl>(D)) {
   4069     bool InstantiationDependent = false;
   4070     const TemplateArgumentListInfo &VarTemplateArgs =
   4071         VarSpec->getTemplateArgsInfo();
   4072     if (TemplateSpecializationType::anyDependentTemplateArguments(
   4073             VarTemplateArgs, InstantiationDependent))
   4074       D = cast<NamedDecl>(
   4075           SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
   4076     return D;
   4077   }
   4078 
   4079   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
   4080     if (!Record->isDependentContext())
   4081       return D;
   4082 
   4083     // Determine whether this record is the "templated" declaration describing
   4084     // a class template or class template partial specialization.
   4085     ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
   4086     if (ClassTemplate)
   4087       ClassTemplate = ClassTemplate->getCanonicalDecl();
   4088     else if (ClassTemplatePartialSpecializationDecl *PartialSpec
   4089                = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
   4090       ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
   4091 
   4092     // Walk the current context to find either the record or an instantiation of
   4093     // it.
   4094     DeclContext *DC = CurContext;
   4095     while (!DC->isFileContext()) {
   4096       // If we're performing substitution while we're inside the template
   4097       // definition, we'll find our own context. We're done.
   4098       if (DC->Equals(Record))
   4099         return Record;
   4100 
   4101       if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
   4102         // Check whether we're in the process of instantiating a class template
   4103         // specialization of the template we're mapping.
   4104         if (ClassTemplateSpecializationDecl *InstSpec
   4105                       = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
   4106           ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
   4107           if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
   4108             return InstRecord;
   4109         }
   4110 
   4111         // Check whether we're in the process of instantiating a member class.
   4112         if (isInstantiationOf(Record, InstRecord))
   4113           return InstRecord;
   4114       }
   4115 
   4116       // Move to the outer template scope.
   4117       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
   4118         if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
   4119           DC = FD->getLexicalDeclContext();
   4120           continue;
   4121         }
   4122       }
   4123 
   4124       DC = DC->getParent();
   4125     }
   4126 
   4127     // Fall through to deal with other dependent record types (e.g.,
   4128     // anonymous unions in class templates).
   4129   }
   4130 
   4131   if (!ParentDC->isDependentContext())
   4132     return D;
   4133 
   4134   ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
   4135   if (!ParentDC)
   4136     return 0;
   4137 
   4138   if (ParentDC != D->getDeclContext()) {
   4139     // We performed some kind of instantiation in the parent context,
   4140     // so now we need to look into the instantiated parent context to
   4141     // find the instantiation of the declaration D.
   4142 
   4143     // If our context used to be dependent, we may need to instantiate
   4144     // it before performing lookup into that context.
   4145     bool IsBeingInstantiated = false;
   4146     if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
   4147       if (!Spec->isDependentContext()) {
   4148         QualType T = Context.getTypeDeclType(Spec);
   4149         const RecordType *Tag = T->getAs<RecordType>();
   4150         assert(Tag && "type of non-dependent record is not a RecordType");
   4151         if (Tag->isBeingDefined())
   4152           IsBeingInstantiated = true;
   4153         if (!Tag->isBeingDefined() &&
   4154             RequireCompleteType(Loc, T, diag::err_incomplete_type))
   4155           return 0;
   4156 
   4157         ParentDC = Tag->getDecl();
   4158       }
   4159     }
   4160 
   4161     NamedDecl *Result = 0;
   4162     if (D->getDeclName()) {
   4163       DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
   4164       Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
   4165     } else {
   4166       // Since we don't have a name for the entity we're looking for,
   4167       // our only option is to walk through all of the declarations to
   4168       // find that name. This will occur in a few cases:
   4169       //
   4170       //   - anonymous struct/union within a template
   4171       //   - unnamed class/struct/union/enum within a template
   4172       //
   4173       // FIXME: Find a better way to find these instantiations!
   4174       Result = findInstantiationOf(Context, D,
   4175                                    ParentDC->decls_begin(),
   4176                                    ParentDC->decls_end());
   4177     }
   4178 
   4179     if (!Result) {
   4180       if (isa<UsingShadowDecl>(D)) {
   4181         // UsingShadowDecls can instantiate to nothing because of using hiding.
   4182       } else if (Diags.hasErrorOccurred()) {
   4183         // We've already complained about something, so most likely this
   4184         // declaration failed to instantiate. There's no point in complaining
   4185         // further, since this is normal in invalid code.
   4186       } else if (IsBeingInstantiated) {
   4187         // The class in which this member exists is currently being
   4188         // instantiated, and we haven't gotten around to instantiating this
   4189         // member yet. This can happen when the code uses forward declarations
   4190         // of member classes, and introduces ordering dependencies via
   4191         // template instantiation.
   4192         Diag(Loc, diag::err_member_not_yet_instantiated)
   4193           << D->getDeclName()
   4194           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
   4195         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
   4196       } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
   4197         // This enumeration constant was found when the template was defined,
   4198         // but can't be found in the instantiation. This can happen if an
   4199         // unscoped enumeration member is explicitly specialized.
   4200         EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
   4201         EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
   4202                                                              TemplateArgs));
   4203         assert(Spec->getTemplateSpecializationKind() ==
   4204                  TSK_ExplicitSpecialization);
   4205         Diag(Loc, diag::err_enumerator_does_not_exist)
   4206           << D->getDeclName()
   4207           << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
   4208         Diag(Spec->getLocation(), diag::note_enum_specialized_here)
   4209           << Context.getTypeDeclType(Spec);
   4210       } else {
   4211         // We should have found something, but didn't.
   4212         llvm_unreachable("Unable to find instantiation of declaration!");
   4213       }
   4214     }
   4215 
   4216     D = Result;
   4217   }
   4218 
   4219   return D;
   4220 }
   4221 
   4222 /// \brief Performs template instantiation for all implicit template
   4223 /// instantiations we have seen until this point.
   4224 void Sema::PerformPendingInstantiations(bool LocalOnly) {
   4225   // Load pending instantiations from the external source.
   4226   if (!LocalOnly && ExternalSource) {
   4227     SmallVector<PendingImplicitInstantiation, 4> Pending;
   4228     ExternalSource->ReadPendingInstantiations(Pending);
   4229     PendingInstantiations.insert(PendingInstantiations.begin(),
   4230                                  Pending.begin(), Pending.end());
   4231   }
   4232 
   4233   while (!PendingLocalImplicitInstantiations.empty() ||
   4234          (!LocalOnly && !PendingInstantiations.empty())) {
   4235     PendingImplicitInstantiation Inst;
   4236 
   4237     if (PendingLocalImplicitInstantiations.empty()) {
   4238       Inst = PendingInstantiations.front();
   4239       PendingInstantiations.pop_front();
   4240     } else {
   4241       Inst = PendingLocalImplicitInstantiations.front();
   4242       PendingLocalImplicitInstantiations.pop_front();
   4243     }
   4244 
   4245     // Instantiate function definitions
   4246     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
   4247       PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
   4248                                           "instantiating function definition");
   4249       bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
   4250                                 TSK_ExplicitInstantiationDefinition;
   4251       InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
   4252                                     DefinitionRequired);
   4253       continue;
   4254     }
   4255 
   4256     // Instantiate variable definitions
   4257     VarDecl *Var = cast<VarDecl>(Inst.first);
   4258 
   4259     assert((Var->isStaticDataMember() ||
   4260             isa<VarTemplateSpecializationDecl>(Var)) &&
   4261            "Not a static data member, nor a variable template"
   4262            " specialization?");
   4263 
   4264     // Don't try to instantiate declarations if the most recent redeclaration
   4265     // is invalid.
   4266     if (Var->getMostRecentDecl()->isInvalidDecl())
   4267       continue;
   4268 
   4269     // Check if the most recent declaration has changed the specialization kind
   4270     // and removed the need for implicit instantiation.
   4271     switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
   4272     case TSK_Undeclared:
   4273       llvm_unreachable("Cannot instantitiate an undeclared specialization.");
   4274     case TSK_ExplicitInstantiationDeclaration:
   4275     case TSK_ExplicitSpecialization:
   4276       continue;  // No longer need to instantiate this type.
   4277     case TSK_ExplicitInstantiationDefinition:
   4278       // We only need an instantiation if the pending instantiation *is* the
   4279       // explicit instantiation.
   4280       if (Var != Var->getMostRecentDecl()) continue;
   4281     case TSK_ImplicitInstantiation:
   4282       break;
   4283     }
   4284 
   4285     PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
   4286                                         "instantiating variable definition");
   4287     bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
   4288                               TSK_ExplicitInstantiationDefinition;
   4289 
   4290     // Instantiate static data member definitions or variable template
   4291     // specializations.
   4292     InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
   4293                                   DefinitionRequired);
   4294   }
   4295 }
   4296 
   4297 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
   4298                        const MultiLevelTemplateArgumentList &TemplateArgs) {
   4299   for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
   4300          E = Pattern->ddiag_end(); I != E; ++I) {
   4301     DependentDiagnostic *DD = *I;
   4302 
   4303     switch (DD->getKind()) {
   4304     case DependentDiagnostic::Access:
   4305       HandleDependentAccessCheck(*DD, TemplateArgs);
   4306       break;
   4307     }
   4308   }
   4309 }
   4310