SemaTemplateInstantiateDecl.cpp revision 8e7e4609012900d1a0eafafb49b5089acddf5b7a
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  FunctionDecl *Function =
496      FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
497                           D->getDeclName(), T, D->getDeclaratorInfo(),
498                           D->getStorageClass(),
499                           D->isInline(), D->hasWrittenPrototype());
500  Function->setLexicalDeclContext(Owner);
501
502  // Attach the parameters
503  for (unsigned P = 0; P < Params.size(); ++P)
504    Params[P]->setOwningFunction(Function);
505  Function->setParams(SemaRef.Context, Params.data(), Params.size());
506
507  // If the original function was part of a friend declaration,
508  // inherit its namespace state and add it to the owner.
509  if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) {
510    bool WasDeclared = (FOK == Decl::FOK_Declared);
511    Function->setObjectOfFriendDecl(WasDeclared);
512    if (!Owner->isDependentContext())
513      DC->makeDeclVisibleInContext(Function, /* Recoverable = */ false);
514
515    Function->setInstantiationOfMemberFunction(D);
516  }
517
518  if (InitFunctionInstantiation(Function, D))
519    Function->setInvalidDecl();
520
521  bool Redeclaration = false;
522  bool OverloadableAttrRequired = false;
523  NamedDecl *PrevDecl = 0;
524  SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
525                                   /*FIXME:*/OverloadableAttrRequired);
526
527  if (FunctionTemplate) {
528    // Record this function template specialization.
529    Function->setFunctionTemplateSpecialization(SemaRef.Context,
530                                                FunctionTemplate,
531                                                &TemplateArgs.getInnermost(),
532                                                InsertPos);
533  }
534
535  return Function;
536}
537
538Decl *
539TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
540                                      TemplateParameterList *TemplateParams) {
541  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
542  void *InsertPos = 0;
543  if (FunctionTemplate && !TemplateParams) {
544    // We are creating a function template specialization from a function
545    // template. Check whether there is already a function template
546    // specialization for this particular set of template arguments.
547    llvm::FoldingSetNodeID ID;
548    FunctionTemplateSpecializationInfo::Profile(ID,
549                            TemplateArgs.getInnermost().getFlatArgumentList(),
550                                      TemplateArgs.getInnermost().flat_size(),
551                                                SemaRef.Context);
552
553    FunctionTemplateSpecializationInfo *Info
554      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
555                                                                   InsertPos);
556
557    // If we already have a function template specialization, return it.
558    if (Info)
559      return Info->Function;
560  }
561
562  Sema::LocalInstantiationScope Scope(SemaRef);
563
564  llvm::SmallVector<ParmVarDecl *, 4> Params;
565  QualType T = SubstFunctionType(D, Params);
566  if (T.isNull())
567    return 0;
568
569  // Build the instantiated method declaration.
570  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
571  CXXMethodDecl *Method = 0;
572
573  DeclarationName Name = D->getDeclName();
574  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
575    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
576    Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
577                                    SemaRef.Context.getCanonicalType(ClassTy));
578    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
579                                        Constructor->getLocation(),
580                                        Name, T,
581                                        Constructor->getDeclaratorInfo(),
582                                        Constructor->isExplicit(),
583                                        Constructor->isInline(), false);
584  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
585    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
586    Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
587                                   SemaRef.Context.getCanonicalType(ClassTy));
588    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
589                                       Destructor->getLocation(), Name,
590                                       T, Destructor->isInline(), false);
591  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
592    CanQualType ConvTy
593      = SemaRef.Context.getCanonicalType(
594                                      T->getAsFunctionType()->getResultType());
595    Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
596                                                                      ConvTy);
597    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
598                                       Conversion->getLocation(), Name,
599                                       T, Conversion->getDeclaratorInfo(),
600                                       Conversion->isInline(),
601                                       Conversion->isExplicit());
602  } else {
603    Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
604                                   D->getDeclName(), T, D->getDeclaratorInfo(),
605                                   D->isStatic(), D->isInline());
606  }
607
608  if (TemplateParams) {
609    // Our resulting instantiation is actually a function template, since we
610    // are substituting only the outer template parameters. For example, given
611    //
612    //   template<typename T>
613    //   struct X {
614    //     template<typename U> void f(T, U);
615    //   };
616    //
617    //   X<int> x;
618    //
619    // We are instantiating the member template "f" within X<int>, which means
620    // substituting int for T, but leaving "f" as a member function template.
621    // Build the function template itself.
622    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
623                                                    Method->getLocation(),
624                                                    Method->getDeclName(),
625                                                    TemplateParams, Method);
626    if (D->isOutOfLine())
627      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
628    Method->setDescribedFunctionTemplate(FunctionTemplate);
629  } else if (!FunctionTemplate)
630    Method->setInstantiationOfMemberFunction(D);
631
632  // If we are instantiating a member function defined
633  // out-of-line, the instantiation will have the same lexical
634  // context (which will be a namespace scope) as the template.
635  if (D->isOutOfLine())
636    Method->setLexicalDeclContext(D->getLexicalDeclContext());
637
638  // Attach the parameters
639  for (unsigned P = 0; P < Params.size(); ++P)
640    Params[P]->setOwningFunction(Method);
641  Method->setParams(SemaRef.Context, Params.data(), Params.size());
642
643  if (InitMethodInstantiation(Method, D))
644    Method->setInvalidDecl();
645
646  NamedDecl *PrevDecl = 0;
647
648  if (!FunctionTemplate || TemplateParams) {
649    PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
650                                           Sema::LookupOrdinaryName, true);
651
652    // In C++, the previous declaration we find might be a tag type
653    // (class or enum). In this case, the new declaration will hide the
654    // tag type. Note that this does does not apply if we're declaring a
655    // typedef (C++ [dcl.typedef]p4).
656    if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
657      PrevDecl = 0;
658  }
659
660  if (FunctionTemplate && !TemplateParams)
661    // Record this function template specialization.
662    Method->setFunctionTemplateSpecialization(SemaRef.Context,
663                                              FunctionTemplate,
664                                              &TemplateArgs.getInnermost(),
665                                              InsertPos);
666
667  bool Redeclaration = false;
668  bool OverloadableAttrRequired = false;
669  SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
670                                   /*FIXME:*/OverloadableAttrRequired);
671
672  if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
673    Owner->addDecl(Method);
674
675  return Method;
676}
677
678Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
679  return VisitCXXMethodDecl(D);
680}
681
682Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
683  return VisitCXXMethodDecl(D);
684}
685
686Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
687  return VisitCXXMethodDecl(D);
688}
689
690ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
691  QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
692                                           D->getLocation(), D->getDeclName());
693  if (OrigT.isNull())
694    return 0;
695
696  QualType T = SemaRef.adjustParameterType(OrigT);
697
698  // Allocate the parameter
699  ParmVarDecl *Param = 0;
700  if (T == OrigT)
701    Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
702                                D->getIdentifier(), T, D->getDeclaratorInfo(),
703                                D->getStorageClass(), 0);
704  else
705    Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
706                                        D->getLocation(), D->getIdentifier(),
707                                        T, D->getDeclaratorInfo(), OrigT,
708                                        D->getStorageClass(), 0);
709
710  // Mark the default argument as being uninstantiated.
711  if (Expr *Arg = D->getDefaultArg())
712    Param->setUninstantiatedDefaultArg(Arg);
713
714  // Note: we don't try to instantiate function parameters until after
715  // we've instantiated the function's type. Therefore, we don't have
716  // to check for 'void' parameter types here.
717  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
718  return Param;
719}
720
721Decl *
722TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
723  // Since parameter types can decay either before or after
724  // instantiation, we simply treat OriginalParmVarDecls as
725  // ParmVarDecls the same way, and create one or the other depending
726  // on what happens after template instantiation.
727  return VisitParmVarDecl(D);
728}
729
730Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
731                                                    TemplateTypeParmDecl *D) {
732  // TODO: don't always clone when decls are refcounted.
733  const Type* T = D->getTypeForDecl();
734  assert(T->isTemplateTypeParmType());
735  const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
736
737  TemplateTypeParmDecl *Inst =
738    TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
739                                 TTPT->getDepth(), TTPT->getIndex(),
740                                 TTPT->getName(),
741                                 D->wasDeclaredWithTypename(),
742                                 D->isParameterPack());
743
744  if (D->hasDefaultArgument()) {
745    QualType DefaultPattern = D->getDefaultArgument();
746    QualType DefaultInst
747      = SemaRef.SubstType(DefaultPattern, TemplateArgs,
748                          D->getDefaultArgumentLoc(),
749                          D->getDeclName());
750
751    Inst->setDefaultArgument(DefaultInst,
752                             D->getDefaultArgumentLoc(),
753                             D->defaultArgumentWasInherited() /* preserve? */);
754  }
755
756  return Inst;
757}
758
759Decl *
760TemplateDeclInstantiator::VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D) {
761  NestedNameSpecifier *NNS =
762    SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
763                                     D->getTargetNestedNameRange(),
764                                     TemplateArgs);
765  if (!NNS)
766    return 0;
767
768  CXXScopeSpec SS;
769  SS.setRange(D->getTargetNestedNameRange());
770  SS.setScopeRep(NNS);
771
772  NamedDecl *UD =
773    SemaRef.BuildUsingDeclaration(D->getLocation(), SS,
774                                  D->getTargetNameLocation(),
775                                  D->getTargetName(), 0, D->isTypeName());
776  if (UD)
777    SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
778                                                           D);
779  return UD;
780}
781
782Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
783                      const MultiLevelTemplateArgumentList &TemplateArgs) {
784  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
785  return Instantiator.Visit(D);
786}
787
788/// \brief Instantiates a nested template parameter list in the current
789/// instantiation context.
790///
791/// \param L The parameter list to instantiate
792///
793/// \returns NULL if there was an error
794TemplateParameterList *
795TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
796  // Get errors for all the parameters before bailing out.
797  bool Invalid = false;
798
799  unsigned N = L->size();
800  typedef llvm::SmallVector<Decl*,8> ParamVector;
801  ParamVector Params;
802  Params.reserve(N);
803  for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
804       PI != PE; ++PI) {
805    Decl *D = Visit(*PI);
806    Params.push_back(D);
807    Invalid = Invalid || !D;
808  }
809
810  // Clean up if we had an error.
811  if (Invalid) {
812    for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
813         PI != PE; ++PI)
814      if (*PI)
815        (*PI)->Destroy(SemaRef.Context);
816    return NULL;
817  }
818
819  TemplateParameterList *InstL
820    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
821                                    L->getLAngleLoc(), &Params.front(), N,
822                                    L->getRAngleLoc());
823  return InstL;
824}
825
826/// \brief Does substitution on the type of the given function, including
827/// all of the function parameters.
828///
829/// \param D The function whose type will be the basis of the substitution
830///
831/// \param Params the instantiated parameter declarations
832
833/// \returns the instantiated function's type if successful, a NULL
834/// type if there was an error.
835QualType
836TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
837                              llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
838  bool InvalidDecl = false;
839
840  // Substitute all of the function's formal parameter types.
841  TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
842  llvm::SmallVector<QualType, 4> ParamTys;
843  for (FunctionDecl::param_iterator P = D->param_begin(),
844                                 PEnd = D->param_end();
845       P != PEnd; ++P) {
846    if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
847      if (PInst->getType()->isVoidType()) {
848        SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
849        PInst->setInvalidDecl();
850      } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
851                                                PInst->getType(),
852                                                diag::err_abstract_type_in_decl,
853                                                Sema::AbstractParamType))
854        PInst->setInvalidDecl();
855
856      Params.push_back(PInst);
857      ParamTys.push_back(PInst->getType());
858
859      if (PInst->isInvalidDecl())
860        InvalidDecl = true;
861    } else
862      InvalidDecl = true;
863  }
864
865  // FIXME: Deallocate dead declarations.
866  if (InvalidDecl)
867    return QualType();
868
869  const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
870  assert(Proto && "Missing prototype?");
871  QualType ResultType
872    = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
873                        D->getLocation(), D->getDeclName());
874  if (ResultType.isNull())
875    return QualType();
876
877  return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
878                                   Proto->isVariadic(), Proto->getTypeQuals(),
879                                   D->getLocation(), D->getDeclName());
880}
881
882/// \brief Initializes the common fields of an instantiation function
883/// declaration (New) from the corresponding fields of its template (Tmpl).
884///
885/// \returns true if there was an error
886bool
887TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
888                                                    FunctionDecl *Tmpl) {
889  if (Tmpl->isDeleted())
890    New->setDeleted();
891
892  // If we are performing substituting explicitly-specified template arguments
893  // or deduced template arguments into a function template and we reach this
894  // point, we are now past the point where SFINAE applies and have committed
895  // to keeping the new function template specialization. We therefore
896  // convert the active template instantiation for the function template
897  // into a template instantiation for this specific function template
898  // specialization, which is not a SFINAE context, so that we diagnose any
899  // further errors in the declaration itself.
900  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
901  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
902  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
903      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
904    if (FunctionTemplateDecl *FunTmpl
905          = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
906      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
907             "Deduction from the wrong function template?");
908      (void) FunTmpl;
909      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
910      ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
911    }
912  }
913
914  return false;
915}
916
917/// \brief Initializes common fields of an instantiated method
918/// declaration (New) from the corresponding fields of its template
919/// (Tmpl).
920///
921/// \returns true if there was an error
922bool
923TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
924                                                  CXXMethodDecl *Tmpl) {
925  if (InitFunctionInstantiation(New, Tmpl))
926    return true;
927
928  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
929  New->setAccess(Tmpl->getAccess());
930  if (Tmpl->isVirtualAsWritten()) {
931    New->setVirtualAsWritten(true);
932    Record->setAggregate(false);
933    Record->setPOD(false);
934    Record->setEmpty(false);
935    Record->setPolymorphic(true);
936  }
937  if (Tmpl->isPure()) {
938    New->setPure();
939    Record->setAbstract(true);
940  }
941
942  // FIXME: attributes
943  // FIXME: New needs a pointer to Tmpl
944  return false;
945}
946
947/// \brief Instantiate the definition of the given function from its
948/// template.
949///
950/// \param PointOfInstantiation the point at which the instantiation was
951/// required. Note that this is not precisely a "point of instantiation"
952/// for the function, but it's close.
953///
954/// \param Function the already-instantiated declaration of a
955/// function template specialization or member function of a class template
956/// specialization.
957///
958/// \param Recursive if true, recursively instantiates any functions that
959/// are required by this instantiation.
960void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
961                                         FunctionDecl *Function,
962                                         bool Recursive) {
963  if (Function->isInvalidDecl())
964    return;
965
966  assert(!Function->getBody() && "Already instantiated!");
967
968  // Find the function body that we'll be substituting.
969  const FunctionDecl *PatternDecl = 0;
970  if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate()) {
971    while (Primary->getInstantiatedFromMemberTemplate())
972      Primary = Primary->getInstantiatedFromMemberTemplate();
973
974    PatternDecl = Primary->getTemplatedDecl();
975  } else
976    PatternDecl = Function->getInstantiatedFromMemberFunction();
977  Stmt *Pattern = 0;
978  if (PatternDecl)
979    Pattern = PatternDecl->getBody(PatternDecl);
980
981  if (!Pattern)
982    return;
983
984  // C++0x [temp.explicit]p9:
985  //   Except for inline functions, other explicit instantiation declarations
986  //   have the effect of suppressing the implicit instantiation of the entity
987  //   to which they refer.
988  if (Function->getTemplateSpecializationKind()
989        == TSK_ExplicitInstantiationDeclaration &&
990      PatternDecl->isOutOfLine() && !PatternDecl->isInline())
991    return;
992
993  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
994  if (Inst)
995    return;
996
997  // If we're performing recursive template instantiation, create our own
998  // queue of pending implicit instantiations that we will instantiate later,
999  // while we're still within our own instantiation context.
1000  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1001  if (Recursive)
1002    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1003
1004  ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1005
1006  // Introduce a new scope where local variable instantiations will be
1007  // recorded.
1008  LocalInstantiationScope Scope(*this);
1009
1010  // Introduce the instantiated function parameters into the local
1011  // instantiation scope.
1012  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1013    Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1014                            Function->getParamDecl(I));
1015
1016  // Enter the scope of this instantiation. We don't use
1017  // PushDeclContext because we don't have a scope.
1018  DeclContext *PreviousContext = CurContext;
1019  CurContext = Function;
1020
1021  MultiLevelTemplateArgumentList TemplateArgs =
1022    getTemplateInstantiationArgs(Function);
1023
1024  // If this is a constructor, instantiate the member initializers.
1025  if (const CXXConstructorDecl *Ctor =
1026        dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1027    InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1028                               TemplateArgs);
1029  }
1030
1031  // Instantiate the function body.
1032  OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
1033
1034  ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
1035                          /*IsInstantiation=*/true);
1036
1037  CurContext = PreviousContext;
1038
1039  DeclGroupRef DG(Function);
1040  Consumer.HandleTopLevelDecl(DG);
1041
1042  if (Recursive) {
1043    // Instantiate any pending implicit instantiations found during the
1044    // instantiation of this template.
1045    PerformPendingImplicitInstantiations();
1046
1047    // Restore the set of pending implicit instantiations.
1048    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1049  }
1050}
1051
1052/// \brief Instantiate the definition of the given variable from its
1053/// template.
1054///
1055/// \param PointOfInstantiation the point at which the instantiation was
1056/// required. Note that this is not precisely a "point of instantiation"
1057/// for the function, but it's close.
1058///
1059/// \param Var the already-instantiated declaration of a static member
1060/// variable of a class template specialization.
1061///
1062/// \param Recursive if true, recursively instantiates any functions that
1063/// are required by this instantiation.
1064void Sema::InstantiateStaticDataMemberDefinition(
1065                                          SourceLocation PointOfInstantiation,
1066                                                 VarDecl *Var,
1067                                                 bool Recursive) {
1068  if (Var->isInvalidDecl())
1069    return;
1070
1071  // Find the out-of-line definition of this static data member.
1072  // FIXME: Do we have to look for specializations separately?
1073  VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1074  bool FoundOutOfLineDef = false;
1075  assert(Def && "This data member was not instantiated from a template?");
1076  assert(Def->isStaticDataMember() && "Not a static data member?");
1077  for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
1078                             RDEnd = Def->redecls_end();
1079       RD != RDEnd; ++RD) {
1080    if (RD->getLexicalDeclContext()->isFileContext()) {
1081      Def = *RD;
1082      FoundOutOfLineDef = true;
1083    }
1084  }
1085
1086  if (!FoundOutOfLineDef) {
1087    // We did not find an out-of-line definition of this static data member,
1088    // so we won't perform any instantiation. Rather, we rely on the user to
1089    // instantiate this definition (or provide a specialization for it) in
1090    // another translation unit.
1091    return;
1092  }
1093
1094  // FIXME: extern templates
1095
1096  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1097  if (Inst)
1098    return;
1099
1100  // If we're performing recursive template instantiation, create our own
1101  // queue of pending implicit instantiations that we will instantiate later,
1102  // while we're still within our own instantiation context.
1103  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1104  if (Recursive)
1105    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1106
1107  // Enter the scope of this instantiation. We don't use
1108  // PushDeclContext because we don't have a scope.
1109  DeclContext *PreviousContext = CurContext;
1110  CurContext = Var->getDeclContext();
1111
1112  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
1113                                          getTemplateInstantiationArgs(Var)));
1114
1115  CurContext = PreviousContext;
1116
1117  if (Var) {
1118    DeclGroupRef DG(Var);
1119    Consumer.HandleTopLevelDecl(DG);
1120  }
1121
1122  if (Recursive) {
1123    // Instantiate any pending implicit instantiations found during the
1124    // instantiation of this template.
1125    PerformPendingImplicitInstantiations();
1126
1127    // Restore the set of pending implicit instantiations.
1128    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1129  }
1130}
1131
1132void
1133Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1134                                 const CXXConstructorDecl *Tmpl,
1135                           const MultiLevelTemplateArgumentList &TemplateArgs) {
1136
1137  llvm::SmallVector<MemInitTy*, 4> NewInits;
1138
1139  // Instantiate all the initializers.
1140  for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
1141                                            InitsEnd = Tmpl->init_end();
1142       Inits != InitsEnd; ++Inits) {
1143    CXXBaseOrMemberInitializer *Init = *Inits;
1144
1145    ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
1146
1147    // Instantiate all the arguments.
1148    for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1149         Args != ArgsEnd; ++Args) {
1150      OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1151
1152      if (NewArg.isInvalid())
1153        New->setInvalidDecl();
1154      else
1155        NewArgs.push_back(NewArg.takeAs<Expr>());
1156    }
1157
1158    MemInitResult NewInit;
1159
1160    if (Init->isBaseInitializer()) {
1161      QualType BaseType(Init->getBaseClass(), 0);
1162      BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(),
1163                           New->getDeclName());
1164
1165      NewInit = BuildBaseInitializer(BaseType,
1166                                     (Expr **)NewArgs.data(),
1167                                     NewArgs.size(),
1168                                     Init->getSourceLocation(),
1169                                     Init->getRParenLoc(),
1170                                     New->getParent());
1171    } else if (Init->isMemberInitializer()) {
1172      FieldDecl *Member;
1173
1174      // Is this an anonymous union?
1175      if (FieldDecl *UnionInit = Init->getAnonUnionMember())
1176        Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit));
1177      else
1178        Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember()));
1179
1180      NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
1181                                       NewArgs.size(),
1182                                       Init->getSourceLocation(),
1183                                       Init->getRParenLoc());
1184    }
1185
1186    if (NewInit.isInvalid())
1187      New->setInvalidDecl();
1188    else {
1189      // FIXME: It would be nice if ASTOwningVector had a release function.
1190      NewArgs.take();
1191
1192      NewInits.push_back((MemInitTy *)NewInit.get());
1193    }
1194  }
1195
1196  // Assign all the initializers to the new constructor.
1197  ActOnMemInitializers(DeclPtrTy::make(New),
1198                       /*FIXME: ColonLoc */
1199                       SourceLocation(),
1200                       NewInits.data(), NewInits.size());
1201}
1202
1203// TODO: this could be templated if the various decl types used the
1204// same method name.
1205static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1206                              ClassTemplateDecl *Instance) {
1207  Pattern = Pattern->getCanonicalDecl();
1208
1209  do {
1210    Instance = Instance->getCanonicalDecl();
1211    if (Pattern == Instance) return true;
1212    Instance = Instance->getInstantiatedFromMemberTemplate();
1213  } while (Instance);
1214
1215  return false;
1216}
1217
1218static bool isInstantiationOf(CXXRecordDecl *Pattern,
1219                              CXXRecordDecl *Instance) {
1220  Pattern = Pattern->getCanonicalDecl();
1221
1222  do {
1223    Instance = Instance->getCanonicalDecl();
1224    if (Pattern == Instance) return true;
1225    Instance = Instance->getInstantiatedFromMemberClass();
1226  } while (Instance);
1227
1228  return false;
1229}
1230
1231static bool isInstantiationOf(FunctionDecl *Pattern,
1232                              FunctionDecl *Instance) {
1233  Pattern = Pattern->getCanonicalDecl();
1234
1235  do {
1236    Instance = Instance->getCanonicalDecl();
1237    if (Pattern == Instance) return true;
1238    Instance = Instance->getInstantiatedFromMemberFunction();
1239  } while (Instance);
1240
1241  return false;
1242}
1243
1244static bool isInstantiationOf(EnumDecl *Pattern,
1245                              EnumDecl *Instance) {
1246  Pattern = Pattern->getCanonicalDecl();
1247
1248  do {
1249    Instance = Instance->getCanonicalDecl();
1250    if (Pattern == Instance) return true;
1251    Instance = Instance->getInstantiatedFromMemberEnum();
1252  } while (Instance);
1253
1254  return false;
1255}
1256
1257static bool isInstantiationOf(UnresolvedUsingDecl *Pattern,
1258                              UsingDecl *Instance,
1259                              ASTContext &C) {
1260  return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1261}
1262
1263static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1264                                              VarDecl *Instance) {
1265  assert(Instance->isStaticDataMember());
1266
1267  Pattern = Pattern->getCanonicalDecl();
1268
1269  do {
1270    Instance = Instance->getCanonicalDecl();
1271    if (Pattern == Instance) return true;
1272    Instance = Instance->getInstantiatedFromStaticDataMember();
1273  } while (Instance);
1274
1275  return false;
1276}
1277
1278static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1279  if (D->getKind() != Other->getKind()) {
1280    if (UnresolvedUsingDecl *UUD = dyn_cast<UnresolvedUsingDecl>(D)) {
1281      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1282        return isInstantiationOf(UUD, UD, Ctx);
1283      }
1284    }
1285
1286    return false;
1287  }
1288
1289  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1290    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
1291
1292  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1293    return isInstantiationOf(cast<FunctionDecl>(D), Function);
1294
1295  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1296    return isInstantiationOf(cast<EnumDecl>(D), Enum);
1297
1298  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
1299    if (Var->isStaticDataMember())
1300      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1301
1302  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1303    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
1304
1305  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
1306    if (!Field->getDeclName()) {
1307      // This is an unnamed field.
1308      return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
1309        cast<FieldDecl>(D);
1310    }
1311  }
1312
1313  return D->getDeclName() && isa<NamedDecl>(Other) &&
1314    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1315}
1316
1317template<typename ForwardIterator>
1318static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1319                                      NamedDecl *D,
1320                                      ForwardIterator first,
1321                                      ForwardIterator last) {
1322  for (; first != last; ++first)
1323    if (isInstantiationOf(Ctx, D, *first))
1324      return cast<NamedDecl>(*first);
1325
1326  return 0;
1327}
1328
1329/// \brief Finds the instantiation of the given declaration context
1330/// within the current instantiation.
1331///
1332/// \returns NULL if there was an error
1333DeclContext *Sema::FindInstantiatedContext(DeclContext* DC) {
1334  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
1335    Decl* ID = FindInstantiatedDecl(D);
1336    return cast_or_null<DeclContext>(ID);
1337  } else return DC;
1338}
1339
1340/// \brief Find the instantiation of the given declaration within the
1341/// current instantiation.
1342///
1343/// This routine is intended to be used when \p D is a declaration
1344/// referenced from within a template, that needs to mapped into the
1345/// corresponding declaration within an instantiation. For example,
1346/// given:
1347///
1348/// \code
1349/// template<typename T>
1350/// struct X {
1351///   enum Kind {
1352///     KnownValue = sizeof(T)
1353///   };
1354///
1355///   bool getKind() const { return KnownValue; }
1356/// };
1357///
1358/// template struct X<int>;
1359/// \endcode
1360///
1361/// In the instantiation of X<int>::getKind(), we need to map the
1362/// EnumConstantDecl for KnownValue (which refers to
1363/// X<T>::<Kind>::KnownValue) to its instantiation
1364/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1365/// this mapping from within the instantiation of X<int>.
1366NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D) {
1367  if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
1368    // Transform all of the elements of the overloaded function set.
1369    OverloadedFunctionDecl *Result
1370      = OverloadedFunctionDecl::Create(Context, CurContext, Ovl->getDeclName());
1371
1372    for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1373                                                FEnd = Ovl->function_end();
1374         F != FEnd; ++F) {
1375      Result->addOverload(
1376                  AnyFunctionDecl::getFromNamedDecl(FindInstantiatedDecl(*F)));
1377    }
1378
1379    return Result;
1380  }
1381
1382  DeclContext *ParentDC = D->getDeclContext();
1383  if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1384    // D is a local of some kind. Look into the map of local
1385    // declarations to their instantiations.
1386    return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1387  }
1388
1389  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
1390    if (ClassTemplateDecl *ClassTemplate
1391          = Record->getDescribedClassTemplate()) {
1392      // When the declaration D was parsed, it referred to the current
1393      // instantiation. Therefore, look through the current context,
1394      // which contains actual instantiations, to find the
1395      // instantiation of the "current instantiation" that D refers
1396      // to. Alternatively, we could just instantiate the
1397      // injected-class-name with the current template arguments, but
1398      // such an instantiation is far more expensive.
1399      for (DeclContext *DC = CurContext; !DC->isFileContext();
1400           DC = DC->getParent()) {
1401        if (ClassTemplateSpecializationDecl *Spec
1402              = dyn_cast<ClassTemplateSpecializationDecl>(DC))
1403          if (isInstantiationOf(ClassTemplate, Spec->getSpecializedTemplate()))
1404            return Spec;
1405      }
1406
1407      assert(false &&
1408             "Unable to find declaration for the current instantiation");
1409    }
1410
1411  ParentDC = FindInstantiatedContext(ParentDC);
1412  if (!ParentDC)
1413    return 0;
1414
1415  if (ParentDC != D->getDeclContext()) {
1416    // We performed some kind of instantiation in the parent context,
1417    // so now we need to look into the instantiated parent context to
1418    // find the instantiation of the declaration D.
1419    NamedDecl *Result = 0;
1420    if (D->getDeclName()) {
1421      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
1422      Result = findInstantiationOf(Context, D, Found.first, Found.second);
1423    } else {
1424      // Since we don't have a name for the entity we're looking for,
1425      // our only option is to walk through all of the declarations to
1426      // find that name. This will occur in a few cases:
1427      //
1428      //   - anonymous struct/union within a template
1429      //   - unnamed class/struct/union/enum within a template
1430      //
1431      // FIXME: Find a better way to find these instantiations!
1432      Result = findInstantiationOf(Context, D,
1433                                   ParentDC->decls_begin(),
1434                                   ParentDC->decls_end());
1435    }
1436
1437    assert(Result && "Unable to find instantiation of declaration!");
1438    D = Result;
1439  }
1440
1441  return D;
1442}
1443
1444/// \brief Performs template instantiation for all implicit template
1445/// instantiations we have seen until this point.
1446void Sema::PerformPendingImplicitInstantiations() {
1447  while (!PendingImplicitInstantiations.empty()) {
1448    PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
1449    PendingImplicitInstantiations.pop_front();
1450
1451    // Instantiate function definitions
1452    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
1453      PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
1454                                            Function->getLocation(), *this,
1455                                            Context.getSourceManager(),
1456                                           "instantiating function definition");
1457
1458      if (!Function->getBody())
1459        InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
1460      continue;
1461    }
1462
1463    // Instantiate static data member definitions.
1464    VarDecl *Var = cast<VarDecl>(Inst.first);
1465    assert(Var->isStaticDataMember() && "Not a static data member?");
1466
1467    PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
1468                                          Var->getLocation(), *this,
1469                                          Context.getSourceManager(),
1470                                          "instantiating static data member "
1471                                          "definition");
1472
1473    InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
1474  }
1475}
1476