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