SemaTemplateInstantiateDecl.cpp revision 0130f3cc4ccd5f46361c48d5fe94133d74619424
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  DeclaratorInfo *DI = D->getTypeDeclaratorInfo();
103  if (DI->getType()->isDependentType()) {
104    DI = SemaRef.SubstType(DI, TemplateArgs,
105                           D->getLocation(), D->getDeclName());
106    if (!DI) {
107      Invalid = true;
108      DI = SemaRef.Context.getTrivialDeclaratorInfo(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(), DI);
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->isInlineSpecified(), 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->isInlineSpecified(), 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->isInlineSpecified(), 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->isInlineSpecified(),
687                                       Conversion->isExplicit());
688  } else {
689    Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
690                                   D->getDeclName(), T, D->getDeclaratorInfo(),
691                                   D->isStatic(), D->isInlineSpecified());
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 = Function->getTemplateInstantiationPattern();
1101  Stmt *Pattern = 0;
1102  if (PatternDecl)
1103    Pattern = PatternDecl->getBody(PatternDecl);
1104
1105  if (!Pattern) {
1106    if (DefinitionRequired) {
1107      if (Function->getPrimaryTemplate())
1108        Diag(PointOfInstantiation,
1109             diag::err_explicit_instantiation_undefined_func_template)
1110          << Function->getPrimaryTemplate();
1111      else
1112        Diag(PointOfInstantiation,
1113             diag::err_explicit_instantiation_undefined_member)
1114          << 1 << Function->getDeclName() << Function->getDeclContext();
1115
1116      if (PatternDecl)
1117        Diag(PatternDecl->getLocation(),
1118             diag::note_explicit_instantiation_here);
1119    }
1120
1121    return;
1122  }
1123
1124  // C++0x [temp.explicit]p9:
1125  //   Except for inline functions, other explicit instantiation declarations
1126  //   have the effect of suppressing the implicit instantiation of the entity
1127  //   to which they refer.
1128  if (Function->getTemplateSpecializationKind()
1129        == TSK_ExplicitInstantiationDeclaration &&
1130      PatternDecl->isOutOfLine() && !PatternDecl->isInlineSpecified())
1131    return;
1132
1133  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1134  if (Inst)
1135    return;
1136
1137  // If we're performing recursive template instantiation, create our own
1138  // queue of pending implicit instantiations that we will instantiate later,
1139  // while we're still within our own instantiation context.
1140  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1141  if (Recursive)
1142    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1143
1144  ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1145
1146  // Introduce a new scope where local variable instantiations will be
1147  // recorded.
1148  LocalInstantiationScope Scope(*this);
1149
1150  // Introduce the instantiated function parameters into the local
1151  // instantiation scope.
1152  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1153    Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1154                            Function->getParamDecl(I));
1155
1156  // Enter the scope of this instantiation. We don't use
1157  // PushDeclContext because we don't have a scope.
1158  DeclContext *PreviousContext = CurContext;
1159  CurContext = Function;
1160
1161  MultiLevelTemplateArgumentList TemplateArgs =
1162    getTemplateInstantiationArgs(Function);
1163
1164  // If this is a constructor, instantiate the member initializers.
1165  if (const CXXConstructorDecl *Ctor =
1166        dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1167    InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1168                               TemplateArgs);
1169  }
1170
1171  // Instantiate the function body.
1172  OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
1173
1174  if (Body.isInvalid())
1175    Function->setInvalidDecl();
1176
1177  ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
1178                          /*IsInstantiation=*/true);
1179
1180  CurContext = PreviousContext;
1181
1182  DeclGroupRef DG(Function);
1183  Consumer.HandleTopLevelDecl(DG);
1184
1185  if (Recursive) {
1186    // Instantiate any pending implicit instantiations found during the
1187    // instantiation of this template.
1188    PerformPendingImplicitInstantiations();
1189
1190    // Restore the set of pending implicit instantiations.
1191    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1192  }
1193}
1194
1195/// \brief Instantiate the definition of the given variable from its
1196/// template.
1197///
1198/// \param PointOfInstantiation the point at which the instantiation was
1199/// required. Note that this is not precisely a "point of instantiation"
1200/// for the function, but it's close.
1201///
1202/// \param Var the already-instantiated declaration of a static member
1203/// variable of a class template specialization.
1204///
1205/// \param Recursive if true, recursively instantiates any functions that
1206/// are required by this instantiation.
1207///
1208/// \param DefinitionRequired if true, then we are performing an explicit
1209/// instantiation where an out-of-line definition of the member variable
1210/// is required. Complain if there is no such definition.
1211void Sema::InstantiateStaticDataMemberDefinition(
1212                                          SourceLocation PointOfInstantiation,
1213                                                 VarDecl *Var,
1214                                                 bool Recursive,
1215                                                 bool DefinitionRequired) {
1216  if (Var->isInvalidDecl())
1217    return;
1218
1219  // Find the out-of-line definition of this static data member.
1220  VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1221  assert(Def && "This data member was not instantiated from a template?");
1222  assert(Def->isStaticDataMember() && "Not a static data member?");
1223  Def = Def->getOutOfLineDefinition();
1224
1225  if (!Def) {
1226    // We did not find an out-of-line definition of this static data member,
1227    // so we won't perform any instantiation. Rather, we rely on the user to
1228    // instantiate this definition (or provide a specialization for it) in
1229    // another translation unit.
1230    if (DefinitionRequired) {
1231      Def = Var->getInstantiatedFromStaticDataMember();
1232      Diag(PointOfInstantiation,
1233           diag::err_explicit_instantiation_undefined_member)
1234        << 2 << Var->getDeclName() << Var->getDeclContext();
1235      Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1236    }
1237
1238    return;
1239  }
1240
1241  // Never instantiate an explicit specialization.
1242  if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1243    return;
1244
1245  // C++0x [temp.explicit]p9:
1246  //   Except for inline functions, other explicit instantiation declarations
1247  //   have the effect of suppressing the implicit instantiation of the entity
1248  //   to which they refer.
1249  if (Var->getTemplateSpecializationKind()
1250        == TSK_ExplicitInstantiationDeclaration)
1251    return;
1252
1253  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1254  if (Inst)
1255    return;
1256
1257  // If we're performing recursive template instantiation, create our own
1258  // queue of pending implicit instantiations that we will instantiate later,
1259  // while we're still within our own instantiation context.
1260  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1261  if (Recursive)
1262    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1263
1264  // Enter the scope of this instantiation. We don't use
1265  // PushDeclContext because we don't have a scope.
1266  DeclContext *PreviousContext = CurContext;
1267  CurContext = Var->getDeclContext();
1268
1269  VarDecl *OldVar = Var;
1270  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
1271                                          getTemplateInstantiationArgs(Var)));
1272  CurContext = PreviousContext;
1273
1274  if (Var) {
1275    Var->setPreviousDeclaration(OldVar);
1276    MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1277    assert(MSInfo && "Missing member specialization information?");
1278    Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1279                                       MSInfo->getPointOfInstantiation());
1280    DeclGroupRef DG(Var);
1281    Consumer.HandleTopLevelDecl(DG);
1282  }
1283
1284  if (Recursive) {
1285    // Instantiate any pending implicit instantiations found during the
1286    // instantiation of this template.
1287    PerformPendingImplicitInstantiations();
1288
1289    // Restore the set of pending implicit instantiations.
1290    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1291  }
1292}
1293
1294void
1295Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1296                                 const CXXConstructorDecl *Tmpl,
1297                           const MultiLevelTemplateArgumentList &TemplateArgs) {
1298
1299  llvm::SmallVector<MemInitTy*, 4> NewInits;
1300
1301  // Instantiate all the initializers.
1302  for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
1303                                            InitsEnd = Tmpl->init_end();
1304       Inits != InitsEnd; ++Inits) {
1305    CXXBaseOrMemberInitializer *Init = *Inits;
1306
1307    ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
1308
1309    // Instantiate all the arguments.
1310    for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1311         Args != ArgsEnd; ++Args) {
1312      OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1313
1314      if (NewArg.isInvalid())
1315        New->setInvalidDecl();
1316      else
1317        NewArgs.push_back(NewArg.takeAs<Expr>());
1318    }
1319
1320    MemInitResult NewInit;
1321
1322    if (Init->isBaseInitializer()) {
1323      QualType BaseType(Init->getBaseClass(), 0);
1324      BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(),
1325                           New->getDeclName());
1326
1327      NewInit = BuildBaseInitializer(BaseType,
1328                                     (Expr **)NewArgs.data(),
1329                                     NewArgs.size(),
1330                                     Init->getSourceLocation(),
1331                                     Init->getRParenLoc(),
1332                                     New->getParent());
1333    } else if (Init->isMemberInitializer()) {
1334      FieldDecl *Member;
1335
1336      // Is this an anonymous union?
1337      if (FieldDecl *UnionInit = Init->getAnonUnionMember())
1338        Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
1339      else
1340        Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1341                                                      TemplateArgs));
1342
1343      NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
1344                                       NewArgs.size(),
1345                                       Init->getSourceLocation(),
1346                                       Init->getRParenLoc());
1347    }
1348
1349    if (NewInit.isInvalid())
1350      New->setInvalidDecl();
1351    else {
1352      // FIXME: It would be nice if ASTOwningVector had a release function.
1353      NewArgs.take();
1354
1355      NewInits.push_back((MemInitTy *)NewInit.get());
1356    }
1357  }
1358
1359  // Assign all the initializers to the new constructor.
1360  ActOnMemInitializers(DeclPtrTy::make(New),
1361                       /*FIXME: ColonLoc */
1362                       SourceLocation(),
1363                       NewInits.data(), NewInits.size());
1364}
1365
1366// TODO: this could be templated if the various decl types used the
1367// same method name.
1368static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1369                              ClassTemplateDecl *Instance) {
1370  Pattern = Pattern->getCanonicalDecl();
1371
1372  do {
1373    Instance = Instance->getCanonicalDecl();
1374    if (Pattern == Instance) return true;
1375    Instance = Instance->getInstantiatedFromMemberTemplate();
1376  } while (Instance);
1377
1378  return false;
1379}
1380
1381static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1382                              FunctionTemplateDecl *Instance) {
1383  Pattern = Pattern->getCanonicalDecl();
1384
1385  do {
1386    Instance = Instance->getCanonicalDecl();
1387    if (Pattern == Instance) return true;
1388    Instance = Instance->getInstantiatedFromMemberTemplate();
1389  } while (Instance);
1390
1391  return false;
1392}
1393
1394static bool isInstantiationOf(CXXRecordDecl *Pattern,
1395                              CXXRecordDecl *Instance) {
1396  Pattern = Pattern->getCanonicalDecl();
1397
1398  do {
1399    Instance = Instance->getCanonicalDecl();
1400    if (Pattern == Instance) return true;
1401    Instance = Instance->getInstantiatedFromMemberClass();
1402  } while (Instance);
1403
1404  return false;
1405}
1406
1407static bool isInstantiationOf(FunctionDecl *Pattern,
1408                              FunctionDecl *Instance) {
1409  Pattern = Pattern->getCanonicalDecl();
1410
1411  do {
1412    Instance = Instance->getCanonicalDecl();
1413    if (Pattern == Instance) return true;
1414    Instance = Instance->getInstantiatedFromMemberFunction();
1415  } while (Instance);
1416
1417  return false;
1418}
1419
1420static bool isInstantiationOf(EnumDecl *Pattern,
1421                              EnumDecl *Instance) {
1422  Pattern = Pattern->getCanonicalDecl();
1423
1424  do {
1425    Instance = Instance->getCanonicalDecl();
1426    if (Pattern == Instance) return true;
1427    Instance = Instance->getInstantiatedFromMemberEnum();
1428  } while (Instance);
1429
1430  return false;
1431}
1432
1433static bool isInstantiationOf(UnresolvedUsingDecl *Pattern,
1434                              UsingDecl *Instance,
1435                              ASTContext &C) {
1436  return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1437}
1438
1439static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1440                                              VarDecl *Instance) {
1441  assert(Instance->isStaticDataMember());
1442
1443  Pattern = Pattern->getCanonicalDecl();
1444
1445  do {
1446    Instance = Instance->getCanonicalDecl();
1447    if (Pattern == Instance) return true;
1448    Instance = Instance->getInstantiatedFromStaticDataMember();
1449  } while (Instance);
1450
1451  return false;
1452}
1453
1454static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1455  if (D->getKind() != Other->getKind()) {
1456    if (UnresolvedUsingDecl *UUD = dyn_cast<UnresolvedUsingDecl>(D)) {
1457      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1458        return isInstantiationOf(UUD, UD, Ctx);
1459      }
1460    }
1461
1462    return false;
1463  }
1464
1465  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1466    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
1467
1468  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1469    return isInstantiationOf(cast<FunctionDecl>(D), Function);
1470
1471  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1472    return isInstantiationOf(cast<EnumDecl>(D), Enum);
1473
1474  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
1475    if (Var->isStaticDataMember())
1476      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1477
1478  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1479    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
1480
1481  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
1482    return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
1483
1484  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
1485    if (!Field->getDeclName()) {
1486      // This is an unnamed field.
1487      return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
1488        cast<FieldDecl>(D);
1489    }
1490  }
1491
1492  return D->getDeclName() && isa<NamedDecl>(Other) &&
1493    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1494}
1495
1496template<typename ForwardIterator>
1497static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1498                                      NamedDecl *D,
1499                                      ForwardIterator first,
1500                                      ForwardIterator last) {
1501  for (; first != last; ++first)
1502    if (isInstantiationOf(Ctx, D, *first))
1503      return cast<NamedDecl>(*first);
1504
1505  return 0;
1506}
1507
1508/// \brief Finds the instantiation of the given declaration context
1509/// within the current instantiation.
1510///
1511/// \returns NULL if there was an error
1512DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
1513                          const MultiLevelTemplateArgumentList &TemplateArgs) {
1514  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
1515    Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
1516    return cast_or_null<DeclContext>(ID);
1517  } else return DC;
1518}
1519
1520/// \brief Find the instantiation of the given declaration within the
1521/// current instantiation.
1522///
1523/// This routine is intended to be used when \p D is a declaration
1524/// referenced from within a template, that needs to mapped into the
1525/// corresponding declaration within an instantiation. For example,
1526/// given:
1527///
1528/// \code
1529/// template<typename T>
1530/// struct X {
1531///   enum Kind {
1532///     KnownValue = sizeof(T)
1533///   };
1534///
1535///   bool getKind() const { return KnownValue; }
1536/// };
1537///
1538/// template struct X<int>;
1539/// \endcode
1540///
1541/// In the instantiation of X<int>::getKind(), we need to map the
1542/// EnumConstantDecl for KnownValue (which refers to
1543/// X<T>::<Kind>::KnownValue) to its instantiation
1544/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1545/// this mapping from within the instantiation of X<int>.
1546NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
1547                          const MultiLevelTemplateArgumentList &TemplateArgs) {
1548  if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
1549    // Transform all of the elements of the overloaded function set.
1550    OverloadedFunctionDecl *Result
1551      = OverloadedFunctionDecl::Create(Context, CurContext, Ovl->getDeclName());
1552
1553    for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1554                                                FEnd = Ovl->function_end();
1555         F != FEnd; ++F) {
1556      Result->addOverload(
1557        AnyFunctionDecl::getFromNamedDecl(FindInstantiatedDecl(*F,
1558                                                               TemplateArgs)));
1559    }
1560
1561    return Result;
1562  }
1563
1564  DeclContext *ParentDC = D->getDeclContext();
1565  if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1566    // D is a local of some kind. Look into the map of local
1567    // declarations to their instantiations.
1568    return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1569  }
1570
1571  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
1572    if (!Record->isDependentContext())
1573      return D;
1574
1575    // If the RecordDecl is actually the injected-class-name or a "templated"
1576    // declaration for a class template or class template partial
1577    // specialization, substitute into the injected-class-name of the
1578    // class template or partial specialization to find the new DeclContext.
1579    QualType T;
1580    ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
1581
1582    if (ClassTemplate) {
1583      T = ClassTemplate->getInjectedClassNameType(Context);
1584    } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1585                 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1586      T = Context.getTypeDeclType(Record);
1587      ClassTemplate = PartialSpec->getSpecializedTemplate();
1588    }
1589
1590    if (!T.isNull()) {
1591      // Substitute into the injected-class-name to get the type corresponding
1592      // to the instantiation we want. This substitution should never fail,
1593      // since we know we can instantiate the injected-class-name or we wouldn't
1594      // have gotten to the injected-class-name!
1595      // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
1596      // instantiation in the common case?
1597      T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
1598      assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
1599
1600      if (!T->isDependentType()) {
1601        assert(T->isRecordType() && "Instantiation must produce a record type");
1602        return T->getAs<RecordType>()->getDecl();
1603      }
1604
1605      // We are performing "partial" template instantiation to create the
1606      // member declarations for the members of a class template
1607      // specialization. Therefore, D is actually referring to something in
1608      // the current instantiation. Look through the current context,
1609      // which contains actual instantiations, to find the instantiation of
1610      // the "current instantiation" that D refers to.
1611      for (DeclContext *DC = CurContext; !DC->isFileContext();
1612           DC = DC->getParent()) {
1613        if (ClassTemplateSpecializationDecl *Spec
1614              = dyn_cast<ClassTemplateSpecializationDecl>(DC))
1615          if (isInstantiationOf(ClassTemplate,
1616                                Spec->getSpecializedTemplate()))
1617            return Spec;
1618      }
1619
1620      assert(false &&
1621             "Unable to find declaration for the current instantiation");
1622      return Record;
1623    }
1624
1625    // Fall through to deal with other dependent record types (e.g.,
1626    // anonymous unions in class templates).
1627  }
1628
1629  if (!ParentDC->isDependentContext())
1630    return D;
1631
1632  ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
1633  if (!ParentDC)
1634    return 0;
1635
1636  if (ParentDC != D->getDeclContext()) {
1637    // We performed some kind of instantiation in the parent context,
1638    // so now we need to look into the instantiated parent context to
1639    // find the instantiation of the declaration D.
1640    NamedDecl *Result = 0;
1641    if (D->getDeclName()) {
1642      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
1643      Result = findInstantiationOf(Context, D, Found.first, Found.second);
1644    } else {
1645      // Since we don't have a name for the entity we're looking for,
1646      // our only option is to walk through all of the declarations to
1647      // find that name. This will occur in a few cases:
1648      //
1649      //   - anonymous struct/union within a template
1650      //   - unnamed class/struct/union/enum within a template
1651      //
1652      // FIXME: Find a better way to find these instantiations!
1653      Result = findInstantiationOf(Context, D,
1654                                   ParentDC->decls_begin(),
1655                                   ParentDC->decls_end());
1656    }
1657
1658    assert(Result && "Unable to find instantiation of declaration!");
1659    D = Result;
1660  }
1661
1662  return D;
1663}
1664
1665/// \brief Performs template instantiation for all implicit template
1666/// instantiations we have seen until this point.
1667void Sema::PerformPendingImplicitInstantiations() {
1668  while (!PendingImplicitInstantiations.empty()) {
1669    PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
1670    PendingImplicitInstantiations.pop_front();
1671
1672    // Instantiate function definitions
1673    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
1674      PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
1675                                            Function->getLocation(), *this,
1676                                            Context.getSourceManager(),
1677                                           "instantiating function definition");
1678
1679      if (!Function->getBody())
1680        InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
1681      continue;
1682    }
1683
1684    // Instantiate static data member definitions.
1685    VarDecl *Var = cast<VarDecl>(Inst.first);
1686    assert(Var->isStaticDataMember() && "Not a static data member?");
1687
1688    PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
1689                                          Var->getLocation(), *this,
1690                                          Context.getSourceManager(),
1691                                          "instantiating static data member "
1692                                          "definition");
1693
1694    InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
1695  }
1696}
1697