SemaTemplateInstantiateDecl.cpp revision a5bf7f13d7772b164750997f95ab18487bbc4114
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  Owner->addDecl(FD);
282  return FD;
283}
284
285Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
286  Expr *AssertExpr = D->getAssertExpr();
287
288  // The expression in a static assertion is not potentially evaluated.
289  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
290
291  OwningExprResult InstantiatedAssertExpr
292    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
293  if (InstantiatedAssertExpr.isInvalid())
294    return 0;
295
296  OwningExprResult Message(SemaRef, D->getMessage());
297  D->getMessage()->Retain();
298  Decl *StaticAssert
299    = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
300                                           move(InstantiatedAssertExpr),
301                                           move(Message)).getAs<Decl>();
302  return StaticAssert;
303}
304
305Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
306  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
307                                    D->getLocation(), D->getIdentifier(),
308                                    D->getTagKeywordLoc(),
309                                    /*PrevDecl=*/0);
310  Enum->setInstantiationOfMemberEnum(D);
311  Enum->setAccess(D->getAccess());
312  Owner->addDecl(Enum);
313  Enum->startDefinition();
314
315  llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
316
317  EnumConstantDecl *LastEnumConst = 0;
318  for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
319         ECEnd = D->enumerator_end();
320       EC != ECEnd; ++EC) {
321    // The specified value for the enumerator.
322    OwningExprResult Value = SemaRef.Owned((Expr *)0);
323    if (Expr *UninstValue = EC->getInitExpr()) {
324      // The enumerator's value expression is not potentially evaluated.
325      EnterExpressionEvaluationContext Unevaluated(SemaRef,
326                                                   Action::Unevaluated);
327
328      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
329    }
330
331    // Drop the initial value and continue.
332    bool isInvalid = false;
333    if (Value.isInvalid()) {
334      Value = SemaRef.Owned((Expr *)0);
335      isInvalid = true;
336    }
337
338    EnumConstantDecl *EnumConst
339      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
340                                  EC->getLocation(), EC->getIdentifier(),
341                                  move(Value));
342
343    if (isInvalid) {
344      if (EnumConst)
345        EnumConst->setInvalidDecl();
346      Enum->setInvalidDecl();
347    }
348
349    if (EnumConst) {
350      Enum->addDecl(EnumConst);
351      Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
352      LastEnumConst = EnumConst;
353    }
354  }
355
356  // FIXME: Fixup LBraceLoc and RBraceLoc
357  // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
358  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
359                        Sema::DeclPtrTy::make(Enum),
360                        &Enumerators[0], Enumerators.size(),
361                        0, 0);
362
363  return Enum;
364}
365
366Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
367  assert(false && "EnumConstantDecls can only occur within EnumDecls.");
368  return 0;
369}
370
371Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
372  TemplateParameterList *TempParams = D->getTemplateParameters();
373  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
374  if (!InstParams)
375    return NULL;
376
377  CXXRecordDecl *Pattern = D->getTemplatedDecl();
378  CXXRecordDecl *RecordInst
379    = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
380                            Pattern->getLocation(), Pattern->getIdentifier(),
381                            Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
382
383  ClassTemplateDecl *Inst
384    = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
385                                D->getIdentifier(), InstParams, RecordInst, 0);
386  RecordInst->setDescribedClassTemplate(Inst);
387  Inst->setAccess(D->getAccess());
388  Inst->setInstantiatedFromMemberTemplate(D);
389
390  Owner->addDecl(Inst);
391  return Inst;
392}
393
394Decl *
395TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
396  TemplateParameterList *TempParams = D->getTemplateParameters();
397  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
398  if (!InstParams)
399    return NULL;
400
401  // FIXME: Handle instantiation of nested function templates that aren't
402  // member function templates. This could happen inside a FriendDecl.
403  assert(isa<CXXMethodDecl>(D->getTemplatedDecl()));
404  CXXMethodDecl *InstMethod
405    = cast_or_null<CXXMethodDecl>(
406                 VisitCXXMethodDecl(cast<CXXMethodDecl>(D->getTemplatedDecl()),
407                                    InstParams));
408  if (!InstMethod)
409    return 0;
410
411  // Link the instantiated function template declaration to the function
412  // template from which it was instantiated.
413  FunctionTemplateDecl *InstTemplate = InstMethod->getDescribedFunctionTemplate();
414  assert(InstTemplate && "VisitCXXMethodDecl didn't create a template!");
415  InstTemplate->setInstantiatedFromMemberTemplate(D);
416  Owner->addDecl(InstTemplate);
417  return InstTemplate;
418}
419
420Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
421  CXXRecordDecl *PrevDecl = 0;
422  if (D->isInjectedClassName())
423    PrevDecl = cast<CXXRecordDecl>(Owner);
424
425  CXXRecordDecl *Record
426    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
427                            D->getLocation(), D->getIdentifier(),
428                            D->getTagKeywordLoc(), PrevDecl);
429  Record->setImplicit(D->isImplicit());
430  // FIXME: Check against AS_none is an ugly hack to work around the issue that
431  // the tag decls introduced by friend class declarations don't have an access
432  // specifier. Remove once this area of the code gets sorted out.
433  if (D->getAccess() != AS_none)
434    Record->setAccess(D->getAccess());
435  if (!D->isInjectedClassName())
436    Record->setInstantiationOfMemberClass(D);
437
438  // If the original function was part of a friend declaration,
439  // inherit its namespace state.
440  if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
441    Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
442
443  Owner->addDecl(Record);
444  return Record;
445}
446
447/// Normal class members are of more specific types and therefore
448/// don't make it here.  This function serves two purposes:
449///   1) instantiating function templates
450///   2) substituting friend declarations
451/// FIXME: preserve function definitions in case #2
452Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
453  // Check whether there is already a function template specialization for
454  // this declaration.
455  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
456  void *InsertPos = 0;
457  if (FunctionTemplate) {
458    llvm::FoldingSetNodeID ID;
459    FunctionTemplateSpecializationInfo::Profile(ID,
460                             TemplateArgs.getInnermost().getFlatArgumentList(),
461                                       TemplateArgs.getInnermost().flat_size(),
462                                                SemaRef.Context);
463
464    FunctionTemplateSpecializationInfo *Info
465      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
466                                                                   InsertPos);
467
468    // If we already have a function template specialization, return it.
469    if (Info)
470      return Info->Function;
471  }
472
473  Sema::LocalInstantiationScope Scope(SemaRef);
474
475  llvm::SmallVector<ParmVarDecl *, 4> Params;
476  QualType T = SubstFunctionType(D, Params);
477  if (T.isNull())
478    return 0;
479
480  // Build the instantiated method declaration.
481  DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext());
482  FunctionDecl *Function =
483      FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
484                           D->getDeclName(), T, D->getDeclaratorInfo(),
485                           D->getStorageClass(),
486                           D->isInline(), D->hasWrittenPrototype());
487  Function->setLexicalDeclContext(Owner);
488
489  // Attach the parameters
490  for (unsigned P = 0; P < Params.size(); ++P)
491    Params[P]->setOwningFunction(Function);
492  Function->setParams(SemaRef.Context, Params.data(), Params.size());
493
494  // If the original function was part of a friend declaration,
495  // inherit its namespace state and add it to the owner.
496  if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) {
497    bool WasDeclared = (FOK == Decl::FOK_Declared);
498    Function->setObjectOfFriendDecl(WasDeclared);
499    if (!Owner->isDependentContext())
500      DC->makeDeclVisibleInContext(Function);
501  }
502
503  if (InitFunctionInstantiation(Function, D))
504    Function->setInvalidDecl();
505
506  bool Redeclaration = false;
507  bool OverloadableAttrRequired = false;
508  NamedDecl *PrevDecl = 0;
509  SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
510                                   /*FIXME:*/OverloadableAttrRequired);
511
512  if (FunctionTemplate) {
513    // Record this function template specialization.
514    Function->setFunctionTemplateSpecialization(SemaRef.Context,
515                                                FunctionTemplate,
516                                                &TemplateArgs.getInnermost(),
517                                                InsertPos);
518  }
519
520  return Function;
521}
522
523Decl *
524TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
525                                      TemplateParameterList *TemplateParams) {
526  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
527  void *InsertPos = 0;
528  if (FunctionTemplate && !TemplateParams) {
529    // We are creating a function template specialization from a function
530    // template. Check whether there is already a function template
531    // specialization for this particular set of template arguments.
532    llvm::FoldingSetNodeID ID;
533    FunctionTemplateSpecializationInfo::Profile(ID,
534                            TemplateArgs.getInnermost().getFlatArgumentList(),
535                                      TemplateArgs.getInnermost().flat_size(),
536                                                SemaRef.Context);
537
538    FunctionTemplateSpecializationInfo *Info
539      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
540                                                                   InsertPos);
541
542    // If we already have a function template specialization, return it.
543    if (Info)
544      return Info->Function;
545  }
546
547  Sema::LocalInstantiationScope Scope(SemaRef);
548
549  llvm::SmallVector<ParmVarDecl *, 4> Params;
550  QualType T = SubstFunctionType(D, Params);
551  if (T.isNull())
552    return 0;
553
554  // Build the instantiated method declaration.
555  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
556  CXXMethodDecl *Method = 0;
557
558  DeclarationName Name = D->getDeclName();
559  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
560    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
561    Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
562                                    SemaRef.Context.getCanonicalType(ClassTy));
563    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
564                                        Constructor->getLocation(),
565                                        Name, T,
566                                        Constructor->getDeclaratorInfo(),
567                                        Constructor->isExplicit(),
568                                        Constructor->isInline(), false);
569  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
570    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
571    Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
572                                   SemaRef.Context.getCanonicalType(ClassTy));
573    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
574                                       Destructor->getLocation(), Name,
575                                       T, Destructor->isInline(), false);
576  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
577    CanQualType ConvTy
578      = SemaRef.Context.getCanonicalType(
579                                      T->getAsFunctionType()->getResultType());
580    Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
581                                                                      ConvTy);
582    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
583                                       Conversion->getLocation(), Name,
584                                       T, Conversion->getDeclaratorInfo(),
585                                       Conversion->isInline(),
586                                       Conversion->isExplicit());
587  } else {
588    Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
589                                   D->getDeclName(), T, D->getDeclaratorInfo(),
590                                   D->isStatic(), D->isInline());
591  }
592
593  if (TemplateParams) {
594    // Our resulting instantiation is actually a function template, since we
595    // are substituting only the outer template parameters. For example, given
596    //
597    //   template<typename T>
598    //   struct X {
599    //     template<typename U> void f(T, U);
600    //   };
601    //
602    //   X<int> x;
603    //
604    // We are instantiating the member template "f" within X<int>, which means
605    // substituting int for T, but leaving "f" as a member function template.
606    // Build the function template itself.
607    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
608                                                    Method->getLocation(),
609                                                    Method->getDeclName(),
610                                                    TemplateParams, Method);
611    if (D->isOutOfLine())
612      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
613    Method->setDescribedFunctionTemplate(FunctionTemplate);
614  } else if (!FunctionTemplate)
615    Method->setInstantiationOfMemberFunction(D);
616
617  // If we are instantiating a member function defined
618  // out-of-line, the instantiation will have the same lexical
619  // context (which will be a namespace scope) as the template.
620  if (D->isOutOfLine())
621    Method->setLexicalDeclContext(D->getLexicalDeclContext());
622
623  // Attach the parameters
624  for (unsigned P = 0; P < Params.size(); ++P)
625    Params[P]->setOwningFunction(Method);
626  Method->setParams(SemaRef.Context, Params.data(), Params.size());
627
628  if (InitMethodInstantiation(Method, D))
629    Method->setInvalidDecl();
630
631  NamedDecl *PrevDecl = 0;
632
633  if (!FunctionTemplate || TemplateParams) {
634    PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
635                                           Sema::LookupOrdinaryName, true);
636
637    // In C++, the previous declaration we find might be a tag type
638    // (class or enum). In this case, the new declaration will hide the
639    // tag type. Note that this does does not apply if we're declaring a
640    // typedef (C++ [dcl.typedef]p4).
641    if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
642      PrevDecl = 0;
643  }
644
645  if (FunctionTemplate && !TemplateParams)
646    // Record this function template specialization.
647    Method->setFunctionTemplateSpecialization(SemaRef.Context,
648                                              FunctionTemplate,
649                                              &TemplateArgs.getInnermost(),
650                                              InsertPos);
651
652  bool Redeclaration = false;
653  bool OverloadableAttrRequired = false;
654  SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
655                                   /*FIXME:*/OverloadableAttrRequired);
656
657  if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
658    Owner->addDecl(Method);
659
660  return Method;
661}
662
663Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
664  return VisitCXXMethodDecl(D);
665}
666
667Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
668  return VisitCXXMethodDecl(D);
669}
670
671Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
672  return VisitCXXMethodDecl(D);
673}
674
675ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
676  QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
677                                           D->getLocation(), D->getDeclName());
678  if (OrigT.isNull())
679    return 0;
680
681  QualType T = SemaRef.adjustParameterType(OrigT);
682
683  // Allocate the parameter
684  ParmVarDecl *Param = 0;
685  if (T == OrigT)
686    Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
687                                D->getIdentifier(), T, D->getDeclaratorInfo(),
688                                D->getStorageClass(), 0);
689  else
690    Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
691                                        D->getLocation(), D->getIdentifier(),
692                                        T, D->getDeclaratorInfo(), OrigT,
693                                        D->getStorageClass(), 0);
694
695  // Mark the default argument as being uninstantiated.
696  if (Expr *Arg = D->getDefaultArg())
697    Param->setUninstantiatedDefaultArg(Arg);
698
699  // Note: we don't try to instantiate function parameters until after
700  // we've instantiated the function's type. Therefore, we don't have
701  // to check for 'void' parameter types here.
702  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
703  return Param;
704}
705
706Decl *
707TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
708  // Since parameter types can decay either before or after
709  // instantiation, we simply treat OriginalParmVarDecls as
710  // ParmVarDecls the same way, and create one or the other depending
711  // on what happens after template instantiation.
712  return VisitParmVarDecl(D);
713}
714
715Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
716                                                    TemplateTypeParmDecl *D) {
717  // TODO: don't always clone when decls are refcounted.
718  const Type* T = D->getTypeForDecl();
719  assert(T->isTemplateTypeParmType());
720  const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
721
722  TemplateTypeParmDecl *Inst =
723    TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
724                                 TTPT->getDepth(), TTPT->getIndex(),
725                                 TTPT->getName(),
726                                 D->wasDeclaredWithTypename(),
727                                 D->isParameterPack());
728
729  if (D->hasDefaultArgument()) {
730    QualType DefaultPattern = D->getDefaultArgument();
731    QualType DefaultInst
732      = SemaRef.SubstType(DefaultPattern, TemplateArgs,
733                          D->getDefaultArgumentLoc(),
734                          D->getDeclName());
735
736    Inst->setDefaultArgument(DefaultInst,
737                             D->getDefaultArgumentLoc(),
738                             D->defaultArgumentWasInherited() /* preserve? */);
739  }
740
741  return Inst;
742}
743
744Decl *
745TemplateDeclInstantiator::VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D) {
746  NestedNameSpecifier *NNS =
747    SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
748                                     D->getTargetNestedNameRange(),
749                                     TemplateArgs);
750  if (!NNS)
751    return 0;
752
753  CXXScopeSpec SS;
754  SS.setRange(D->getTargetNestedNameRange());
755  SS.setScopeRep(NNS);
756
757  return SemaRef.BuildUsingDeclaration(D->getLocation(), SS,
758                                       D->getTargetNameLocation(),
759                                       D->getTargetName(), 0, D->isTypeName());
760}
761
762Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
763                      const MultiLevelTemplateArgumentList &TemplateArgs) {
764  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
765  return Instantiator.Visit(D);
766}
767
768/// \brief Instantiates a nested template parameter list in the current
769/// instantiation context.
770///
771/// \param L The parameter list to instantiate
772///
773/// \returns NULL if there was an error
774TemplateParameterList *
775TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
776  // Get errors for all the parameters before bailing out.
777  bool Invalid = false;
778
779  unsigned N = L->size();
780  typedef llvm::SmallVector<Decl*,8> ParamVector;
781  ParamVector Params;
782  Params.reserve(N);
783  for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
784       PI != PE; ++PI) {
785    Decl *D = Visit(*PI);
786    Params.push_back(D);
787    Invalid = Invalid || !D;
788  }
789
790  // Clean up if we had an error.
791  if (Invalid) {
792    for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
793         PI != PE; ++PI)
794      if (*PI)
795        (*PI)->Destroy(SemaRef.Context);
796    return NULL;
797  }
798
799  TemplateParameterList *InstL
800    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
801                                    L->getLAngleLoc(), &Params.front(), N,
802                                    L->getRAngleLoc());
803  return InstL;
804}
805
806/// \brief Does substitution on the type of the given function, including
807/// all of the function parameters.
808///
809/// \param D The function whose type will be the basis of the substitution
810///
811/// \param Params the instantiated parameter declarations
812
813/// \returns the instantiated function's type if successful, a NULL
814/// type if there was an error.
815QualType
816TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
817                              llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
818  bool InvalidDecl = false;
819
820  // Substitute all of the function's formal parameter types.
821  TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
822  llvm::SmallVector<QualType, 4> ParamTys;
823  for (FunctionDecl::param_iterator P = D->param_begin(),
824                                 PEnd = D->param_end();
825       P != PEnd; ++P) {
826    if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
827      if (PInst->getType()->isVoidType()) {
828        SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
829        PInst->setInvalidDecl();
830      } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
831                                                PInst->getType(),
832                                                diag::err_abstract_type_in_decl,
833                                                Sema::AbstractParamType))
834        PInst->setInvalidDecl();
835
836      Params.push_back(PInst);
837      ParamTys.push_back(PInst->getType());
838
839      if (PInst->isInvalidDecl())
840        InvalidDecl = true;
841    } else
842      InvalidDecl = true;
843  }
844
845  // FIXME: Deallocate dead declarations.
846  if (InvalidDecl)
847    return QualType();
848
849  const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
850  assert(Proto && "Missing prototype?");
851  QualType ResultType
852    = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
853                        D->getLocation(), D->getDeclName());
854  if (ResultType.isNull())
855    return QualType();
856
857  return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
858                                   Proto->isVariadic(), Proto->getTypeQuals(),
859                                   D->getLocation(), D->getDeclName());
860}
861
862/// \brief Initializes the common fields of an instantiation function
863/// declaration (New) from the corresponding fields of its template (Tmpl).
864///
865/// \returns true if there was an error
866bool
867TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
868                                                    FunctionDecl *Tmpl) {
869  if (Tmpl->isDeleted())
870    New->setDeleted();
871
872  // If we are performing substituting explicitly-specified template arguments
873  // or deduced template arguments into a function template and we reach this
874  // point, we are now past the point where SFINAE applies and have committed
875  // to keeping the new function template specialization. We therefore
876  // convert the active template instantiation for the function template
877  // into a template instantiation for this specific function template
878  // specialization, which is not a SFINAE context, so that we diagnose any
879  // further errors in the declaration itself.
880  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
881  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
882  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
883      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
884    if (FunctionTemplateDecl *FunTmpl
885          = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
886      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
887             "Deduction from the wrong function template?");
888      (void) FunTmpl;
889      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
890      ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
891    }
892  }
893
894  return false;
895}
896
897/// \brief Initializes common fields of an instantiated method
898/// declaration (New) from the corresponding fields of its template
899/// (Tmpl).
900///
901/// \returns true if there was an error
902bool
903TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
904                                                  CXXMethodDecl *Tmpl) {
905  if (InitFunctionInstantiation(New, Tmpl))
906    return true;
907
908  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
909  New->setAccess(Tmpl->getAccess());
910  if (Tmpl->isVirtualAsWritten()) {
911    New->setVirtualAsWritten(true);
912    Record->setAggregate(false);
913    Record->setPOD(false);
914    Record->setEmpty(false);
915    Record->setPolymorphic(true);
916  }
917  if (Tmpl->isPure()) {
918    New->setPure();
919    Record->setAbstract(true);
920  }
921
922  // FIXME: attributes
923  // FIXME: New needs a pointer to Tmpl
924  return false;
925}
926
927/// \brief Instantiate the definition of the given function from its
928/// template.
929///
930/// \param PointOfInstantiation the point at which the instantiation was
931/// required. Note that this is not precisely a "point of instantiation"
932/// for the function, but it's close.
933///
934/// \param Function the already-instantiated declaration of a
935/// function template specialization or member function of a class template
936/// specialization.
937///
938/// \param Recursive if true, recursively instantiates any functions that
939/// are required by this instantiation.
940void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
941                                         FunctionDecl *Function,
942                                         bool Recursive) {
943  if (Function->isInvalidDecl())
944    return;
945
946  assert(!Function->getBody() && "Already instantiated!");
947
948  // Find the function body that we'll be substituting.
949  const FunctionDecl *PatternDecl = 0;
950  if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate()) {
951    while (Primary->getInstantiatedFromMemberTemplate())
952      Primary = Primary->getInstantiatedFromMemberTemplate();
953
954    PatternDecl = Primary->getTemplatedDecl();
955  } else
956    PatternDecl = Function->getInstantiatedFromMemberFunction();
957  Stmt *Pattern = 0;
958  if (PatternDecl)
959    Pattern = PatternDecl->getBody(PatternDecl);
960
961  if (!Pattern)
962    return;
963
964  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
965  if (Inst)
966    return;
967
968  // If we're performing recursive template instantiation, create our own
969  // queue of pending implicit instantiations that we will instantiate later,
970  // while we're still within our own instantiation context.
971  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
972  if (Recursive)
973    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
974
975  ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
976
977  // Introduce a new scope where local variable instantiations will be
978  // recorded.
979  LocalInstantiationScope Scope(*this);
980
981  // Introduce the instantiated function parameters into the local
982  // instantiation scope.
983  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
984    Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
985                            Function->getParamDecl(I));
986
987  // Enter the scope of this instantiation. We don't use
988  // PushDeclContext because we don't have a scope.
989  DeclContext *PreviousContext = CurContext;
990  CurContext = Function;
991
992  // Instantiate the function body.
993  OwningStmtResult Body
994    = SubstStmt(Pattern, getTemplateInstantiationArgs(Function));
995
996  ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
997                          /*IsInstantiation=*/true);
998
999  CurContext = PreviousContext;
1000
1001  DeclGroupRef DG(Function);
1002  Consumer.HandleTopLevelDecl(DG);
1003
1004  if (Recursive) {
1005    // Instantiate any pending implicit instantiations found during the
1006    // instantiation of this template.
1007    PerformPendingImplicitInstantiations();
1008
1009    // Restore the set of pending implicit instantiations.
1010    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1011  }
1012}
1013
1014/// \brief Instantiate the definition of the given variable from its
1015/// template.
1016///
1017/// \param PointOfInstantiation the point at which the instantiation was
1018/// required. Note that this is not precisely a "point of instantiation"
1019/// for the function, but it's close.
1020///
1021/// \param Var the already-instantiated declaration of a static member
1022/// variable of a class template specialization.
1023///
1024/// \param Recursive if true, recursively instantiates any functions that
1025/// are required by this instantiation.
1026void Sema::InstantiateStaticDataMemberDefinition(
1027                                          SourceLocation PointOfInstantiation,
1028                                                 VarDecl *Var,
1029                                                 bool Recursive) {
1030  if (Var->isInvalidDecl())
1031    return;
1032
1033  // Find the out-of-line definition of this static data member.
1034  // FIXME: Do we have to look for specializations separately?
1035  VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1036  bool FoundOutOfLineDef = false;
1037  assert(Def && "This data member was not instantiated from a template?");
1038  assert(Def->isStaticDataMember() && "Not a static data member?");
1039  for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
1040                             RDEnd = Def->redecls_end();
1041       RD != RDEnd; ++RD) {
1042    if (RD->getLexicalDeclContext()->isFileContext()) {
1043      Def = *RD;
1044      FoundOutOfLineDef = true;
1045    }
1046  }
1047
1048  if (!FoundOutOfLineDef) {
1049    // We did not find an out-of-line definition of this static data member,
1050    // so we won't perform any instantiation. Rather, we rely on the user to
1051    // instantiate this definition (or provide a specialization for it) in
1052    // another translation unit.
1053    return;
1054  }
1055
1056  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1057  if (Inst)
1058    return;
1059
1060  // If we're performing recursive template instantiation, create our own
1061  // queue of pending implicit instantiations that we will instantiate later,
1062  // while we're still within our own instantiation context.
1063  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1064  if (Recursive)
1065    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1066
1067  // Enter the scope of this instantiation. We don't use
1068  // PushDeclContext because we don't have a scope.
1069  DeclContext *PreviousContext = CurContext;
1070  CurContext = Var->getDeclContext();
1071
1072#if 0
1073  // Instantiate the initializer of this static data member.
1074  OwningExprResult Init
1075    = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
1076  if (Init.isInvalid()) {
1077    // If instantiation of the initializer failed, mark the declaration invalid
1078    // and don't instantiate anything else that was triggered by this
1079    // instantiation.
1080    Var->setInvalidDecl();
1081
1082    // Restore the set of pending implicit instantiations.
1083    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1084
1085    return;
1086  }
1087
1088  // Type-check the initializer.
1089  if (Init.get())
1090    AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
1091                         Def->hasCXXDirectInitializer());
1092  else
1093    ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
1094#else
1095  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
1096                                          getTemplateInstantiationArgs(Var)));
1097#endif
1098
1099  CurContext = PreviousContext;
1100
1101  if (Var) {
1102    DeclGroupRef DG(Var);
1103    Consumer.HandleTopLevelDecl(DG);
1104  }
1105
1106  if (Recursive) {
1107    // Instantiate any pending implicit instantiations found during the
1108    // instantiation of this template.
1109    PerformPendingImplicitInstantiations();
1110
1111    // Restore the set of pending implicit instantiations.
1112    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1113  }
1114}
1115
1116static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1117  if (D->getKind() != Other->getKind())
1118    return false;
1119
1120  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) {
1121    if (CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass())
1122      return Pattern->getCanonicalDecl() == D->getCanonicalDecl();
1123    else
1124      return false;
1125  }
1126
1127  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) {
1128    if (FunctionDecl *Pattern = Function->getInstantiatedFromMemberFunction())
1129      return Pattern->getCanonicalDecl() == D->getCanonicalDecl();
1130    else
1131      return false;
1132  }
1133
1134  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) {
1135    if (EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum())
1136      return Pattern->getCanonicalDecl() == D->getCanonicalDecl();
1137    else
1138      return false;
1139  }
1140
1141  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
1142    if (Var->isStaticDataMember()) {
1143      if (VarDecl *Pattern = Var->getInstantiatedFromStaticDataMember())
1144        return Pattern->getCanonicalDecl() == D->getCanonicalDecl();
1145      else
1146        return false;
1147    }
1148
1149  // FIXME: How can we find instantiations of anonymous unions?
1150
1151  return D->getDeclName() && isa<NamedDecl>(Other) &&
1152    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1153}
1154
1155template<typename ForwardIterator>
1156static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1157                                      NamedDecl *D,
1158                                      ForwardIterator first,
1159                                      ForwardIterator last) {
1160  for (; first != last; ++first)
1161    if (isInstantiationOf(Ctx, D, *first))
1162      return cast<NamedDecl>(*first);
1163
1164  return 0;
1165}
1166
1167/// \brief Finds the instantiation of the given declaration context
1168/// within the current instantiation.
1169///
1170/// \returns NULL if there was an error
1171DeclContext *Sema::FindInstantiatedContext(DeclContext* DC) {
1172  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
1173    Decl* ID = FindInstantiatedDecl(D);
1174    return cast_or_null<DeclContext>(ID);
1175  } else return DC;
1176}
1177
1178/// \brief Find the instantiation of the given declaration within the
1179/// current instantiation.
1180///
1181/// This routine is intended to be used when \p D is a declaration
1182/// referenced from within a template, that needs to mapped into the
1183/// corresponding declaration within an instantiation. For example,
1184/// given:
1185///
1186/// \code
1187/// template<typename T>
1188/// struct X {
1189///   enum Kind {
1190///     KnownValue = sizeof(T)
1191///   };
1192///
1193///   bool getKind() const { return KnownValue; }
1194/// };
1195///
1196/// template struct X<int>;
1197/// \endcode
1198///
1199/// In the instantiation of X<int>::getKind(), we need to map the
1200/// EnumConstantDecl for KnownValue (which refers to
1201/// X<T>::<Kind>::KnownValue) to its instantiation
1202/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1203/// this mapping from within the instantiation of X<int>.
1204NamedDecl * Sema::FindInstantiatedDecl(NamedDecl *D) {
1205  DeclContext *ParentDC = D->getDeclContext();
1206  if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1207    // D is a local of some kind. Look into the map of local
1208    // declarations to their instantiations.
1209    return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1210  }
1211
1212  ParentDC = FindInstantiatedContext(ParentDC);
1213  if (!ParentDC) return 0;
1214
1215  if (ParentDC != D->getDeclContext()) {
1216    // We performed some kind of instantiation in the parent context,
1217    // so now we need to look into the instantiated parent context to
1218    // find the instantiation of the declaration D.
1219    NamedDecl *Result = 0;
1220    if (D->getDeclName()) {
1221      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
1222      Result = findInstantiationOf(Context, D, Found.first, Found.second);
1223    } else {
1224      // Since we don't have a name for the entity we're looking for,
1225      // our only option is to walk through all of the declarations to
1226      // find that name. This will occur in a few cases:
1227      //
1228      //   - anonymous struct/union within a template
1229      //   - unnamed class/struct/union/enum within a template
1230      //
1231      // FIXME: Find a better way to find these instantiations!
1232      Result = findInstantiationOf(Context, D,
1233                                   ParentDC->decls_begin(),
1234                                   ParentDC->decls_end());
1235    }
1236    assert(Result && "Unable to find instantiation of declaration!");
1237    D = Result;
1238  }
1239
1240  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
1241    if (ClassTemplateDecl *ClassTemplate
1242          = Record->getDescribedClassTemplate()) {
1243      // When the declaration D was parsed, it referred to the current
1244      // instantiation. Therefore, look through the current context,
1245      // which contains actual instantiations, to find the
1246      // instantiation of the "current instantiation" that D refers
1247      // to. Alternatively, we could just instantiate the
1248      // injected-class-name with the current template arguments, but
1249      // such an instantiation is far more expensive.
1250      for (DeclContext *DC = CurContext; !DC->isFileContext();
1251           DC = DC->getParent()) {
1252        if (ClassTemplateSpecializationDecl *Spec
1253              = dyn_cast<ClassTemplateSpecializationDecl>(DC))
1254          if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1255              == ClassTemplate->getCanonicalDecl())
1256            return Spec;
1257      }
1258
1259      assert(false &&
1260             "Unable to find declaration for the current instantiation");
1261    }
1262
1263  return D;
1264}
1265
1266/// \brief Performs template instantiation for all implicit template
1267/// instantiations we have seen until this point.
1268void Sema::PerformPendingImplicitInstantiations() {
1269  while (!PendingImplicitInstantiations.empty()) {
1270    PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
1271    PendingImplicitInstantiations.pop_front();
1272
1273    // Instantiate function definitions
1274    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
1275      if (!Function->getBody())
1276        InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
1277      continue;
1278    }
1279
1280    // Instantiate static data member definitions.
1281    VarDecl *Var = cast<VarDecl>(Inst.first);
1282    assert(Var->isStaticDataMember() && "Not a static data member?");
1283    InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
1284  }
1285}
1286