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