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