blob: 461302f81d58003b9010b79b25dd4bcf4a1d1efc [file] [log] [blame]
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001//===--- 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"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000013#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000014#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
Chris Lattnerb28317a2009-03-28 19:18:32 +000024 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000025 Sema &SemaRef;
26 DeclContext *Owner;
Douglas Gregor7e063902009-05-11 23:53:27 +000027 const TemplateArgumentList &TemplateArgs;
Douglas Gregor8dbc2692009-03-17 21:15:40 +000028
29 public:
30 typedef Sema::OwningExprResult OwningExprResult;
31
32 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregor7e063902009-05-11 23:53:27 +000033 const TemplateArgumentList &TemplateArgs)
34 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Douglas Gregor8dbc2692009-03-17 21:15:40 +000035
Mike Stump390b4cc2009-05-16 07:39:55 +000036 // FIXME: Once we get closer to completion, replace these manually-written
37 // declarations with automatically-generated ones from
38 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000039 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
40 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000041 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000042 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000043 Decl *VisitFieldDecl(FieldDecl *D);
44 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
45 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000046 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregord475b8d2009-03-25 21:17:03 +000047 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000048 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
Douglas Gregor615c5d42009-03-24 16:43:20 +000049 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000050 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000051 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000052 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000053 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
Douglas Gregor5545e162009-03-24 00:38:23 +000054
Douglas Gregor8dbc2692009-03-17 21:15:40 +000055 // Base case. FIXME: Remove once we can instantiate everything.
56 Decl *VisitDecl(Decl *) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000057 assert(false && "Template instantiation of unknown declaration kind!");
Douglas Gregor8dbc2692009-03-17 21:15:40 +000058 return 0;
59 }
Douglas Gregor5545e162009-03-24 00:38:23 +000060
61 // Helper functions for instantiating methods.
62 QualType InstantiateFunctionType(FunctionDecl *D,
63 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
64 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000065 };
66}
67
Douglas Gregor4f722be2009-03-25 15:45:12 +000068Decl *
69TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
70 assert(false && "Translation units cannot be instantiated");
71 return D;
72}
73
74Decl *
75TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
76 assert(false && "Namespaces cannot be instantiated");
77 return D;
78}
79
Douglas Gregor8dbc2692009-03-17 21:15:40 +000080Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
81 bool Invalid = false;
82 QualType T = D->getUnderlyingType();
83 if (T->isDependentType()) {
Douglas Gregor1eee0e72009-05-14 21:06:31 +000084 T = SemaRef.InstantiateType(T, TemplateArgs,
85 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +000086 if (T.isNull()) {
87 Invalid = true;
88 T = SemaRef.Context.IntTy;
89 }
90 }
91
92 // Create the new typedef
93 TypedefDecl *Typedef
94 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
95 D->getIdentifier(), T);
96 if (Invalid)
97 Typedef->setInvalidDecl();
98
Douglas Gregor6ab35242009-04-09 21:40:53 +000099 Owner->addDecl(SemaRef.Context, Typedef);
Douglas Gregorbc221632009-05-28 16:34:51 +0000100
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000101 return Typedef;
102}
103
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000104Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
105 // Instantiate the type of the declaration
106 QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs,
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000107 D->getTypeSpecStartLoc(),
108 D->getDeclName());
109 if (T.isNull())
110 return 0;
111
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000112 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000113 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
114 D->getLocation(), D->getIdentifier(),
115 T, D->getStorageClass(),
116 D->getTypeSpecStartLoc());
117 Var->setThreadSpecified(D->isThreadSpecified());
118 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
119 Var->setDeclaredInCondition(D->isDeclaredInCondition());
120
Mike Stump390b4cc2009-05-16 07:39:55 +0000121 // FIXME: In theory, we could have a previous declaration for variables that
122 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000123 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000124 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000125 Owner->addDecl(SemaRef.Context, Var);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000126
127 if (D->getInit()) {
128 OwningExprResult Init
Douglas Gregor7e063902009-05-11 23:53:27 +0000129 = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000130 if (Init.isInvalid())
131 Var->setInvalidDecl();
132 else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000133 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000134 D->hasCXXDirectInitializer());
Douglas Gregord308e622009-05-18 20:51:54 +0000135 } else {
136 // FIXME: Call ActOnUninitializedDecl? (Not always)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000137 }
138
139 return Var;
140}
141
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000142Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
143 bool Invalid = false;
144 QualType T = D->getType();
145 if (T->isDependentType()) {
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000146 T = SemaRef.InstantiateType(T, TemplateArgs,
147 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000148 if (!T.isNull() && T->isFunctionType()) {
149 // C++ [temp.arg.type]p3:
150 // If a declaration acquires a function type through a type
151 // dependent on a template-parameter and this causes a
152 // declaration that does not use the syntactic form of a
153 // function declarator to have function type, the program is
154 // ill-formed.
155 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
156 << T;
157 T = QualType();
158 Invalid = true;
159 }
160 }
161
162 Expr *BitWidth = D->getBitWidth();
163 if (Invalid)
164 BitWidth = 0;
165 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000166 // The bit-width expression is not potentially evaluated.
167 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
168
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000169 OwningExprResult InstantiatedBitWidth
Douglas Gregor7e063902009-05-11 23:53:27 +0000170 = SemaRef.InstantiateExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000171 if (InstantiatedBitWidth.isInvalid()) {
172 Invalid = true;
173 BitWidth = 0;
174 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000175 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000176 }
177
178 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
179 cast<RecordDecl>(Owner),
180 D->getLocation(),
181 D->isMutable(),
182 BitWidth,
183 D->getAccess(),
184 0);
185 if (Field) {
186 if (Invalid)
187 Field->setInvalidDecl();
188
Douglas Gregor6ab35242009-04-09 21:40:53 +0000189 Owner->addDecl(SemaRef.Context, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000190 }
191
192 return Field;
193}
194
195Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
196 Expr *AssertExpr = D->getAssertExpr();
197
Douglas Gregorac7610d2009-06-22 20:57:11 +0000198 // The expression in a static assertion is not potentially evaluated.
199 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
200
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000201 OwningExprResult InstantiatedAssertExpr
Douglas Gregor7e063902009-05-11 23:53:27 +0000202 = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000203 if (InstantiatedAssertExpr.isInvalid())
204 return 0;
205
206 OwningExprResult Message = SemaRef.Clone(D->getMessage());
207 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000208 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
209 move(InstantiatedAssertExpr),
210 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000211 return StaticAssert;
212}
213
214Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
215 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
216 D->getLocation(), D->getIdentifier(),
217 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000218 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000219 Enum->setAccess(D->getAccess());
Douglas Gregor6ab35242009-04-09 21:40:53 +0000220 Owner->addDecl(SemaRef.Context, Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000221 Enum->startDefinition();
222
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000223 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000224
225 EnumConstantDecl *LastEnumConst = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000226 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(SemaRef.Context),
227 ECEnd = D->enumerator_end(SemaRef.Context);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000228 EC != ECEnd; ++EC) {
229 // The specified value for the enumerator.
230 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000231 if (Expr *UninstValue = EC->getInitExpr()) {
232 // The enumerator's value expression is not potentially evaluated.
233 EnterExpressionEvaluationContext Unevaluated(SemaRef,
234 Action::Unevaluated);
235
Douglas Gregor7e063902009-05-11 23:53:27 +0000236 Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000237 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000238
239 // Drop the initial value and continue.
240 bool isInvalid = false;
241 if (Value.isInvalid()) {
242 Value = SemaRef.Owned((Expr *)0);
243 isInvalid = true;
244 }
245
246 EnumConstantDecl *EnumConst
247 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
248 EC->getLocation(), EC->getIdentifier(),
249 move(Value));
250
251 if (isInvalid) {
252 if (EnumConst)
253 EnumConst->setInvalidDecl();
254 Enum->setInvalidDecl();
255 }
256
257 if (EnumConst) {
Douglas Gregor6ab35242009-04-09 21:40:53 +0000258 Enum->addDecl(SemaRef.Context, EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000259 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000260 LastEnumConst = EnumConst;
261 }
262 }
263
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000264 // FIXME: Fixup LBraceLoc and RBraceLoc
265 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
266 Sema::DeclPtrTy::make(Enum),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000267 &Enumerators[0], Enumerators.size());
268
269 return Enum;
270}
271
Douglas Gregor6477b692009-03-25 15:04:13 +0000272Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
273 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
274 return 0;
275}
276
Douglas Gregord475b8d2009-03-25 21:17:03 +0000277Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
278 CXXRecordDecl *PrevDecl = 0;
279 if (D->isInjectedClassName())
280 PrevDecl = cast<CXXRecordDecl>(Owner);
281
282 CXXRecordDecl *Record
283 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
284 D->getLocation(), D->getIdentifier(), PrevDecl);
285 Record->setImplicit(D->isImplicit());
286 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000287 if (!D->isInjectedClassName())
288 Record->setInstantiationOfMemberClass(D);
289
Douglas Gregor6ab35242009-04-09 21:40:53 +0000290 Owner->addDecl(SemaRef.Context, Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000291 return Record;
292}
293
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000294Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
295 // Only handle actual methods; we'll deal with constructors,
296 // destructors, etc. separately.
297 if (D->getKind() != Decl::CXXMethod)
298 return 0;
299
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000300 Sema::LocalInstantiationScope Scope(SemaRef);
301
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000302 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000303 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000304 if (T.isNull())
305 return 0;
306
307 // Build the instantiated method declaration.
308 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
309 CXXMethodDecl *Method
310 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
311 D->getDeclName(), T, D->isStatic(),
312 D->isInline());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000313 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000314
Douglas Gregor5545e162009-03-24 00:38:23 +0000315 // Attach the parameters
316 for (unsigned P = 0; P < Params.size(); ++P)
317 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000318 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000319
320 if (InitMethodInstantiation(Method, D))
321 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000322
323 NamedDecl *PrevDecl
324 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
325 Sema::LookupOrdinaryName, true);
326 // In C++, the previous declaration we find might be a tag type
327 // (class or enum). In this case, the new declaration will hide the
328 // tag type. Note that this does does not apply if we're declaring a
329 // typedef (C++ [dcl.typedef]p4).
330 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
331 PrevDecl = 0;
332 bool Redeclaration = false;
333 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000334 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
335 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000336
337 if (!Method->isInvalidDecl() || !PrevDecl)
Douglas Gregor6ab35242009-04-09 21:40:53 +0000338 Owner->addDecl(SemaRef.Context, Method);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000339 return Method;
340}
341
Douglas Gregor615c5d42009-03-24 16:43:20 +0000342Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000343 Sema::LocalInstantiationScope Scope(SemaRef);
344
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000345 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor615c5d42009-03-24 16:43:20 +0000346 QualType T = InstantiateFunctionType(D, Params);
347 if (T.isNull())
348 return 0;
349
350 // Build the instantiated method declaration.
351 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
352 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
353 DeclarationName Name
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000354 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
355 SemaRef.Context.getCanonicalType(ClassTy));
Douglas Gregor615c5d42009-03-24 16:43:20 +0000356 CXXConstructorDecl *Constructor
357 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
358 Name, T, D->isExplicit(), D->isInline(),
359 false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000360 Constructor->setInstantiationOfMemberFunction(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000361
362 // Attach the parameters
363 for (unsigned P = 0; P < Params.size(); ++P)
364 Params[P]->setOwningFunction(Constructor);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000365 Constructor->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor615c5d42009-03-24 16:43:20 +0000366
367 if (InitMethodInstantiation(Constructor, D))
368 Constructor->setInvalidDecl();
369
370 NamedDecl *PrevDecl
371 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
372
373 // In C++, the previous declaration we find might be a tag type
374 // (class or enum). In this case, the new declaration will hide the
375 // tag type. Note that this does does not apply if we're declaring a
376 // typedef (C++ [dcl.typedef]p4).
377 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
378 PrevDecl = 0;
379 bool Redeclaration = false;
380 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000381 SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
382 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000383
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000384 Record->addedConstructor(SemaRef.Context, Constructor);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000385 Owner->addDecl(SemaRef.Context, Constructor);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000386 return Constructor;
387}
388
Douglas Gregor03b2b072009-03-24 00:15:49 +0000389Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000390 Sema::LocalInstantiationScope Scope(SemaRef);
391
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000392 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000393 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000394 if (T.isNull())
395 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +0000396 assert(Params.size() == 0 && "Destructor with parameters?");
397
Douglas Gregor03b2b072009-03-24 00:15:49 +0000398 // Build the instantiated destructor declaration.
399 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000400 QualType ClassTy =
401 SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record));
Douglas Gregor03b2b072009-03-24 00:15:49 +0000402 CXXDestructorDecl *Destructor
403 = CXXDestructorDecl::Create(SemaRef.Context, Record,
404 D->getLocation(),
405 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
406 T, D->isInline(), false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000407 Destructor->setInstantiationOfMemberFunction(D);
Douglas Gregor5545e162009-03-24 00:38:23 +0000408 if (InitMethodInstantiation(Destructor, D))
409 Destructor->setInvalidDecl();
Douglas Gregor03b2b072009-03-24 00:15:49 +0000410
411 bool Redeclaration = false;
412 bool OverloadableAttrRequired = false;
413 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000414 SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
415 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000416 Owner->addDecl(SemaRef.Context, Destructor);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000417 return Destructor;
418}
419
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000420Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000421 Sema::LocalInstantiationScope Scope(SemaRef);
422
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000423 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000424 QualType T = InstantiateFunctionType(D, Params);
425 if (T.isNull())
426 return 0;
427 assert(Params.size() == 0 && "Destructor with parameters?");
428
429 // Build the instantiated conversion declaration.
430 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
431 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
432 QualType ConvTy
433 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
434 CXXConversionDecl *Conversion
435 = CXXConversionDecl::Create(SemaRef.Context, Record,
436 D->getLocation(),
437 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
438 T, D->isInline(), D->isExplicit());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000439 Conversion->setInstantiationOfMemberFunction(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000440 if (InitMethodInstantiation(Conversion, D))
441 Conversion->setInvalidDecl();
442
443 bool Redeclaration = false;
444 bool OverloadableAttrRequired = false;
445 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000446 SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
447 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000448 Owner->addDecl(SemaRef.Context, Conversion);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000449 return Conversion;
450}
451
Douglas Gregor6477b692009-03-25 15:04:13 +0000452ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000453 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000454 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000455 if (OrigT.isNull())
456 return 0;
457
458 QualType T = SemaRef.adjustParameterType(OrigT);
459
460 if (D->getDefaultArg()) {
461 // FIXME: Leave a marker for "uninstantiated" default
462 // arguments. They only get instantiated on demand at the call
463 // site.
464 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
465 "sorry, dropping default argument during template instantiation");
466 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
467 << D->getDefaultArg()->getSourceRange();
468 }
469
470 // Allocate the parameter
471 ParmVarDecl *Param = 0;
472 if (T == OrigT)
473 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
474 D->getIdentifier(), T, D->getStorageClass(),
475 0);
476 else
477 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
478 D->getLocation(), D->getIdentifier(),
479 T, OrigT, D->getStorageClass(), 0);
480
481 // Note: we don't try to instantiate function parameters until after
482 // we've instantiated the function's type. Therefore, we don't have
483 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000484 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000485 return Param;
486}
487
488Decl *
489TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
490 // Since parameter types can decay either before or after
491 // instantiation, we simply treat OriginalParmVarDecls as
492 // ParmVarDecls the same way, and create one or the other depending
493 // on what happens after template instantiation.
494 return VisitParmVarDecl(D);
495}
496
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000497Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
Douglas Gregor7e063902009-05-11 23:53:27 +0000498 const TemplateArgumentList &TemplateArgs) {
499 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000500 return Instantiator.Visit(D);
501}
502
Douglas Gregor5545e162009-03-24 00:38:23 +0000503/// \brief Instantiates the type of the given function, including
504/// instantiating all of the function parameters.
505///
506/// \param D The function that we will be instantiated
507///
508/// \param Params the instantiated parameter declarations
509
510/// \returns the instantiated function's type if successfull, a NULL
511/// type if there was an error.
512QualType
513TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
514 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
515 bool InvalidDecl = false;
516
517 // Instantiate the function parameters
Douglas Gregor7e063902009-05-11 23:53:27 +0000518 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000519 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000520 for (FunctionDecl::param_iterator P = D->param_begin(),
521 PEnd = D->param_end();
522 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000523 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000524 if (PInst->getType()->isVoidType()) {
525 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
526 PInst->setInvalidDecl();
527 }
528 else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
529 PInst->getType(),
530 diag::err_abstract_type_in_decl,
Anders Carlsson8211eff2009-03-24 01:19:16 +0000531 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000532 PInst->setInvalidDecl();
533
534 Params.push_back(PInst);
535 ParamTys.push_back(PInst->getType());
536
537 if (PInst->isInvalidDecl())
538 InvalidDecl = true;
539 } else
540 InvalidDecl = true;
541 }
542
543 // FIXME: Deallocate dead declarations.
544 if (InvalidDecl)
545 return QualType();
546
547 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
548 assert(Proto && "Missing prototype?");
549 QualType ResultType
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000550 = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs,
Douglas Gregor5545e162009-03-24 00:38:23 +0000551 D->getLocation(), D->getDeclName());
552 if (ResultType.isNull())
553 return QualType();
554
Jay Foadbeaaccd2009-05-21 09:52:38 +0000555 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000556 Proto->isVariadic(), Proto->getTypeQuals(),
557 D->getLocation(), D->getDeclName());
558}
559
560/// \brief Initializes common fields of an instantiated method
561/// declaration (New) from the corresponding fields of its template
562/// (Tmpl).
563///
564/// \returns true if there was an error
565bool
566TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
567 CXXMethodDecl *Tmpl) {
568 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
569 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000570 if (Tmpl->isVirtualAsWritten()) {
571 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000572 Record->setAggregate(false);
573 Record->setPOD(false);
574 Record->setPolymorphic(true);
575 }
576 if (Tmpl->isDeleted())
577 New->setDeleted();
578 if (Tmpl->isPure()) {
579 New->setPure();
580 Record->setAbstract(true);
581 }
582
583 // FIXME: attributes
584 // FIXME: New needs a pointer to Tmpl
585 return false;
586}
Douglas Gregora58861f2009-05-13 20:28:22 +0000587
588/// \brief Instantiate the definition of the given function from its
589/// template.
590///
591/// \param Function the already-instantiated declaration of a
592/// function.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000593void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
594 FunctionDecl *Function) {
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000595 // FIXME: make this work for function template specializations, too.
596
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000597 if (Function->isInvalidDecl())
598 return;
599
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000600 // Find the function body that we'll be substituting.
601 const FunctionDecl *PatternDecl
602 = Function->getInstantiatedFromMemberFunction();
603 Stmt *Pattern = 0;
604 if (PatternDecl)
605 Pattern = PatternDecl->getBody(Context, PatternDecl);
606
607 if (!Pattern)
608 return;
609
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000610 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
611 if (Inst)
612 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000613
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000614 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
615
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000616 // Introduce a new scope where local variable instantiations will be
617 // recorded.
618 LocalInstantiationScope Scope(*this);
619
620 // Introduce the instantiated function parameters into the local
621 // instantiation scope.
622 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
623 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
624 Function->getParamDecl(I));
625
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000626 // Enter the scope of this instantiation. We don't use
627 // PushDeclContext because we don't have a scope.
628 DeclContext *PreviousContext = CurContext;
629 CurContext = Function;
630
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000631 // Instantiate the function body.
632 OwningStmtResult Body
633 = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function));
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000634
635 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
636 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000637
638 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000639
640 DeclGroupRef DG(Function);
641 Consumer.HandleTopLevelDecl(DG);
Douglas Gregora58861f2009-05-13 20:28:22 +0000642}
643
644/// \brief Instantiate the definition of the given variable from its
645/// template.
646///
647/// \param Var the already-instantiated declaration of a variable.
648void Sema::InstantiateVariableDefinition(VarDecl *Var) {
649 // FIXME: Implement this!
650}
Douglas Gregor815215d2009-05-27 05:35:12 +0000651
652static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
653 if (D->getKind() != Other->getKind())
654 return false;
655
656 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
657 return Ctx.getCanonicalDecl(Record->getInstantiatedFromMemberClass())
658 == Ctx.getCanonicalDecl(D);
659
660 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
661 return Ctx.getCanonicalDecl(Function->getInstantiatedFromMemberFunction())
662 == Ctx.getCanonicalDecl(D);
663
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000664 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
665 return Ctx.getCanonicalDecl(Enum->getInstantiatedFromMemberEnum())
666 == Ctx.getCanonicalDecl(D);
Douglas Gregor815215d2009-05-27 05:35:12 +0000667
668 // FIXME: How can we find instantiations of anonymous unions?
669
670 return D->getDeclName() && isa<NamedDecl>(Other) &&
671 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
672}
673
674template<typename ForwardIterator>
675static NamedDecl *findInstantiationOf(ASTContext &Ctx,
676 NamedDecl *D,
677 ForwardIterator first,
678 ForwardIterator last) {
679 for (; first != last; ++first)
680 if (isInstantiationOf(Ctx, D, *first))
681 return cast<NamedDecl>(*first);
682
683 return 0;
684}
685
Douglas Gregored961e72009-05-27 17:54:46 +0000686/// \brief Find the instantiation of the given declaration within the
687/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +0000688///
689/// This routine is intended to be used when \p D is a declaration
690/// referenced from within a template, that needs to mapped into the
691/// corresponding declaration within an instantiation. For example,
692/// given:
693///
694/// \code
695/// template<typename T>
696/// struct X {
697/// enum Kind {
698/// KnownValue = sizeof(T)
699/// };
700///
701/// bool getKind() const { return KnownValue; }
702/// };
703///
704/// template struct X<int>;
705/// \endcode
706///
707/// In the instantiation of X<int>::getKind(), we need to map the
708/// EnumConstantDecl for KnownValue (which refers to
709/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +0000710/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
711/// this mapping from within the instantiation of X<int>.
712NamedDecl * Sema::InstantiateCurrentDeclRef(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +0000713 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +0000714 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
715 // D is a local of some kind. Look into the map of local
716 // declarations to their instantiations.
717 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
718 }
Douglas Gregor815215d2009-05-27 05:35:12 +0000719
Douglas Gregor2bba76b2009-05-27 17:07:49 +0000720 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
Douglas Gregored961e72009-05-27 17:54:46 +0000721 ParentDecl = InstantiateCurrentDeclRef(ParentDecl);
Douglas Gregor815215d2009-05-27 05:35:12 +0000722 if (!ParentDecl)
723 return 0;
724
725 ParentDC = cast<DeclContext>(ParentDecl);
726 }
727
Douglas Gregor815215d2009-05-27 05:35:12 +0000728 if (ParentDC != D->getDeclContext()) {
729 // We performed some kind of instantiation in the parent context,
730 // so now we need to look into the instantiated parent context to
731 // find the instantiation of the declaration D.
732 NamedDecl *Result = 0;
733 if (D->getDeclName()) {
734 DeclContext::lookup_result Found
735 = ParentDC->lookup(Context, D->getDeclName());
736 Result = findInstantiationOf(Context, D, Found.first, Found.second);
737 } else {
738 // Since we don't have a name for the entity we're looking for,
739 // our only option is to walk through all of the declarations to
740 // find that name. This will occur in a few cases:
741 //
742 // - anonymous struct/union within a template
743 // - unnamed class/struct/union/enum within a template
744 //
745 // FIXME: Find a better way to find these instantiations!
746 Result = findInstantiationOf(Context, D,
747 ParentDC->decls_begin(Context),
748 ParentDC->decls_end(Context));
749 }
750 assert(Result && "Unable to find instantiation of declaration!");
751 D = Result;
752 }
753
Douglas Gregor815215d2009-05-27 05:35:12 +0000754 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
Douglas Gregored961e72009-05-27 17:54:46 +0000755 if (ClassTemplateDecl *ClassTemplate
756 = Record->getDescribedClassTemplate()) {
757 // When the declaration D was parsed, it referred to the current
758 // instantiation. Therefore, look through the current context,
759 // which contains actual instantiations, to find the
760 // instantiation of the "current instantiation" that D refers
761 // to. Alternatively, we could just instantiate the
762 // injected-class-name with the current template arguments, but
763 // such an instantiation is far more expensive.
764 for (DeclContext *DC = CurContext; !DC->isFileContext();
765 DC = DC->getParent()) {
766 if (ClassTemplateSpecializationDecl *Spec
767 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
768 if (Context.getCanonicalDecl(Spec->getSpecializedTemplate())
769 == Context.getCanonicalDecl(ClassTemplate))
770 return Spec;
771 }
772
773 assert(false &&
774 "Unable to find declaration for the current instantiation");
Douglas Gregor815215d2009-05-27 05:35:12 +0000775 }
776
777 return D;
778}