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