SemaTemplateInstantiateDecl.cpp revision 3fb9e4b89f72823f162096086f0f964e6dcf66d6
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/Sema/Lookup.h"
14#include "clang/Sema/PrettyDeclStackTrace.h"
15#include "clang/Sema/Template.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/DeclVisitor.h"
20#include "clang/AST/DependentDiagnostic.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/TypeLoc.h"
24#include "clang/Lex/Preprocessor.h"
25
26using namespace clang;
27
28bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29                                              DeclaratorDecl *NewDecl) {
30  NestedNameSpecifier *OldQual = OldDecl->getQualifier();
31  if (!OldQual) return false;
32
33  SourceRange QualRange = OldDecl->getQualifierRange();
34
35  NestedNameSpecifier *NewQual
36    = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
37  if (!NewQual)
38    return true;
39
40  NewDecl->setQualifierInfo(NewQual, QualRange);
41  return false;
42}
43
44bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
45                                              TagDecl *NewDecl) {
46  NestedNameSpecifier *OldQual = OldDecl->getQualifier();
47  if (!OldQual) return false;
48
49  SourceRange QualRange = OldDecl->getQualifierRange();
50
51  NestedNameSpecifier *NewQual
52    = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
53  if (!NewQual)
54    return true;
55
56  NewDecl->setQualifierInfo(NewQual, QualRange);
57  return false;
58}
59
60// FIXME: Is this still too simple?
61void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
62                            Decl *Tmpl, Decl *New) {
63  for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
64       i != e; ++i) {
65    const Attr *TmplAttr = *i;
66    // FIXME: This should be generalized to more than just the AlignedAttr.
67    if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
68      if (Aligned->isAlignmentDependent()) {
69        // The alignment expression is not potentially evaluated.
70        EnterExpressionEvaluationContext Unevaluated(*this,
71                                                     Sema::Unevaluated);
72
73        if (Aligned->isAlignmentExpr()) {
74          ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
75                                        TemplateArgs);
76          if (!Result.isInvalid())
77            AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>());
78        }
79        else {
80          TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
81                                             TemplateArgs,
82                                             Aligned->getLocation(),
83                                             DeclarationName());
84          if (Result)
85            AddAlignedAttr(Aligned->getLocation(), New, Result);
86        }
87        continue;
88      }
89    }
90
91    // FIXME: Is cloning correct for all attributes?
92    Attr *NewAttr = TmplAttr->clone(Context);
93    New->addAttr(NewAttr);
94  }
95}
96
97Decl *
98TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
99  assert(false && "Translation units cannot be instantiated");
100  return D;
101}
102
103Decl *
104TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
105  assert(false && "Namespaces cannot be instantiated");
106  return D;
107}
108
109Decl *
110TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
111  NamespaceAliasDecl *Inst
112    = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
113                                 D->getNamespaceLoc(),
114                                 D->getAliasLoc(),
115                                 D->getNamespace()->getIdentifier(),
116                                 D->getQualifierRange(),
117                                 D->getQualifier(),
118                                 D->getTargetNameLoc(),
119                                 D->getNamespace());
120  Owner->addDecl(Inst);
121  return Inst;
122}
123
124Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
125  bool Invalid = false;
126  TypeSourceInfo *DI = D->getTypeSourceInfo();
127  if (DI->getType()->isDependentType() ||
128      DI->getType()->isVariablyModifiedType()) {
129    DI = SemaRef.SubstType(DI, TemplateArgs,
130                           D->getLocation(), D->getDeclName());
131    if (!DI) {
132      Invalid = true;
133      DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
134    }
135  } else {
136    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
137  }
138
139  // Create the new typedef
140  TypedefDecl *Typedef
141    = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
142                          D->getIdentifier(), DI);
143  if (Invalid)
144    Typedef->setInvalidDecl();
145
146  if (const TagType *TT = DI->getType()->getAs<TagType>()) {
147    TagDecl *TD = TT->getDecl();
148
149    // If the TagDecl that the TypedefDecl points to is an anonymous decl
150    // keep track of the TypedefDecl.
151    if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
152      TD->setTypedefForAnonDecl(Typedef);
153  }
154
155  if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
156    NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
157                                                       TemplateArgs);
158    Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
159  }
160
161  SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
162
163  Typedef->setAccess(D->getAccess());
164  Owner->addDecl(Typedef);
165
166  return Typedef;
167}
168
169/// \brief Instantiate the arguments provided as part of initialization.
170///
171/// \returns true if an error occurred, false otherwise.
172static bool InstantiateInitializationArguments(Sema &SemaRef,
173                                               Expr **Args, unsigned NumArgs,
174                           const MultiLevelTemplateArgumentList &TemplateArgs,
175                           ASTOwningVector<Expr*> &InitArgs) {
176  for (unsigned I = 0; I != NumArgs; ++I) {
177    // When we hit the first defaulted argument, break out of the loop:
178    // we don't pass those default arguments on.
179    if (Args[I]->isDefaultArgument())
180      break;
181
182    ExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
183    if (Arg.isInvalid())
184      return true;
185
186    InitArgs.push_back(Arg.release());
187  }
188
189  return false;
190}
191
192/// \brief Instantiate an initializer, breaking it into separate
193/// initialization arguments.
194///
195/// \param S The semantic analysis object.
196///
197/// \param Init The initializer to instantiate.
198///
199/// \param TemplateArgs Template arguments to be substituted into the
200/// initializer.
201///
202/// \param NewArgs Will be filled in with the instantiation arguments.
203///
204/// \returns true if an error occurred, false otherwise
205static bool InstantiateInitializer(Sema &S, Expr *Init,
206                            const MultiLevelTemplateArgumentList &TemplateArgs,
207                                   SourceLocation &LParenLoc,
208                                   ASTOwningVector<Expr*> &NewArgs,
209                                   SourceLocation &RParenLoc) {
210  NewArgs.clear();
211  LParenLoc = SourceLocation();
212  RParenLoc = SourceLocation();
213
214  if (!Init)
215    return false;
216
217  if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
218    Init = ExprTemp->getSubExpr();
219
220  while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
221    Init = Binder->getSubExpr();
222
223  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
224    Init = ICE->getSubExprAsWritten();
225
226  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
227    LParenLoc = ParenList->getLParenLoc();
228    RParenLoc = ParenList->getRParenLoc();
229    return InstantiateInitializationArguments(S, ParenList->getExprs(),
230                                              ParenList->getNumExprs(),
231                                              TemplateArgs, NewArgs);
232  }
233
234  if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
235    if (!isa<CXXTemporaryObjectExpr>(Construct)) {
236      if (InstantiateInitializationArguments(S,
237                                             Construct->getArgs(),
238                                             Construct->getNumArgs(),
239                                             TemplateArgs, NewArgs))
240        return true;
241
242      // FIXME: Fake locations!
243      LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
244      RParenLoc = LParenLoc;
245      return false;
246    }
247  }
248
249  ExprResult Result = S.SubstExpr(Init, TemplateArgs);
250  if (Result.isInvalid())
251    return true;
252
253  NewArgs.push_back(Result.takeAs<Expr>());
254  return false;
255}
256
257Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
258  // If this is the variable for an anonymous struct or union,
259  // instantiate the anonymous struct/union type first.
260  if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
261    if (RecordTy->getDecl()->isAnonymousStructOrUnion())
262      if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
263        return 0;
264
265  // Do substitution on the type of the declaration
266  TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
267                                         TemplateArgs,
268                                         D->getTypeSpecStartLoc(),
269                                         D->getDeclName());
270  if (!DI)
271    return 0;
272
273  if (DI->getType()->isFunctionType()) {
274    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
275      << D->isStaticDataMember() << DI->getType();
276    return 0;
277  }
278
279  // Build the instantiated declaration
280  VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
281                                 D->getLocation(), D->getIdentifier(),
282                                 DI->getType(), DI,
283                                 D->getStorageClass(),
284                                 D->getStorageClassAsWritten());
285  Var->setThreadSpecified(D->isThreadSpecified());
286  Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
287
288  // Substitute the nested name specifier, if any.
289  if (SubstQualifier(D, Var))
290    return 0;
291
292  // If we are instantiating a static data member defined
293  // out-of-line, the instantiation will have the same lexical
294  // context (which will be a namespace scope) as the template.
295  if (D->isOutOfLine())
296    Var->setLexicalDeclContext(D->getLexicalDeclContext());
297
298  Var->setAccess(D->getAccess());
299
300  if (!D->isStaticDataMember())
301    Var->setUsed(D->isUsed(false));
302
303  // FIXME: In theory, we could have a previous declaration for variables that
304  // are not static data members.
305  bool Redeclaration = false;
306  // FIXME: having to fake up a LookupResult is dumb.
307  LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
308                        Sema::LookupOrdinaryName, Sema::ForRedeclaration);
309  if (D->isStaticDataMember())
310    SemaRef.LookupQualifiedName(Previous, Owner, false);
311  SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
312
313  if (D->isOutOfLine()) {
314    if (!D->isStaticDataMember())
315      D->getLexicalDeclContext()->addDecl(Var);
316    Owner->makeDeclVisibleInContext(Var);
317  } else {
318    Owner->addDecl(Var);
319    if (Owner->isFunctionOrMethod())
320      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
321  }
322  SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
323
324  // Link instantiations of static data members back to the template from
325  // which they were instantiated.
326  if (Var->isStaticDataMember())
327    SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
328                                                     TSK_ImplicitInstantiation);
329
330  if (Var->getAnyInitializer()) {
331    // We already have an initializer in the class.
332  } else if (D->getInit()) {
333    if (Var->isStaticDataMember() && !D->isOutOfLine())
334      SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
335    else
336      SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
337
338    // Instantiate the initializer.
339    SourceLocation LParenLoc, RParenLoc;
340    ASTOwningVector<Expr*> InitArgs(SemaRef);
341    if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
342                                InitArgs, RParenLoc)) {
343      // Attach the initializer to the declaration.
344      if (D->hasCXXDirectInitializer()) {
345        // Add the direct initializer to the declaration.
346        SemaRef.AddCXXDirectInitializerToDecl(Var,
347                                              LParenLoc,
348                                              move_arg(InitArgs),
349                                              RParenLoc);
350      } else if (InitArgs.size() == 1) {
351        Expr *Init = InitArgs.take()[0];
352        SemaRef.AddInitializerToDecl(Var, Init, false);
353      } else {
354        assert(InitArgs.size() == 0);
355        SemaRef.ActOnUninitializedDecl(Var, false);
356      }
357    } else {
358      // FIXME: Not too happy about invalidating the declaration
359      // because of a bogus initializer.
360      Var->setInvalidDecl();
361    }
362
363    SemaRef.PopExpressionEvaluationContext();
364  } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
365    SemaRef.ActOnUninitializedDecl(Var, false);
366
367  // Diagnose unused local variables.
368  if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
369    SemaRef.DiagnoseUnusedDecl(Var);
370
371  return Var;
372}
373
374Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
375  AccessSpecDecl* AD
376    = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
377                             D->getAccessSpecifierLoc(), D->getColonLoc());
378  Owner->addHiddenDecl(AD);
379  return AD;
380}
381
382Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
383  bool Invalid = false;
384  TypeSourceInfo *DI = D->getTypeSourceInfo();
385  if (DI->getType()->isDependentType() ||
386      DI->getType()->isVariablyModifiedType())  {
387    DI = SemaRef.SubstType(DI, TemplateArgs,
388                           D->getLocation(), D->getDeclName());
389    if (!DI) {
390      DI = D->getTypeSourceInfo();
391      Invalid = true;
392    } else if (DI->getType()->isFunctionType()) {
393      // C++ [temp.arg.type]p3:
394      //   If a declaration acquires a function type through a type
395      //   dependent on a template-parameter and this causes a
396      //   declaration that does not use the syntactic form of a
397      //   function declarator to have function type, the program is
398      //   ill-formed.
399      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
400        << DI->getType();
401      Invalid = true;
402    }
403  } else {
404    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
405  }
406
407  Expr *BitWidth = D->getBitWidth();
408  if (Invalid)
409    BitWidth = 0;
410  else if (BitWidth) {
411    // The bit-width expression is not potentially evaluated.
412    EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
413
414    ExprResult InstantiatedBitWidth
415      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
416    if (InstantiatedBitWidth.isInvalid()) {
417      Invalid = true;
418      BitWidth = 0;
419    } else
420      BitWidth = InstantiatedBitWidth.takeAs<Expr>();
421  }
422
423  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
424                                            DI->getType(), DI,
425                                            cast<RecordDecl>(Owner),
426                                            D->getLocation(),
427                                            D->isMutable(),
428                                            BitWidth,
429                                            D->getTypeSpecStartLoc(),
430                                            D->getAccess(),
431                                            0);
432  if (!Field) {
433    cast<Decl>(Owner)->setInvalidDecl();
434    return 0;
435  }
436
437  SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
438
439  if (Invalid)
440    Field->setInvalidDecl();
441
442  if (!Field->getDeclName()) {
443    // Keep track of where this decl came from.
444    SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
445  }
446  if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
447    if (Parent->isAnonymousStructOrUnion() &&
448        Parent->getRedeclContext()->isFunctionOrMethod())
449      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
450  }
451
452  Field->setImplicit(D->isImplicit());
453  Field->setAccess(D->getAccess());
454  Owner->addDecl(Field);
455
456  return Field;
457}
458
459Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
460  NamedDecl **NamedChain =
461    new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
462
463  int i = 0;
464  for (IndirectFieldDecl::chain_iterator PI =
465       D->chain_begin(), PE = D->chain_end();
466       PI != PE; ++PI)
467    NamedChain[i++] = (SemaRef.FindInstantiatedDecl(D->getLocation(),
468                                            *PI, TemplateArgs));
469
470  QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
471  IndirectFieldDecl* IndirectField
472    = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
473                                D->getIdentifier(), T,
474                                NamedChain, D->getChainingSize());
475
476
477  IndirectField->setImplicit(D->isImplicit());
478  IndirectField->setAccess(D->getAccess());
479  Owner->addDecl(IndirectField);
480  return IndirectField;
481}
482
483Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
484  // Handle friend type expressions by simply substituting template
485  // parameters into the pattern type and checking the result.
486  if (TypeSourceInfo *Ty = D->getFriendType()) {
487    TypeSourceInfo *InstTy =
488      SemaRef.SubstType(Ty, TemplateArgs,
489                        D->getLocation(), DeclarationName());
490    if (!InstTy)
491      return 0;
492
493    FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
494    if (!FD)
495      return 0;
496
497    FD->setAccess(AS_public);
498    FD->setUnsupportedFriend(D->isUnsupportedFriend());
499    Owner->addDecl(FD);
500    return FD;
501  }
502
503  NamedDecl *ND = D->getFriendDecl();
504  assert(ND && "friend decl must be a decl or a type!");
505
506  // All of the Visit implementations for the various potential friend
507  // declarations have to be carefully written to work for friend
508  // objects, with the most important detail being that the target
509  // decl should almost certainly not be placed in Owner.
510  Decl *NewND = Visit(ND);
511  if (!NewND) return 0;
512
513  FriendDecl *FD =
514    FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
515                       cast<NamedDecl>(NewND), D->getFriendLoc());
516  FD->setAccess(AS_public);
517  FD->setUnsupportedFriend(D->isUnsupportedFriend());
518  Owner->addDecl(FD);
519  return FD;
520}
521
522Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
523  Expr *AssertExpr = D->getAssertExpr();
524
525  // The expression in a static assertion is not potentially evaluated.
526  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
527
528  ExprResult InstantiatedAssertExpr
529    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
530  if (InstantiatedAssertExpr.isInvalid())
531    return 0;
532
533  ExprResult Message(D->getMessage());
534  D->getMessage();
535  return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
536                                              InstantiatedAssertExpr.get(),
537                                              Message.get());
538}
539
540Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
541  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
542                                    D->getLocation(), D->getIdentifier(),
543                                    D->getTagKeywordLoc(),
544                                    /*PrevDecl=*/0, D->isScoped(),
545                                    D->isScopedUsingClassTag(), D->isFixed());
546  if (D->isFixed()) {
547    if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
548      // If we have type source information for the underlying type, it means it
549      // has been explicitly set by the user. Perform substitution on it before
550      // moving on.
551      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
552      Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
553                                                       TemplateArgs,
554                                                       UnderlyingLoc,
555                                                       DeclarationName()));
556
557      if (!Enum->getIntegerTypeSourceInfo())
558        Enum->setIntegerType(SemaRef.Context.IntTy);
559    }
560    else {
561      assert(!D->getIntegerType()->isDependentType()
562             && "Dependent type without type source info");
563      Enum->setIntegerType(D->getIntegerType());
564    }
565  }
566
567  SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
568
569  Enum->setInstantiationOfMemberEnum(D);
570  Enum->setAccess(D->getAccess());
571  if (SubstQualifier(D, Enum)) return 0;
572  Owner->addDecl(Enum);
573  Enum->startDefinition();
574
575  if (D->getDeclContext()->isFunctionOrMethod())
576    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
577
578  llvm::SmallVector<Decl*, 4> Enumerators;
579
580  EnumConstantDecl *LastEnumConst = 0;
581  for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
582         ECEnd = D->enumerator_end();
583       EC != ECEnd; ++EC) {
584    // The specified value for the enumerator.
585    ExprResult Value = SemaRef.Owned((Expr *)0);
586    if (Expr *UninstValue = EC->getInitExpr()) {
587      // The enumerator's value expression is not potentially evaluated.
588      EnterExpressionEvaluationContext Unevaluated(SemaRef,
589                                                   Sema::Unevaluated);
590
591      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
592    }
593
594    // Drop the initial value and continue.
595    bool isInvalid = false;
596    if (Value.isInvalid()) {
597      Value = SemaRef.Owned((Expr *)0);
598      isInvalid = true;
599    }
600
601    EnumConstantDecl *EnumConst
602      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
603                                  EC->getLocation(), EC->getIdentifier(),
604                                  Value.get());
605
606    if (isInvalid) {
607      if (EnumConst)
608        EnumConst->setInvalidDecl();
609      Enum->setInvalidDecl();
610    }
611
612    if (EnumConst) {
613      SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
614
615      EnumConst->setAccess(Enum->getAccess());
616      Enum->addDecl(EnumConst);
617      Enumerators.push_back(EnumConst);
618      LastEnumConst = EnumConst;
619
620      if (D->getDeclContext()->isFunctionOrMethod()) {
621        // If the enumeration is within a function or method, record the enum
622        // constant as a local.
623        SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
624      }
625    }
626  }
627
628  // FIXME: Fixup LBraceLoc and RBraceLoc
629  // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
630  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
631                        Enum,
632                        Enumerators.data(), Enumerators.size(),
633                        0, 0);
634
635  return Enum;
636}
637
638Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
639  assert(false && "EnumConstantDecls can only occur within EnumDecls.");
640  return 0;
641}
642
643Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
644  bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
645
646  // Create a local instantiation scope for this class template, which
647  // will contain the instantiations of the template parameters.
648  LocalInstantiationScope Scope(SemaRef);
649  TemplateParameterList *TempParams = D->getTemplateParameters();
650  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
651  if (!InstParams)
652    return NULL;
653
654  CXXRecordDecl *Pattern = D->getTemplatedDecl();
655
656  // Instantiate the qualifier.  We have to do this first in case
657  // we're a friend declaration, because if we are then we need to put
658  // the new declaration in the appropriate context.
659  NestedNameSpecifier *Qualifier = Pattern->getQualifier();
660  if (Qualifier) {
661    Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
662                                                 Pattern->getQualifierRange(),
663                                                 TemplateArgs);
664    if (!Qualifier) return 0;
665  }
666
667  CXXRecordDecl *PrevDecl = 0;
668  ClassTemplateDecl *PrevClassTemplate = 0;
669
670  if (!isFriend && Pattern->getPreviousDeclaration()) {
671    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
672    if (Found.first != Found.second) {
673      PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
674      if (PrevClassTemplate)
675        PrevDecl = PrevClassTemplate->getTemplatedDecl();
676    }
677  }
678
679  // If this isn't a friend, then it's a member template, in which
680  // case we just want to build the instantiation in the
681  // specialization.  If it is a friend, we want to build it in
682  // the appropriate context.
683  DeclContext *DC = Owner;
684  if (isFriend) {
685    if (Qualifier) {
686      CXXScopeSpec SS;
687      SS.setScopeRep(Qualifier);
688      SS.setRange(Pattern->getQualifierRange());
689      DC = SemaRef.computeDeclContext(SS);
690      if (!DC) return 0;
691    } else {
692      DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
693                                           Pattern->getDeclContext(),
694                                           TemplateArgs);
695    }
696
697    // Look for a previous declaration of the template in the owning
698    // context.
699    LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
700                   Sema::LookupOrdinaryName, Sema::ForRedeclaration);
701    SemaRef.LookupQualifiedName(R, DC);
702
703    if (R.isSingleResult()) {
704      PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
705      if (PrevClassTemplate)
706        PrevDecl = PrevClassTemplate->getTemplatedDecl();
707    }
708
709    if (!PrevClassTemplate && Qualifier) {
710      SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
711        << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
712        << Pattern->getQualifierRange();
713      return 0;
714    }
715
716    bool AdoptedPreviousTemplateParams = false;
717    if (PrevClassTemplate) {
718      bool Complain = true;
719
720      // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
721      // template for struct std::tr1::__detail::_Map_base, where the
722      // template parameters of the friend declaration don't match the
723      // template parameters of the original declaration. In this one
724      // case, we don't complain about the ill-formed friend
725      // declaration.
726      if (isFriend && Pattern->getIdentifier() &&
727          Pattern->getIdentifier()->isStr("_Map_base") &&
728          DC->isNamespace() &&
729          cast<NamespaceDecl>(DC)->getIdentifier() &&
730          cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
731        DeclContext *DCParent = DC->getParent();
732        if (DCParent->isNamespace() &&
733            cast<NamespaceDecl>(DCParent)->getIdentifier() &&
734            cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
735          DeclContext *DCParent2 = DCParent->getParent();
736          if (DCParent2->isNamespace() &&
737              cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
738              cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
739              DCParent2->getParent()->isTranslationUnit())
740            Complain = false;
741        }
742      }
743
744      TemplateParameterList *PrevParams
745        = PrevClassTemplate->getTemplateParameters();
746
747      // Make sure the parameter lists match.
748      if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
749                                                  Complain,
750                                                  Sema::TPL_TemplateMatch)) {
751        if (Complain)
752          return 0;
753
754        AdoptedPreviousTemplateParams = true;
755        InstParams = PrevParams;
756      }
757
758      // Do some additional validation, then merge default arguments
759      // from the existing declarations.
760      if (!AdoptedPreviousTemplateParams &&
761          SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
762                                             Sema::TPC_ClassTemplate))
763        return 0;
764    }
765  }
766
767  CXXRecordDecl *RecordInst
768    = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
769                            Pattern->getLocation(), Pattern->getIdentifier(),
770                            Pattern->getTagKeywordLoc(), PrevDecl,
771                            /*DelayTypeCreation=*/true);
772
773  if (Qualifier)
774    RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
775
776  ClassTemplateDecl *Inst
777    = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
778                                D->getIdentifier(), InstParams, RecordInst,
779                                PrevClassTemplate);
780  RecordInst->setDescribedClassTemplate(Inst);
781
782  if (isFriend) {
783    if (PrevClassTemplate)
784      Inst->setAccess(PrevClassTemplate->getAccess());
785    else
786      Inst->setAccess(D->getAccess());
787
788    Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
789    // TODO: do we want to track the instantiation progeny of this
790    // friend target decl?
791  } else {
792    Inst->setAccess(D->getAccess());
793    if (!PrevClassTemplate)
794      Inst->setInstantiatedFromMemberTemplate(D);
795  }
796
797  // Trigger creation of the type for the instantiation.
798  SemaRef.Context.getInjectedClassNameType(RecordInst,
799                                    Inst->getInjectedClassNameSpecialization());
800
801  // Finish handling of friends.
802  if (isFriend) {
803    DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
804    return Inst;
805  }
806
807  Owner->addDecl(Inst);
808
809  if (!PrevClassTemplate) {
810    // Queue up any out-of-line partial specializations of this member
811    // class template; the client will force their instantiation once
812    // the enclosing class has been instantiated.
813    llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
814    D->getPartialSpecializations(PartialSpecs);
815    for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
816      if (PartialSpecs[I]->isOutOfLine())
817        OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
818  }
819
820  return Inst;
821}
822
823Decl *
824TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
825                                   ClassTemplatePartialSpecializationDecl *D) {
826  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
827
828  // Lookup the already-instantiated declaration in the instantiation
829  // of the class template and return that.
830  DeclContext::lookup_result Found
831    = Owner->lookup(ClassTemplate->getDeclName());
832  if (Found.first == Found.second)
833    return 0;
834
835  ClassTemplateDecl *InstClassTemplate
836    = dyn_cast<ClassTemplateDecl>(*Found.first);
837  if (!InstClassTemplate)
838    return 0;
839
840  if (ClassTemplatePartialSpecializationDecl *Result
841        = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
842    return Result;
843
844  return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
845}
846
847Decl *
848TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
849  // Create a local instantiation scope for this function template, which
850  // will contain the instantiations of the template parameters and then get
851  // merged with the local instantiation scope for the function template
852  // itself.
853  LocalInstantiationScope Scope(SemaRef);
854
855  TemplateParameterList *TempParams = D->getTemplateParameters();
856  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
857  if (!InstParams)
858    return NULL;
859
860  FunctionDecl *Instantiated = 0;
861  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
862    Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
863                                                                 InstParams));
864  else
865    Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
866                                                          D->getTemplatedDecl(),
867                                                                InstParams));
868
869  if (!Instantiated)
870    return 0;
871
872  Instantiated->setAccess(D->getAccess());
873
874  // Link the instantiated function template declaration to the function
875  // template from which it was instantiated.
876  FunctionTemplateDecl *InstTemplate
877    = Instantiated->getDescribedFunctionTemplate();
878  InstTemplate->setAccess(D->getAccess());
879  assert(InstTemplate &&
880         "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
881
882  bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
883
884  // Link the instantiation back to the pattern *unless* this is a
885  // non-definition friend declaration.
886  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
887      !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
888    InstTemplate->setInstantiatedFromMemberTemplate(D);
889
890  // Make declarations visible in the appropriate context.
891  if (!isFriend)
892    Owner->addDecl(InstTemplate);
893
894  return InstTemplate;
895}
896
897Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
898  CXXRecordDecl *PrevDecl = 0;
899  if (D->isInjectedClassName())
900    PrevDecl = cast<CXXRecordDecl>(Owner);
901  else if (D->getPreviousDeclaration()) {
902    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
903                                                   D->getPreviousDeclaration(),
904                                                   TemplateArgs);
905    if (!Prev) return 0;
906    PrevDecl = cast<CXXRecordDecl>(Prev);
907  }
908
909  CXXRecordDecl *Record
910    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
911                            D->getLocation(), D->getIdentifier(),
912                            D->getTagKeywordLoc(), PrevDecl);
913
914  // Substitute the nested name specifier, if any.
915  if (SubstQualifier(D, Record))
916    return 0;
917
918  Record->setImplicit(D->isImplicit());
919  // FIXME: Check against AS_none is an ugly hack to work around the issue that
920  // the tag decls introduced by friend class declarations don't have an access
921  // specifier. Remove once this area of the code gets sorted out.
922  if (D->getAccess() != AS_none)
923    Record->setAccess(D->getAccess());
924  if (!D->isInjectedClassName())
925    Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
926
927  // If the original function was part of a friend declaration,
928  // inherit its namespace state.
929  if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
930    Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
931
932  // Make sure that anonymous structs and unions are recorded.
933  if (D->isAnonymousStructOrUnion()) {
934    Record->setAnonymousStructOrUnion(true);
935    if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
936      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
937  }
938
939  Owner->addDecl(Record);
940  return Record;
941}
942
943/// Normal class members are of more specific types and therefore
944/// don't make it here.  This function serves two purposes:
945///   1) instantiating function templates
946///   2) substituting friend declarations
947/// FIXME: preserve function definitions in case #2
948Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
949                                       TemplateParameterList *TemplateParams) {
950  // Check whether there is already a function template specialization for
951  // this declaration.
952  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
953  void *InsertPos = 0;
954  if (FunctionTemplate && !TemplateParams) {
955    std::pair<const TemplateArgument *, unsigned> Innermost
956      = TemplateArgs.getInnermost();
957
958    FunctionDecl *SpecFunc
959      = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
960                                             InsertPos);
961
962    // If we already have a function template specialization, return it.
963    if (SpecFunc)
964      return SpecFunc;
965  }
966
967  bool isFriend;
968  if (FunctionTemplate)
969    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
970  else
971    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
972
973  bool MergeWithParentScope = (TemplateParams != 0) ||
974    Owner->isFunctionOrMethod() ||
975    !(isa<Decl>(Owner) &&
976      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
977  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
978
979  llvm::SmallVector<ParmVarDecl *, 4> Params;
980  TypeSourceInfo *TInfo = D->getTypeSourceInfo();
981  TInfo = SubstFunctionType(D, Params);
982  if (!TInfo)
983    return 0;
984  QualType T = TInfo->getType();
985
986  NestedNameSpecifier *Qualifier = D->getQualifier();
987  if (Qualifier) {
988    Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
989                                                 D->getQualifierRange(),
990                                                 TemplateArgs);
991    if (!Qualifier) return 0;
992  }
993
994  // If we're instantiating a local function declaration, put the result
995  // in the owner;  otherwise we need to find the instantiated context.
996  DeclContext *DC;
997  if (D->getDeclContext()->isFunctionOrMethod())
998    DC = Owner;
999  else if (isFriend && Qualifier) {
1000    CXXScopeSpec SS;
1001    SS.setScopeRep(Qualifier);
1002    SS.setRange(D->getQualifierRange());
1003    DC = SemaRef.computeDeclContext(SS);
1004    if (!DC) return 0;
1005  } else {
1006    DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1007                                         TemplateArgs);
1008  }
1009
1010  FunctionDecl *Function =
1011      FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
1012                           D->getDeclName(), T, TInfo,
1013                           D->getStorageClass(), D->getStorageClassAsWritten(),
1014                           D->isInlineSpecified(), D->hasWrittenPrototype());
1015
1016  if (Qualifier)
1017    Function->setQualifierInfo(Qualifier, D->getQualifierRange());
1018
1019  DeclContext *LexicalDC = Owner;
1020  if (!isFriend && D->isOutOfLine()) {
1021    assert(D->getDeclContext()->isFileContext());
1022    LexicalDC = D->getDeclContext();
1023  }
1024
1025  Function->setLexicalDeclContext(LexicalDC);
1026
1027  // Attach the parameters
1028  for (unsigned P = 0; P < Params.size(); ++P)
1029    if (Params[P])
1030      Params[P]->setOwningFunction(Function);
1031  Function->setParams(Params.data(), Params.size());
1032
1033  SourceLocation InstantiateAtPOI;
1034  if (TemplateParams) {
1035    // Our resulting instantiation is actually a function template, since we
1036    // are substituting only the outer template parameters. For example, given
1037    //
1038    //   template<typename T>
1039    //   struct X {
1040    //     template<typename U> friend void f(T, U);
1041    //   };
1042    //
1043    //   X<int> x;
1044    //
1045    // We are instantiating the friend function template "f" within X<int>,
1046    // which means substituting int for T, but leaving "f" as a friend function
1047    // template.
1048    // Build the function template itself.
1049    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1050                                                    Function->getLocation(),
1051                                                    Function->getDeclName(),
1052                                                    TemplateParams, Function);
1053    Function->setDescribedFunctionTemplate(FunctionTemplate);
1054
1055    FunctionTemplate->setLexicalDeclContext(LexicalDC);
1056
1057    if (isFriend && D->isThisDeclarationADefinition()) {
1058      // TODO: should we remember this connection regardless of whether
1059      // the friend declaration provided a body?
1060      FunctionTemplate->setInstantiatedFromMemberTemplate(
1061                                           D->getDescribedFunctionTemplate());
1062    }
1063  } else if (FunctionTemplate) {
1064    // Record this function template specialization.
1065    std::pair<const TemplateArgument *, unsigned> Innermost
1066      = TemplateArgs.getInnermost();
1067    Function->setFunctionTemplateSpecialization(FunctionTemplate,
1068                            TemplateArgumentList::CreateCopy(SemaRef.Context,
1069                                                             Innermost.first,
1070                                                             Innermost.second),
1071                                                InsertPos);
1072  } else if (isFriend && D->isThisDeclarationADefinition()) {
1073    // TODO: should we remember this connection regardless of whether
1074    // the friend declaration provided a body?
1075    Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1076  }
1077
1078  if (InitFunctionInstantiation(Function, D))
1079    Function->setInvalidDecl();
1080
1081  bool Redeclaration = false;
1082  bool OverloadableAttrRequired = false;
1083  bool isExplicitSpecialization = false;
1084
1085  LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1086                        Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1087
1088  if (DependentFunctionTemplateSpecializationInfo *Info
1089        = D->getDependentSpecializationInfo()) {
1090    assert(isFriend && "non-friend has dependent specialization info?");
1091
1092    // This needs to be set now for future sanity.
1093    Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1094
1095    // Instantiate the explicit template arguments.
1096    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1097                                          Info->getRAngleLoc());
1098    if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1099                      ExplicitArgs, TemplateArgs))
1100      return 0;
1101
1102    // Map the candidate templates to their instantiations.
1103    for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1104      Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1105                                                Info->getTemplate(I),
1106                                                TemplateArgs);
1107      if (!Temp) return 0;
1108
1109      Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1110    }
1111
1112    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1113                                                    &ExplicitArgs,
1114                                                    Previous))
1115      Function->setInvalidDecl();
1116
1117    isExplicitSpecialization = true;
1118
1119  } else if (TemplateParams || !FunctionTemplate) {
1120    // Look only into the namespace where the friend would be declared to
1121    // find a previous declaration. This is the innermost enclosing namespace,
1122    // as described in ActOnFriendFunctionDecl.
1123    SemaRef.LookupQualifiedName(Previous, DC);
1124
1125    // In C++, the previous declaration we find might be a tag type
1126    // (class or enum). In this case, the new declaration will hide the
1127    // tag type. Note that this does does not apply if we're declaring a
1128    // typedef (C++ [dcl.typedef]p4).
1129    if (Previous.isSingleTagDecl())
1130      Previous.clear();
1131  }
1132
1133  SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1134                                   isExplicitSpecialization, Redeclaration,
1135                                   /*FIXME:*/OverloadableAttrRequired);
1136
1137  NamedDecl *PrincipalDecl = (TemplateParams
1138                              ? cast<NamedDecl>(FunctionTemplate)
1139                              : Function);
1140
1141  // If the original function was part of a friend declaration,
1142  // inherit its namespace state and add it to the owner.
1143  if (isFriend) {
1144    NamedDecl *PrevDecl;
1145    if (TemplateParams)
1146      PrevDecl = FunctionTemplate->getPreviousDeclaration();
1147    else
1148      PrevDecl = Function->getPreviousDeclaration();
1149
1150    PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1151    DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
1152
1153    bool queuedInstantiation = false;
1154
1155    if (!SemaRef.getLangOptions().CPlusPlus0x &&
1156        D->isThisDeclarationADefinition()) {
1157      // Check for a function body.
1158      const FunctionDecl *Definition = 0;
1159      if (Function->hasBody(Definition) &&
1160          Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1161        SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1162          << Function->getDeclName();
1163        SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1164        Function->setInvalidDecl();
1165      }
1166      // Check for redefinitions due to other instantiations of this or
1167      // a similar friend function.
1168      else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1169                                           REnd = Function->redecls_end();
1170                R != REnd; ++R) {
1171        if (*R == Function)
1172          continue;
1173        switch (R->getFriendObjectKind()) {
1174        case Decl::FOK_None:
1175          if (!queuedInstantiation && R->isUsed(false)) {
1176            if (MemberSpecializationInfo *MSInfo
1177                = Function->getMemberSpecializationInfo()) {
1178              if (MSInfo->getPointOfInstantiation().isInvalid()) {
1179                SourceLocation Loc = R->getLocation(); // FIXME
1180                MSInfo->setPointOfInstantiation(Loc);
1181                SemaRef.PendingLocalImplicitInstantiations.push_back(
1182                                                 std::make_pair(Function, Loc));
1183                queuedInstantiation = true;
1184              }
1185            }
1186          }
1187          break;
1188        default:
1189          if (const FunctionDecl *RPattern
1190              = R->getTemplateInstantiationPattern())
1191            if (RPattern->hasBody(RPattern)) {
1192              SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1193                << Function->getDeclName();
1194              SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1195              Function->setInvalidDecl();
1196              break;
1197            }
1198        }
1199      }
1200    }
1201  }
1202
1203  if (Function->isOverloadedOperator() && !DC->isRecord() &&
1204      PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1205    PrincipalDecl->setNonMemberOperator();
1206
1207  return Function;
1208}
1209
1210Decl *
1211TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1212                                      TemplateParameterList *TemplateParams) {
1213  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1214  void *InsertPos = 0;
1215  if (FunctionTemplate && !TemplateParams) {
1216    // We are creating a function template specialization from a function
1217    // template. Check whether there is already a function template
1218    // specialization for this particular set of template arguments.
1219    std::pair<const TemplateArgument *, unsigned> Innermost
1220      = TemplateArgs.getInnermost();
1221
1222    FunctionDecl *SpecFunc
1223      = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1224                                             InsertPos);
1225
1226    // If we already have a function template specialization, return it.
1227    if (SpecFunc)
1228      return SpecFunc;
1229  }
1230
1231  bool isFriend;
1232  if (FunctionTemplate)
1233    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1234  else
1235    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1236
1237  bool MergeWithParentScope = (TemplateParams != 0) ||
1238    !(isa<Decl>(Owner) &&
1239      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1240  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1241
1242  // Instantiate enclosing template arguments for friends.
1243  llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1244  unsigned NumTempParamLists = 0;
1245  if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1246    TempParamLists.set_size(NumTempParamLists);
1247    for (unsigned I = 0; I != NumTempParamLists; ++I) {
1248      TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1249      TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1250      if (!InstParams)
1251        return NULL;
1252      TempParamLists[I] = InstParams;
1253    }
1254  }
1255
1256  llvm::SmallVector<ParmVarDecl *, 4> Params;
1257  TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1258  TInfo = SubstFunctionType(D, Params);
1259  if (!TInfo)
1260    return 0;
1261  QualType T = TInfo->getType();
1262
1263  // \brief If the type of this function, after ignoring parentheses,
1264  // is not *directly* a function type, then we're instantiating a function
1265  // that was declared via a typedef, e.g.,
1266  //
1267  //   typedef int functype(int, int);
1268  //   functype func;
1269  //
1270  // In this case, we'll just go instantiate the ParmVarDecls that we
1271  // synthesized in the method declaration.
1272  if (!isa<FunctionProtoType>(T.IgnoreParens())) {
1273    assert(!Params.size() && "Instantiating type could not yield parameters");
1274    for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) {
1275      ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I),
1276                                                TemplateArgs);
1277      if (!P)
1278        return 0;
1279
1280      Params.push_back(P);
1281    }
1282  }
1283
1284  NestedNameSpecifier *Qualifier = D->getQualifier();
1285  if (Qualifier) {
1286    Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1287                                                 D->getQualifierRange(),
1288                                                 TemplateArgs);
1289    if (!Qualifier) return 0;
1290  }
1291
1292  DeclContext *DC = Owner;
1293  if (isFriend) {
1294    if (Qualifier) {
1295      CXXScopeSpec SS;
1296      SS.setScopeRep(Qualifier);
1297      SS.setRange(D->getQualifierRange());
1298      DC = SemaRef.computeDeclContext(SS);
1299
1300      if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1301        return 0;
1302    } else {
1303      DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1304                                           D->getDeclContext(),
1305                                           TemplateArgs);
1306    }
1307    if (!DC) return 0;
1308  }
1309
1310  // Build the instantiated method declaration.
1311  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1312  CXXMethodDecl *Method = 0;
1313
1314  DeclarationNameInfo NameInfo
1315    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1316  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1317    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1318                                        NameInfo, T, TInfo,
1319                                        Constructor->isExplicit(),
1320                                        Constructor->isInlineSpecified(),
1321                                        false);
1322  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1323    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1324                                       NameInfo, T, TInfo,
1325                                       Destructor->isInlineSpecified(),
1326                                       false);
1327  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1328    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1329                                       NameInfo, T, TInfo,
1330                                       Conversion->isInlineSpecified(),
1331                                       Conversion->isExplicit());
1332  } else {
1333    Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1334                                   NameInfo, T, TInfo,
1335                                   D->isStatic(),
1336                                   D->getStorageClassAsWritten(),
1337                                   D->isInlineSpecified());
1338  }
1339
1340  if (Qualifier)
1341    Method->setQualifierInfo(Qualifier, D->getQualifierRange());
1342
1343  if (TemplateParams) {
1344    // Our resulting instantiation is actually a function template, since we
1345    // are substituting only the outer template parameters. For example, given
1346    //
1347    //   template<typename T>
1348    //   struct X {
1349    //     template<typename U> void f(T, U);
1350    //   };
1351    //
1352    //   X<int> x;
1353    //
1354    // We are instantiating the member template "f" within X<int>, which means
1355    // substituting int for T, but leaving "f" as a member function template.
1356    // Build the function template itself.
1357    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1358                                                    Method->getLocation(),
1359                                                    Method->getDeclName(),
1360                                                    TemplateParams, Method);
1361    if (isFriend) {
1362      FunctionTemplate->setLexicalDeclContext(Owner);
1363      FunctionTemplate->setObjectOfFriendDecl(true);
1364    } else if (D->isOutOfLine())
1365      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1366    Method->setDescribedFunctionTemplate(FunctionTemplate);
1367  } else if (FunctionTemplate) {
1368    // Record this function template specialization.
1369    std::pair<const TemplateArgument *, unsigned> Innermost
1370      = TemplateArgs.getInnermost();
1371    Method->setFunctionTemplateSpecialization(FunctionTemplate,
1372                         TemplateArgumentList::CreateCopy(SemaRef.Context,
1373                                                          Innermost.first,
1374                                                          Innermost.second),
1375                                              InsertPos);
1376  } else if (!isFriend) {
1377    // Record that this is an instantiation of a member function.
1378    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1379  }
1380
1381  // If we are instantiating a member function defined
1382  // out-of-line, the instantiation will have the same lexical
1383  // context (which will be a namespace scope) as the template.
1384  if (isFriend) {
1385    if (NumTempParamLists)
1386      Method->setTemplateParameterListsInfo(SemaRef.Context,
1387                                            NumTempParamLists,
1388                                            TempParamLists.data());
1389
1390    Method->setLexicalDeclContext(Owner);
1391    Method->setObjectOfFriendDecl(true);
1392  } else if (D->isOutOfLine())
1393    Method->setLexicalDeclContext(D->getLexicalDeclContext());
1394
1395  // Attach the parameters
1396  for (unsigned P = 0; P < Params.size(); ++P)
1397    Params[P]->setOwningFunction(Method);
1398  Method->setParams(Params.data(), Params.size());
1399
1400  if (InitMethodInstantiation(Method, D))
1401    Method->setInvalidDecl();
1402
1403  LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1404                        Sema::ForRedeclaration);
1405
1406  if (!FunctionTemplate || TemplateParams || isFriend) {
1407    SemaRef.LookupQualifiedName(Previous, Record);
1408
1409    // In C++, the previous declaration we find might be a tag type
1410    // (class or enum). In this case, the new declaration will hide the
1411    // tag type. Note that this does does not apply if we're declaring a
1412    // typedef (C++ [dcl.typedef]p4).
1413    if (Previous.isSingleTagDecl())
1414      Previous.clear();
1415  }
1416
1417  bool Redeclaration = false;
1418  bool OverloadableAttrRequired = false;
1419  SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
1420                                   /*FIXME:*/OverloadableAttrRequired);
1421
1422  if (D->isPure())
1423    SemaRef.CheckPureMethod(Method, SourceRange());
1424
1425  Method->setAccess(D->getAccess());
1426
1427  if (FunctionTemplate) {
1428    // If there's a function template, let our caller handle it.
1429  } else if (Method->isInvalidDecl() && !Previous.empty()) {
1430    // Don't hide a (potentially) valid declaration with an invalid one.
1431  } else {
1432    NamedDecl *DeclToAdd = (TemplateParams
1433                            ? cast<NamedDecl>(FunctionTemplate)
1434                            : Method);
1435    if (isFriend)
1436      Record->makeDeclVisibleInContext(DeclToAdd);
1437    else
1438      Owner->addDecl(DeclToAdd);
1439  }
1440
1441  return Method;
1442}
1443
1444Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1445  return VisitCXXMethodDecl(D);
1446}
1447
1448Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1449  return VisitCXXMethodDecl(D);
1450}
1451
1452Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1453  return VisitCXXMethodDecl(D);
1454}
1455
1456ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1457  return SemaRef.SubstParmVarDecl(D, TemplateArgs);
1458}
1459
1460Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1461                                                    TemplateTypeParmDecl *D) {
1462  // TODO: don't always clone when decls are refcounted.
1463  const Type* T = D->getTypeForDecl();
1464  assert(T->isTemplateTypeParmType());
1465  const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
1466
1467  TemplateTypeParmDecl *Inst =
1468    TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1469                                 TTPT->getDepth() - TemplateArgs.getNumLevels(),
1470                                 TTPT->getIndex(), D->getIdentifier(),
1471                                 D->wasDeclaredWithTypename(),
1472                                 D->isParameterPack());
1473
1474  if (D->hasDefaultArgument())
1475    Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1476
1477  // Introduce this template parameter's instantiation into the instantiation
1478  // scope.
1479  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1480
1481  return Inst;
1482}
1483
1484Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1485                                                 NonTypeTemplateParmDecl *D) {
1486  // Substitute into the type of the non-type template parameter.
1487  QualType T;
1488  TypeSourceInfo *DI = D->getTypeSourceInfo();
1489  if (DI) {
1490    DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1491                           D->getDeclName());
1492    if (DI) T = DI->getType();
1493  } else {
1494    T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1495                          D->getDeclName());
1496    DI = 0;
1497  }
1498  if (T.isNull())
1499    return 0;
1500
1501  // Check that this type is acceptable for a non-type template parameter.
1502  bool Invalid = false;
1503  T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1504  if (T.isNull()) {
1505    T = SemaRef.Context.IntTy;
1506    Invalid = true;
1507  }
1508
1509  // FIXME: Variadic templates.
1510  NonTypeTemplateParmDecl *Param
1511    = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1512                                    D->getDepth() - TemplateArgs.getNumLevels(),
1513                                      D->getPosition(), D->getIdentifier(), T,
1514                                      D->isParameterPack(), DI);
1515  if (Invalid)
1516    Param->setInvalidDecl();
1517
1518  Param->setDefaultArgument(D->getDefaultArgument(), false);
1519
1520  // Introduce this template parameter's instantiation into the instantiation
1521  // scope.
1522  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1523  return Param;
1524}
1525
1526Decl *
1527TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1528                                                  TemplateTemplateParmDecl *D) {
1529  // Instantiate the template parameter list of the template template parameter.
1530  TemplateParameterList *TempParams = D->getTemplateParameters();
1531  TemplateParameterList *InstParams;
1532  {
1533    // Perform the actual substitution of template parameters within a new,
1534    // local instantiation scope.
1535    LocalInstantiationScope Scope(SemaRef);
1536    InstParams = SubstTemplateParams(TempParams);
1537    if (!InstParams)
1538      return NULL;
1539  }
1540
1541  // Build the template template parameter.
1542  TemplateTemplateParmDecl *Param
1543    = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1544                                   D->getDepth() - TemplateArgs.getNumLevels(),
1545                                       D->getPosition(), D->getIdentifier(),
1546                                       InstParams);
1547  Param->setDefaultArgument(D->getDefaultArgument(), false);
1548
1549  // Introduce this template parameter's instantiation into the instantiation
1550  // scope.
1551  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1552
1553  return Param;
1554}
1555
1556Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1557  // Using directives are never dependent, so they require no explicit
1558
1559  UsingDirectiveDecl *Inst
1560    = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1561                                 D->getNamespaceKeyLocation(),
1562                                 D->getQualifierRange(), D->getQualifier(),
1563                                 D->getIdentLocation(),
1564                                 D->getNominatedNamespace(),
1565                                 D->getCommonAncestor());
1566  Owner->addDecl(Inst);
1567  return Inst;
1568}
1569
1570Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1571
1572  // The nested name specifier may be dependent, for example
1573  //     template <typename T> struct t {
1574  //       struct s1 { T f1(); };
1575  //       struct s2 : s1 { using s1::f1; };
1576  //     };
1577  //     template struct t<int>;
1578  // Here, in using s1::f1, s1 refers to t<T>::s1;
1579  // we need to substitute for t<int>::s1.
1580  NestedNameSpecifier *NNS =
1581      SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameDecl(),
1582      D->getNestedNameRange(),
1583      TemplateArgs);
1584  if (!NNS)
1585      return 0;
1586
1587  // The name info is non-dependent, so no transformation
1588  // is required.
1589  DeclarationNameInfo NameInfo = D->getNameInfo();
1590
1591  // We only need to do redeclaration lookups if we're in a class
1592  // scope (in fact, it's not really even possible in non-class
1593  // scopes).
1594  bool CheckRedeclaration = Owner->isRecord();
1595
1596  LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1597                    Sema::ForRedeclaration);
1598
1599  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1600                                       D->getNestedNameRange(),
1601                                       D->getUsingLocation(),
1602                                       NNS,
1603                                       NameInfo,
1604                                       D->isTypeName());
1605
1606  CXXScopeSpec SS;
1607  SS.setScopeRep(NNS);
1608  SS.setRange(D->getNestedNameRange());
1609
1610  if (CheckRedeclaration) {
1611    Prev.setHideTags(false);
1612    SemaRef.LookupQualifiedName(Prev, Owner);
1613
1614    // Check for invalid redeclarations.
1615    if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1616                                            D->isTypeName(), SS,
1617                                            D->getLocation(), Prev))
1618      NewUD->setInvalidDecl();
1619
1620  }
1621
1622  if (!NewUD->isInvalidDecl() &&
1623      SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
1624                                      D->getLocation()))
1625    NewUD->setInvalidDecl();
1626
1627  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1628  NewUD->setAccess(D->getAccess());
1629  Owner->addDecl(NewUD);
1630
1631  // Don't process the shadow decls for an invalid decl.
1632  if (NewUD->isInvalidDecl())
1633    return NewUD;
1634
1635  bool isFunctionScope = Owner->isFunctionOrMethod();
1636
1637  // Process the shadow decls.
1638  for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1639         I != E; ++I) {
1640    UsingShadowDecl *Shadow = *I;
1641    NamedDecl *InstTarget =
1642      cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1643                                                   Shadow->getTargetDecl(),
1644                                                   TemplateArgs));
1645
1646    if (CheckRedeclaration &&
1647        SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1648      continue;
1649
1650    UsingShadowDecl *InstShadow
1651      = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1652    SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
1653
1654    if (isFunctionScope)
1655      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
1656  }
1657
1658  return NewUD;
1659}
1660
1661Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
1662  // Ignore these;  we handle them in bulk when processing the UsingDecl.
1663  return 0;
1664}
1665
1666Decl * TemplateDeclInstantiator
1667    ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1668  NestedNameSpecifier *NNS =
1669    SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1670                                     D->getTargetNestedNameRange(),
1671                                     TemplateArgs);
1672  if (!NNS)
1673    return 0;
1674
1675  CXXScopeSpec SS;
1676  SS.setRange(D->getTargetNestedNameRange());
1677  SS.setScopeRep(NNS);
1678
1679  // Since NameInfo refers to a typename, it cannot be a C++ special name.
1680  // Hence, no tranformation is required for it.
1681  DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
1682  NamedDecl *UD =
1683    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1684                                  D->getUsingLoc(), SS, NameInfo, 0,
1685                                  /*instantiation*/ true,
1686                                  /*typename*/ true, D->getTypenameLoc());
1687  if (UD)
1688    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1689
1690  return UD;
1691}
1692
1693Decl * TemplateDeclInstantiator
1694    ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1695  NestedNameSpecifier *NNS =
1696    SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1697                                     D->getTargetNestedNameRange(),
1698                                     TemplateArgs);
1699  if (!NNS)
1700    return 0;
1701
1702  CXXScopeSpec SS;
1703  SS.setRange(D->getTargetNestedNameRange());
1704  SS.setScopeRep(NNS);
1705
1706  DeclarationNameInfo NameInfo
1707    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1708
1709  NamedDecl *UD =
1710    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1711                                  D->getUsingLoc(), SS, NameInfo, 0,
1712                                  /*instantiation*/ true,
1713                                  /*typename*/ false, SourceLocation());
1714  if (UD)
1715    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1716
1717  return UD;
1718}
1719
1720Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
1721                      const MultiLevelTemplateArgumentList &TemplateArgs) {
1722  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
1723  if (D->isInvalidDecl())
1724    return 0;
1725
1726  return Instantiator.Visit(D);
1727}
1728
1729/// \brief Instantiates a nested template parameter list in the current
1730/// instantiation context.
1731///
1732/// \param L The parameter list to instantiate
1733///
1734/// \returns NULL if there was an error
1735TemplateParameterList *
1736TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
1737  // Get errors for all the parameters before bailing out.
1738  bool Invalid = false;
1739
1740  unsigned N = L->size();
1741  typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
1742  ParamVector Params;
1743  Params.reserve(N);
1744  for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1745       PI != PE; ++PI) {
1746    NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
1747    Params.push_back(D);
1748    Invalid = Invalid || !D || D->isInvalidDecl();
1749  }
1750
1751  // Clean up if we had an error.
1752  if (Invalid)
1753    return NULL;
1754
1755  TemplateParameterList *InstL
1756    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1757                                    L->getLAngleLoc(), &Params.front(), N,
1758                                    L->getRAngleLoc());
1759  return InstL;
1760}
1761
1762/// \brief Instantiate the declaration of a class template partial
1763/// specialization.
1764///
1765/// \param ClassTemplate the (instantiated) class template that is partially
1766// specialized by the instantiation of \p PartialSpec.
1767///
1768/// \param PartialSpec the (uninstantiated) class template partial
1769/// specialization that we are instantiating.
1770///
1771/// \returns The instantiated partial specialization, if successful; otherwise,
1772/// NULL to indicate an error.
1773ClassTemplatePartialSpecializationDecl *
1774TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1775                                            ClassTemplateDecl *ClassTemplate,
1776                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
1777  // Create a local instantiation scope for this class template partial
1778  // specialization, which will contain the instantiations of the template
1779  // parameters.
1780  LocalInstantiationScope Scope(SemaRef);
1781
1782  // Substitute into the template parameters of the class template partial
1783  // specialization.
1784  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1785  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1786  if (!InstParams)
1787    return 0;
1788
1789  // Substitute into the template arguments of the class template partial
1790  // specialization.
1791  TemplateArgumentListInfo InstTemplateArgs; // no angle locations
1792  if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
1793                    PartialSpec->getNumTemplateArgsAsWritten(),
1794                    InstTemplateArgs, TemplateArgs))
1795    return 0;
1796
1797  // Check that the template argument list is well-formed for this
1798  // class template.
1799  llvm::SmallVector<TemplateArgument, 4> Converted;
1800  if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1801                                        PartialSpec->getLocation(),
1802                                        InstTemplateArgs,
1803                                        false,
1804                                        Converted))
1805    return 0;
1806
1807  // Figure out where to insert this class template partial specialization
1808  // in the member template's set of class template partial specializations.
1809  void *InsertPos = 0;
1810  ClassTemplateSpecializationDecl *PrevDecl
1811    = ClassTemplate->findPartialSpecialization(Converted.data(),
1812                                               Converted.size(), InsertPos);
1813
1814  // Build the canonical type that describes the converted template
1815  // arguments of the class template partial specialization.
1816  QualType CanonType
1817    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1818                                                    Converted.data(),
1819                                                    Converted.size());
1820
1821  // Build the fully-sugared type for this class template
1822  // specialization as the user wrote in the specialization
1823  // itself. This means that we'll pretty-print the type retrieved
1824  // from the specialization's declaration the way that the user
1825  // actually wrote the specialization, rather than formatting the
1826  // name based on the "canonical" representation used to store the
1827  // template arguments in the specialization.
1828  TypeSourceInfo *WrittenTy
1829    = SemaRef.Context.getTemplateSpecializationTypeInfo(
1830                                                    TemplateName(ClassTemplate),
1831                                                    PartialSpec->getLocation(),
1832                                                    InstTemplateArgs,
1833                                                    CanonType);
1834
1835  if (PrevDecl) {
1836    // We've already seen a partial specialization with the same template
1837    // parameters and template arguments. This can happen, for example, when
1838    // substituting the outer template arguments ends up causing two
1839    // class template partial specializations of a member class template
1840    // to have identical forms, e.g.,
1841    //
1842    //   template<typename T, typename U>
1843    //   struct Outer {
1844    //     template<typename X, typename Y> struct Inner;
1845    //     template<typename Y> struct Inner<T, Y>;
1846    //     template<typename Y> struct Inner<U, Y>;
1847    //   };
1848    //
1849    //   Outer<int, int> outer; // error: the partial specializations of Inner
1850    //                          // have the same signature.
1851    SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1852      << WrittenTy->getType();
1853    SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1854      << SemaRef.Context.getTypeDeclType(PrevDecl);
1855    return 0;
1856  }
1857
1858
1859  // Create the class template partial specialization declaration.
1860  ClassTemplatePartialSpecializationDecl *InstPartialSpec
1861    = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1862                                                     PartialSpec->getTagKind(),
1863                                                     Owner,
1864                                                     PartialSpec->getLocation(),
1865                                                     InstParams,
1866                                                     ClassTemplate,
1867                                                     Converted.data(),
1868                                                     Converted.size(),
1869                                                     InstTemplateArgs,
1870                                                     CanonType,
1871                                                     0,
1872                             ClassTemplate->getNextPartialSpecSequenceNumber());
1873  // Substitute the nested name specifier, if any.
1874  if (SubstQualifier(PartialSpec, InstPartialSpec))
1875    return 0;
1876
1877  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1878  InstPartialSpec->setTypeAsWritten(WrittenTy);
1879
1880  // Add this partial specialization to the set of class template partial
1881  // specializations.
1882  ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
1883  return InstPartialSpec;
1884}
1885
1886TypeSourceInfo*
1887TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
1888                              llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1889  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1890  assert(OldTInfo && "substituting function without type source info");
1891  assert(Params.empty() && "parameter vector is non-empty at start");
1892  TypeSourceInfo *NewTInfo
1893    = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1894                                    D->getTypeSpecStartLoc(),
1895                                    D->getDeclName());
1896  if (!NewTInfo)
1897    return 0;
1898
1899  if (NewTInfo != OldTInfo) {
1900    // Get parameters from the new type info.
1901    TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
1902    if (FunctionProtoTypeLoc *OldProtoLoc
1903                                  = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1904      TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
1905      FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1906      assert(NewProtoLoc && "Missing prototype?");
1907      for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1908        // FIXME: Variadic templates will break this.
1909        Params.push_back(NewProtoLoc->getArg(i));
1910        SemaRef.CurrentInstantiationScope->InstantiatedLocal(
1911                                                        OldProtoLoc->getArg(i),
1912                                                        NewProtoLoc->getArg(i));
1913      }
1914    }
1915  } else {
1916    // The function type itself was not dependent and therefore no
1917    // substitution occurred. However, we still need to instantiate
1918    // the function parameters themselves.
1919    TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
1920    if (FunctionProtoTypeLoc *OldProtoLoc
1921                                    = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1922      for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1923        ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1924        if (!Parm)
1925          return 0;
1926        Params.push_back(Parm);
1927      }
1928    }
1929  }
1930  return NewTInfo;
1931}
1932
1933/// \brief Initializes the common fields of an instantiation function
1934/// declaration (New) from the corresponding fields of its template (Tmpl).
1935///
1936/// \returns true if there was an error
1937bool
1938TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
1939                                                    FunctionDecl *Tmpl) {
1940  if (Tmpl->isDeleted())
1941    New->setDeleted();
1942
1943  // If we are performing substituting explicitly-specified template arguments
1944  // or deduced template arguments into a function template and we reach this
1945  // point, we are now past the point where SFINAE applies and have committed
1946  // to keeping the new function template specialization. We therefore
1947  // convert the active template instantiation for the function template
1948  // into a template instantiation for this specific function template
1949  // specialization, which is not a SFINAE context, so that we diagnose any
1950  // further errors in the declaration itself.
1951  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1952  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1953  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1954      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
1955    if (FunctionTemplateDecl *FunTmpl
1956          = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
1957      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
1958             "Deduction from the wrong function template?");
1959      (void) FunTmpl;
1960      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1961      ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
1962      --SemaRef.NonInstantiationEntries;
1963    }
1964  }
1965
1966  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1967  assert(Proto && "Function template without prototype?");
1968
1969  if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1970      Proto->getNoReturnAttr()) {
1971    // The function has an exception specification or a "noreturn"
1972    // attribute. Substitute into each of the exception types.
1973    llvm::SmallVector<QualType, 4> Exceptions;
1974    for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1975      // FIXME: Poor location information!
1976      if (const PackExpansionType *PackExpansion
1977            = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
1978        // We have a pack expansion. Instantiate it.
1979        llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1980        SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
1981                                                Unexpanded);
1982        assert(!Unexpanded.empty() &&
1983               "Pack expansion without parameter packs?");
1984
1985        bool Expand = false;
1986        unsigned NumExpansions = 0;
1987        if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
1988                                                    SourceRange(),
1989                                                    Unexpanded.data(),
1990                                                    Unexpanded.size(),
1991                                                    TemplateArgs,
1992                                                    Expand, NumExpansions))
1993          break;
1994
1995        if (!Expand) {
1996          // We can't expand this pack expansion into separate arguments yet;
1997          // just substitute into the argument pack.
1998          Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1999          QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2000                                         TemplateArgs,
2001                                       New->getLocation(), New->getDeclName());
2002          if (T.isNull())
2003            break;
2004
2005          Exceptions.push_back(T);
2006          continue;
2007        }
2008
2009        // Substitute into the pack expansion pattern for each template
2010        bool Invalid = false;
2011        for (unsigned ArgIdx = 0; ArgIdx != NumExpansions; ++ArgIdx) {
2012          Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2013
2014          QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2015                                         TemplateArgs,
2016                                       New->getLocation(), New->getDeclName());
2017          if (T.isNull()) {
2018            Invalid = true;
2019            break;
2020          }
2021
2022          Exceptions.push_back(T);
2023        }
2024
2025        if (Invalid)
2026          break;
2027
2028        continue;
2029      }
2030
2031      QualType T
2032        = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2033                            New->getLocation(), New->getDeclName());
2034      if (T.isNull() ||
2035          SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2036        continue;
2037
2038      Exceptions.push_back(T);
2039    }
2040
2041    // Rebuild the function type
2042
2043    FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2044    EPI.HasExceptionSpec = Proto->hasExceptionSpec();
2045    EPI.HasAnyExceptionSpec = Proto->hasAnyExceptionSpec();
2046    EPI.NumExceptions = Exceptions.size();
2047    EPI.Exceptions = Exceptions.data();
2048    EPI.ExtInfo = Proto->getExtInfo();
2049
2050    const FunctionProtoType *NewProto
2051      = New->getType()->getAs<FunctionProtoType>();
2052    assert(NewProto && "Template instantiation without function prototype?");
2053    New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2054                                                 NewProto->arg_type_begin(),
2055                                                 NewProto->getNumArgs(),
2056                                                 EPI));
2057  }
2058
2059  SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
2060
2061  return false;
2062}
2063
2064/// \brief Initializes common fields of an instantiated method
2065/// declaration (New) from the corresponding fields of its template
2066/// (Tmpl).
2067///
2068/// \returns true if there was an error
2069bool
2070TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
2071                                                  CXXMethodDecl *Tmpl) {
2072  if (InitFunctionInstantiation(New, Tmpl))
2073    return true;
2074
2075  New->setAccess(Tmpl->getAccess());
2076  if (Tmpl->isVirtualAsWritten())
2077    New->setVirtualAsWritten(true);
2078
2079  // FIXME: attributes
2080  // FIXME: New needs a pointer to Tmpl
2081  return false;
2082}
2083
2084/// \brief Instantiate the definition of the given function from its
2085/// template.
2086///
2087/// \param PointOfInstantiation the point at which the instantiation was
2088/// required. Note that this is not precisely a "point of instantiation"
2089/// for the function, but it's close.
2090///
2091/// \param Function the already-instantiated declaration of a
2092/// function template specialization or member function of a class template
2093/// specialization.
2094///
2095/// \param Recursive if true, recursively instantiates any functions that
2096/// are required by this instantiation.
2097///
2098/// \param DefinitionRequired if true, then we are performing an explicit
2099/// instantiation where the body of the function is required. Complain if
2100/// there is no such body.
2101void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
2102                                         FunctionDecl *Function,
2103                                         bool Recursive,
2104                                         bool DefinitionRequired) {
2105  if (Function->isInvalidDecl() || Function->hasBody())
2106    return;
2107
2108  // Never instantiate an explicit specialization.
2109  if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2110    return;
2111
2112  // Find the function body that we'll be substituting.
2113  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
2114  Stmt *Pattern = 0;
2115  if (PatternDecl)
2116    Pattern = PatternDecl->getBody(PatternDecl);
2117
2118  if (!Pattern) {
2119    if (DefinitionRequired) {
2120      if (Function->getPrimaryTemplate())
2121        Diag(PointOfInstantiation,
2122             diag::err_explicit_instantiation_undefined_func_template)
2123          << Function->getPrimaryTemplate();
2124      else
2125        Diag(PointOfInstantiation,
2126             diag::err_explicit_instantiation_undefined_member)
2127          << 1 << Function->getDeclName() << Function->getDeclContext();
2128
2129      if (PatternDecl)
2130        Diag(PatternDecl->getLocation(),
2131             diag::note_explicit_instantiation_here);
2132      Function->setInvalidDecl();
2133    } else if (Function->getTemplateSpecializationKind()
2134                 == TSK_ExplicitInstantiationDefinition) {
2135      PendingInstantiations.push_back(
2136        std::make_pair(Function, PointOfInstantiation));
2137    }
2138
2139    return;
2140  }
2141
2142  // C++0x [temp.explicit]p9:
2143  //   Except for inline functions, other explicit instantiation declarations
2144  //   have the effect of suppressing the implicit instantiation of the entity
2145  //   to which they refer.
2146  if (Function->getTemplateSpecializationKind()
2147        == TSK_ExplicitInstantiationDeclaration &&
2148      !PatternDecl->isInlined())
2149    return;
2150
2151  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2152  if (Inst)
2153    return;
2154
2155  // If we're performing recursive template instantiation, create our own
2156  // queue of pending implicit instantiations that we will instantiate later,
2157  // while we're still within our own instantiation context.
2158  llvm::SmallVector<VTableUse, 16> SavedVTableUses;
2159  std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2160  if (Recursive) {
2161    VTableUses.swap(SavedVTableUses);
2162    PendingInstantiations.swap(SavedPendingInstantiations);
2163  }
2164
2165  EnterExpressionEvaluationContext EvalContext(*this,
2166                                               Sema::PotentiallyEvaluated);
2167  ActOnStartOfFunctionDef(0, Function);
2168
2169  // Introduce a new scope where local variable instantiations will be
2170  // recorded, unless we're actually a member function within a local
2171  // class, in which case we need to merge our results with the parent
2172  // scope (of the enclosing function).
2173  bool MergeWithParentScope = false;
2174  if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2175    MergeWithParentScope = Rec->isLocalClass();
2176
2177  LocalInstantiationScope Scope(*this, MergeWithParentScope);
2178
2179  // Introduce the instantiated function parameters into the local
2180  // instantiation scope, and set the parameter names to those used
2181  // in the template.
2182  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2183    const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2184    ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2185    FunctionParam->setDeclName(PatternParam->getDeclName());
2186    Scope.InstantiatedLocal(PatternParam, FunctionParam);
2187  }
2188
2189  // Enter the scope of this instantiation. We don't use
2190  // PushDeclContext because we don't have a scope.
2191  DeclContext *PreviousContext = CurContext;
2192  CurContext = Function;
2193
2194  MultiLevelTemplateArgumentList TemplateArgs =
2195    getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2196
2197  // If this is a constructor, instantiate the member initializers.
2198  if (const CXXConstructorDecl *Ctor =
2199        dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2200    InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2201                               TemplateArgs);
2202  }
2203
2204  // Instantiate the function body.
2205  StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2206
2207  if (Body.isInvalid())
2208    Function->setInvalidDecl();
2209
2210  ActOnFinishFunctionBody(Function, Body.get(),
2211                          /*IsInstantiation=*/true);
2212
2213  PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2214
2215  CurContext = PreviousContext;
2216
2217  DeclGroupRef DG(Function);
2218  Consumer.HandleTopLevelDecl(DG);
2219
2220  // This class may have local implicit instantiations that need to be
2221  // instantiation within this scope.
2222  PerformPendingInstantiations(/*LocalOnly=*/true);
2223  Scope.Exit();
2224
2225  if (Recursive) {
2226    // Define any pending vtables.
2227    DefineUsedVTables();
2228
2229    // Instantiate any pending implicit instantiations found during the
2230    // instantiation of this template.
2231    PerformPendingInstantiations();
2232
2233    // Restore the set of pending vtables.
2234    VTableUses.swap(SavedVTableUses);
2235
2236    // Restore the set of pending implicit instantiations.
2237    PendingInstantiations.swap(SavedPendingInstantiations);
2238  }
2239}
2240
2241/// \brief Instantiate the definition of the given variable from its
2242/// template.
2243///
2244/// \param PointOfInstantiation the point at which the instantiation was
2245/// required. Note that this is not precisely a "point of instantiation"
2246/// for the function, but it's close.
2247///
2248/// \param Var the already-instantiated declaration of a static member
2249/// variable of a class template specialization.
2250///
2251/// \param Recursive if true, recursively instantiates any functions that
2252/// are required by this instantiation.
2253///
2254/// \param DefinitionRequired if true, then we are performing an explicit
2255/// instantiation where an out-of-line definition of the member variable
2256/// is required. Complain if there is no such definition.
2257void Sema::InstantiateStaticDataMemberDefinition(
2258                                          SourceLocation PointOfInstantiation,
2259                                                 VarDecl *Var,
2260                                                 bool Recursive,
2261                                                 bool DefinitionRequired) {
2262  if (Var->isInvalidDecl())
2263    return;
2264
2265  // Find the out-of-line definition of this static data member.
2266  VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
2267  assert(Def && "This data member was not instantiated from a template?");
2268  assert(Def->isStaticDataMember() && "Not a static data member?");
2269  Def = Def->getOutOfLineDefinition();
2270
2271  if (!Def) {
2272    // We did not find an out-of-line definition of this static data member,
2273    // so we won't perform any instantiation. Rather, we rely on the user to
2274    // instantiate this definition (or provide a specialization for it) in
2275    // another translation unit.
2276    if (DefinitionRequired) {
2277      Def = Var->getInstantiatedFromStaticDataMember();
2278      Diag(PointOfInstantiation,
2279           diag::err_explicit_instantiation_undefined_member)
2280        << 2 << Var->getDeclName() << Var->getDeclContext();
2281      Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2282    } else if (Var->getTemplateSpecializationKind()
2283                 == TSK_ExplicitInstantiationDefinition) {
2284      PendingInstantiations.push_back(
2285        std::make_pair(Var, PointOfInstantiation));
2286    }
2287
2288    return;
2289  }
2290
2291  // Never instantiate an explicit specialization.
2292  if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2293    return;
2294
2295  // C++0x [temp.explicit]p9:
2296  //   Except for inline functions, other explicit instantiation declarations
2297  //   have the effect of suppressing the implicit instantiation of the entity
2298  //   to which they refer.
2299  if (Var->getTemplateSpecializationKind()
2300        == TSK_ExplicitInstantiationDeclaration)
2301    return;
2302
2303  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2304  if (Inst)
2305    return;
2306
2307  // If we're performing recursive template instantiation, create our own
2308  // queue of pending implicit instantiations that we will instantiate later,
2309  // while we're still within our own instantiation context.
2310  std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2311  if (Recursive)
2312    PendingInstantiations.swap(SavedPendingInstantiations);
2313
2314  // Enter the scope of this instantiation. We don't use
2315  // PushDeclContext because we don't have a scope.
2316  DeclContext *PreviousContext = CurContext;
2317  CurContext = Var->getDeclContext();
2318
2319  VarDecl *OldVar = Var;
2320  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
2321                                        getTemplateInstantiationArgs(Var)));
2322  CurContext = PreviousContext;
2323
2324  if (Var) {
2325    MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2326    assert(MSInfo && "Missing member specialization information?");
2327    Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2328                                       MSInfo->getPointOfInstantiation());
2329    DeclGroupRef DG(Var);
2330    Consumer.HandleTopLevelDecl(DG);
2331  }
2332
2333  if (Recursive) {
2334    // Instantiate any pending implicit instantiations found during the
2335    // instantiation of this template.
2336    PerformPendingInstantiations();
2337
2338    // Restore the set of pending implicit instantiations.
2339    PendingInstantiations.swap(SavedPendingInstantiations);
2340  }
2341}
2342
2343void
2344Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2345                                 const CXXConstructorDecl *Tmpl,
2346                           const MultiLevelTemplateArgumentList &TemplateArgs) {
2347
2348  llvm::SmallVector<MemInitTy*, 4> NewInits;
2349  bool AnyErrors = false;
2350
2351  // Instantiate all the initializers.
2352  for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
2353                                            InitsEnd = Tmpl->init_end();
2354       Inits != InitsEnd; ++Inits) {
2355    CXXBaseOrMemberInitializer *Init = *Inits;
2356
2357    // Only instantiate written initializers, let Sema re-construct implicit
2358    // ones.
2359    if (!Init->isWritten())
2360      continue;
2361
2362    SourceLocation LParenLoc, RParenLoc;
2363    ASTOwningVector<Expr*> NewArgs(*this);
2364
2365    SourceLocation EllipsisLoc;
2366
2367    if (Init->isPackExpansion()) {
2368      // This is a pack expansion. We should expand it now.
2369      TypeLoc BaseTL = Init->getBaseClassInfo()->getTypeLoc();
2370      llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2371      collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2372      bool ShouldExpand = false;
2373      unsigned NumExpansions = 0;
2374      if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2375                                          BaseTL.getSourceRange(),
2376                                          Unexpanded.data(),
2377                                          Unexpanded.size(),
2378                                          TemplateArgs, ShouldExpand,
2379                                          NumExpansions)) {
2380        AnyErrors = true;
2381        New->setInvalidDecl();
2382        continue;
2383      }
2384      assert(ShouldExpand && "Partial instantiation of base initializer?");
2385
2386      // Loop over all of the arguments in the argument pack(s),
2387      for (unsigned I = 0; I != NumExpansions; ++I) {
2388        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2389
2390        // Instantiate the initializer.
2391        if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2392                                   LParenLoc, NewArgs, RParenLoc)) {
2393          AnyErrors = true;
2394          break;
2395        }
2396
2397        // Instantiate the base type.
2398        TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2399                                              TemplateArgs,
2400                                              Init->getSourceLocation(),
2401                                              New->getDeclName());
2402        if (!BaseTInfo) {
2403          AnyErrors = true;
2404          break;
2405        }
2406
2407        // Build the initializer.
2408        MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2409                                                     BaseTInfo,
2410                                                     (Expr **)NewArgs.data(),
2411                                                     NewArgs.size(),
2412                                                     Init->getLParenLoc(),
2413                                                     Init->getRParenLoc(),
2414                                                     New->getParent(),
2415                                                     SourceLocation());
2416        if (NewInit.isInvalid()) {
2417          AnyErrors = true;
2418          break;
2419        }
2420
2421        NewInits.push_back(NewInit.get());
2422        NewArgs.clear();
2423      }
2424
2425      continue;
2426    }
2427
2428    // Instantiate the initializer.
2429    if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2430                               LParenLoc, NewArgs, RParenLoc)) {
2431      AnyErrors = true;
2432      continue;
2433    }
2434
2435    MemInitResult NewInit;
2436    if (Init->isBaseInitializer()) {
2437      TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2438                                            TemplateArgs,
2439                                            Init->getSourceLocation(),
2440                                            New->getDeclName());
2441      if (!BaseTInfo) {
2442        AnyErrors = true;
2443        New->setInvalidDecl();
2444        continue;
2445      }
2446
2447      NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
2448                                     (Expr **)NewArgs.data(),
2449                                     NewArgs.size(),
2450                                     Init->getLParenLoc(),
2451                                     Init->getRParenLoc(),
2452                                     New->getParent(),
2453                                     EllipsisLoc);
2454    } else if (Init->isMemberInitializer()) {
2455      FieldDecl *Member = cast<FieldDecl>(FindInstantiatedDecl(
2456                                                     Init->getMemberLocation(),
2457                                                     Init->getMember(),
2458                                                     TemplateArgs));
2459
2460      NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
2461                                       NewArgs.size(),
2462                                       Init->getSourceLocation(),
2463                                       Init->getLParenLoc(),
2464                                       Init->getRParenLoc());
2465    } else if (Init->isIndirectMemberInitializer()) {
2466      IndirectFieldDecl *IndirectMember =
2467         cast<IndirectFieldDecl>(FindInstantiatedDecl(
2468                                 Init->getMemberLocation(),
2469                                 Init->getIndirectMember(), TemplateArgs));
2470
2471      NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(),
2472                                       NewArgs.size(),
2473                                       Init->getSourceLocation(),
2474                                       Init->getLParenLoc(),
2475                                       Init->getRParenLoc());
2476    }
2477
2478    if (NewInit.isInvalid()) {
2479      AnyErrors = true;
2480      New->setInvalidDecl();
2481    } else {
2482      // FIXME: It would be nice if ASTOwningVector had a release function.
2483      NewArgs.take();
2484
2485      NewInits.push_back((MemInitTy *)NewInit.get());
2486    }
2487  }
2488
2489  // Assign all the initializers to the new constructor.
2490  ActOnMemInitializers(New,
2491                       /*FIXME: ColonLoc */
2492                       SourceLocation(),
2493                       NewInits.data(), NewInits.size(),
2494                       AnyErrors);
2495}
2496
2497// TODO: this could be templated if the various decl types used the
2498// same method name.
2499static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2500                              ClassTemplateDecl *Instance) {
2501  Pattern = Pattern->getCanonicalDecl();
2502
2503  do {
2504    Instance = Instance->getCanonicalDecl();
2505    if (Pattern == Instance) return true;
2506    Instance = Instance->getInstantiatedFromMemberTemplate();
2507  } while (Instance);
2508
2509  return false;
2510}
2511
2512static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2513                              FunctionTemplateDecl *Instance) {
2514  Pattern = Pattern->getCanonicalDecl();
2515
2516  do {
2517    Instance = Instance->getCanonicalDecl();
2518    if (Pattern == Instance) return true;
2519    Instance = Instance->getInstantiatedFromMemberTemplate();
2520  } while (Instance);
2521
2522  return false;
2523}
2524
2525static bool
2526isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2527                  ClassTemplatePartialSpecializationDecl *Instance) {
2528  Pattern
2529    = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2530  do {
2531    Instance = cast<ClassTemplatePartialSpecializationDecl>(
2532                                                Instance->getCanonicalDecl());
2533    if (Pattern == Instance)
2534      return true;
2535    Instance = Instance->getInstantiatedFromMember();
2536  } while (Instance);
2537
2538  return false;
2539}
2540
2541static bool isInstantiationOf(CXXRecordDecl *Pattern,
2542                              CXXRecordDecl *Instance) {
2543  Pattern = Pattern->getCanonicalDecl();
2544
2545  do {
2546    Instance = Instance->getCanonicalDecl();
2547    if (Pattern == Instance) return true;
2548    Instance = Instance->getInstantiatedFromMemberClass();
2549  } while (Instance);
2550
2551  return false;
2552}
2553
2554static bool isInstantiationOf(FunctionDecl *Pattern,
2555                              FunctionDecl *Instance) {
2556  Pattern = Pattern->getCanonicalDecl();
2557
2558  do {
2559    Instance = Instance->getCanonicalDecl();
2560    if (Pattern == Instance) return true;
2561    Instance = Instance->getInstantiatedFromMemberFunction();
2562  } while (Instance);
2563
2564  return false;
2565}
2566
2567static bool isInstantiationOf(EnumDecl *Pattern,
2568                              EnumDecl *Instance) {
2569  Pattern = Pattern->getCanonicalDecl();
2570
2571  do {
2572    Instance = Instance->getCanonicalDecl();
2573    if (Pattern == Instance) return true;
2574    Instance = Instance->getInstantiatedFromMemberEnum();
2575  } while (Instance);
2576
2577  return false;
2578}
2579
2580static bool isInstantiationOf(UsingShadowDecl *Pattern,
2581                              UsingShadowDecl *Instance,
2582                              ASTContext &C) {
2583  return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2584}
2585
2586static bool isInstantiationOf(UsingDecl *Pattern,
2587                              UsingDecl *Instance,
2588                              ASTContext &C) {
2589  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2590}
2591
2592static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2593                              UsingDecl *Instance,
2594                              ASTContext &C) {
2595  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2596}
2597
2598static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
2599                              UsingDecl *Instance,
2600                              ASTContext &C) {
2601  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2602}
2603
2604static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2605                                              VarDecl *Instance) {
2606  assert(Instance->isStaticDataMember());
2607
2608  Pattern = Pattern->getCanonicalDecl();
2609
2610  do {
2611    Instance = Instance->getCanonicalDecl();
2612    if (Pattern == Instance) return true;
2613    Instance = Instance->getInstantiatedFromStaticDataMember();
2614  } while (Instance);
2615
2616  return false;
2617}
2618
2619// Other is the prospective instantiation
2620// D is the prospective pattern
2621static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
2622  if (D->getKind() != Other->getKind()) {
2623    if (UnresolvedUsingTypenameDecl *UUD
2624          = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2625      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2626        return isInstantiationOf(UUD, UD, Ctx);
2627      }
2628    }
2629
2630    if (UnresolvedUsingValueDecl *UUD
2631          = dyn_cast<UnresolvedUsingValueDecl>(D)) {
2632      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2633        return isInstantiationOf(UUD, UD, Ctx);
2634      }
2635    }
2636
2637    return false;
2638  }
2639
2640  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2641    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
2642
2643  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2644    return isInstantiationOf(cast<FunctionDecl>(D), Function);
2645
2646  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2647    return isInstantiationOf(cast<EnumDecl>(D), Enum);
2648
2649  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
2650    if (Var->isStaticDataMember())
2651      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2652
2653  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2654    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
2655
2656  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2657    return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2658
2659  if (ClassTemplatePartialSpecializationDecl *PartialSpec
2660        = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2661    return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2662                             PartialSpec);
2663
2664  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2665    if (!Field->getDeclName()) {
2666      // This is an unnamed field.
2667      return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
2668        cast<FieldDecl>(D);
2669    }
2670  }
2671
2672  if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2673    return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2674
2675  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2676    return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2677
2678  return D->getDeclName() && isa<NamedDecl>(Other) &&
2679    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2680}
2681
2682template<typename ForwardIterator>
2683static NamedDecl *findInstantiationOf(ASTContext &Ctx,
2684                                      NamedDecl *D,
2685                                      ForwardIterator first,
2686                                      ForwardIterator last) {
2687  for (; first != last; ++first)
2688    if (isInstantiationOf(Ctx, D, *first))
2689      return cast<NamedDecl>(*first);
2690
2691  return 0;
2692}
2693
2694/// \brief Finds the instantiation of the given declaration context
2695/// within the current instantiation.
2696///
2697/// \returns NULL if there was an error
2698DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
2699                          const MultiLevelTemplateArgumentList &TemplateArgs) {
2700  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
2701    Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
2702    return cast_or_null<DeclContext>(ID);
2703  } else return DC;
2704}
2705
2706/// \brief Find the instantiation of the given declaration within the
2707/// current instantiation.
2708///
2709/// This routine is intended to be used when \p D is a declaration
2710/// referenced from within a template, that needs to mapped into the
2711/// corresponding declaration within an instantiation. For example,
2712/// given:
2713///
2714/// \code
2715/// template<typename T>
2716/// struct X {
2717///   enum Kind {
2718///     KnownValue = sizeof(T)
2719///   };
2720///
2721///   bool getKind() const { return KnownValue; }
2722/// };
2723///
2724/// template struct X<int>;
2725/// \endcode
2726///
2727/// In the instantiation of X<int>::getKind(), we need to map the
2728/// EnumConstantDecl for KnownValue (which refers to
2729/// X<T>::<Kind>::KnownValue) to its instantiation
2730/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2731/// this mapping from within the instantiation of X<int>.
2732NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
2733                          const MultiLevelTemplateArgumentList &TemplateArgs) {
2734  DeclContext *ParentDC = D->getDeclContext();
2735  if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2736      isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
2737      (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
2738    // D is a local of some kind. Look into the map of local
2739    // declarations to their instantiations.
2740    return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2741  }
2742
2743  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2744    if (!Record->isDependentContext())
2745      return D;
2746
2747    // If the RecordDecl is actually the injected-class-name or a
2748    // "templated" declaration for a class template, class template
2749    // partial specialization, or a member class of a class template,
2750    // substitute into the injected-class-name of the class template
2751    // or partial specialization to find the new DeclContext.
2752    QualType T;
2753    ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2754
2755    if (ClassTemplate) {
2756      T = ClassTemplate->getInjectedClassNameSpecialization();
2757    } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2758                 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2759      ClassTemplate = PartialSpec->getSpecializedTemplate();
2760
2761      // If we call SubstType with an InjectedClassNameType here we
2762      // can end up in an infinite loop.
2763      T = Context.getTypeDeclType(Record);
2764      assert(isa<InjectedClassNameType>(T) &&
2765             "type of partial specialization is not an InjectedClassNameType");
2766      T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
2767    }
2768
2769    if (!T.isNull()) {
2770      // Substitute into the injected-class-name to get the type
2771      // corresponding to the instantiation we want, which may also be
2772      // the current instantiation (if we're in a template
2773      // definition). This substitution should never fail, since we
2774      // know we can instantiate the injected-class-name or we
2775      // wouldn't have gotten to the injected-class-name!
2776
2777      // FIXME: Can we use the CurrentInstantiationScope to avoid this
2778      // extra instantiation in the common case?
2779      T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2780      assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2781
2782      if (!T->isDependentType()) {
2783        assert(T->isRecordType() && "Instantiation must produce a record type");
2784        return T->getAs<RecordType>()->getDecl();
2785      }
2786
2787      // We are performing "partial" template instantiation to create
2788      // the member declarations for the members of a class template
2789      // specialization. Therefore, D is actually referring to something
2790      // in the current instantiation. Look through the current
2791      // context, which contains actual instantiations, to find the
2792      // instantiation of the "current instantiation" that D refers
2793      // to.
2794      bool SawNonDependentContext = false;
2795      for (DeclContext *DC = CurContext; !DC->isFileContext();
2796           DC = DC->getParent()) {
2797        if (ClassTemplateSpecializationDecl *Spec
2798                          = dyn_cast<ClassTemplateSpecializationDecl>(DC))
2799          if (isInstantiationOf(ClassTemplate,
2800                                Spec->getSpecializedTemplate()))
2801            return Spec;
2802
2803        if (!DC->isDependentContext())
2804          SawNonDependentContext = true;
2805      }
2806
2807      // We're performing "instantiation" of a member of the current
2808      // instantiation while we are type-checking the
2809      // definition. Compute the declaration context and return that.
2810      assert(!SawNonDependentContext &&
2811             "No dependent context while instantiating record");
2812      DeclContext *DC = computeDeclContext(T);
2813      assert(DC &&
2814             "Unable to find declaration for the current instantiation");
2815      return cast<CXXRecordDecl>(DC);
2816    }
2817
2818    // Fall through to deal with other dependent record types (e.g.,
2819    // anonymous unions in class templates).
2820  }
2821
2822  if (!ParentDC->isDependentContext())
2823    return D;
2824
2825  ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
2826  if (!ParentDC)
2827    return 0;
2828
2829  if (ParentDC != D->getDeclContext()) {
2830    // We performed some kind of instantiation in the parent context,
2831    // so now we need to look into the instantiated parent context to
2832    // find the instantiation of the declaration D.
2833
2834    // If our context used to be dependent, we may need to instantiate
2835    // it before performing lookup into that context.
2836    if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
2837      if (!Spec->isDependentContext()) {
2838        QualType T = Context.getTypeDeclType(Spec);
2839        const RecordType *Tag = T->getAs<RecordType>();
2840        assert(Tag && "type of non-dependent record is not a RecordType");
2841        if (!Tag->isBeingDefined() &&
2842            RequireCompleteType(Loc, T, diag::err_incomplete_type))
2843          return 0;
2844
2845        ParentDC = Tag->getDecl();
2846      }
2847    }
2848
2849    NamedDecl *Result = 0;
2850    if (D->getDeclName()) {
2851      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
2852      Result = findInstantiationOf(Context, D, Found.first, Found.second);
2853    } else {
2854      // Since we don't have a name for the entity we're looking for,
2855      // our only option is to walk through all of the declarations to
2856      // find that name. This will occur in a few cases:
2857      //
2858      //   - anonymous struct/union within a template
2859      //   - unnamed class/struct/union/enum within a template
2860      //
2861      // FIXME: Find a better way to find these instantiations!
2862      Result = findInstantiationOf(Context, D,
2863                                   ParentDC->decls_begin(),
2864                                   ParentDC->decls_end());
2865    }
2866
2867    // UsingShadowDecls can instantiate to nothing because of using hiding.
2868    assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2869            cast<Decl>(ParentDC)->isInvalidDecl())
2870           && "Unable to find instantiation of declaration!");
2871
2872    D = Result;
2873  }
2874
2875  return D;
2876}
2877
2878/// \brief Performs template instantiation for all implicit template
2879/// instantiations we have seen until this point.
2880void Sema::PerformPendingInstantiations(bool LocalOnly) {
2881  while (!PendingLocalImplicitInstantiations.empty() ||
2882         (!LocalOnly && !PendingInstantiations.empty())) {
2883    PendingImplicitInstantiation Inst;
2884
2885    if (PendingLocalImplicitInstantiations.empty()) {
2886      Inst = PendingInstantiations.front();
2887      PendingInstantiations.pop_front();
2888    } else {
2889      Inst = PendingLocalImplicitInstantiations.front();
2890      PendingLocalImplicitInstantiations.pop_front();
2891    }
2892
2893    // Instantiate function definitions
2894    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
2895      PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
2896                                          "instantiating function definition");
2897      bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
2898                                TSK_ExplicitInstantiationDefinition;
2899      InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
2900                                    DefinitionRequired);
2901      continue;
2902    }
2903
2904    // Instantiate static data member definitions.
2905    VarDecl *Var = cast<VarDecl>(Inst.first);
2906    assert(Var->isStaticDataMember() && "Not a static data member?");
2907
2908    // Don't try to instantiate declarations if the most recent redeclaration
2909    // is invalid.
2910    if (Var->getMostRecentDeclaration()->isInvalidDecl())
2911      continue;
2912
2913    // Check if the most recent declaration has changed the specialization kind
2914    // and removed the need for implicit instantiation.
2915    switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2916    case TSK_Undeclared:
2917      assert(false && "Cannot instantitiate an undeclared specialization.");
2918    case TSK_ExplicitInstantiationDeclaration:
2919    case TSK_ExplicitSpecialization:
2920      continue;  // No longer need to instantiate this type.
2921    case TSK_ExplicitInstantiationDefinition:
2922      // We only need an instantiation if the pending instantiation *is* the
2923      // explicit instantiation.
2924      if (Var != Var->getMostRecentDeclaration()) continue;
2925    case TSK_ImplicitInstantiation:
2926      break;
2927    }
2928
2929    PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
2930                                        "instantiating static data member "
2931                                        "definition");
2932
2933    bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
2934                              TSK_ExplicitInstantiationDefinition;
2935    InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
2936                                          DefinitionRequired);
2937  }
2938}
2939
2940void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2941                       const MultiLevelTemplateArgumentList &TemplateArgs) {
2942  for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2943         E = Pattern->ddiag_end(); I != E; ++I) {
2944    DependentDiagnostic *DD = *I;
2945
2946    switch (DD->getKind()) {
2947    case DependentDiagnostic::Access:
2948      HandleDependentAccessCheck(*DD, TemplateArgs);
2949      break;
2950    }
2951  }
2952}
2953