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