SemaTemplateInstantiateDecl.cpp revision e6cd706648aa42c1022d30c68e3b77f2a7a68a73
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 "Sema.h"
13#include "Lookup.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/Basic/PrettyStackTrace.h"
21#include "clang/Lex/Preprocessor.h"
22
23using namespace clang;
24
25namespace {
26  class TemplateDeclInstantiator
27    : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
28    Sema &SemaRef;
29    DeclContext *Owner;
30    const MultiLevelTemplateArgumentList &TemplateArgs;
31
32    void InstantiateAttrs(Decl *Tmpl, Decl *New);
33
34  public:
35    typedef Sema::OwningExprResult OwningExprResult;
36
37    TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
38                             const MultiLevelTemplateArgumentList &TemplateArgs)
39      : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
40
41    // FIXME: Once we get closer to completion, replace these manually-written
42    // declarations with automatically-generated ones from
43    // clang/AST/DeclNodes.def.
44    Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
45    Decl *VisitNamespaceDecl(NamespaceDecl *D);
46    Decl *VisitTypedefDecl(TypedefDecl *D);
47    Decl *VisitVarDecl(VarDecl *D);
48    Decl *VisitFieldDecl(FieldDecl *D);
49    Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
50    Decl *VisitEnumDecl(EnumDecl *D);
51    Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
52    Decl *VisitFriendDecl(FriendDecl *D);
53    Decl *VisitFunctionDecl(FunctionDecl *D,
54                            TemplateParameterList *TemplateParams = 0);
55    Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
56    Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
57                             TemplateParameterList *TemplateParams = 0);
58    Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
59    Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
60    Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
61    ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
62    Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
63    Decl *VisitClassTemplatePartialSpecializationDecl(
64                                    ClassTemplatePartialSpecializationDecl *D);
65    Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
66    Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
67    Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
68    Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
69    Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
70    Decl *VisitUsingDecl(UsingDecl *D);
71    Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
72    Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
73    Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
74
75    // Base case. FIXME: Remove once we can instantiate everything.
76    Decl *VisitDecl(Decl *D) {
77      unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
78                                                            Diagnostic::Error,
79                                                   "cannot instantiate %0 yet");
80      SemaRef.Diag(D->getLocation(), DiagID)
81        << D->getDeclKindName();
82
83      return 0;
84    }
85
86    const LangOptions &getLangOptions() {
87      return SemaRef.getLangOptions();
88    }
89
90    // Helper functions for instantiating methods.
91    QualType SubstFunctionType(FunctionDecl *D,
92                             llvm::SmallVectorImpl<ParmVarDecl *> &Params);
93    bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
94    bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
95
96    TemplateParameterList *
97      SubstTemplateParams(TemplateParameterList *List);
98
99    bool InstantiateClassTemplatePartialSpecialization(
100                                              ClassTemplateDecl *ClassTemplate,
101                           ClassTemplatePartialSpecializationDecl *PartialSpec);
102  };
103}
104
105// FIXME: Is this too simple?
106void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
107  for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
108       TmplAttr = TmplAttr->getNext()) {
109
110    // FIXME: Is cloning correct for all attributes?
111    Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
112
113    New->addAttr(NewAttr);
114  }
115}
116
117Decl *
118TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
119  assert(false && "Translation units cannot be instantiated");
120  return D;
121}
122
123Decl *
124TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
125  assert(false && "Namespaces cannot be instantiated");
126  return D;
127}
128
129Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
130  bool Invalid = false;
131  TypeSourceInfo *DI = D->getTypeSourceInfo();
132  if (DI->getType()->isDependentType()) {
133    DI = SemaRef.SubstType(DI, TemplateArgs,
134                           D->getLocation(), D->getDeclName());
135    if (!DI) {
136      Invalid = true;
137      DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
138    }
139  }
140
141  // Create the new typedef
142  TypedefDecl *Typedef
143    = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
144                          D->getIdentifier(), DI);
145  if (Invalid)
146    Typedef->setInvalidDecl();
147
148  if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
149    NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(Prev, TemplateArgs);
150    Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
151  }
152
153  Owner->addDecl(Typedef);
154
155  return Typedef;
156}
157
158/// \brief Instantiate the arguments provided as part of initialization.
159///
160/// \returns true if an error occurred, false otherwise.
161static bool InstantiateInitializationArguments(Sema &SemaRef,
162                                               Expr **Args, unsigned NumArgs,
163                           const MultiLevelTemplateArgumentList &TemplateArgs,
164                         llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
165                           ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
166  for (unsigned I = 0; I != NumArgs; ++I) {
167    // When we hit the first defaulted argument, break out of the loop:
168    // we don't pass those default arguments on.
169    if (Args[I]->isDefaultArgument())
170      break;
171
172    Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
173    if (Arg.isInvalid())
174      return true;
175
176    Expr *ArgExpr = (Expr *)Arg.get();
177    InitArgs.push_back(Arg.release());
178
179    // FIXME: We're faking all of the comma locations. Do we need them?
180    FakeCommaLocs.push_back(
181                          SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
182  }
183
184  return false;
185}
186
187Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
188  // Do substitution on the type of the declaration
189  TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
190                                         TemplateArgs,
191                                         D->getTypeSpecStartLoc(),
192                                         D->getDeclName());
193  if (!DI)
194    return 0;
195
196  // Build the instantiated declaration
197  VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
198                                 D->getLocation(), D->getIdentifier(),
199                                 DI->getType(), DI,
200                                 D->getStorageClass());
201  Var->setThreadSpecified(D->isThreadSpecified());
202  Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
203  Var->setDeclaredInCondition(D->isDeclaredInCondition());
204
205  // If we are instantiating a static data member defined
206  // out-of-line, the instantiation will have the same lexical
207  // context (which will be a namespace scope) as the template.
208  if (D->isOutOfLine())
209    Var->setLexicalDeclContext(D->getLexicalDeclContext());
210
211  // FIXME: In theory, we could have a previous declaration for variables that
212  // are not static data members.
213  bool Redeclaration = false;
214  // FIXME: having to fake up a LookupResult is dumb.
215  LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
216                        Sema::LookupOrdinaryName);
217  SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
218
219  if (D->isOutOfLine()) {
220    D->getLexicalDeclContext()->addDecl(Var);
221    Owner->makeDeclVisibleInContext(Var);
222  } else {
223    Owner->addDecl(Var);
224  }
225
226  // Link instantiations of static data members back to the template from
227  // which they were instantiated.
228  if (Var->isStaticDataMember())
229    SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
230                                                     TSK_ImplicitInstantiation);
231
232  if (D->getInit()) {
233    if (Var->isStaticDataMember() && !D->isOutOfLine())
234      SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
235    else
236      SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
237
238    // Extract the initializer, skipping through any temporary-binding
239    // expressions and look at the subexpression as it was written.
240    Expr *DInit = D->getInit();
241    while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(DInit))
242      DInit = Binder->getSubExpr();
243    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(DInit))
244      DInit = ICE->getSubExprAsWritten();
245
246    if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(DInit)) {
247      // The initializer is a parenthesized list of expressions that is
248      // type-dependent. Instantiate each of the expressions; we'll be
249      // performing direct initialization with them.
250      llvm::SmallVector<SourceLocation, 4> CommaLocs;
251      ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
252      if (!InstantiateInitializationArguments(SemaRef,
253                                              PLE->getExprs(),
254                                              PLE->getNumExprs(),
255                                              TemplateArgs,
256                                              CommaLocs, InitArgs)) {
257        // Add the direct initializer to the declaration.
258        SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
259                                              PLE->getLParenLoc(),
260                                              move_arg(InitArgs),
261                                              CommaLocs.data(),
262                                              PLE->getRParenLoc());
263      }
264    } else if (CXXConstructExpr *Construct =dyn_cast<CXXConstructExpr>(DInit)) {
265      // The initializer resolved to a constructor. Instantiate the constructor
266      // arguments.
267      llvm::SmallVector<SourceLocation, 4> CommaLocs;
268      ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
269
270      if (!InstantiateInitializationArguments(SemaRef,
271                                              Construct->getArgs(),
272                                              Construct->getNumArgs(),
273                                              TemplateArgs,
274                                              CommaLocs, InitArgs)) {
275        if (D->hasCXXDirectInitializer()) {
276          SourceLocation FakeLParenLoc =
277            SemaRef.PP.getLocForEndOfToken(D->getLocation());
278          SourceLocation FakeRParenLoc = CommaLocs.empty()? FakeLParenLoc
279                                                          : CommaLocs.back();
280          SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
281                                                FakeLParenLoc,
282                                                move_arg(InitArgs),
283                                                CommaLocs.data(),
284                                                FakeRParenLoc);
285        } else if (InitArgs.size() == 1) {
286          Expr *Init = (Expr*)(InitArgs.take()[0]);
287          SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
288                                       SemaRef.Owned(Init),
289                                       false);
290        } else {
291          assert(InitArgs.size() == 0);
292          SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
293        }
294      }
295    } else {
296      OwningExprResult Init
297        = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
298
299      // FIXME: Not happy about invalidating decls just because of a bad
300      // initializer, unless it affects the type.
301      if (Init.isInvalid())
302        Var->setInvalidDecl();
303      else
304        SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
305                                     D->hasCXXDirectInitializer());
306    }
307
308    SemaRef.PopExpressionEvaluationContext();
309  } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
310    SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
311
312  return Var;
313}
314
315Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
316  bool Invalid = false;
317  TypeSourceInfo *DI = D->getTypeSourceInfo();
318  if (DI->getType()->isDependentType())  {
319    DI = SemaRef.SubstType(DI, TemplateArgs,
320                           D->getLocation(), D->getDeclName());
321    if (!DI) {
322      DI = D->getTypeSourceInfo();
323      Invalid = true;
324    } else if (DI->getType()->isFunctionType()) {
325      // C++ [temp.arg.type]p3:
326      //   If a declaration acquires a function type through a type
327      //   dependent on a template-parameter and this causes a
328      //   declaration that does not use the syntactic form of a
329      //   function declarator to have function type, the program is
330      //   ill-formed.
331      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
332        << DI->getType();
333      Invalid = true;
334    }
335  }
336
337  Expr *BitWidth = D->getBitWidth();
338  if (Invalid)
339    BitWidth = 0;
340  else if (BitWidth) {
341    // The bit-width expression is not potentially evaluated.
342    EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
343
344    OwningExprResult InstantiatedBitWidth
345      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
346    if (InstantiatedBitWidth.isInvalid()) {
347      Invalid = true;
348      BitWidth = 0;
349    } else
350      BitWidth = InstantiatedBitWidth.takeAs<Expr>();
351  }
352
353  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
354                                            DI->getType(), DI,
355                                            cast<RecordDecl>(Owner),
356                                            D->getLocation(),
357                                            D->isMutable(),
358                                            BitWidth,
359                                            D->getTypeSpecStartLoc(),
360                                            D->getAccess(),
361                                            0);
362  if (!Field) {
363    cast<Decl>(Owner)->setInvalidDecl();
364    return 0;
365  }
366
367  InstantiateAttrs(D, Field);
368
369  if (Invalid)
370    Field->setInvalidDecl();
371
372  if (!Field->getDeclName()) {
373    // Keep track of where this decl came from.
374    SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
375  }
376
377  Field->setImplicit(D->isImplicit());
378  Owner->addDecl(Field);
379
380  return Field;
381}
382
383Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
384  FriendDecl::FriendUnion FU;
385
386  // Handle friend type expressions by simply substituting template
387  // parameters into the pattern type.
388  if (Type *Ty = D->getFriendType()) {
389    QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
390                                   D->getLocation(), DeclarationName());
391    if (T.isNull()) return 0;
392
393    assert(getLangOptions().CPlusPlus0x || T->isRecordType());
394    FU = T.getTypePtr();
395
396  // Handle everything else by appropriate substitution.
397  } else {
398    NamedDecl *ND = D->getFriendDecl();
399    assert(ND && "friend decl must be a decl or a type!");
400
401    // FIXME: We have a problem here, because the nested call to Visit(ND)
402    // will inject the thing that the friend references into the current
403    // owner, which is wrong.
404    Decl *NewND;
405
406    // Hack to make this work almost well pending a rewrite.
407    if (ND->getDeclContext()->isRecord())
408      NewND = SemaRef.FindInstantiatedDecl(ND, TemplateArgs);
409    else if (D->wasSpecialization()) {
410      // Totally egregious hack to work around PR5866
411      return 0;
412    } else
413      NewND = Visit(ND);
414    if (!NewND) return 0;
415
416    FU = cast<NamedDecl>(NewND);
417  }
418
419  FriendDecl *FD =
420    FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
421                       D->getFriendLoc());
422  FD->setAccess(AS_public);
423  Owner->addDecl(FD);
424  return FD;
425}
426
427Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
428  Expr *AssertExpr = D->getAssertExpr();
429
430  // The expression in a static assertion is not potentially evaluated.
431  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
432
433  OwningExprResult InstantiatedAssertExpr
434    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
435  if (InstantiatedAssertExpr.isInvalid())
436    return 0;
437
438  OwningExprResult Message(SemaRef, D->getMessage());
439  D->getMessage()->Retain();
440  Decl *StaticAssert
441    = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
442                                           move(InstantiatedAssertExpr),
443                                           move(Message)).getAs<Decl>();
444  return StaticAssert;
445}
446
447Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
448  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
449                                    D->getLocation(), D->getIdentifier(),
450                                    D->getTagKeywordLoc(),
451                                    /*PrevDecl=*/0);
452  Enum->setInstantiationOfMemberEnum(D);
453  Enum->setAccess(D->getAccess());
454  Owner->addDecl(Enum);
455  Enum->startDefinition();
456
457  llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
458
459  EnumConstantDecl *LastEnumConst = 0;
460  for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
461         ECEnd = D->enumerator_end();
462       EC != ECEnd; ++EC) {
463    // The specified value for the enumerator.
464    OwningExprResult Value = SemaRef.Owned((Expr *)0);
465    if (Expr *UninstValue = EC->getInitExpr()) {
466      // The enumerator's value expression is not potentially evaluated.
467      EnterExpressionEvaluationContext Unevaluated(SemaRef,
468                                                   Action::Unevaluated);
469
470      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
471    }
472
473    // Drop the initial value and continue.
474    bool isInvalid = false;
475    if (Value.isInvalid()) {
476      Value = SemaRef.Owned((Expr *)0);
477      isInvalid = true;
478    }
479
480    EnumConstantDecl *EnumConst
481      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
482                                  EC->getLocation(), EC->getIdentifier(),
483                                  move(Value));
484
485    if (isInvalid) {
486      if (EnumConst)
487        EnumConst->setInvalidDecl();
488      Enum->setInvalidDecl();
489    }
490
491    if (EnumConst) {
492      Enum->addDecl(EnumConst);
493      Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
494      LastEnumConst = EnumConst;
495    }
496  }
497
498  // FIXME: Fixup LBraceLoc and RBraceLoc
499  // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
500  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
501                        Sema::DeclPtrTy::make(Enum),
502                        &Enumerators[0], Enumerators.size(),
503                        0, 0);
504
505  return Enum;
506}
507
508Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
509  assert(false && "EnumConstantDecls can only occur within EnumDecls.");
510  return 0;
511}
512
513namespace {
514  class SortDeclByLocation {
515    SourceManager &SourceMgr;
516
517  public:
518    explicit SortDeclByLocation(SourceManager &SourceMgr)
519      : SourceMgr(SourceMgr) { }
520
521    bool operator()(const Decl *X, const Decl *Y) const {
522      return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
523                                                 Y->getLocation());
524    }
525  };
526}
527
528Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
529  // Create a local instantiation scope for this class template, which
530  // will contain the instantiations of the template parameters.
531  Sema::LocalInstantiationScope Scope(SemaRef);
532  TemplateParameterList *TempParams = D->getTemplateParameters();
533  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
534  if (!InstParams)
535    return NULL;
536
537  CXXRecordDecl *Pattern = D->getTemplatedDecl();
538  CXXRecordDecl *RecordInst
539    = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
540                            Pattern->getLocation(), Pattern->getIdentifier(),
541                            Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
542                            /*DelayTypeCreation=*/true);
543
544  ClassTemplateDecl *Inst
545    = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
546                                D->getIdentifier(), InstParams, RecordInst, 0);
547  RecordInst->setDescribedClassTemplate(Inst);
548  if (D->getFriendObjectKind())
549    Inst->setObjectOfFriendDecl(true);
550  else
551    Inst->setAccess(D->getAccess());
552  Inst->setInstantiatedFromMemberTemplate(D);
553
554  // Trigger creation of the type for the instantiation.
555  SemaRef.Context.getTypeDeclType(RecordInst);
556
557  // Finish handling of friends.
558  if (Inst->getFriendObjectKind()) {
559    return Inst;
560  }
561
562  Owner->addDecl(Inst);
563
564  // First, we sort the partial specializations by location, so
565  // that we instantiate them in the order they were declared.
566  llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
567  for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
568         P = D->getPartialSpecializations().begin(),
569         PEnd = D->getPartialSpecializations().end();
570       P != PEnd; ++P)
571    PartialSpecs.push_back(&*P);
572  std::sort(PartialSpecs.begin(), PartialSpecs.end(),
573            SortDeclByLocation(SemaRef.SourceMgr));
574
575  // Instantiate all of the partial specializations of this member class
576  // template.
577  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
578    InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
579
580  return Inst;
581}
582
583Decl *
584TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
585                                   ClassTemplatePartialSpecializationDecl *D) {
586  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
587
588  // Lookup the already-instantiated declaration in the instantiation
589  // of the class template and return that.
590  DeclContext::lookup_result Found
591    = Owner->lookup(ClassTemplate->getDeclName());
592  if (Found.first == Found.second)
593    return 0;
594
595  ClassTemplateDecl *InstClassTemplate
596    = dyn_cast<ClassTemplateDecl>(*Found.first);
597  if (!InstClassTemplate)
598    return 0;
599
600  Decl *DCanon = D->getCanonicalDecl();
601  for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
602            P = InstClassTemplate->getPartialSpecializations().begin(),
603         PEnd = InstClassTemplate->getPartialSpecializations().end();
604       P != PEnd; ++P) {
605    if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
606      return &*P;
607  }
608
609  return 0;
610}
611
612Decl *
613TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
614  // Create a local instantiation scope for this function template, which
615  // will contain the instantiations of the template parameters and then get
616  // merged with the local instantiation scope for the function template
617  // itself.
618  Sema::LocalInstantiationScope Scope(SemaRef);
619
620  TemplateParameterList *TempParams = D->getTemplateParameters();
621  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
622  if (!InstParams)
623    return NULL;
624
625  FunctionDecl *Instantiated = 0;
626  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
627    Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
628                                                                 InstParams));
629  else
630    Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
631                                                          D->getTemplatedDecl(),
632                                                                InstParams));
633
634  if (!Instantiated)
635    return 0;
636
637  // Link the instantiated function template declaration to the function
638  // template from which it was instantiated.
639  FunctionTemplateDecl *InstTemplate
640    = Instantiated->getDescribedFunctionTemplate();
641  InstTemplate->setAccess(D->getAccess());
642  assert(InstTemplate &&
643         "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
644
645  // Link the instantiation back to the pattern *unless* this is a
646  // non-definition friend declaration.
647  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
648      !(InstTemplate->getFriendObjectKind() &&
649        !D->getTemplatedDecl()->isThisDeclarationADefinition()))
650    InstTemplate->setInstantiatedFromMemberTemplate(D);
651
652  // Add non-friends into the owner.
653  if (!InstTemplate->getFriendObjectKind())
654    Owner->addDecl(InstTemplate);
655  return InstTemplate;
656}
657
658Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
659  CXXRecordDecl *PrevDecl = 0;
660  if (D->isInjectedClassName())
661    PrevDecl = cast<CXXRecordDecl>(Owner);
662  else if (D->getPreviousDeclaration()) {
663    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getPreviousDeclaration(),
664                                                   TemplateArgs);
665    if (!Prev) return 0;
666    PrevDecl = cast<CXXRecordDecl>(Prev);
667  }
668
669  CXXRecordDecl *Record
670    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
671                            D->getLocation(), D->getIdentifier(),
672                            D->getTagKeywordLoc(), PrevDecl);
673  Record->setImplicit(D->isImplicit());
674  // FIXME: Check against AS_none is an ugly hack to work around the issue that
675  // the tag decls introduced by friend class declarations don't have an access
676  // specifier. Remove once this area of the code gets sorted out.
677  if (D->getAccess() != AS_none)
678    Record->setAccess(D->getAccess());
679  if (!D->isInjectedClassName())
680    Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
681
682  // If the original function was part of a friend declaration,
683  // inherit its namespace state.
684  if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
685    Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
686
687  Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
688
689  Owner->addDecl(Record);
690  return Record;
691}
692
693/// Normal class members are of more specific types and therefore
694/// don't make it here.  This function serves two purposes:
695///   1) instantiating function templates
696///   2) substituting friend declarations
697/// FIXME: preserve function definitions in case #2
698Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
699                                       TemplateParameterList *TemplateParams) {
700  // Check whether there is already a function template specialization for
701  // this declaration.
702  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
703  void *InsertPos = 0;
704  if (FunctionTemplate && !TemplateParams) {
705    llvm::FoldingSetNodeID ID;
706    FunctionTemplateSpecializationInfo::Profile(ID,
707                             TemplateArgs.getInnermost().getFlatArgumentList(),
708                                       TemplateArgs.getInnermost().flat_size(),
709                                                SemaRef.Context);
710
711    FunctionTemplateSpecializationInfo *Info
712      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
713                                                                   InsertPos);
714
715    // If we already have a function template specialization, return it.
716    if (Info)
717      return Info->Function;
718  }
719
720  Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
721
722  llvm::SmallVector<ParmVarDecl *, 4> Params;
723  QualType T = SubstFunctionType(D, Params);
724  if (T.isNull())
725    return 0;
726
727  // Build the instantiated method declaration.
728  DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
729                                                    TemplateArgs);
730  FunctionDecl *Function =
731      FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
732                           D->getDeclName(), T, D->getTypeSourceInfo(),
733                           D->getStorageClass(),
734                           D->isInlineSpecified(), D->hasWrittenPrototype());
735  Function->setLexicalDeclContext(Owner);
736
737  // Attach the parameters
738  for (unsigned P = 0; P < Params.size(); ++P)
739    Params[P]->setOwningFunction(Function);
740  Function->setParams(SemaRef.Context, Params.data(), Params.size());
741
742  if (TemplateParams) {
743    // Our resulting instantiation is actually a function template, since we
744    // are substituting only the outer template parameters. For example, given
745    //
746    //   template<typename T>
747    //   struct X {
748    //     template<typename U> friend void f(T, U);
749    //   };
750    //
751    //   X<int> x;
752    //
753    // We are instantiating the friend function template "f" within X<int>,
754    // which means substituting int for T, but leaving "f" as a friend function
755    // template.
756    // Build the function template itself.
757    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
758                                                    Function->getLocation(),
759                                                    Function->getDeclName(),
760                                                    TemplateParams, Function);
761    Function->setDescribedFunctionTemplate(FunctionTemplate);
762    FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
763  } else if (FunctionTemplate) {
764    // Record this function template specialization.
765    Function->setFunctionTemplateSpecialization(SemaRef.Context,
766                                                FunctionTemplate,
767                                                &TemplateArgs.getInnermost(),
768                                                InsertPos);
769  }
770
771  if (InitFunctionInstantiation(Function, D))
772    Function->setInvalidDecl();
773
774  bool Redeclaration = false;
775  bool OverloadableAttrRequired = false;
776
777  LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
778                        Sema::LookupOrdinaryName, Sema::ForRedeclaration);
779
780  if (TemplateParams || !FunctionTemplate) {
781    // Look only into the namespace where the friend would be declared to
782    // find a previous declaration. This is the innermost enclosing namespace,
783    // as described in ActOnFriendFunctionDecl.
784    SemaRef.LookupQualifiedName(Previous, DC);
785
786    // In C++, the previous declaration we find might be a tag type
787    // (class or enum). In this case, the new declaration will hide the
788    // tag type. Note that this does does not apply if we're declaring a
789    // typedef (C++ [dcl.typedef]p4).
790    if (Previous.isSingleTagDecl())
791      Previous.clear();
792  }
793
794  SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
795                                   false, Redeclaration,
796                                   /*FIXME:*/OverloadableAttrRequired);
797
798  // If the original function was part of a friend declaration,
799  // inherit its namespace state and add it to the owner.
800  NamedDecl *FromFriendD
801      = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
802  if (FromFriendD->getFriendObjectKind()) {
803    NamedDecl *ToFriendD = 0;
804    NamedDecl *PrevDecl;
805    if (TemplateParams) {
806      ToFriendD = cast<NamedDecl>(FunctionTemplate);
807      PrevDecl = FunctionTemplate->getPreviousDeclaration();
808    } else {
809      ToFriendD = Function;
810      PrevDecl = Function->getPreviousDeclaration();
811    }
812    ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
813    if (!Owner->isDependentContext() && !PrevDecl)
814      DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
815
816    if (!TemplateParams)
817      Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
818  }
819
820  return Function;
821}
822
823Decl *
824TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
825                                      TemplateParameterList *TemplateParams) {
826  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
827  void *InsertPos = 0;
828  if (FunctionTemplate && !TemplateParams) {
829    // We are creating a function template specialization from a function
830    // template. Check whether there is already a function template
831    // specialization for this particular set of template arguments.
832    llvm::FoldingSetNodeID ID;
833    FunctionTemplateSpecializationInfo::Profile(ID,
834                            TemplateArgs.getInnermost().getFlatArgumentList(),
835                                      TemplateArgs.getInnermost().flat_size(),
836                                                SemaRef.Context);
837
838    FunctionTemplateSpecializationInfo *Info
839      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
840                                                                   InsertPos);
841
842    // If we already have a function template specialization, return it.
843    if (Info)
844      return Info->Function;
845  }
846
847  Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
848
849  llvm::SmallVector<ParmVarDecl *, 4> Params;
850  QualType T = SubstFunctionType(D, Params);
851  if (T.isNull())
852    return 0;
853
854  // Build the instantiated method declaration.
855  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
856  CXXMethodDecl *Method = 0;
857
858  DeclarationName Name = D->getDeclName();
859  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
860    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
861    Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
862                                    SemaRef.Context.getCanonicalType(ClassTy));
863    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
864                                        Constructor->getLocation(),
865                                        Name, T,
866                                        Constructor->getTypeSourceInfo(),
867                                        Constructor->isExplicit(),
868                                        Constructor->isInlineSpecified(), false);
869  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
870    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
871    Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
872                                   SemaRef.Context.getCanonicalType(ClassTy));
873    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
874                                       Destructor->getLocation(), Name,
875                                       T, Destructor->isInlineSpecified(), false);
876  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
877    CanQualType ConvTy
878      = SemaRef.Context.getCanonicalType(
879                                      T->getAs<FunctionType>()->getResultType());
880    Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
881                                                                      ConvTy);
882    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
883                                       Conversion->getLocation(), Name,
884                                       T, Conversion->getTypeSourceInfo(),
885                                       Conversion->isInlineSpecified(),
886                                       Conversion->isExplicit());
887  } else {
888    Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
889                                   D->getDeclName(), T, D->getTypeSourceInfo(),
890                                   D->isStatic(), D->isInlineSpecified());
891  }
892
893  if (TemplateParams) {
894    // Our resulting instantiation is actually a function template, since we
895    // are substituting only the outer template parameters. For example, given
896    //
897    //   template<typename T>
898    //   struct X {
899    //     template<typename U> void f(T, U);
900    //   };
901    //
902    //   X<int> x;
903    //
904    // We are instantiating the member template "f" within X<int>, which means
905    // substituting int for T, but leaving "f" as a member function template.
906    // Build the function template itself.
907    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
908                                                    Method->getLocation(),
909                                                    Method->getDeclName(),
910                                                    TemplateParams, Method);
911    if (D->isOutOfLine())
912      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
913    Method->setDescribedFunctionTemplate(FunctionTemplate);
914  } else if (FunctionTemplate) {
915    // Record this function template specialization.
916    Method->setFunctionTemplateSpecialization(SemaRef.Context,
917                                              FunctionTemplate,
918                                              &TemplateArgs.getInnermost(),
919                                              InsertPos);
920  } else {
921    // Record that this is an instantiation of a member function.
922    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
923  }
924
925  // If we are instantiating a member function defined
926  // out-of-line, the instantiation will have the same lexical
927  // context (which will be a namespace scope) as the template.
928  if (D->isOutOfLine())
929    Method->setLexicalDeclContext(D->getLexicalDeclContext());
930
931  // Attach the parameters
932  for (unsigned P = 0; P < Params.size(); ++P)
933    Params[P]->setOwningFunction(Method);
934  Method->setParams(SemaRef.Context, Params.data(), Params.size());
935
936  if (InitMethodInstantiation(Method, D))
937    Method->setInvalidDecl();
938
939  LookupResult Previous(SemaRef, Name, SourceLocation(),
940                        Sema::LookupOrdinaryName, Sema::ForRedeclaration);
941
942  if (!FunctionTemplate || TemplateParams) {
943    SemaRef.LookupQualifiedName(Previous, Owner);
944
945    // In C++, the previous declaration we find might be a tag type
946    // (class or enum). In this case, the new declaration will hide the
947    // tag type. Note that this does does not apply if we're declaring a
948    // typedef (C++ [dcl.typedef]p4).
949    if (Previous.isSingleTagDecl())
950      Previous.clear();
951  }
952
953  bool Redeclaration = false;
954  bool OverloadableAttrRequired = false;
955  SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
956                                   /*FIXME:*/OverloadableAttrRequired);
957
958  if (D->isPure())
959    SemaRef.CheckPureMethod(Method, SourceRange());
960
961  if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
962      !Method->getFriendObjectKind())
963    Owner->addDecl(Method);
964
965  return Method;
966}
967
968Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
969  return VisitCXXMethodDecl(D);
970}
971
972Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
973  return VisitCXXMethodDecl(D);
974}
975
976Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
977  return VisitCXXMethodDecl(D);
978}
979
980ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
981  QualType T;
982  TypeSourceInfo *DI = D->getTypeSourceInfo();
983  if (DI) {
984    DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
985                           D->getDeclName());
986    if (DI) T = DI->getType();
987  } else {
988    T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
989                          D->getDeclName());
990    DI = 0;
991  }
992
993  if (T.isNull())
994    return 0;
995
996  T = SemaRef.adjustParameterType(T);
997
998  // Allocate the parameter
999  ParmVarDecl *Param
1000    = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1001                          D->getIdentifier(), T, DI, D->getStorageClass(), 0);
1002
1003  // Mark the default argument as being uninstantiated.
1004  if (D->hasUninstantiatedDefaultArg())
1005    Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
1006  else if (Expr *Arg = D->getDefaultArg())
1007    Param->setUninstantiatedDefaultArg(Arg);
1008
1009  // Note: we don't try to instantiate function parameters until after
1010  // we've instantiated the function's type. Therefore, we don't have
1011  // to check for 'void' parameter types here.
1012  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1013  return Param;
1014}
1015
1016Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1017                                                    TemplateTypeParmDecl *D) {
1018  // TODO: don't always clone when decls are refcounted.
1019  const Type* T = D->getTypeForDecl();
1020  assert(T->isTemplateTypeParmType());
1021  const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
1022
1023  TemplateTypeParmDecl *Inst =
1024    TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1025                                 TTPT->getDepth() - 1, TTPT->getIndex(),
1026                                 TTPT->getName(),
1027                                 D->wasDeclaredWithTypename(),
1028                                 D->isParameterPack());
1029
1030  if (D->hasDefaultArgument())
1031    Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1032
1033  // Introduce this template parameter's instantiation into the instantiation
1034  // scope.
1035  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1036
1037  return Inst;
1038}
1039
1040Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1041                                                 NonTypeTemplateParmDecl *D) {
1042  // Substitute into the type of the non-type template parameter.
1043  QualType T;
1044  TypeSourceInfo *DI = D->getTypeSourceInfo();
1045  if (DI) {
1046    DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1047                           D->getDeclName());
1048    if (DI) T = DI->getType();
1049  } else {
1050    T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1051                          D->getDeclName());
1052    DI = 0;
1053  }
1054  if (T.isNull())
1055    return 0;
1056
1057  // Check that this type is acceptable for a non-type template parameter.
1058  bool Invalid = false;
1059  T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1060  if (T.isNull()) {
1061    T = SemaRef.Context.IntTy;
1062    Invalid = true;
1063  }
1064
1065  NonTypeTemplateParmDecl *Param
1066    = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1067                                      D->getDepth() - 1, D->getPosition(),
1068                                      D->getIdentifier(), T, DI);
1069  if (Invalid)
1070    Param->setInvalidDecl();
1071
1072  Param->setDefaultArgument(D->getDefaultArgument());
1073
1074  // Introduce this template parameter's instantiation into the instantiation
1075  // scope.
1076  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1077  return Param;
1078}
1079
1080Decl *
1081TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1082                                                  TemplateTemplateParmDecl *D) {
1083  // Instantiate the template parameter list of the template template parameter.
1084  TemplateParameterList *TempParams = D->getTemplateParameters();
1085  TemplateParameterList *InstParams;
1086  {
1087    // Perform the actual substitution of template parameters within a new,
1088    // local instantiation scope.
1089    Sema::LocalInstantiationScope Scope(SemaRef);
1090    InstParams = SubstTemplateParams(TempParams);
1091    if (!InstParams)
1092      return NULL;
1093  }
1094
1095  // Build the template template parameter.
1096  TemplateTemplateParmDecl *Param
1097    = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1098                                       D->getDepth() - 1, D->getPosition(),
1099                                       D->getIdentifier(), InstParams);
1100  Param->setDefaultArgument(D->getDefaultArgument());
1101
1102  // Introduce this template parameter's instantiation into the instantiation
1103  // scope.
1104  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1105
1106  return Param;
1107}
1108
1109Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1110  // Using directives are never dependent, so they require no explicit
1111
1112  UsingDirectiveDecl *Inst
1113    = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1114                                 D->getNamespaceKeyLocation(),
1115                                 D->getQualifierRange(), D->getQualifier(),
1116                                 D->getIdentLocation(),
1117                                 D->getNominatedNamespace(),
1118                                 D->getCommonAncestor());
1119  Owner->addDecl(Inst);
1120  return Inst;
1121}
1122
1123Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1124  // The nested name specifier is non-dependent, so no transformation
1125  // is required.
1126
1127  // We only need to do redeclaration lookups if we're in a class
1128  // scope (in fact, it's not really even possible in non-class
1129  // scopes).
1130  bool CheckRedeclaration = Owner->isRecord();
1131
1132  LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1133                    Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1134
1135  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1136                                       D->getLocation(),
1137                                       D->getNestedNameRange(),
1138                                       D->getUsingLocation(),
1139                                       D->getTargetNestedNameDecl(),
1140                                       D->getDeclName(),
1141                                       D->isTypeName());
1142
1143  CXXScopeSpec SS;
1144  SS.setScopeRep(D->getTargetNestedNameDecl());
1145  SS.setRange(D->getNestedNameRange());
1146
1147  if (CheckRedeclaration) {
1148    Prev.setHideTags(false);
1149    SemaRef.LookupQualifiedName(Prev, Owner);
1150
1151    // Check for invalid redeclarations.
1152    if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1153                                            D->isTypeName(), SS,
1154                                            D->getLocation(), Prev))
1155      NewUD->setInvalidDecl();
1156
1157  }
1158
1159  if (!NewUD->isInvalidDecl() &&
1160      SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
1161                                      D->getLocation()))
1162    NewUD->setInvalidDecl();
1163
1164  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1165  NewUD->setAccess(D->getAccess());
1166  Owner->addDecl(NewUD);
1167
1168  // Don't process the shadow decls for an invalid decl.
1169  if (NewUD->isInvalidDecl())
1170    return NewUD;
1171
1172  bool isFunctionScope = Owner->isFunctionOrMethod();
1173
1174  // Process the shadow decls.
1175  for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1176         I != E; ++I) {
1177    UsingShadowDecl *Shadow = *I;
1178    NamedDecl *InstTarget =
1179      cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getTargetDecl(),
1180                                                   TemplateArgs));
1181
1182    if (CheckRedeclaration &&
1183        SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1184      continue;
1185
1186    UsingShadowDecl *InstShadow
1187      = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1188    SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
1189
1190    if (isFunctionScope)
1191      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
1192  }
1193
1194  return NewUD;
1195}
1196
1197Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
1198  // Ignore these;  we handle them in bulk when processing the UsingDecl.
1199  return 0;
1200}
1201
1202Decl * TemplateDeclInstantiator
1203    ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1204  NestedNameSpecifier *NNS =
1205    SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1206                                     D->getTargetNestedNameRange(),
1207                                     TemplateArgs);
1208  if (!NNS)
1209    return 0;
1210
1211  CXXScopeSpec SS;
1212  SS.setRange(D->getTargetNestedNameRange());
1213  SS.setScopeRep(NNS);
1214
1215  NamedDecl *UD =
1216    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1217                                  D->getUsingLoc(), SS, D->getLocation(),
1218                                  D->getDeclName(), 0,
1219                                  /*instantiation*/ true,
1220                                  /*typename*/ true, D->getTypenameLoc());
1221  if (UD)
1222    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1223
1224  return UD;
1225}
1226
1227Decl * TemplateDeclInstantiator
1228    ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1229  NestedNameSpecifier *NNS =
1230    SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1231                                     D->getTargetNestedNameRange(),
1232                                     TemplateArgs);
1233  if (!NNS)
1234    return 0;
1235
1236  CXXScopeSpec SS;
1237  SS.setRange(D->getTargetNestedNameRange());
1238  SS.setScopeRep(NNS);
1239
1240  NamedDecl *UD =
1241    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1242                                  D->getUsingLoc(), SS, D->getLocation(),
1243                                  D->getDeclName(), 0,
1244                                  /*instantiation*/ true,
1245                                  /*typename*/ false, SourceLocation());
1246  if (UD)
1247    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1248
1249  return UD;
1250}
1251
1252Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
1253                      const MultiLevelTemplateArgumentList &TemplateArgs) {
1254  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
1255  return Instantiator.Visit(D);
1256}
1257
1258/// \brief Instantiates a nested template parameter list in the current
1259/// instantiation context.
1260///
1261/// \param L The parameter list to instantiate
1262///
1263/// \returns NULL if there was an error
1264TemplateParameterList *
1265TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
1266  // Get errors for all the parameters before bailing out.
1267  bool Invalid = false;
1268
1269  unsigned N = L->size();
1270  typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
1271  ParamVector Params;
1272  Params.reserve(N);
1273  for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1274       PI != PE; ++PI) {
1275    NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
1276    Params.push_back(D);
1277    Invalid = Invalid || !D || D->isInvalidDecl();
1278  }
1279
1280  // Clean up if we had an error.
1281  if (Invalid) {
1282    for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1283         PI != PE; ++PI)
1284      if (*PI)
1285        (*PI)->Destroy(SemaRef.Context);
1286    return NULL;
1287  }
1288
1289  TemplateParameterList *InstL
1290    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1291                                    L->getLAngleLoc(), &Params.front(), N,
1292                                    L->getRAngleLoc());
1293  return InstL;
1294}
1295
1296/// \brief Instantiate the declaration of a class template partial
1297/// specialization.
1298///
1299/// \param ClassTemplate the (instantiated) class template that is partially
1300// specialized by the instantiation of \p PartialSpec.
1301///
1302/// \param PartialSpec the (uninstantiated) class template partial
1303/// specialization that we are instantiating.
1304///
1305/// \returns true if there was an error, false otherwise.
1306bool
1307TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1308                                            ClassTemplateDecl *ClassTemplate,
1309                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
1310  // Create a local instantiation scope for this class template partial
1311  // specialization, which will contain the instantiations of the template
1312  // parameters.
1313  Sema::LocalInstantiationScope Scope(SemaRef);
1314
1315  // Substitute into the template parameters of the class template partial
1316  // specialization.
1317  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1318  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1319  if (!InstParams)
1320    return true;
1321
1322  // Substitute into the template arguments of the class template partial
1323  // specialization.
1324  const TemplateArgumentLoc *PartialSpecTemplateArgs
1325    = PartialSpec->getTemplateArgsAsWritten();
1326  unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1327
1328  TemplateArgumentListInfo InstTemplateArgs; // no angle locations
1329  for (unsigned I = 0; I != N; ++I) {
1330    TemplateArgumentLoc Loc;
1331    if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
1332      return true;
1333    InstTemplateArgs.addArgument(Loc);
1334  }
1335
1336
1337  // Check that the template argument list is well-formed for this
1338  // class template.
1339  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1340                                        InstTemplateArgs.size());
1341  if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1342                                        PartialSpec->getLocation(),
1343                                        InstTemplateArgs,
1344                                        false,
1345                                        Converted))
1346    return true;
1347
1348  // Figure out where to insert this class template partial specialization
1349  // in the member template's set of class template partial specializations.
1350  llvm::FoldingSetNodeID ID;
1351  ClassTemplatePartialSpecializationDecl::Profile(ID,
1352                                                  Converted.getFlatArguments(),
1353                                                  Converted.flatSize(),
1354                                                  SemaRef.Context);
1355  void *InsertPos = 0;
1356  ClassTemplateSpecializationDecl *PrevDecl
1357    = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1358                                                                     InsertPos);
1359
1360  // Build the canonical type that describes the converted template
1361  // arguments of the class template partial specialization.
1362  QualType CanonType
1363    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1364                                                  Converted.getFlatArguments(),
1365                                                    Converted.flatSize());
1366
1367  // Build the fully-sugared type for this class template
1368  // specialization as the user wrote in the specialization
1369  // itself. This means that we'll pretty-print the type retrieved
1370  // from the specialization's declaration the way that the user
1371  // actually wrote the specialization, rather than formatting the
1372  // name based on the "canonical" representation used to store the
1373  // template arguments in the specialization.
1374  QualType WrittenTy
1375    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1376                                                    InstTemplateArgs,
1377                                                    CanonType);
1378
1379  if (PrevDecl) {
1380    // We've already seen a partial specialization with the same template
1381    // parameters and template arguments. This can happen, for example, when
1382    // substituting the outer template arguments ends up causing two
1383    // class template partial specializations of a member class template
1384    // to have identical forms, e.g.,
1385    //
1386    //   template<typename T, typename U>
1387    //   struct Outer {
1388    //     template<typename X, typename Y> struct Inner;
1389    //     template<typename Y> struct Inner<T, Y>;
1390    //     template<typename Y> struct Inner<U, Y>;
1391    //   };
1392    //
1393    //   Outer<int, int> outer; // error: the partial specializations of Inner
1394    //                          // have the same signature.
1395    SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1396      << WrittenTy;
1397    SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1398      << SemaRef.Context.getTypeDeclType(PrevDecl);
1399    return true;
1400  }
1401
1402
1403  // Create the class template partial specialization declaration.
1404  ClassTemplatePartialSpecializationDecl *InstPartialSpec
1405    = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1406                                                     PartialSpec->getLocation(),
1407                                                     InstParams,
1408                                                     ClassTemplate,
1409                                                     Converted,
1410                                                     InstTemplateArgs,
1411                                                     0);
1412  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1413  InstPartialSpec->setTypeAsWritten(WrittenTy);
1414
1415  // Add this partial specialization to the set of class template partial
1416  // specializations.
1417  ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1418                                                        InsertPos);
1419  return false;
1420}
1421
1422/// \brief Does substitution on the type of the given function, including
1423/// all of the function parameters.
1424///
1425/// \param D The function whose type will be the basis of the substitution
1426///
1427/// \param Params the instantiated parameter declarations
1428
1429/// \returns the instantiated function's type if successful, a NULL
1430/// type if there was an error.
1431QualType
1432TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
1433                              llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1434  bool InvalidDecl = false;
1435
1436  // Substitute all of the function's formal parameter types.
1437  TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
1438  llvm::SmallVector<QualType, 4> ParamTys;
1439  for (FunctionDecl::param_iterator P = D->param_begin(),
1440                                 PEnd = D->param_end();
1441       P != PEnd; ++P) {
1442    if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
1443      if (PInst->getType()->isVoidType()) {
1444        SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1445        PInst->setInvalidDecl();
1446      } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
1447                                                PInst->getType(),
1448                                                diag::err_abstract_type_in_decl,
1449                                                Sema::AbstractParamType))
1450        PInst->setInvalidDecl();
1451
1452      Params.push_back(PInst);
1453      ParamTys.push_back(PInst->getType());
1454
1455      if (PInst->isInvalidDecl())
1456        InvalidDecl = true;
1457    } else
1458      InvalidDecl = true;
1459  }
1460
1461  // FIXME: Deallocate dead declarations.
1462  if (InvalidDecl)
1463    return QualType();
1464
1465  const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
1466  assert(Proto && "Missing prototype?");
1467  QualType ResultType
1468    = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1469                        D->getLocation(), D->getDeclName());
1470  if (ResultType.isNull())
1471    return QualType();
1472
1473  return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
1474                                   Proto->isVariadic(), Proto->getTypeQuals(),
1475                                   D->getLocation(), D->getDeclName());
1476}
1477
1478/// \brief Initializes the common fields of an instantiation function
1479/// declaration (New) from the corresponding fields of its template (Tmpl).
1480///
1481/// \returns true if there was an error
1482bool
1483TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
1484                                                    FunctionDecl *Tmpl) {
1485  if (Tmpl->isDeleted())
1486    New->setDeleted();
1487
1488  // If we are performing substituting explicitly-specified template arguments
1489  // or deduced template arguments into a function template and we reach this
1490  // point, we are now past the point where SFINAE applies and have committed
1491  // to keeping the new function template specialization. We therefore
1492  // convert the active template instantiation for the function template
1493  // into a template instantiation for this specific function template
1494  // specialization, which is not a SFINAE context, so that we diagnose any
1495  // further errors in the declaration itself.
1496  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1497  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1498  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1499      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
1500    if (FunctionTemplateDecl *FunTmpl
1501          = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
1502      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
1503             "Deduction from the wrong function template?");
1504      (void) FunTmpl;
1505      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1506      ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
1507      --SemaRef.NonInstantiationEntries;
1508    }
1509  }
1510
1511  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1512  assert(Proto && "Function template without prototype?");
1513
1514  if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1515      Proto->getNoReturnAttr()) {
1516    // The function has an exception specification or a "noreturn"
1517    // attribute. Substitute into each of the exception types.
1518    llvm::SmallVector<QualType, 4> Exceptions;
1519    for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1520      // FIXME: Poor location information!
1521      QualType T
1522        = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1523                            New->getLocation(), New->getDeclName());
1524      if (T.isNull() ||
1525          SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1526        continue;
1527
1528      Exceptions.push_back(T);
1529    }
1530
1531    // Rebuild the function type
1532
1533    const FunctionProtoType *NewProto
1534      = New->getType()->getAs<FunctionProtoType>();
1535    assert(NewProto && "Template instantiation without function prototype?");
1536    New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1537                                                 NewProto->arg_type_begin(),
1538                                                 NewProto->getNumArgs(),
1539                                                 NewProto->isVariadic(),
1540                                                 NewProto->getTypeQuals(),
1541                                                 Proto->hasExceptionSpec(),
1542                                                 Proto->hasAnyExceptionSpec(),
1543                                                 Exceptions.size(),
1544                                                 Exceptions.data(),
1545                                                 Proto->getNoReturnAttr()));
1546  }
1547
1548  return false;
1549}
1550
1551/// \brief Initializes common fields of an instantiated method
1552/// declaration (New) from the corresponding fields of its template
1553/// (Tmpl).
1554///
1555/// \returns true if there was an error
1556bool
1557TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
1558                                                  CXXMethodDecl *Tmpl) {
1559  if (InitFunctionInstantiation(New, Tmpl))
1560    return true;
1561
1562  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1563  New->setAccess(Tmpl->getAccess());
1564  if (Tmpl->isVirtualAsWritten())
1565    Record->setMethodAsVirtual(New);
1566
1567  // FIXME: attributes
1568  // FIXME: New needs a pointer to Tmpl
1569  return false;
1570}
1571
1572/// \brief Instantiate the definition of the given function from its
1573/// template.
1574///
1575/// \param PointOfInstantiation the point at which the instantiation was
1576/// required. Note that this is not precisely a "point of instantiation"
1577/// for the function, but it's close.
1578///
1579/// \param Function the already-instantiated declaration of a
1580/// function template specialization or member function of a class template
1581/// specialization.
1582///
1583/// \param Recursive if true, recursively instantiates any functions that
1584/// are required by this instantiation.
1585///
1586/// \param DefinitionRequired if true, then we are performing an explicit
1587/// instantiation where the body of the function is required. Complain if
1588/// there is no such body.
1589void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
1590                                         FunctionDecl *Function,
1591                                         bool Recursive,
1592                                         bool DefinitionRequired) {
1593  if (Function->isInvalidDecl())
1594    return;
1595
1596  assert(!Function->getBody() && "Already instantiated!");
1597
1598  // Never instantiate an explicit specialization.
1599  if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1600    return;
1601
1602  // Find the function body that we'll be substituting.
1603  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
1604  Stmt *Pattern = 0;
1605  if (PatternDecl)
1606    Pattern = PatternDecl->getBody(PatternDecl);
1607
1608  if (!Pattern) {
1609    if (DefinitionRequired) {
1610      if (Function->getPrimaryTemplate())
1611        Diag(PointOfInstantiation,
1612             diag::err_explicit_instantiation_undefined_func_template)
1613          << Function->getPrimaryTemplate();
1614      else
1615        Diag(PointOfInstantiation,
1616             diag::err_explicit_instantiation_undefined_member)
1617          << 1 << Function->getDeclName() << Function->getDeclContext();
1618
1619      if (PatternDecl)
1620        Diag(PatternDecl->getLocation(),
1621             diag::note_explicit_instantiation_here);
1622    }
1623
1624    return;
1625  }
1626
1627  // C++0x [temp.explicit]p9:
1628  //   Except for inline functions, other explicit instantiation declarations
1629  //   have the effect of suppressing the implicit instantiation of the entity
1630  //   to which they refer.
1631  if (Function->getTemplateSpecializationKind()
1632        == TSK_ExplicitInstantiationDeclaration &&
1633      !PatternDecl->isInlined())
1634    return;
1635
1636  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1637  if (Inst)
1638    return;
1639
1640  // If we're performing recursive template instantiation, create our own
1641  // queue of pending implicit instantiations that we will instantiate later,
1642  // while we're still within our own instantiation context.
1643  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1644  if (Recursive)
1645    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1646
1647  ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1648
1649  // Introduce a new scope where local variable instantiations will be
1650  // recorded.
1651  LocalInstantiationScope Scope(*this);
1652
1653  // Introduce the instantiated function parameters into the local
1654  // instantiation scope.
1655  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1656    Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1657                            Function->getParamDecl(I));
1658
1659  // Enter the scope of this instantiation. We don't use
1660  // PushDeclContext because we don't have a scope.
1661  DeclContext *PreviousContext = CurContext;
1662  CurContext = Function;
1663
1664  MultiLevelTemplateArgumentList TemplateArgs =
1665    getTemplateInstantiationArgs(Function);
1666
1667  // If this is a constructor, instantiate the member initializers.
1668  if (const CXXConstructorDecl *Ctor =
1669        dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1670    InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1671                               TemplateArgs);
1672  }
1673
1674  // Instantiate the function body.
1675  OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
1676
1677  if (Body.isInvalid())
1678    Function->setInvalidDecl();
1679
1680  ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
1681                          /*IsInstantiation=*/true);
1682
1683  CurContext = PreviousContext;
1684
1685  DeclGroupRef DG(Function);
1686  Consumer.HandleTopLevelDecl(DG);
1687
1688  if (Recursive) {
1689    // Instantiate any pending implicit instantiations found during the
1690    // instantiation of this template.
1691    PerformPendingImplicitInstantiations();
1692
1693    // Restore the set of pending implicit instantiations.
1694    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1695  }
1696}
1697
1698/// \brief Instantiate the definition of the given variable from its
1699/// template.
1700///
1701/// \param PointOfInstantiation the point at which the instantiation was
1702/// required. Note that this is not precisely a "point of instantiation"
1703/// for the function, but it's close.
1704///
1705/// \param Var the already-instantiated declaration of a static member
1706/// variable of a class template specialization.
1707///
1708/// \param Recursive if true, recursively instantiates any functions that
1709/// are required by this instantiation.
1710///
1711/// \param DefinitionRequired if true, then we are performing an explicit
1712/// instantiation where an out-of-line definition of the member variable
1713/// is required. Complain if there is no such definition.
1714void Sema::InstantiateStaticDataMemberDefinition(
1715                                          SourceLocation PointOfInstantiation,
1716                                                 VarDecl *Var,
1717                                                 bool Recursive,
1718                                                 bool DefinitionRequired) {
1719  if (Var->isInvalidDecl())
1720    return;
1721
1722  // Find the out-of-line definition of this static data member.
1723  VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1724  assert(Def && "This data member was not instantiated from a template?");
1725  assert(Def->isStaticDataMember() && "Not a static data member?");
1726  Def = Def->getOutOfLineDefinition();
1727
1728  if (!Def) {
1729    // We did not find an out-of-line definition of this static data member,
1730    // so we won't perform any instantiation. Rather, we rely on the user to
1731    // instantiate this definition (or provide a specialization for it) in
1732    // another translation unit.
1733    if (DefinitionRequired) {
1734      Def = Var->getInstantiatedFromStaticDataMember();
1735      Diag(PointOfInstantiation,
1736           diag::err_explicit_instantiation_undefined_member)
1737        << 2 << Var->getDeclName() << Var->getDeclContext();
1738      Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1739    }
1740
1741    return;
1742  }
1743
1744  // Never instantiate an explicit specialization.
1745  if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1746    return;
1747
1748  // C++0x [temp.explicit]p9:
1749  //   Except for inline functions, other explicit instantiation declarations
1750  //   have the effect of suppressing the implicit instantiation of the entity
1751  //   to which they refer.
1752  if (Var->getTemplateSpecializationKind()
1753        == TSK_ExplicitInstantiationDeclaration)
1754    return;
1755
1756  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1757  if (Inst)
1758    return;
1759
1760  // If we're performing recursive template instantiation, create our own
1761  // queue of pending implicit instantiations that we will instantiate later,
1762  // while we're still within our own instantiation context.
1763  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1764  if (Recursive)
1765    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1766
1767  // Enter the scope of this instantiation. We don't use
1768  // PushDeclContext because we don't have a scope.
1769  DeclContext *PreviousContext = CurContext;
1770  CurContext = Var->getDeclContext();
1771
1772  VarDecl *OldVar = Var;
1773  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
1774                                          getTemplateInstantiationArgs(Var)));
1775  CurContext = PreviousContext;
1776
1777  if (Var) {
1778    Var->setPreviousDeclaration(OldVar);
1779    MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1780    assert(MSInfo && "Missing member specialization information?");
1781    Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1782                                       MSInfo->getPointOfInstantiation());
1783    DeclGroupRef DG(Var);
1784    Consumer.HandleTopLevelDecl(DG);
1785  }
1786
1787  if (Recursive) {
1788    // Instantiate any pending implicit instantiations found during the
1789    // instantiation of this template.
1790    PerformPendingImplicitInstantiations();
1791
1792    // Restore the set of pending implicit instantiations.
1793    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1794  }
1795}
1796
1797void
1798Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1799                                 const CXXConstructorDecl *Tmpl,
1800                           const MultiLevelTemplateArgumentList &TemplateArgs) {
1801
1802  llvm::SmallVector<MemInitTy*, 4> NewInits;
1803
1804  // Instantiate all the initializers.
1805  for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
1806                                            InitsEnd = Tmpl->init_end();
1807       Inits != InitsEnd; ++Inits) {
1808    CXXBaseOrMemberInitializer *Init = *Inits;
1809
1810    ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
1811
1812    // Instantiate all the arguments.
1813    for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1814         Args != ArgsEnd; ++Args) {
1815      OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1816
1817      if (NewArg.isInvalid())
1818        New->setInvalidDecl();
1819      else
1820        NewArgs.push_back(NewArg.takeAs<Expr>());
1821    }
1822
1823    MemInitResult NewInit;
1824
1825    if (Init->isBaseInitializer()) {
1826      TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
1827                                            TemplateArgs,
1828                                            Init->getSourceLocation(),
1829                                            New->getDeclName());
1830      if (!BaseTInfo) {
1831        New->setInvalidDecl();
1832        continue;
1833      }
1834
1835      NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
1836                                     (Expr **)NewArgs.data(),
1837                                     NewArgs.size(),
1838                                     Init->getLParenLoc(),
1839                                     Init->getRParenLoc(),
1840                                     New->getParent());
1841    } else if (Init->isMemberInitializer()) {
1842      FieldDecl *Member;
1843
1844      // Is this an anonymous union?
1845      if (FieldDecl *UnionInit = Init->getAnonUnionMember())
1846        Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
1847      else
1848        Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1849                                                      TemplateArgs));
1850
1851      NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
1852                                       NewArgs.size(),
1853                                       Init->getSourceLocation(),
1854                                       Init->getLParenLoc(),
1855                                       Init->getRParenLoc());
1856    }
1857
1858    if (NewInit.isInvalid())
1859      New->setInvalidDecl();
1860    else {
1861      // FIXME: It would be nice if ASTOwningVector had a release function.
1862      NewArgs.take();
1863
1864      NewInits.push_back((MemInitTy *)NewInit.get());
1865    }
1866  }
1867
1868  // Assign all the initializers to the new constructor.
1869  ActOnMemInitializers(DeclPtrTy::make(New),
1870                       /*FIXME: ColonLoc */
1871                       SourceLocation(),
1872                       NewInits.data(), NewInits.size());
1873}
1874
1875// TODO: this could be templated if the various decl types used the
1876// same method name.
1877static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1878                              ClassTemplateDecl *Instance) {
1879  Pattern = Pattern->getCanonicalDecl();
1880
1881  do {
1882    Instance = Instance->getCanonicalDecl();
1883    if (Pattern == Instance) return true;
1884    Instance = Instance->getInstantiatedFromMemberTemplate();
1885  } while (Instance);
1886
1887  return false;
1888}
1889
1890static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1891                              FunctionTemplateDecl *Instance) {
1892  Pattern = Pattern->getCanonicalDecl();
1893
1894  do {
1895    Instance = Instance->getCanonicalDecl();
1896    if (Pattern == Instance) return true;
1897    Instance = Instance->getInstantiatedFromMemberTemplate();
1898  } while (Instance);
1899
1900  return false;
1901}
1902
1903static bool
1904isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1905                  ClassTemplatePartialSpecializationDecl *Instance) {
1906  Pattern
1907    = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1908  do {
1909    Instance = cast<ClassTemplatePartialSpecializationDecl>(
1910                                                Instance->getCanonicalDecl());
1911    if (Pattern == Instance)
1912      return true;
1913    Instance = Instance->getInstantiatedFromMember();
1914  } while (Instance);
1915
1916  return false;
1917}
1918
1919static bool isInstantiationOf(CXXRecordDecl *Pattern,
1920                              CXXRecordDecl *Instance) {
1921  Pattern = Pattern->getCanonicalDecl();
1922
1923  do {
1924    Instance = Instance->getCanonicalDecl();
1925    if (Pattern == Instance) return true;
1926    Instance = Instance->getInstantiatedFromMemberClass();
1927  } while (Instance);
1928
1929  return false;
1930}
1931
1932static bool isInstantiationOf(FunctionDecl *Pattern,
1933                              FunctionDecl *Instance) {
1934  Pattern = Pattern->getCanonicalDecl();
1935
1936  do {
1937    Instance = Instance->getCanonicalDecl();
1938    if (Pattern == Instance) return true;
1939    Instance = Instance->getInstantiatedFromMemberFunction();
1940  } while (Instance);
1941
1942  return false;
1943}
1944
1945static bool isInstantiationOf(EnumDecl *Pattern,
1946                              EnumDecl *Instance) {
1947  Pattern = Pattern->getCanonicalDecl();
1948
1949  do {
1950    Instance = Instance->getCanonicalDecl();
1951    if (Pattern == Instance) return true;
1952    Instance = Instance->getInstantiatedFromMemberEnum();
1953  } while (Instance);
1954
1955  return false;
1956}
1957
1958static bool isInstantiationOf(UsingShadowDecl *Pattern,
1959                              UsingShadowDecl *Instance,
1960                              ASTContext &C) {
1961  return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
1962}
1963
1964static bool isInstantiationOf(UsingDecl *Pattern,
1965                              UsingDecl *Instance,
1966                              ASTContext &C) {
1967  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
1968}
1969
1970static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1971                              UsingDecl *Instance,
1972                              ASTContext &C) {
1973  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
1974}
1975
1976static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
1977                              UsingDecl *Instance,
1978                              ASTContext &C) {
1979  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
1980}
1981
1982static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1983                                              VarDecl *Instance) {
1984  assert(Instance->isStaticDataMember());
1985
1986  Pattern = Pattern->getCanonicalDecl();
1987
1988  do {
1989    Instance = Instance->getCanonicalDecl();
1990    if (Pattern == Instance) return true;
1991    Instance = Instance->getInstantiatedFromStaticDataMember();
1992  } while (Instance);
1993
1994  return false;
1995}
1996
1997// Other is the prospective instantiation
1998// D is the prospective pattern
1999static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
2000  if (D->getKind() != Other->getKind()) {
2001    if (UnresolvedUsingTypenameDecl *UUD
2002          = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2003      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2004        return isInstantiationOf(UUD, UD, Ctx);
2005      }
2006    }
2007
2008    if (UnresolvedUsingValueDecl *UUD
2009          = dyn_cast<UnresolvedUsingValueDecl>(D)) {
2010      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2011        return isInstantiationOf(UUD, UD, Ctx);
2012      }
2013    }
2014
2015    return false;
2016  }
2017
2018  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2019    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
2020
2021  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2022    return isInstantiationOf(cast<FunctionDecl>(D), Function);
2023
2024  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2025    return isInstantiationOf(cast<EnumDecl>(D), Enum);
2026
2027  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
2028    if (Var->isStaticDataMember())
2029      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2030
2031  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2032    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
2033
2034  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2035    return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2036
2037  if (ClassTemplatePartialSpecializationDecl *PartialSpec
2038        = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2039    return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2040                             PartialSpec);
2041
2042  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2043    if (!Field->getDeclName()) {
2044      // This is an unnamed field.
2045      return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
2046        cast<FieldDecl>(D);
2047    }
2048  }
2049
2050  if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2051    return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2052
2053  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2054    return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2055
2056  return D->getDeclName() && isa<NamedDecl>(Other) &&
2057    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2058}
2059
2060template<typename ForwardIterator>
2061static NamedDecl *findInstantiationOf(ASTContext &Ctx,
2062                                      NamedDecl *D,
2063                                      ForwardIterator first,
2064                                      ForwardIterator last) {
2065  for (; first != last; ++first)
2066    if (isInstantiationOf(Ctx, D, *first))
2067      return cast<NamedDecl>(*first);
2068
2069  return 0;
2070}
2071
2072/// \brief Finds the instantiation of the given declaration context
2073/// within the current instantiation.
2074///
2075/// \returns NULL if there was an error
2076DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
2077                          const MultiLevelTemplateArgumentList &TemplateArgs) {
2078  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
2079    Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
2080    return cast_or_null<DeclContext>(ID);
2081  } else return DC;
2082}
2083
2084/// \brief Find the instantiation of the given declaration within the
2085/// current instantiation.
2086///
2087/// This routine is intended to be used when \p D is a declaration
2088/// referenced from within a template, that needs to mapped into the
2089/// corresponding declaration within an instantiation. For example,
2090/// given:
2091///
2092/// \code
2093/// template<typename T>
2094/// struct X {
2095///   enum Kind {
2096///     KnownValue = sizeof(T)
2097///   };
2098///
2099///   bool getKind() const { return KnownValue; }
2100/// };
2101///
2102/// template struct X<int>;
2103/// \endcode
2104///
2105/// In the instantiation of X<int>::getKind(), we need to map the
2106/// EnumConstantDecl for KnownValue (which refers to
2107/// X<T>::<Kind>::KnownValue) to its instantiation
2108/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2109/// this mapping from within the instantiation of X<int>.
2110NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
2111                          const MultiLevelTemplateArgumentList &TemplateArgs) {
2112  DeclContext *ParentDC = D->getDeclContext();
2113  if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2114      isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2115      ParentDC->isFunctionOrMethod()) {
2116    // D is a local of some kind. Look into the map of local
2117    // declarations to their instantiations.
2118    return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2119  }
2120
2121  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2122    if (!Record->isDependentContext())
2123      return D;
2124
2125    // If the RecordDecl is actually the injected-class-name or a "templated"
2126    // declaration for a class template or class template partial
2127    // specialization, substitute into the injected-class-name of the
2128    // class template or partial specialization to find the new DeclContext.
2129    QualType T;
2130    ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2131
2132    if (ClassTemplate) {
2133      T = ClassTemplate->getInjectedClassNameType(Context);
2134    } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2135                 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2136      T = Context.getTypeDeclType(Record);
2137      ClassTemplate = PartialSpec->getSpecializedTemplate();
2138    }
2139
2140    if (!T.isNull()) {
2141      // Substitute into the injected-class-name to get the type corresponding
2142      // to the instantiation we want. This substitution should never fail,
2143      // since we know we can instantiate the injected-class-name or we wouldn't
2144      // have gotten to the injected-class-name!
2145      // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
2146      // instantiation in the common case?
2147      T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2148      assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2149
2150      if (!T->isDependentType()) {
2151        assert(T->isRecordType() && "Instantiation must produce a record type");
2152        return T->getAs<RecordType>()->getDecl();
2153      }
2154
2155      // We are performing "partial" template instantiation to create the
2156      // member declarations for the members of a class template
2157      // specialization. Therefore, D is actually referring to something in
2158      // the current instantiation. Look through the current context,
2159      // which contains actual instantiations, to find the instantiation of
2160      // the "current instantiation" that D refers to.
2161      for (DeclContext *DC = CurContext; !DC->isFileContext();
2162           DC = DC->getParent()) {
2163        if (ClassTemplateSpecializationDecl *Spec
2164              = dyn_cast<ClassTemplateSpecializationDecl>(DC))
2165          if (isInstantiationOf(ClassTemplate,
2166                                Spec->getSpecializedTemplate()))
2167            return Spec;
2168      }
2169
2170      assert(false &&
2171             "Unable to find declaration for the current instantiation");
2172      return Record;
2173    }
2174
2175    // Fall through to deal with other dependent record types (e.g.,
2176    // anonymous unions in class templates).
2177  }
2178
2179  if (!ParentDC->isDependentContext())
2180    return D;
2181
2182  ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
2183  if (!ParentDC)
2184    return 0;
2185
2186  if (ParentDC != D->getDeclContext()) {
2187    // We performed some kind of instantiation in the parent context,
2188    // so now we need to look into the instantiated parent context to
2189    // find the instantiation of the declaration D.
2190    NamedDecl *Result = 0;
2191    if (D->getDeclName()) {
2192      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
2193      Result = findInstantiationOf(Context, D, Found.first, Found.second);
2194    } else {
2195      // Since we don't have a name for the entity we're looking for,
2196      // our only option is to walk through all of the declarations to
2197      // find that name. This will occur in a few cases:
2198      //
2199      //   - anonymous struct/union within a template
2200      //   - unnamed class/struct/union/enum within a template
2201      //
2202      // FIXME: Find a better way to find these instantiations!
2203      Result = findInstantiationOf(Context, D,
2204                                   ParentDC->decls_begin(),
2205                                   ParentDC->decls_end());
2206    }
2207
2208    // UsingShadowDecls can instantiate to nothing because of using hiding.
2209    assert((Result || isa<UsingShadowDecl>(D))
2210           && "Unable to find instantiation of declaration!");
2211
2212    D = Result;
2213  }
2214
2215  return D;
2216}
2217
2218/// \brief Performs template instantiation for all implicit template
2219/// instantiations we have seen until this point.
2220void Sema::PerformPendingImplicitInstantiations() {
2221  while (!PendingImplicitInstantiations.empty()) {
2222    PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
2223    PendingImplicitInstantiations.pop_front();
2224
2225    // Instantiate function definitions
2226    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
2227      PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
2228                                            Function->getLocation(), *this,
2229                                            Context.getSourceManager(),
2230                                           "instantiating function definition");
2231
2232      if (!Function->getBody())
2233        InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
2234      continue;
2235    }
2236
2237    // Instantiate static data member definitions.
2238    VarDecl *Var = cast<VarDecl>(Inst.first);
2239    assert(Var->isStaticDataMember() && "Not a static data member?");
2240
2241    PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
2242                                          Var->getLocation(), *this,
2243                                          Context.getSourceManager(),
2244                                          "instantiating static data member "
2245                                          "definition");
2246
2247    InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
2248  }
2249}
2250