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