SemaTemplateInstantiateDecl.cpp revision 0b5a4153437fd6e8d76adf8fa105126cd67c06f1
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 "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
17#include "clang/AST/Expr.h"
18#include "clang/Basic/PrettyStackTrace.h"
19#include "clang/Lex/Preprocessor.h"
20#include "llvm/Support/Compiler.h"
21
22using namespace clang;
23
24namespace {
25  class VISIBILITY_HIDDEN TemplateDeclInstantiator
26    : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
27    Sema &SemaRef;
28    DeclContext *Owner;
29    const MultiLevelTemplateArgumentList &TemplateArgs;
30
31  public:
32    typedef Sema::OwningExprResult OwningExprResult;
33
34    TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
35                             const MultiLevelTemplateArgumentList &TemplateArgs)
36      : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
37
38    // FIXME: Once we get closer to completion, replace these manually-written
39    // declarations with automatically-generated ones from
40    // clang/AST/DeclNodes.def.
41    Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
42    Decl *VisitNamespaceDecl(NamespaceDecl *D);
43    Decl *VisitTypedefDecl(TypedefDecl *D);
44    Decl *VisitVarDecl(VarDecl *D);
45    Decl *VisitFieldDecl(FieldDecl *D);
46    Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
47    Decl *VisitEnumDecl(EnumDecl *D);
48    Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
49    Decl *VisitFriendDecl(FriendDecl *D);
50    Decl *VisitFunctionDecl(FunctionDecl *D);
51    Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
52    Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
53                             TemplateParameterList *TemplateParams = 0);
54    Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
55    Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
56    Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
57    ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
58    Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
59    Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
60    Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
61    Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
62    Decl *VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D);
63
64    // Base case. FIXME: Remove once we can instantiate everything.
65    Decl *VisitDecl(Decl *) {
66      assert(false && "Template instantiation of unknown declaration kind!");
67      return 0;
68    }
69
70    const LangOptions &getLangOptions() {
71      return SemaRef.getLangOptions();
72    }
73
74    // Helper functions for instantiating methods.
75    QualType SubstFunctionType(FunctionDecl *D,
76                             llvm::SmallVectorImpl<ParmVarDecl *> &Params);
77    bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
78    bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
79
80    TemplateParameterList *
81      SubstTemplateParams(TemplateParameterList *List);
82  };
83}
84
85Decl *
86TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
87  assert(false && "Translation units cannot be instantiated");
88  return D;
89}
90
91Decl *
92TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
93  assert(false && "Namespaces cannot be instantiated");
94  return D;
95}
96
97Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
98  bool Invalid = false;
99  QualType T = D->getUnderlyingType();
100  if (T->isDependentType()) {
101    T = SemaRef.SubstType(T, TemplateArgs,
102                          D->getLocation(), D->getDeclName());
103    if (T.isNull()) {
104      Invalid = true;
105      T = SemaRef.Context.IntTy;
106    }
107  }
108
109  // Create the new typedef
110  TypedefDecl *Typedef
111    = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
112                          D->getIdentifier(), T);
113  if (Invalid)
114    Typedef->setInvalidDecl();
115
116  Owner->addDecl(Typedef);
117
118  return Typedef;
119}
120
121Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
122  // Do substitution on the type of the declaration
123  QualType T = SemaRef.SubstType(D->getType(), TemplateArgs,
124                                 D->getTypeSpecStartLoc(),
125                                 D->getDeclName());
126  if (T.isNull())
127    return 0;
128
129  // Build the instantiated declaration
130  VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
131                                 D->getLocation(), D->getIdentifier(),
132                                 T, D->getDeclaratorInfo(),
133                                 D->getStorageClass());
134  Var->setThreadSpecified(D->isThreadSpecified());
135  Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
136  Var->setDeclaredInCondition(D->isDeclaredInCondition());
137
138  // If we are instantiating a static data member defined
139  // out-of-line, the instantiation will have the same lexical
140  // context (which will be a namespace scope) as the template.
141  if (D->isOutOfLine())
142    Var->setLexicalDeclContext(D->getLexicalDeclContext());
143
144  // FIXME: In theory, we could have a previous declaration for variables that
145  // are not static data members.
146  bool Redeclaration = false;
147  SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
148
149  if (D->isOutOfLine()) {
150    D->getLexicalDeclContext()->addDecl(Var);
151    Owner->makeDeclVisibleInContext(Var);
152  } else {
153    Owner->addDecl(Var);
154  }
155
156  if (D->getInit()) {
157    OwningExprResult Init
158      = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
159    if (Init.isInvalid())
160      Var->setInvalidDecl();
161    else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
162      // FIXME: We're faking all of the comma locations, which is suboptimal.
163      // Do we even need these comma locations?
164      llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
165      if (PLE->getNumExprs() > 0) {
166        FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
167        for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
168          Expr *E = PLE->getExpr(I)->Retain();
169          FakeCommaLocs.push_back(
170                                SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
171        }
172        PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
173      }
174
175      // Add the direct initializer to the declaration.
176      SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
177                                            PLE->getLParenLoc(),
178                                            Sema::MultiExprArg(SemaRef,
179                                                       (void**)PLE->getExprs(),
180                                                           PLE->getNumExprs()),
181                                            FakeCommaLocs.data(),
182                                            PLE->getRParenLoc());
183
184      // When Init is destroyed, it will destroy the instantiated ParenListExpr;
185      // we've explicitly retained all of its subexpressions already.
186    } else
187      SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
188                                   D->hasCXXDirectInitializer());
189  } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
190    SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
191
192  // Link instantiations of static data members back to the template from
193  // which they were instantiated.
194  if (Var->isStaticDataMember())
195    SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
196
197  return Var;
198}
199
200Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
201  bool Invalid = false;
202  QualType T = D->getType();
203  if (T->isDependentType())  {
204    T = SemaRef.SubstType(T, TemplateArgs,
205                          D->getLocation(), D->getDeclName());
206    if (!T.isNull() && T->isFunctionType()) {
207      // C++ [temp.arg.type]p3:
208      //   If a declaration acquires a function type through a type
209      //   dependent on a template-parameter and this causes a
210      //   declaration that does not use the syntactic form of a
211      //   function declarator to have function type, the program is
212      //   ill-formed.
213      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
214        << T;
215      T = QualType();
216      Invalid = true;
217    }
218  }
219
220  Expr *BitWidth = D->getBitWidth();
221  if (Invalid)
222    BitWidth = 0;
223  else if (BitWidth) {
224    // The bit-width expression is not potentially evaluated.
225    EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
226
227    OwningExprResult InstantiatedBitWidth
228      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
229    if (InstantiatedBitWidth.isInvalid()) {
230      Invalid = true;
231      BitWidth = 0;
232    } else
233      BitWidth = InstantiatedBitWidth.takeAs<Expr>();
234  }
235
236  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
237                                            D->getDeclaratorInfo(),
238                                            cast<RecordDecl>(Owner),
239                                            D->getLocation(),
240                                            D->isMutable(),
241                                            BitWidth,
242                                            D->getTypeSpecStartLoc(),
243                                            D->getAccess(),
244                                            0);
245  if (!Field)
246    return 0;
247
248  if (Invalid)
249    Field->setInvalidDecl();
250
251  if (!Field->getDeclName()) {
252    // Keep track of where this decl came from.
253    SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
254  }
255
256  Field->setImplicit(D->isImplicit());
257  Owner->addDecl(Field);
258
259  return Field;
260}
261
262Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
263  FriendDecl::FriendUnion FU;
264
265  // Handle friend type expressions by simply substituting template
266  // parameters into the pattern type.
267  if (Type *Ty = D->getFriendType()) {
268    QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
269                                   D->getLocation(), DeclarationName());
270    if (T.isNull()) return 0;
271
272    assert(getLangOptions().CPlusPlus0x || T->isRecordType());
273    FU = T.getTypePtr();
274
275  // Handle everything else by appropriate substitution.
276  } else {
277    NamedDecl *ND = D->getFriendDecl();
278    assert(ND && "friend decl must be a decl or a type!");
279
280    Decl *NewND = Visit(ND);
281    if (!NewND) return 0;
282
283    FU = cast<NamedDecl>(NewND);
284  }
285
286  FriendDecl *FD =
287    FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
288                       D->getFriendLoc());
289  FD->setAccess(AS_public);
290  Owner->addDecl(FD);
291  return FD;
292}
293
294Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
295  Expr *AssertExpr = D->getAssertExpr();
296
297  // The expression in a static assertion is not potentially evaluated.
298  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
299
300  OwningExprResult InstantiatedAssertExpr
301    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
302  if (InstantiatedAssertExpr.isInvalid())
303    return 0;
304
305  OwningExprResult Message(SemaRef, D->getMessage());
306  D->getMessage()->Retain();
307  Decl *StaticAssert
308    = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
309                                           move(InstantiatedAssertExpr),
310                                           move(Message)).getAs<Decl>();
311  return StaticAssert;
312}
313
314Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
315  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
316                                    D->getLocation(), D->getIdentifier(),
317                                    D->getTagKeywordLoc(),
318                                    /*PrevDecl=*/0);
319  Enum->setInstantiationOfMemberEnum(D);
320  Enum->setAccess(D->getAccess());
321  Owner->addDecl(Enum);
322  Enum->startDefinition();
323
324  llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
325
326  EnumConstantDecl *LastEnumConst = 0;
327  for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
328         ECEnd = D->enumerator_end();
329       EC != ECEnd; ++EC) {
330    // The specified value for the enumerator.
331    OwningExprResult Value = SemaRef.Owned((Expr *)0);
332    if (Expr *UninstValue = EC->getInitExpr()) {
333      // The enumerator's value expression is not potentially evaluated.
334      EnterExpressionEvaluationContext Unevaluated(SemaRef,
335                                                   Action::Unevaluated);
336
337      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
338    }
339
340    // Drop the initial value and continue.
341    bool isInvalid = false;
342    if (Value.isInvalid()) {
343      Value = SemaRef.Owned((Expr *)0);
344      isInvalid = true;
345    }
346
347    EnumConstantDecl *EnumConst
348      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
349                                  EC->getLocation(), EC->getIdentifier(),
350                                  move(Value));
351
352    if (isInvalid) {
353      if (EnumConst)
354        EnumConst->setInvalidDecl();
355      Enum->setInvalidDecl();
356    }
357
358    if (EnumConst) {
359      Enum->addDecl(EnumConst);
360      Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
361      LastEnumConst = EnumConst;
362    }
363  }
364
365  // FIXME: Fixup LBraceLoc and RBraceLoc
366  // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
367  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
368                        Sema::DeclPtrTy::make(Enum),
369                        &Enumerators[0], Enumerators.size(),
370                        0, 0);
371
372  return Enum;
373}
374
375Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
376  assert(false && "EnumConstantDecls can only occur within EnumDecls.");
377  return 0;
378}
379
380Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
381  TemplateParameterList *TempParams = D->getTemplateParameters();
382  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
383  if (!InstParams)
384    return NULL;
385
386  CXXRecordDecl *Pattern = D->getTemplatedDecl();
387  CXXRecordDecl *RecordInst
388    = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
389                            Pattern->getLocation(), Pattern->getIdentifier(),
390                            Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
391
392  ClassTemplateDecl *Inst
393    = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
394                                D->getIdentifier(), InstParams, RecordInst, 0);
395  RecordInst->setDescribedClassTemplate(Inst);
396  Inst->setAccess(D->getAccess());
397  Inst->setInstantiatedFromMemberTemplate(D);
398
399  Owner->addDecl(Inst);
400  return Inst;
401}
402
403Decl *
404TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
405  // FIXME: Dig out the out-of-line definition of this function template?
406
407  TemplateParameterList *TempParams = D->getTemplateParameters();
408  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
409  if (!InstParams)
410    return NULL;
411
412  // FIXME: Handle instantiation of nested function templates that aren't
413  // member function templates. This could happen inside a FriendDecl.
414  assert(isa<CXXMethodDecl>(D->getTemplatedDecl()));
415  CXXMethodDecl *InstMethod
416    = cast_or_null<CXXMethodDecl>(
417                 VisitCXXMethodDecl(cast<CXXMethodDecl>(D->getTemplatedDecl()),
418                                    InstParams));
419  if (!InstMethod)
420    return 0;
421
422  // Link the instantiated function template declaration to the function
423  // template from which it was instantiated.
424  FunctionTemplateDecl *InstTemplate = InstMethod->getDescribedFunctionTemplate();
425  assert(InstTemplate && "VisitCXXMethodDecl didn't create a template!");
426  InstTemplate->setInstantiatedFromMemberTemplate(D);
427  Owner->addDecl(InstTemplate);
428  return InstTemplate;
429}
430
431Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
432  CXXRecordDecl *PrevDecl = 0;
433  if (D->isInjectedClassName())
434    PrevDecl = cast<CXXRecordDecl>(Owner);
435
436  CXXRecordDecl *Record
437    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
438                            D->getLocation(), D->getIdentifier(),
439                            D->getTagKeywordLoc(), PrevDecl);
440  Record->setImplicit(D->isImplicit());
441  // FIXME: Check against AS_none is an ugly hack to work around the issue that
442  // the tag decls introduced by friend class declarations don't have an access
443  // specifier. Remove once this area of the code gets sorted out.
444  if (D->getAccess() != AS_none)
445    Record->setAccess(D->getAccess());
446  if (!D->isInjectedClassName())
447    Record->setInstantiationOfMemberClass(D);
448
449  // If the original function was part of a friend declaration,
450  // inherit its namespace state.
451  if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
452    Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
453
454  Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
455
456  Owner->addDecl(Record);
457  return Record;
458}
459
460/// Normal class members are of more specific types and therefore
461/// don't make it here.  This function serves two purposes:
462///   1) instantiating function templates
463///   2) substituting friend declarations
464/// FIXME: preserve function definitions in case #2
465Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
466  // Check whether there is already a function template specialization for
467  // this declaration.
468  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
469  void *InsertPos = 0;
470  if (FunctionTemplate) {
471    llvm::FoldingSetNodeID ID;
472    FunctionTemplateSpecializationInfo::Profile(ID,
473                             TemplateArgs.getInnermost().getFlatArgumentList(),
474                                       TemplateArgs.getInnermost().flat_size(),
475                                                SemaRef.Context);
476
477    FunctionTemplateSpecializationInfo *Info
478      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
479                                                                   InsertPos);
480
481    // If we already have a function template specialization, return it.
482    if (Info)
483      return Info->Function;
484  }
485
486  Sema::LocalInstantiationScope Scope(SemaRef);
487
488  llvm::SmallVector<ParmVarDecl *, 4> Params;
489  QualType T = SubstFunctionType(D, Params);
490  if (T.isNull())
491    return 0;
492
493  // Build the instantiated method declaration.
494  DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
495                                                    TemplateArgs);
496  FunctionDecl *Function =
497      FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
498                           D->getDeclName(), T, D->getDeclaratorInfo(),
499                           D->getStorageClass(),
500                           D->isInline(), D->hasWrittenPrototype());
501  Function->setLexicalDeclContext(Owner);
502
503  // Attach the parameters
504  for (unsigned P = 0; P < Params.size(); ++P)
505    Params[P]->setOwningFunction(Function);
506  Function->setParams(SemaRef.Context, Params.data(), Params.size());
507
508  // If the original function was part of a friend declaration,
509  // inherit its namespace state and add it to the owner.
510  if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) {
511    bool WasDeclared = (FOK == Decl::FOK_Declared);
512    Function->setObjectOfFriendDecl(WasDeclared);
513    if (!Owner->isDependentContext())
514      DC->makeDeclVisibleInContext(Function, /* Recoverable = */ false);
515
516    Function->setInstantiationOfMemberFunction(D);
517  }
518
519  if (InitFunctionInstantiation(Function, D))
520    Function->setInvalidDecl();
521
522  bool Redeclaration = false;
523  bool OverloadableAttrRequired = false;
524  NamedDecl *PrevDecl = 0;
525  SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
526                                   /*FIXME:*/OverloadableAttrRequired);
527
528  if (FunctionTemplate) {
529    // Record this function template specialization.
530    Function->setFunctionTemplateSpecialization(SemaRef.Context,
531                                                FunctionTemplate,
532                                                &TemplateArgs.getInnermost(),
533                                                InsertPos);
534  }
535
536  return Function;
537}
538
539Decl *
540TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
541                                      TemplateParameterList *TemplateParams) {
542  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
543  void *InsertPos = 0;
544  if (FunctionTemplate && !TemplateParams) {
545    // We are creating a function template specialization from a function
546    // template. Check whether there is already a function template
547    // specialization for this particular set of template arguments.
548    llvm::FoldingSetNodeID ID;
549    FunctionTemplateSpecializationInfo::Profile(ID,
550                            TemplateArgs.getInnermost().getFlatArgumentList(),
551                                      TemplateArgs.getInnermost().flat_size(),
552                                                SemaRef.Context);
553
554    FunctionTemplateSpecializationInfo *Info
555      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
556                                                                   InsertPos);
557
558    // If we already have a function template specialization, return it.
559    if (Info)
560      return Info->Function;
561  }
562
563  Sema::LocalInstantiationScope Scope(SemaRef);
564
565  llvm::SmallVector<ParmVarDecl *, 4> Params;
566  QualType T = SubstFunctionType(D, Params);
567  if (T.isNull())
568    return 0;
569
570  // Build the instantiated method declaration.
571  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
572  CXXMethodDecl *Method = 0;
573
574  DeclarationName Name = D->getDeclName();
575  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
576    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
577    Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
578                                    SemaRef.Context.getCanonicalType(ClassTy));
579    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
580                                        Constructor->getLocation(),
581                                        Name, T,
582                                        Constructor->getDeclaratorInfo(),
583                                        Constructor->isExplicit(),
584                                        Constructor->isInline(), false);
585  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
586    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
587    Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
588                                   SemaRef.Context.getCanonicalType(ClassTy));
589    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
590                                       Destructor->getLocation(), Name,
591                                       T, Destructor->isInline(), false);
592  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
593    CanQualType ConvTy
594      = SemaRef.Context.getCanonicalType(
595                                      T->getAs<FunctionType>()->getResultType());
596    Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
597                                                                      ConvTy);
598    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
599                                       Conversion->getLocation(), Name,
600                                       T, Conversion->getDeclaratorInfo(),
601                                       Conversion->isInline(),
602                                       Conversion->isExplicit());
603  } else {
604    Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
605                                   D->getDeclName(), T, D->getDeclaratorInfo(),
606                                   D->isStatic(), D->isInline());
607  }
608
609  if (TemplateParams) {
610    // Our resulting instantiation is actually a function template, since we
611    // are substituting only the outer template parameters. For example, given
612    //
613    //   template<typename T>
614    //   struct X {
615    //     template<typename U> void f(T, U);
616    //   };
617    //
618    //   X<int> x;
619    //
620    // We are instantiating the member template "f" within X<int>, which means
621    // substituting int for T, but leaving "f" as a member function template.
622    // Build the function template itself.
623    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
624                                                    Method->getLocation(),
625                                                    Method->getDeclName(),
626                                                    TemplateParams, Method);
627    if (D->isOutOfLine())
628      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
629    Method->setDescribedFunctionTemplate(FunctionTemplate);
630  } else if (!FunctionTemplate)
631    Method->setInstantiationOfMemberFunction(D);
632
633  // If we are instantiating a member function defined
634  // out-of-line, the instantiation will have the same lexical
635  // context (which will be a namespace scope) as the template.
636  if (D->isOutOfLine())
637    Method->setLexicalDeclContext(D->getLexicalDeclContext());
638
639  // Attach the parameters
640  for (unsigned P = 0; P < Params.size(); ++P)
641    Params[P]->setOwningFunction(Method);
642  Method->setParams(SemaRef.Context, Params.data(), Params.size());
643
644  if (InitMethodInstantiation(Method, D))
645    Method->setInvalidDecl();
646
647  NamedDecl *PrevDecl = 0;
648
649  if (!FunctionTemplate || TemplateParams) {
650    PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
651                                           Sema::LookupOrdinaryName, true);
652
653    // In C++, the previous declaration we find might be a tag type
654    // (class or enum). In this case, the new declaration will hide the
655    // tag type. Note that this does does not apply if we're declaring a
656    // typedef (C++ [dcl.typedef]p4).
657    if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
658      PrevDecl = 0;
659  }
660
661  if (FunctionTemplate && !TemplateParams)
662    // Record this function template specialization.
663    Method->setFunctionTemplateSpecialization(SemaRef.Context,
664                                              FunctionTemplate,
665                                              &TemplateArgs.getInnermost(),
666                                              InsertPos);
667
668  bool Redeclaration = false;
669  bool OverloadableAttrRequired = false;
670  SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
671                                   /*FIXME:*/OverloadableAttrRequired);
672
673  if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
674    Owner->addDecl(Method);
675
676  return Method;
677}
678
679Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
680  return VisitCXXMethodDecl(D);
681}
682
683Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
684  return VisitCXXMethodDecl(D);
685}
686
687Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
688  return VisitCXXMethodDecl(D);
689}
690
691ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
692  QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
693                                           D->getLocation(), D->getDeclName());
694  if (OrigT.isNull())
695    return 0;
696
697  QualType T = SemaRef.adjustParameterType(OrigT);
698
699  // Allocate the parameter
700  ParmVarDecl *Param = 0;
701  if (T == OrigT)
702    Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
703                                D->getIdentifier(), T, D->getDeclaratorInfo(),
704                                D->getStorageClass(), 0);
705  else
706    Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
707                                        D->getLocation(), D->getIdentifier(),
708                                        T, D->getDeclaratorInfo(), OrigT,
709                                        D->getStorageClass(), 0);
710
711  // Mark the default argument as being uninstantiated.
712  if (D->hasUninstantiatedDefaultArg())
713    Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
714  else if (Expr *Arg = D->getDefaultArg())
715    Param->setUninstantiatedDefaultArg(Arg);
716
717  // Note: we don't try to instantiate function parameters until after
718  // we've instantiated the function's type. Therefore, we don't have
719  // to check for 'void' parameter types here.
720  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
721  return Param;
722}
723
724Decl *
725TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
726  // Since parameter types can decay either before or after
727  // instantiation, we simply treat OriginalParmVarDecls as
728  // ParmVarDecls the same way, and create one or the other depending
729  // on what happens after template instantiation.
730  return VisitParmVarDecl(D);
731}
732
733Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
734                                                    TemplateTypeParmDecl *D) {
735  // TODO: don't always clone when decls are refcounted.
736  const Type* T = D->getTypeForDecl();
737  assert(T->isTemplateTypeParmType());
738  const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
739
740  TemplateTypeParmDecl *Inst =
741    TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
742                                 TTPT->getDepth(), TTPT->getIndex(),
743                                 TTPT->getName(),
744                                 D->wasDeclaredWithTypename(),
745                                 D->isParameterPack());
746
747  if (D->hasDefaultArgument()) {
748    QualType DefaultPattern = D->getDefaultArgument();
749    QualType DefaultInst
750      = SemaRef.SubstType(DefaultPattern, TemplateArgs,
751                          D->getDefaultArgumentLoc(),
752                          D->getDeclName());
753
754    Inst->setDefaultArgument(DefaultInst,
755                             D->getDefaultArgumentLoc(),
756                             D->defaultArgumentWasInherited() /* preserve? */);
757  }
758
759  return Inst;
760}
761
762Decl *
763TemplateDeclInstantiator::VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D) {
764  NestedNameSpecifier *NNS =
765    SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
766                                     D->getTargetNestedNameRange(),
767                                     TemplateArgs);
768  if (!NNS)
769    return 0;
770
771  CXXScopeSpec SS;
772  SS.setRange(D->getTargetNestedNameRange());
773  SS.setScopeRep(NNS);
774
775  NamedDecl *UD =
776    SemaRef.BuildUsingDeclaration(D->getLocation(), SS,
777                                  D->getTargetNameLocation(),
778                                  D->getTargetName(), 0, D->isTypeName());
779  if (UD)
780    SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
781                                                           D);
782  return UD;
783}
784
785Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
786                      const MultiLevelTemplateArgumentList &TemplateArgs) {
787  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
788  return Instantiator.Visit(D);
789}
790
791/// \brief Instantiates a nested template parameter list in the current
792/// instantiation context.
793///
794/// \param L The parameter list to instantiate
795///
796/// \returns NULL if there was an error
797TemplateParameterList *
798TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
799  // Get errors for all the parameters before bailing out.
800  bool Invalid = false;
801
802  unsigned N = L->size();
803  typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
804  ParamVector Params;
805  Params.reserve(N);
806  for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
807       PI != PE; ++PI) {
808    NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
809    Params.push_back(D);
810    Invalid = Invalid || !D;
811  }
812
813  // Clean up if we had an error.
814  if (Invalid) {
815    for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
816         PI != PE; ++PI)
817      if (*PI)
818        (*PI)->Destroy(SemaRef.Context);
819    return NULL;
820  }
821
822  TemplateParameterList *InstL
823    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
824                                    L->getLAngleLoc(), &Params.front(), N,
825                                    L->getRAngleLoc());
826  return InstL;
827}
828
829/// \brief Does substitution on the type of the given function, including
830/// all of the function parameters.
831///
832/// \param D The function whose type will be the basis of the substitution
833///
834/// \param Params the instantiated parameter declarations
835
836/// \returns the instantiated function's type if successful, a NULL
837/// type if there was an error.
838QualType
839TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
840                              llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
841  bool InvalidDecl = false;
842
843  // Substitute all of the function's formal parameter types.
844  TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
845  llvm::SmallVector<QualType, 4> ParamTys;
846  for (FunctionDecl::param_iterator P = D->param_begin(),
847                                 PEnd = D->param_end();
848       P != PEnd; ++P) {
849    if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
850      if (PInst->getType()->isVoidType()) {
851        SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
852        PInst->setInvalidDecl();
853      } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
854                                                PInst->getType(),
855                                                diag::err_abstract_type_in_decl,
856                                                Sema::AbstractParamType))
857        PInst->setInvalidDecl();
858
859      Params.push_back(PInst);
860      ParamTys.push_back(PInst->getType());
861
862      if (PInst->isInvalidDecl())
863        InvalidDecl = true;
864    } else
865      InvalidDecl = true;
866  }
867
868  // FIXME: Deallocate dead declarations.
869  if (InvalidDecl)
870    return QualType();
871
872  const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
873  assert(Proto && "Missing prototype?");
874  QualType ResultType
875    = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
876                        D->getLocation(), D->getDeclName());
877  if (ResultType.isNull())
878    return QualType();
879
880  return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
881                                   Proto->isVariadic(), Proto->getTypeQuals(),
882                                   D->getLocation(), D->getDeclName());
883}
884
885/// \brief Initializes the common fields of an instantiation function
886/// declaration (New) from the corresponding fields of its template (Tmpl).
887///
888/// \returns true if there was an error
889bool
890TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
891                                                    FunctionDecl *Tmpl) {
892  if (Tmpl->isDeleted())
893    New->setDeleted();
894
895  // If we are performing substituting explicitly-specified template arguments
896  // or deduced template arguments into a function template and we reach this
897  // point, we are now past the point where SFINAE applies and have committed
898  // to keeping the new function template specialization. We therefore
899  // convert the active template instantiation for the function template
900  // into a template instantiation for this specific function template
901  // specialization, which is not a SFINAE context, so that we diagnose any
902  // further errors in the declaration itself.
903  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
904  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
905  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
906      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
907    if (FunctionTemplateDecl *FunTmpl
908          = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
909      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
910             "Deduction from the wrong function template?");
911      (void) FunTmpl;
912      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
913      ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
914    }
915  }
916
917  return false;
918}
919
920/// \brief Initializes common fields of an instantiated method
921/// declaration (New) from the corresponding fields of its template
922/// (Tmpl).
923///
924/// \returns true if there was an error
925bool
926TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
927                                                  CXXMethodDecl *Tmpl) {
928  if (InitFunctionInstantiation(New, Tmpl))
929    return true;
930
931  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
932  New->setAccess(Tmpl->getAccess());
933  if (Tmpl->isVirtualAsWritten()) {
934    New->setVirtualAsWritten(true);
935    Record->setAggregate(false);
936    Record->setPOD(false);
937    Record->setEmpty(false);
938    Record->setPolymorphic(true);
939  }
940  if (Tmpl->isPure()) {
941    New->setPure();
942    Record->setAbstract(true);
943  }
944
945  // FIXME: attributes
946  // FIXME: New needs a pointer to Tmpl
947  return false;
948}
949
950/// \brief Instantiate the definition of the given function from its
951/// template.
952///
953/// \param PointOfInstantiation the point at which the instantiation was
954/// required. Note that this is not precisely a "point of instantiation"
955/// for the function, but it's close.
956///
957/// \param Function the already-instantiated declaration of a
958/// function template specialization or member function of a class template
959/// specialization.
960///
961/// \param Recursive if true, recursively instantiates any functions that
962/// are required by this instantiation.
963void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
964                                         FunctionDecl *Function,
965                                         bool Recursive) {
966  if (Function->isInvalidDecl())
967    return;
968
969  assert(!Function->getBody() && "Already instantiated!");
970
971  // Find the function body that we'll be substituting.
972  const FunctionDecl *PatternDecl = 0;
973  if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate()) {
974    while (Primary->getInstantiatedFromMemberTemplate())
975      Primary = Primary->getInstantiatedFromMemberTemplate();
976
977    PatternDecl = Primary->getTemplatedDecl();
978  } else
979    PatternDecl = Function->getInstantiatedFromMemberFunction();
980  Stmt *Pattern = 0;
981  if (PatternDecl)
982    Pattern = PatternDecl->getBody(PatternDecl);
983
984  if (!Pattern)
985    return;
986
987  // C++0x [temp.explicit]p9:
988  //   Except for inline functions, other explicit instantiation declarations
989  //   have the effect of suppressing the implicit instantiation of the entity
990  //   to which they refer.
991  if (Function->getTemplateSpecializationKind()
992        == TSK_ExplicitInstantiationDeclaration &&
993      PatternDecl->isOutOfLine() && !PatternDecl->isInline())
994    return;
995
996  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
997  if (Inst)
998    return;
999
1000  // If we're performing recursive template instantiation, create our own
1001  // queue of pending implicit instantiations that we will instantiate later,
1002  // while we're still within our own instantiation context.
1003  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1004  if (Recursive)
1005    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1006
1007  ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1008
1009  // Introduce a new scope where local variable instantiations will be
1010  // recorded.
1011  LocalInstantiationScope Scope(*this);
1012
1013  // Introduce the instantiated function parameters into the local
1014  // instantiation scope.
1015  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1016    Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1017                            Function->getParamDecl(I));
1018
1019  // Enter the scope of this instantiation. We don't use
1020  // PushDeclContext because we don't have a scope.
1021  DeclContext *PreviousContext = CurContext;
1022  CurContext = Function;
1023
1024  MultiLevelTemplateArgumentList TemplateArgs =
1025    getTemplateInstantiationArgs(Function);
1026
1027  // If this is a constructor, instantiate the member initializers.
1028  if (const CXXConstructorDecl *Ctor =
1029        dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1030    InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1031                               TemplateArgs);
1032  }
1033
1034  // Instantiate the function body.
1035  OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
1036
1037  if (Body.isInvalid())
1038    Function->setInvalidDecl();
1039
1040  ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
1041                          /*IsInstantiation=*/true);
1042
1043  CurContext = PreviousContext;
1044
1045  DeclGroupRef DG(Function);
1046  Consumer.HandleTopLevelDecl(DG);
1047
1048  if (Recursive) {
1049    // Instantiate any pending implicit instantiations found during the
1050    // instantiation of this template.
1051    PerformPendingImplicitInstantiations();
1052
1053    // Restore the set of pending implicit instantiations.
1054    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1055  }
1056}
1057
1058/// \brief Instantiate the definition of the given variable from its
1059/// template.
1060///
1061/// \param PointOfInstantiation the point at which the instantiation was
1062/// required. Note that this is not precisely a "point of instantiation"
1063/// for the function, but it's close.
1064///
1065/// \param Var the already-instantiated declaration of a static member
1066/// variable of a class template specialization.
1067///
1068/// \param Recursive if true, recursively instantiates any functions that
1069/// are required by this instantiation.
1070void Sema::InstantiateStaticDataMemberDefinition(
1071                                          SourceLocation PointOfInstantiation,
1072                                                 VarDecl *Var,
1073                                                 bool Recursive) {
1074  if (Var->isInvalidDecl())
1075    return;
1076
1077  // Find the out-of-line definition of this static data member.
1078  // FIXME: Do we have to look for specializations separately?
1079  VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1080  bool FoundOutOfLineDef = false;
1081  assert(Def && "This data member was not instantiated from a template?");
1082  assert(Def->isStaticDataMember() && "Not a static data member?");
1083  for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
1084                             RDEnd = Def->redecls_end();
1085       RD != RDEnd; ++RD) {
1086    if (RD->getLexicalDeclContext()->isFileContext()) {
1087      Def = *RD;
1088      FoundOutOfLineDef = true;
1089    }
1090  }
1091
1092  if (!FoundOutOfLineDef) {
1093    // We did not find an out-of-line definition of this static data member,
1094    // so we won't perform any instantiation. Rather, we rely on the user to
1095    // instantiate this definition (or provide a specialization for it) in
1096    // another translation unit.
1097    return;
1098  }
1099
1100  // FIXME: extern templates
1101
1102  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1103  if (Inst)
1104    return;
1105
1106  // If we're performing recursive template instantiation, create our own
1107  // queue of pending implicit instantiations that we will instantiate later,
1108  // while we're still within our own instantiation context.
1109  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1110  if (Recursive)
1111    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1112
1113  // Enter the scope of this instantiation. We don't use
1114  // PushDeclContext because we don't have a scope.
1115  DeclContext *PreviousContext = CurContext;
1116  CurContext = Var->getDeclContext();
1117
1118  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
1119                                          getTemplateInstantiationArgs(Var)));
1120
1121  CurContext = PreviousContext;
1122
1123  if (Var) {
1124    DeclGroupRef DG(Var);
1125    Consumer.HandleTopLevelDecl(DG);
1126  }
1127
1128  if (Recursive) {
1129    // Instantiate any pending implicit instantiations found during the
1130    // instantiation of this template.
1131    PerformPendingImplicitInstantiations();
1132
1133    // Restore the set of pending implicit instantiations.
1134    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1135  }
1136}
1137
1138void
1139Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1140                                 const CXXConstructorDecl *Tmpl,
1141                           const MultiLevelTemplateArgumentList &TemplateArgs) {
1142
1143  llvm::SmallVector<MemInitTy*, 4> NewInits;
1144
1145  // Instantiate all the initializers.
1146  for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
1147                                            InitsEnd = Tmpl->init_end();
1148       Inits != InitsEnd; ++Inits) {
1149    CXXBaseOrMemberInitializer *Init = *Inits;
1150
1151    ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
1152
1153    // Instantiate all the arguments.
1154    for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1155         Args != ArgsEnd; ++Args) {
1156      OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1157
1158      if (NewArg.isInvalid())
1159        New->setInvalidDecl();
1160      else
1161        NewArgs.push_back(NewArg.takeAs<Expr>());
1162    }
1163
1164    MemInitResult NewInit;
1165
1166    if (Init->isBaseInitializer()) {
1167      QualType BaseType(Init->getBaseClass(), 0);
1168      BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(),
1169                           New->getDeclName());
1170
1171      NewInit = BuildBaseInitializer(BaseType,
1172                                     (Expr **)NewArgs.data(),
1173                                     NewArgs.size(),
1174                                     Init->getSourceLocation(),
1175                                     Init->getRParenLoc(),
1176                                     New->getParent());
1177    } else if (Init->isMemberInitializer()) {
1178      FieldDecl *Member;
1179
1180      // Is this an anonymous union?
1181      if (FieldDecl *UnionInit = Init->getAnonUnionMember())
1182        Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
1183      else
1184        Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1185                                                      TemplateArgs));
1186
1187      NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
1188                                       NewArgs.size(),
1189                                       Init->getSourceLocation(),
1190                                       Init->getRParenLoc());
1191    }
1192
1193    if (NewInit.isInvalid())
1194      New->setInvalidDecl();
1195    else {
1196      // FIXME: It would be nice if ASTOwningVector had a release function.
1197      NewArgs.take();
1198
1199      NewInits.push_back((MemInitTy *)NewInit.get());
1200    }
1201  }
1202
1203  // Assign all the initializers to the new constructor.
1204  ActOnMemInitializers(DeclPtrTy::make(New),
1205                       /*FIXME: ColonLoc */
1206                       SourceLocation(),
1207                       NewInits.data(), NewInits.size());
1208}
1209
1210// TODO: this could be templated if the various decl types used the
1211// same method name.
1212static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1213                              ClassTemplateDecl *Instance) {
1214  Pattern = Pattern->getCanonicalDecl();
1215
1216  do {
1217    Instance = Instance->getCanonicalDecl();
1218    if (Pattern == Instance) return true;
1219    Instance = Instance->getInstantiatedFromMemberTemplate();
1220  } while (Instance);
1221
1222  return false;
1223}
1224
1225static bool isInstantiationOf(CXXRecordDecl *Pattern,
1226                              CXXRecordDecl *Instance) {
1227  Pattern = Pattern->getCanonicalDecl();
1228
1229  do {
1230    Instance = Instance->getCanonicalDecl();
1231    if (Pattern == Instance) return true;
1232    Instance = Instance->getInstantiatedFromMemberClass();
1233  } while (Instance);
1234
1235  return false;
1236}
1237
1238static bool isInstantiationOf(FunctionDecl *Pattern,
1239                              FunctionDecl *Instance) {
1240  Pattern = Pattern->getCanonicalDecl();
1241
1242  do {
1243    Instance = Instance->getCanonicalDecl();
1244    if (Pattern == Instance) return true;
1245    Instance = Instance->getInstantiatedFromMemberFunction();
1246  } while (Instance);
1247
1248  return false;
1249}
1250
1251static bool isInstantiationOf(EnumDecl *Pattern,
1252                              EnumDecl *Instance) {
1253  Pattern = Pattern->getCanonicalDecl();
1254
1255  do {
1256    Instance = Instance->getCanonicalDecl();
1257    if (Pattern == Instance) return true;
1258    Instance = Instance->getInstantiatedFromMemberEnum();
1259  } while (Instance);
1260
1261  return false;
1262}
1263
1264static bool isInstantiationOf(UnresolvedUsingDecl *Pattern,
1265                              UsingDecl *Instance,
1266                              ASTContext &C) {
1267  return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1268}
1269
1270static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1271                                              VarDecl *Instance) {
1272  assert(Instance->isStaticDataMember());
1273
1274  Pattern = Pattern->getCanonicalDecl();
1275
1276  do {
1277    Instance = Instance->getCanonicalDecl();
1278    if (Pattern == Instance) return true;
1279    Instance = Instance->getInstantiatedFromStaticDataMember();
1280  } while (Instance);
1281
1282  return false;
1283}
1284
1285static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1286  if (D->getKind() != Other->getKind()) {
1287    if (UnresolvedUsingDecl *UUD = dyn_cast<UnresolvedUsingDecl>(D)) {
1288      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1289        return isInstantiationOf(UUD, UD, Ctx);
1290      }
1291    }
1292
1293    return false;
1294  }
1295
1296  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1297    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
1298
1299  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1300    return isInstantiationOf(cast<FunctionDecl>(D), Function);
1301
1302  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1303    return isInstantiationOf(cast<EnumDecl>(D), Enum);
1304
1305  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
1306    if (Var->isStaticDataMember())
1307      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1308
1309  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1310    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
1311
1312  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
1313    if (!Field->getDeclName()) {
1314      // This is an unnamed field.
1315      return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
1316        cast<FieldDecl>(D);
1317    }
1318  }
1319
1320  return D->getDeclName() && isa<NamedDecl>(Other) &&
1321    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1322}
1323
1324template<typename ForwardIterator>
1325static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1326                                      NamedDecl *D,
1327                                      ForwardIterator first,
1328                                      ForwardIterator last) {
1329  for (; first != last; ++first)
1330    if (isInstantiationOf(Ctx, D, *first))
1331      return cast<NamedDecl>(*first);
1332
1333  return 0;
1334}
1335
1336/// \brief Finds the instantiation of the given declaration context
1337/// within the current instantiation.
1338///
1339/// \returns NULL if there was an error
1340DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
1341                          const MultiLevelTemplateArgumentList &TemplateArgs) {
1342  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
1343    Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
1344    return cast_or_null<DeclContext>(ID);
1345  } else return DC;
1346}
1347
1348/// \brief Find the instantiation of the given declaration within the
1349/// current instantiation.
1350///
1351/// This routine is intended to be used when \p D is a declaration
1352/// referenced from within a template, that needs to mapped into the
1353/// corresponding declaration within an instantiation. For example,
1354/// given:
1355///
1356/// \code
1357/// template<typename T>
1358/// struct X {
1359///   enum Kind {
1360///     KnownValue = sizeof(T)
1361///   };
1362///
1363///   bool getKind() const { return KnownValue; }
1364/// };
1365///
1366/// template struct X<int>;
1367/// \endcode
1368///
1369/// In the instantiation of X<int>::getKind(), we need to map the
1370/// EnumConstantDecl for KnownValue (which refers to
1371/// X<T>::<Kind>::KnownValue) to its instantiation
1372/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1373/// this mapping from within the instantiation of X<int>.
1374NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
1375                          const MultiLevelTemplateArgumentList &TemplateArgs) {
1376  if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
1377    // Transform all of the elements of the overloaded function set.
1378    OverloadedFunctionDecl *Result
1379      = OverloadedFunctionDecl::Create(Context, CurContext, Ovl->getDeclName());
1380
1381    for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1382                                                FEnd = Ovl->function_end();
1383         F != FEnd; ++F) {
1384      Result->addOverload(
1385        AnyFunctionDecl::getFromNamedDecl(FindInstantiatedDecl(*F,
1386                                                               TemplateArgs)));
1387    }
1388
1389    return Result;
1390  }
1391
1392  DeclContext *ParentDC = D->getDeclContext();
1393  if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1394    // D is a local of some kind. Look into the map of local
1395    // declarations to their instantiations.
1396    return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1397  }
1398
1399  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
1400    if (!Record->isDependentContext())
1401      return D;
1402
1403    // If the RecordDecl is actually the injected-class-name or a "templated"
1404    // declaration for a class template or class template partial
1405    // specialization, substitute into the injected-class-name of the
1406    // class template or partial specialization to find the new DeclContext.
1407    QualType T;
1408    ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
1409
1410    if (ClassTemplate) {
1411      T = ClassTemplate->getInjectedClassNameType(Context);
1412    } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1413                 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1414      T = Context.getTypeDeclType(Record);
1415      ClassTemplate = PartialSpec->getSpecializedTemplate();
1416    }
1417
1418    if (!T.isNull()) {
1419      // Substitute into the injected-class-name to get the type corresponding
1420      // to the instantiation we want. This substitution should never fail,
1421      // since we know we can instantiate the injected-class-name or we wouldn't
1422      // have gotten to the injected-class-name!
1423      // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
1424      // instantiation in the common case?
1425      T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
1426      assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
1427
1428      if (!T->isDependentType()) {
1429        assert(T->isRecordType() && "Instantiation must produce a record type");
1430        return T->getAs<RecordType>()->getDecl();
1431      }
1432
1433      // We are performing "partial" template instantiation to create the
1434      // member declarations for the members of a class template
1435      // specialization. Therefore, D is actually referring to something in
1436      // the current instantiation. Look through the current context,
1437      // which contains actual instantiations, to find the instantiation of
1438      // the "current instantiation" that D refers to.
1439      for (DeclContext *DC = CurContext; !DC->isFileContext();
1440           DC = DC->getParent()) {
1441        if (ClassTemplateSpecializationDecl *Spec
1442              = dyn_cast<ClassTemplateSpecializationDecl>(DC))
1443          if (isInstantiationOf(ClassTemplate,
1444                                Spec->getSpecializedTemplate()))
1445            return Spec;
1446      }
1447
1448      assert(false &&
1449             "Unable to find declaration for the current instantiation");
1450      return Record;
1451    }
1452
1453    // Fall through to deal with other dependent record types (e.g.,
1454    // anonymous unions in class templates).
1455  }
1456
1457  if (!ParentDC->isDependentContext())
1458    return D;
1459
1460  ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
1461  if (!ParentDC)
1462    return 0;
1463
1464  if (ParentDC != D->getDeclContext()) {
1465    // We performed some kind of instantiation in the parent context,
1466    // so now we need to look into the instantiated parent context to
1467    // find the instantiation of the declaration D.
1468    NamedDecl *Result = 0;
1469    if (D->getDeclName()) {
1470      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
1471      Result = findInstantiationOf(Context, D, Found.first, Found.second);
1472    } else {
1473      // Since we don't have a name for the entity we're looking for,
1474      // our only option is to walk through all of the declarations to
1475      // find that name. This will occur in a few cases:
1476      //
1477      //   - anonymous struct/union within a template
1478      //   - unnamed class/struct/union/enum within a template
1479      //
1480      // FIXME: Find a better way to find these instantiations!
1481      Result = findInstantiationOf(Context, D,
1482                                   ParentDC->decls_begin(),
1483                                   ParentDC->decls_end());
1484    }
1485
1486    assert(Result && "Unable to find instantiation of declaration!");
1487    D = Result;
1488  }
1489
1490  return D;
1491}
1492
1493/// \brief Performs template instantiation for all implicit template
1494/// instantiations we have seen until this point.
1495void Sema::PerformPendingImplicitInstantiations() {
1496  while (!PendingImplicitInstantiations.empty()) {
1497    PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
1498    PendingImplicitInstantiations.pop_front();
1499
1500    // Instantiate function definitions
1501    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
1502      PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
1503                                            Function->getLocation(), *this,
1504                                            Context.getSourceManager(),
1505                                           "instantiating function definition");
1506
1507      if (!Function->getBody())
1508        InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
1509      continue;
1510    }
1511
1512    // Instantiate static data member definitions.
1513    VarDecl *Var = cast<VarDecl>(Inst.first);
1514    assert(Var->isStaticDataMember() && "Not a static data member?");
1515
1516    PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
1517                                          Var->getLocation(), *this,
1518                                          Context.getSourceManager(),
1519                                          "instantiating static data member "
1520                                          "definition");
1521
1522    InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
1523  }
1524}
1525