SemaTemplateInstantiateDecl.cpp revision 127102b5196ffe04bdb70fd553fe62c265ab10a9
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 "llvm/Support/Compiler.h"
19
20using namespace clang;
21
22namespace {
23  class VISIBILITY_HIDDEN TemplateDeclInstantiator
24    : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
25    Sema &SemaRef;
26    DeclContext *Owner;
27    const TemplateArgumentList &TemplateArgs;
28
29  public:
30    typedef Sema::OwningExprResult OwningExprResult;
31
32    TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
33                             const TemplateArgumentList &TemplateArgs)
34      : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
35
36    // FIXME: Once we get closer to completion, replace these manually-written
37    // declarations with automatically-generated ones from
38    // clang/AST/DeclNodes.def.
39    Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
40    Decl *VisitNamespaceDecl(NamespaceDecl *D);
41    Decl *VisitTypedefDecl(TypedefDecl *D);
42    Decl *VisitVarDecl(VarDecl *D);
43    Decl *VisitFieldDecl(FieldDecl *D);
44    Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
45    Decl *VisitEnumDecl(EnumDecl *D);
46    Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
47    Decl *VisitFunctionDecl(FunctionDecl *D);
48    Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
49    Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
50    Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
51    Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
52    Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
53    ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
54    Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
55
56    // Base case. FIXME: Remove once we can instantiate everything.
57    Decl *VisitDecl(Decl *) {
58      assert(false && "Template instantiation of unknown declaration kind!");
59      return 0;
60    }
61
62    // Helper functions for instantiating methods.
63    QualType InstantiateFunctionType(FunctionDecl *D,
64                             llvm::SmallVectorImpl<ParmVarDecl *> &Params);
65    bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
66    bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
67  };
68}
69
70Decl *
71TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
72  assert(false && "Translation units cannot be instantiated");
73  return D;
74}
75
76Decl *
77TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
78  assert(false && "Namespaces cannot be instantiated");
79  return D;
80}
81
82Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
83  bool Invalid = false;
84  QualType T = D->getUnderlyingType();
85  if (T->isDependentType()) {
86    T = SemaRef.InstantiateType(T, TemplateArgs,
87                                D->getLocation(), D->getDeclName());
88    if (T.isNull()) {
89      Invalid = true;
90      T = SemaRef.Context.IntTy;
91    }
92  }
93
94  // Create the new typedef
95  TypedefDecl *Typedef
96    = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
97                          D->getIdentifier(), T);
98  if (Invalid)
99    Typedef->setInvalidDecl();
100
101  Owner->addDecl(SemaRef.Context, Typedef);
102
103  return Typedef;
104}
105
106Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
107  // Instantiate the type of the declaration
108  QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs,
109                                       D->getTypeSpecStartLoc(),
110                                       D->getDeclName());
111  if (T.isNull())
112    return 0;
113
114  // Build the instantiated declaration
115  VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
116                                 D->getLocation(), D->getIdentifier(),
117                                 T, D->getStorageClass(),
118                                 D->getTypeSpecStartLoc());
119  Var->setThreadSpecified(D->isThreadSpecified());
120  Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
121  Var->setDeclaredInCondition(D->isDeclaredInCondition());
122
123  // FIXME: In theory, we could have a previous declaration for variables that
124  // are not static data members.
125  bool Redeclaration = false;
126  SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
127  Owner->addDecl(SemaRef.Context, Var);
128
129  if (D->getInit()) {
130    OwningExprResult Init
131      = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs);
132    if (Init.isInvalid())
133      Var->setInvalidDecl();
134    else
135      SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
136                                   D->hasCXXDirectInitializer());
137  } else {
138    // FIXME: Call ActOnUninitializedDecl? (Not always)
139  }
140
141  return Var;
142}
143
144Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
145  bool Invalid = false;
146  QualType T = D->getType();
147  if (T->isDependentType())  {
148    T = SemaRef.InstantiateType(T, TemplateArgs,
149                                D->getLocation(), D->getDeclName());
150    if (!T.isNull() && T->isFunctionType()) {
151      // C++ [temp.arg.type]p3:
152      //   If a declaration acquires a function type through a type
153      //   dependent on a template-parameter and this causes a
154      //   declaration that does not use the syntactic form of a
155      //   function declarator to have function type, the program is
156      //   ill-formed.
157      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
158        << T;
159      T = QualType();
160      Invalid = true;
161    }
162  }
163
164  Expr *BitWidth = D->getBitWidth();
165  if (Invalid)
166    BitWidth = 0;
167  else if (BitWidth) {
168    // The bit-width expression is not potentially evaluated.
169    EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
170
171    OwningExprResult InstantiatedBitWidth
172      = SemaRef.InstantiateExpr(BitWidth, TemplateArgs);
173    if (InstantiatedBitWidth.isInvalid()) {
174      Invalid = true;
175      BitWidth = 0;
176    } else
177      BitWidth = InstantiatedBitWidth.takeAs<Expr>();
178  }
179
180  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
181                                            cast<RecordDecl>(Owner),
182                                            D->getLocation(),
183                                            D->isMutable(),
184                                            BitWidth,
185                                            D->getAccess(),
186                                            0);
187  if (Field) {
188    if (Invalid)
189      Field->setInvalidDecl();
190
191    Owner->addDecl(SemaRef.Context, Field);
192  }
193
194  return Field;
195}
196
197Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
198  Expr *AssertExpr = D->getAssertExpr();
199
200  // The expression in a static assertion is not potentially evaluated.
201  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
202
203  OwningExprResult InstantiatedAssertExpr
204    = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs);
205  if (InstantiatedAssertExpr.isInvalid())
206    return 0;
207
208  OwningExprResult Message = SemaRef.Clone(D->getMessage());
209  Decl *StaticAssert
210    = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
211                                           move(InstantiatedAssertExpr),
212                                           move(Message)).getAs<Decl>();
213  return StaticAssert;
214}
215
216Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
217  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
218                                    D->getLocation(), D->getIdentifier(),
219                                    /*PrevDecl=*/0);
220  Enum->setInstantiationOfMemberEnum(D);
221  Enum->setAccess(D->getAccess());
222  Owner->addDecl(SemaRef.Context, Enum);
223  Enum->startDefinition();
224
225  llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
226
227  EnumConstantDecl *LastEnumConst = 0;
228  for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(SemaRef.Context),
229         ECEnd = D->enumerator_end(SemaRef.Context);
230       EC != ECEnd; ++EC) {
231    // The specified value for the enumerator.
232    OwningExprResult Value = SemaRef.Owned((Expr *)0);
233    if (Expr *UninstValue = EC->getInitExpr()) {
234      // The enumerator's value expression is not potentially evaluated.
235      EnterExpressionEvaluationContext Unevaluated(SemaRef,
236                                                   Action::Unevaluated);
237
238      Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs);
239    }
240
241    // Drop the initial value and continue.
242    bool isInvalid = false;
243    if (Value.isInvalid()) {
244      Value = SemaRef.Owned((Expr *)0);
245      isInvalid = true;
246    }
247
248    EnumConstantDecl *EnumConst
249      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
250                                  EC->getLocation(), EC->getIdentifier(),
251                                  move(Value));
252
253    if (isInvalid) {
254      if (EnumConst)
255        EnumConst->setInvalidDecl();
256      Enum->setInvalidDecl();
257    }
258
259    if (EnumConst) {
260      Enum->addDecl(SemaRef.Context, EnumConst);
261      Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
262      LastEnumConst = EnumConst;
263    }
264  }
265
266  // FIXME: Fixup LBraceLoc and RBraceLoc
267  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
268                        Sema::DeclPtrTy::make(Enum),
269                        &Enumerators[0], Enumerators.size());
270
271  return Enum;
272}
273
274Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
275  assert(false && "EnumConstantDecls can only occur within EnumDecls.");
276  return 0;
277}
278
279Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
280  CXXRecordDecl *PrevDecl = 0;
281  if (D->isInjectedClassName())
282    PrevDecl = cast<CXXRecordDecl>(Owner);
283
284  CXXRecordDecl *Record
285    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
286                            D->getLocation(), D->getIdentifier(), PrevDecl);
287  Record->setImplicit(D->isImplicit());
288  Record->setAccess(D->getAccess());
289  if (!D->isInjectedClassName())
290    Record->setInstantiationOfMemberClass(D);
291
292  Owner->addDecl(SemaRef.Context, Record);
293  return Record;
294}
295
296Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
297  // Check whether there is already a function template specialization for
298  // this declaration.
299  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
300  void *InsertPos = 0;
301  if (FunctionTemplate) {
302    llvm::FoldingSetNodeID ID;
303    FunctionTemplateSpecializationInfo::Profile(ID,
304                                          TemplateArgs.getFlatArgumentList(),
305                                                TemplateArgs.flat_size());
306
307    FunctionTemplateSpecializationInfo *Info
308      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
309                                                                   InsertPos);
310
311    // If we already have a function template specialization, return it.
312    if (Info)
313      return Info->Function;
314  }
315
316  Sema::LocalInstantiationScope Scope(SemaRef);
317
318  llvm::SmallVector<ParmVarDecl *, 4> Params;
319  QualType T = InstantiateFunctionType(D, Params);
320  if (T.isNull())
321    return 0;
322
323  // Build the instantiated method declaration.
324  FunctionDecl *Function
325    = FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(),
326                           D->getDeclName(), T, D->getStorageClass(),
327                           D->isInline(), D->hasWrittenPrototype(),
328                           D->getTypeSpecStartLoc());
329
330  // FIXME: friend functions
331
332  // Attach the parameters
333  for (unsigned P = 0; P < Params.size(); ++P)
334    Params[P]->setOwningFunction(Function);
335  Function->setParams(SemaRef.Context, Params.data(), Params.size());
336
337  if (InitFunctionInstantiation(Function, D))
338    Function->setInvalidDecl();
339
340  bool Redeclaration = false;
341  bool OverloadableAttrRequired = false;
342  NamedDecl *PrevDecl = 0;
343  SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
344                                   /*FIXME:*/OverloadableAttrRequired);
345
346  if (FunctionTemplate) {
347    // Record this function template specialization.
348    Function->setFunctionTemplateSpecialization(SemaRef.Context,
349                                                FunctionTemplate,
350                                                &TemplateArgs,
351                                                InsertPos);
352   }
353
354  return Function;
355}
356
357Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
358  // FIXME: Look for existing, explicit specializations.
359  Sema::LocalInstantiationScope Scope(SemaRef);
360
361  llvm::SmallVector<ParmVarDecl *, 4> Params;
362  QualType T = InstantiateFunctionType(D, Params);
363  if (T.isNull())
364    return 0;
365
366  // Build the instantiated method declaration.
367  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
368  CXXMethodDecl *Method
369    = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
370                            D->getDeclName(), T, D->isStatic(),
371                            D->isInline());
372  Method->setInstantiationOfMemberFunction(D);
373
374  // Attach the parameters
375  for (unsigned P = 0; P < Params.size(); ++P)
376    Params[P]->setOwningFunction(Method);
377  Method->setParams(SemaRef.Context, Params.data(), Params.size());
378
379  if (InitMethodInstantiation(Method, D))
380    Method->setInvalidDecl();
381
382  NamedDecl *PrevDecl
383    = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
384                                  Sema::LookupOrdinaryName, true);
385  // In C++, the previous declaration we find might be a tag type
386  // (class or enum). In this case, the new declaration will hide the
387  // tag type. Note that this does does not apply if we're declaring a
388  // typedef (C++ [dcl.typedef]p4).
389  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
390    PrevDecl = 0;
391  bool Redeclaration = false;
392  bool OverloadableAttrRequired = false;
393  SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
394                                   /*FIXME:*/OverloadableAttrRequired);
395
396  if (!Method->isInvalidDecl() || !PrevDecl)
397    Owner->addDecl(SemaRef.Context, Method);
398  return Method;
399}
400
401Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
402  // FIXME: Look for existing, explicit specializations.
403  Sema::LocalInstantiationScope Scope(SemaRef);
404
405  llvm::SmallVector<ParmVarDecl *, 4> Params;
406  QualType T = InstantiateFunctionType(D, Params);
407  if (T.isNull())
408    return 0;
409
410  // Build the instantiated method declaration.
411  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
412  QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
413  DeclarationName Name
414    = SemaRef.Context.DeclarationNames.getCXXConstructorName(
415                                 SemaRef.Context.getCanonicalType(ClassTy));
416  CXXConstructorDecl *Constructor
417    = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
418                                 Name, T, D->isExplicit(), D->isInline(),
419                                 false);
420  Constructor->setInstantiationOfMemberFunction(D);
421
422  // Attach the parameters
423  for (unsigned P = 0; P < Params.size(); ++P)
424    Params[P]->setOwningFunction(Constructor);
425  Constructor->setParams(SemaRef.Context, Params.data(), Params.size());
426
427  if (InitMethodInstantiation(Constructor, D))
428    Constructor->setInvalidDecl();
429
430  NamedDecl *PrevDecl
431    = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
432
433  // In C++, the previous declaration we find might be a tag type
434  // (class or enum). In this case, the new declaration will hide the
435  // tag type. Note that this does does not apply if we're declaring a
436  // typedef (C++ [dcl.typedef]p4).
437  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
438    PrevDecl = 0;
439  bool Redeclaration = false;
440  bool OverloadableAttrRequired = false;
441  SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
442                                   /*FIXME:*/OverloadableAttrRequired);
443
444  Record->addedConstructor(SemaRef.Context, Constructor);
445  Owner->addDecl(SemaRef.Context, Constructor);
446  return Constructor;
447}
448
449Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
450  // FIXME: Look for existing, explicit specializations.
451  Sema::LocalInstantiationScope Scope(SemaRef);
452
453  llvm::SmallVector<ParmVarDecl *, 4> Params;
454  QualType T = InstantiateFunctionType(D, Params);
455  if (T.isNull())
456    return 0;
457  assert(Params.size() == 0 && "Destructor with parameters?");
458
459  // Build the instantiated destructor declaration.
460  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
461  QualType ClassTy =
462    SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record));
463  CXXDestructorDecl *Destructor
464    = CXXDestructorDecl::Create(SemaRef.Context, Record,
465                                D->getLocation(),
466             SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
467                                T, D->isInline(), false);
468  Destructor->setInstantiationOfMemberFunction(D);
469  if (InitMethodInstantiation(Destructor, D))
470    Destructor->setInvalidDecl();
471
472  bool Redeclaration = false;
473  bool OverloadableAttrRequired = false;
474  NamedDecl *PrevDecl = 0;
475  SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
476                                   /*FIXME:*/OverloadableAttrRequired);
477  Owner->addDecl(SemaRef.Context, Destructor);
478  return Destructor;
479}
480
481Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
482  // FIXME: Look for existing, explicit specializations.
483  Sema::LocalInstantiationScope Scope(SemaRef);
484
485  llvm::SmallVector<ParmVarDecl *, 4> Params;
486  QualType T = InstantiateFunctionType(D, Params);
487  if (T.isNull())
488    return 0;
489  assert(Params.size() == 0 && "Destructor with parameters?");
490
491  // Build the instantiated conversion declaration.
492  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
493  QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
494  QualType ConvTy
495    = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
496  CXXConversionDecl *Conversion
497    = CXXConversionDecl::Create(SemaRef.Context, Record,
498                                D->getLocation(),
499         SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
500                                T, D->isInline(), D->isExplicit());
501  Conversion->setInstantiationOfMemberFunction(D);
502  if (InitMethodInstantiation(Conversion, D))
503    Conversion->setInvalidDecl();
504
505  bool Redeclaration = false;
506  bool OverloadableAttrRequired = false;
507  NamedDecl *PrevDecl = 0;
508  SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
509                                   /*FIXME:*/OverloadableAttrRequired);
510  Owner->addDecl(SemaRef.Context, Conversion);
511  return Conversion;
512}
513
514ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
515  QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
516                                           D->getLocation(), D->getDeclName());
517  if (OrigT.isNull())
518    return 0;
519
520  QualType T = SemaRef.adjustParameterType(OrigT);
521
522  if (D->getDefaultArg()) {
523    // FIXME: Leave a marker for "uninstantiated" default
524    // arguments. They only get instantiated on demand at the call
525    // site.
526    unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
527        "sorry, dropping default argument during template instantiation");
528    SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
529      << D->getDefaultArg()->getSourceRange();
530  }
531
532  // Allocate the parameter
533  ParmVarDecl *Param = 0;
534  if (T == OrigT)
535    Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
536                                D->getIdentifier(), T, D->getStorageClass(),
537                                0);
538  else
539    Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
540                                        D->getLocation(), D->getIdentifier(),
541                                        T, OrigT, D->getStorageClass(), 0);
542
543  // Note: we don't try to instantiate function parameters until after
544  // we've instantiated the function's type. Therefore, we don't have
545  // to check for 'void' parameter types here.
546  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
547  return Param;
548}
549
550Decl *
551TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
552  // Since parameter types can decay either before or after
553  // instantiation, we simply treat OriginalParmVarDecls as
554  // ParmVarDecls the same way, and create one or the other depending
555  // on what happens after template instantiation.
556  return VisitParmVarDecl(D);
557}
558
559Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
560                            const TemplateArgumentList &TemplateArgs) {
561  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
562  return Instantiator.Visit(D);
563}
564
565/// \brief Instantiates the type of the given function, including
566/// instantiating all of the function parameters.
567///
568/// \param D The function that we will be instantiated
569///
570/// \param Params the instantiated parameter declarations
571
572/// \returns the instantiated function's type if successfull, a NULL
573/// type if there was an error.
574QualType
575TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
576                              llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
577  bool InvalidDecl = false;
578
579  // Instantiate the function parameters
580  TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
581  llvm::SmallVector<QualType, 4> ParamTys;
582  for (FunctionDecl::param_iterator P = D->param_begin(),
583                                 PEnd = D->param_end();
584       P != PEnd; ++P) {
585    if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
586      if (PInst->getType()->isVoidType()) {
587        SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
588        PInst->setInvalidDecl();
589      }
590      else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
591                                              PInst->getType(),
592                                              diag::err_abstract_type_in_decl,
593                                              Sema::AbstractParamType))
594        PInst->setInvalidDecl();
595
596      Params.push_back(PInst);
597      ParamTys.push_back(PInst->getType());
598
599      if (PInst->isInvalidDecl())
600        InvalidDecl = true;
601    } else
602      InvalidDecl = true;
603  }
604
605  // FIXME: Deallocate dead declarations.
606  if (InvalidDecl)
607    return QualType();
608
609  const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
610  assert(Proto && "Missing prototype?");
611  QualType ResultType
612    = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs,
613                              D->getLocation(), D->getDeclName());
614  if (ResultType.isNull())
615    return QualType();
616
617  return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
618                                   Proto->isVariadic(), Proto->getTypeQuals(),
619                                   D->getLocation(), D->getDeclName());
620}
621
622/// \brief Initializes the common fields of an instantiation function
623/// declaration (New) from the corresponding fields of its template (Tmpl).
624///
625/// \returns true if there was an error
626bool
627TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
628                                                    FunctionDecl *Tmpl) {
629  if (Tmpl->isDeleted())
630    New->setDeleted();
631  return false;
632}
633
634/// \brief Initializes common fields of an instantiated method
635/// declaration (New) from the corresponding fields of its template
636/// (Tmpl).
637///
638/// \returns true if there was an error
639bool
640TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
641                                                  CXXMethodDecl *Tmpl) {
642  if (InitFunctionInstantiation(New, Tmpl))
643    return true;
644
645  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
646  New->setAccess(Tmpl->getAccess());
647  if (Tmpl->isVirtualAsWritten()) {
648    New->setVirtualAsWritten(true);
649    Record->setAggregate(false);
650    Record->setPOD(false);
651    Record->setPolymorphic(true);
652  }
653  if (Tmpl->isPure()) {
654    New->setPure();
655    Record->setAbstract(true);
656  }
657
658  // FIXME: attributes
659  // FIXME: New needs a pointer to Tmpl
660  return false;
661}
662
663/// \brief Instantiate the definition of the given function from its
664/// template.
665///
666/// \param Function the already-instantiated declaration of a
667/// function.
668void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
669                                         FunctionDecl *Function) {
670  if (Function->isInvalidDecl())
671    return;
672
673  assert(!Function->getBody(Context) && "Already instantiated!");
674
675  // Find the function body that we'll be substituting.
676  const FunctionDecl *PatternDecl = 0;
677  if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
678    PatternDecl = Primary->getTemplatedDecl();
679  else
680    PatternDecl = Function->getInstantiatedFromMemberFunction();
681  Stmt *Pattern = 0;
682  if (PatternDecl)
683    Pattern = PatternDecl->getBody(Context, PatternDecl);
684
685  if (!Pattern)
686    return;
687
688  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
689  if (Inst)
690    return;
691
692  ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
693
694  // Introduce a new scope where local variable instantiations will be
695  // recorded.
696  LocalInstantiationScope Scope(*this);
697
698  // Introduce the instantiated function parameters into the local
699  // instantiation scope.
700  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
701    Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
702                            Function->getParamDecl(I));
703
704  // Enter the scope of this instantiation. We don't use
705  // PushDeclContext because we don't have a scope.
706  DeclContext *PreviousContext = CurContext;
707  CurContext = Function;
708
709  // Instantiate the function body.
710  OwningStmtResult Body
711    = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function));
712
713  ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
714                          /*IsInstantiation=*/true);
715
716  CurContext = PreviousContext;
717
718  DeclGroupRef DG(Function);
719  Consumer.HandleTopLevelDecl(DG);
720}
721
722/// \brief Instantiate the definition of the given variable from its
723/// template.
724///
725/// \param Var the already-instantiated declaration of a variable.
726void Sema::InstantiateVariableDefinition(VarDecl *Var) {
727  // FIXME: Implement this!
728}
729
730static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
731  if (D->getKind() != Other->getKind())
732    return false;
733
734  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
735    return Ctx.getCanonicalDecl(Record->getInstantiatedFromMemberClass())
736             == Ctx.getCanonicalDecl(D);
737
738  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
739    return Ctx.getCanonicalDecl(Function->getInstantiatedFromMemberFunction())
740             == Ctx.getCanonicalDecl(D);
741
742  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
743    return Ctx.getCanonicalDecl(Enum->getInstantiatedFromMemberEnum())
744             == Ctx.getCanonicalDecl(D);
745
746  // FIXME: How can we find instantiations of anonymous unions?
747
748  return D->getDeclName() && isa<NamedDecl>(Other) &&
749    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
750}
751
752template<typename ForwardIterator>
753static NamedDecl *findInstantiationOf(ASTContext &Ctx,
754                                      NamedDecl *D,
755                                      ForwardIterator first,
756                                      ForwardIterator last) {
757  for (; first != last; ++first)
758    if (isInstantiationOf(Ctx, D, *first))
759      return cast<NamedDecl>(*first);
760
761  return 0;
762}
763
764/// \brief Find the instantiation of the given declaration within the
765/// current instantiation.
766///
767/// This routine is intended to be used when \p D is a declaration
768/// referenced from within a template, that needs to mapped into the
769/// corresponding declaration within an instantiation. For example,
770/// given:
771///
772/// \code
773/// template<typename T>
774/// struct X {
775///   enum Kind {
776///     KnownValue = sizeof(T)
777///   };
778///
779///   bool getKind() const { return KnownValue; }
780/// };
781///
782/// template struct X<int>;
783/// \endcode
784///
785/// In the instantiation of X<int>::getKind(), we need to map the
786/// EnumConstantDecl for KnownValue (which refers to
787/// X<T>::<Kind>::KnownValue) to its instantiation
788/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
789/// this mapping from within the instantiation of X<int>.
790NamedDecl * Sema::InstantiateCurrentDeclRef(NamedDecl *D) {
791  DeclContext *ParentDC = D->getDeclContext();
792  if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
793    // D is a local of some kind. Look into the map of local
794    // declarations to their instantiations.
795    return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
796  }
797
798  if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
799    ParentDecl = InstantiateCurrentDeclRef(ParentDecl);
800    if (!ParentDecl)
801      return 0;
802
803    ParentDC = cast<DeclContext>(ParentDecl);
804  }
805
806  if (ParentDC != D->getDeclContext()) {
807    // We performed some kind of instantiation in the parent context,
808    // so now we need to look into the instantiated parent context to
809    // find the instantiation of the declaration D.
810    NamedDecl *Result = 0;
811    if (D->getDeclName()) {
812      DeclContext::lookup_result Found
813        = ParentDC->lookup(Context, D->getDeclName());
814      Result = findInstantiationOf(Context, D, Found.first, Found.second);
815    } else {
816      // Since we don't have a name for the entity we're looking for,
817      // our only option is to walk through all of the declarations to
818      // find that name. This will occur in a few cases:
819      //
820      //   - anonymous struct/union within a template
821      //   - unnamed class/struct/union/enum within a template
822      //
823      // FIXME: Find a better way to find these instantiations!
824      Result = findInstantiationOf(Context, D,
825                                   ParentDC->decls_begin(Context),
826                                   ParentDC->decls_end(Context));
827    }
828    assert(Result && "Unable to find instantiation of declaration!");
829    D = Result;
830  }
831
832  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
833    if (ClassTemplateDecl *ClassTemplate
834          = Record->getDescribedClassTemplate()) {
835      // When the declaration D was parsed, it referred to the current
836      // instantiation. Therefore, look through the current context,
837      // which contains actual instantiations, to find the
838      // instantiation of the "current instantiation" that D refers
839      // to. Alternatively, we could just instantiate the
840      // injected-class-name with the current template arguments, but
841      // such an instantiation is far more expensive.
842      for (DeclContext *DC = CurContext; !DC->isFileContext();
843           DC = DC->getParent()) {
844        if (ClassTemplateSpecializationDecl *Spec
845              = dyn_cast<ClassTemplateSpecializationDecl>(DC))
846          if (Context.getCanonicalDecl(Spec->getSpecializedTemplate())
847              == Context.getCanonicalDecl(ClassTemplate))
848            return Spec;
849      }
850
851      assert(false &&
852             "Unable to find declaration for the current instantiation");
853    }
854
855  return D;
856}
857
858/// \brief Performs template instantiation for all implicit template
859/// instantiations we have seen until this point.
860void Sema::PerformPendingImplicitInstantiations() {
861  while (!PendingImplicitInstantiations.empty()) {
862    PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
863    PendingImplicitInstantiations.pop();
864
865    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first))
866      if (!Function->getBody(Context))
867        InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function);
868
869    // FIXME: instantiation static member variables
870  }
871}
872