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