blob: 021a6ad2ab447de9e1df6810f6dca3b33b842130 [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 Gregore53060f2009-06-25 22:08:12 +000047 Decl *VisitFunctionDecl(FunctionDecl *D);
Douglas Gregord475b8d2009-03-25 21:17:03 +000048 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000049 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
Douglas Gregor615c5d42009-03-24 16:43:20 +000050 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000051 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000052 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000053 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000054 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
Douglas Gregor5545e162009-03-24 00:38:23 +000055
Douglas Gregor8dbc2692009-03-17 21:15:40 +000056 // Base case. FIXME: Remove once we can instantiate everything.
57 Decl *VisitDecl(Decl *) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000058 assert(false && "Template instantiation of unknown declaration kind!");
Douglas Gregor8dbc2692009-03-17 21:15:40 +000059 return 0;
60 }
Douglas Gregor5545e162009-03-24 00:38:23 +000061
62 // Helper functions for instantiating methods.
63 QualType InstantiateFunctionType(FunctionDecl *D,
64 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000065 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000066 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000067 };
68}
69
Douglas Gregor4f722be2009-03-25 15:45:12 +000070Decl *
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
Douglas Gregor8dbc2692009-03-17 21:15:40 +000082Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
83 bool Invalid = false;
84 QualType T = D->getUnderlyingType();
85 if (T->isDependentType()) {
Douglas Gregor1eee0e72009-05-14 21:06:31 +000086 T = SemaRef.InstantiateType(T, TemplateArgs,
87 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +000088 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
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000101 Owner->addDecl(Typedef);
Douglas Gregorbc221632009-05-28 16:34:51 +0000102
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000103 return Typedef;
104}
105
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000106Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
107 // Instantiate the type of the declaration
108 QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs,
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000109 D->getTypeSpecStartLoc(),
110 D->getDeclName());
111 if (T.isNull())
112 return 0;
113
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000114 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000115 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
Douglas Gregor7caa6822009-07-24 20:34:43 +0000123 // If we are instantiating a static data member defined
124 // out-of-line, the instantiation will have the same lexical
125 // context (which will be a namespace scope) as the template.
126 if (D->isOutOfLine())
127 Var->setLexicalDeclContext(D->getLexicalDeclContext());
128
Mike Stump390b4cc2009-05-16 07:39:55 +0000129 // FIXME: In theory, we could have a previous declaration for variables that
130 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000131 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000132 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000133
134 if (D->isOutOfLine()) {
135 D->getLexicalDeclContext()->addDecl(Var);
136 Owner->makeDeclVisibleInContext(Var);
137 } else {
138 Owner->addDecl(Var);
139 }
140
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000141 if (D->getInit()) {
142 OwningExprResult Init
Douglas Gregor7e063902009-05-11 23:53:27 +0000143 = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000144 if (Init.isInvalid())
145 Var->setInvalidDecl();
146 else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000147 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000148 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000149 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
150 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000151
Douglas Gregor7caa6822009-07-24 20:34:43 +0000152 // Link instantiations of static data members back to the template from
153 // which they were instantiated.
154 if (Var->isStaticDataMember())
155 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
156
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000157 return Var;
158}
159
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000160Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
161 bool Invalid = false;
162 QualType T = D->getType();
163 if (T->isDependentType()) {
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000164 T = SemaRef.InstantiateType(T, TemplateArgs,
165 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000166 if (!T.isNull() && T->isFunctionType()) {
167 // C++ [temp.arg.type]p3:
168 // If a declaration acquires a function type through a type
169 // dependent on a template-parameter and this causes a
170 // declaration that does not use the syntactic form of a
171 // function declarator to have function type, the program is
172 // ill-formed.
173 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
174 << T;
175 T = QualType();
176 Invalid = true;
177 }
178 }
179
180 Expr *BitWidth = D->getBitWidth();
181 if (Invalid)
182 BitWidth = 0;
183 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000184 // The bit-width expression is not potentially evaluated.
185 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
186
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000187 OwningExprResult InstantiatedBitWidth
Douglas Gregor7e063902009-05-11 23:53:27 +0000188 = SemaRef.InstantiateExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000189 if (InstantiatedBitWidth.isInvalid()) {
190 Invalid = true;
191 BitWidth = 0;
192 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000193 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000194 }
195
196 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
197 cast<RecordDecl>(Owner),
198 D->getLocation(),
199 D->isMutable(),
200 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000201 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000202 D->getAccess(),
203 0);
204 if (Field) {
205 if (Invalid)
206 Field->setInvalidDecl();
207
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000208 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000209 }
210
211 return Field;
212}
213
214Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
215 Expr *AssertExpr = D->getAssertExpr();
216
Douglas Gregorac7610d2009-06-22 20:57:11 +0000217 // The expression in a static assertion is not potentially evaluated.
218 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
219
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000220 OwningExprResult InstantiatedAssertExpr
Douglas Gregor7e063902009-05-11 23:53:27 +0000221 = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000222 if (InstantiatedAssertExpr.isInvalid())
223 return 0;
224
225 OwningExprResult Message = SemaRef.Clone(D->getMessage());
226 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000227 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
228 move(InstantiatedAssertExpr),
229 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000230 return StaticAssert;
231}
232
233Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
234 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
235 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000236 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000237 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000238 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000239 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000240 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000241 Enum->startDefinition();
242
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000243 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000244
245 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000246 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
247 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000248 EC != ECEnd; ++EC) {
249 // The specified value for the enumerator.
250 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000251 if (Expr *UninstValue = EC->getInitExpr()) {
252 // The enumerator's value expression is not potentially evaluated.
253 EnterExpressionEvaluationContext Unevaluated(SemaRef,
254 Action::Unevaluated);
255
Douglas Gregor7e063902009-05-11 23:53:27 +0000256 Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000257 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000258
259 // Drop the initial value and continue.
260 bool isInvalid = false;
261 if (Value.isInvalid()) {
262 Value = SemaRef.Owned((Expr *)0);
263 isInvalid = true;
264 }
265
266 EnumConstantDecl *EnumConst
267 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
268 EC->getLocation(), EC->getIdentifier(),
269 move(Value));
270
271 if (isInvalid) {
272 if (EnumConst)
273 EnumConst->setInvalidDecl();
274 Enum->setInvalidDecl();
275 }
276
277 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000278 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000279 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000280 LastEnumConst = EnumConst;
281 }
282 }
283
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000284 // FIXME: Fixup LBraceLoc and RBraceLoc
285 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
286 Sema::DeclPtrTy::make(Enum),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000287 &Enumerators[0], Enumerators.size());
288
289 return Enum;
290}
291
Douglas Gregor6477b692009-03-25 15:04:13 +0000292Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
293 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
294 return 0;
295}
296
Douglas Gregord475b8d2009-03-25 21:17:03 +0000297Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
298 CXXRecordDecl *PrevDecl = 0;
299 if (D->isInjectedClassName())
300 PrevDecl = cast<CXXRecordDecl>(Owner);
301
302 CXXRecordDecl *Record
303 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000304 D->getLocation(), D->getIdentifier(),
305 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000306 Record->setImplicit(D->isImplicit());
307 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000308 if (!D->isInjectedClassName())
309 Record->setInstantiationOfMemberClass(D);
310
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000311 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000312 return Record;
313}
314
Douglas Gregore53060f2009-06-25 22:08:12 +0000315Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000316 // Check whether there is already a function template specialization for
317 // this declaration.
318 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
319 void *InsertPos = 0;
320 if (FunctionTemplate) {
321 llvm::FoldingSetNodeID ID;
322 FunctionTemplateSpecializationInfo::Profile(ID,
323 TemplateArgs.getFlatArgumentList(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000324 TemplateArgs.flat_size(),
325 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000326
327 FunctionTemplateSpecializationInfo *Info
328 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
329 InsertPos);
330
331 // If we already have a function template specialization, return it.
332 if (Info)
333 return Info->Function;
334 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000335
336 Sema::LocalInstantiationScope Scope(SemaRef);
337
338 llvm::SmallVector<ParmVarDecl *, 4> Params;
339 QualType T = InstantiateFunctionType(D, Params);
340 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000341 return 0;
Douglas Gregore53060f2009-06-25 22:08:12 +0000342
343 // Build the instantiated method declaration.
344 FunctionDecl *Function
345 = FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(),
346 D->getDeclName(), T, D->getStorageClass(),
347 D->isInline(), D->hasWrittenPrototype(),
348 D->getTypeSpecStartLoc());
349
350 // FIXME: friend functions
351
352 // Attach the parameters
353 for (unsigned P = 0; P < Params.size(); ++P)
354 Params[P]->setOwningFunction(Function);
355 Function->setParams(SemaRef.Context, Params.data(), Params.size());
356
357 if (InitFunctionInstantiation(Function, D))
358 Function->setInvalidDecl();
359
360 bool Redeclaration = false;
361 bool OverloadableAttrRequired = false;
362 NamedDecl *PrevDecl = 0;
363 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
364 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000365
Douglas Gregor127102b2009-06-29 20:59:39 +0000366 if (FunctionTemplate) {
367 // Record this function template specialization.
368 Function->setFunctionTemplateSpecialization(SemaRef.Context,
369 FunctionTemplate,
370 &TemplateArgs,
371 InsertPos);
372 }
373
Douglas Gregore53060f2009-06-25 22:08:12 +0000374 return Function;
375}
376
377Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
378 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000379 Sema::LocalInstantiationScope Scope(SemaRef);
380
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000381 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000382 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000383 if (T.isNull())
384 return 0;
385
386 // Build the instantiated method declaration.
387 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
388 CXXMethodDecl *Method
389 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
390 D->getDeclName(), T, D->isStatic(),
391 D->isInline());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000392 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000393
Douglas Gregor7caa6822009-07-24 20:34:43 +0000394 // If we are instantiating a member function defined
395 // out-of-line, the instantiation will have the same lexical
396 // context (which will be a namespace scope) as the template.
397 if (D->isOutOfLine())
398 Method->setLexicalDeclContext(D->getLexicalDeclContext());
399
Douglas Gregor5545e162009-03-24 00:38:23 +0000400 // Attach the parameters
401 for (unsigned P = 0; P < Params.size(); ++P)
402 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000403 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000404
405 if (InitMethodInstantiation(Method, D))
406 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000407
408 NamedDecl *PrevDecl
409 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
410 Sema::LookupOrdinaryName, true);
411 // In C++, the previous declaration we find might be a tag type
412 // (class or enum). In this case, the new declaration will hide the
413 // tag type. Note that this does does not apply if we're declaring a
414 // typedef (C++ [dcl.typedef]p4).
415 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
416 PrevDecl = 0;
417 bool Redeclaration = false;
418 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000419 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
420 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000421
422 if (!Method->isInvalidDecl() || !PrevDecl)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000423 Owner->addDecl(Method);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000424 return Method;
425}
426
Douglas Gregor615c5d42009-03-24 16:43:20 +0000427Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000428 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000429 Sema::LocalInstantiationScope Scope(SemaRef);
430
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000431 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor615c5d42009-03-24 16:43:20 +0000432 QualType T = InstantiateFunctionType(D, Params);
433 if (T.isNull())
434 return 0;
435
436 // Build the instantiated method declaration.
437 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
438 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
439 DeclarationName Name
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000440 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
441 SemaRef.Context.getCanonicalType(ClassTy));
Douglas Gregor615c5d42009-03-24 16:43:20 +0000442 CXXConstructorDecl *Constructor
443 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
444 Name, T, D->isExplicit(), D->isInline(),
445 false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000446 Constructor->setInstantiationOfMemberFunction(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000447
448 // Attach the parameters
449 for (unsigned P = 0; P < Params.size(); ++P)
450 Params[P]->setOwningFunction(Constructor);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000451 Constructor->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor615c5d42009-03-24 16:43:20 +0000452
453 if (InitMethodInstantiation(Constructor, D))
454 Constructor->setInvalidDecl();
455
456 NamedDecl *PrevDecl
457 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
458
459 // In C++, the previous declaration we find might be a tag type
460 // (class or enum). In this case, the new declaration will hide the
461 // tag type. Note that this does does not apply if we're declaring a
462 // typedef (C++ [dcl.typedef]p4).
463 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
464 PrevDecl = 0;
465 bool Redeclaration = false;
466 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000467 SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
468 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000469
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000470 Record->addedConstructor(SemaRef.Context, Constructor);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000471 Owner->addDecl(Constructor);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000472 return Constructor;
473}
474
Douglas Gregor03b2b072009-03-24 00:15:49 +0000475Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000476 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000477 Sema::LocalInstantiationScope Scope(SemaRef);
478
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000479 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000480 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000481 if (T.isNull())
482 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +0000483 assert(Params.size() == 0 && "Destructor with parameters?");
484
Douglas Gregor03b2b072009-03-24 00:15:49 +0000485 // Build the instantiated destructor declaration.
486 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregor50d62d12009-08-05 05:36:45 +0000487 CanQualType ClassTy =
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000488 SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record));
Douglas Gregor03b2b072009-03-24 00:15:49 +0000489 CXXDestructorDecl *Destructor
490 = CXXDestructorDecl::Create(SemaRef.Context, Record,
491 D->getLocation(),
492 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
493 T, D->isInline(), false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000494 Destructor->setInstantiationOfMemberFunction(D);
Douglas Gregor5545e162009-03-24 00:38:23 +0000495 if (InitMethodInstantiation(Destructor, D))
496 Destructor->setInvalidDecl();
Douglas Gregor03b2b072009-03-24 00:15:49 +0000497
498 bool Redeclaration = false;
499 bool OverloadableAttrRequired = false;
500 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000501 SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
502 /*FIXME:*/OverloadableAttrRequired);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000503 Owner->addDecl(Destructor);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000504 return Destructor;
505}
506
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000507Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000508 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000509 Sema::LocalInstantiationScope Scope(SemaRef);
510
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000511 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000512 QualType T = InstantiateFunctionType(D, Params);
513 if (T.isNull())
514 return 0;
515 assert(Params.size() == 0 && "Destructor with parameters?");
516
517 // Build the instantiated conversion declaration.
518 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
519 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
Douglas Gregor50d62d12009-08-05 05:36:45 +0000520 CanQualType ConvTy
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000521 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
522 CXXConversionDecl *Conversion
523 = CXXConversionDecl::Create(SemaRef.Context, Record,
524 D->getLocation(),
525 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
526 T, D->isInline(), D->isExplicit());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000527 Conversion->setInstantiationOfMemberFunction(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000528 if (InitMethodInstantiation(Conversion, D))
529 Conversion->setInvalidDecl();
530
531 bool Redeclaration = false;
532 bool OverloadableAttrRequired = false;
533 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000534 SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
535 /*FIXME:*/OverloadableAttrRequired);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000536 Owner->addDecl(Conversion);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000537 return Conversion;
538}
539
Douglas Gregor6477b692009-03-25 15:04:13 +0000540ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000541 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000542 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000543 if (OrigT.isNull())
544 return 0;
545
546 QualType T = SemaRef.adjustParameterType(OrigT);
547
548 if (D->getDefaultArg()) {
549 // FIXME: Leave a marker for "uninstantiated" default
550 // arguments. They only get instantiated on demand at the call
551 // site.
552 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
553 "sorry, dropping default argument during template instantiation");
554 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
555 << D->getDefaultArg()->getSourceRange();
556 }
557
558 // Allocate the parameter
559 ParmVarDecl *Param = 0;
560 if (T == OrigT)
561 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
562 D->getIdentifier(), T, D->getStorageClass(),
563 0);
564 else
565 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
566 D->getLocation(), D->getIdentifier(),
567 T, OrigT, D->getStorageClass(), 0);
568
569 // Note: we don't try to instantiate function parameters until after
570 // we've instantiated the function's type. Therefore, we don't have
571 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000572 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000573 return Param;
574}
575
576Decl *
577TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
578 // Since parameter types can decay either before or after
579 // instantiation, we simply treat OriginalParmVarDecls as
580 // ParmVarDecls the same way, and create one or the other depending
581 // on what happens after template instantiation.
582 return VisitParmVarDecl(D);
583}
584
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000585Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
Douglas Gregor7e063902009-05-11 23:53:27 +0000586 const TemplateArgumentList &TemplateArgs) {
587 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000588 return Instantiator.Visit(D);
589}
590
Douglas Gregor5545e162009-03-24 00:38:23 +0000591/// \brief Instantiates the type of the given function, including
592/// instantiating all of the function parameters.
593///
594/// \param D The function that we will be instantiated
595///
596/// \param Params the instantiated parameter declarations
597
598/// \returns the instantiated function's type if successfull, a NULL
599/// type if there was an error.
600QualType
601TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
602 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
603 bool InvalidDecl = false;
604
605 // Instantiate the function parameters
Douglas Gregor7e063902009-05-11 23:53:27 +0000606 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000607 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000608 for (FunctionDecl::param_iterator P = D->param_begin(),
609 PEnd = D->param_end();
610 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000611 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000612 if (PInst->getType()->isVoidType()) {
613 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
614 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000615 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
616 PInst->getType(),
617 diag::err_abstract_type_in_decl,
618 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000619 PInst->setInvalidDecl();
620
621 Params.push_back(PInst);
622 ParamTys.push_back(PInst->getType());
623
624 if (PInst->isInvalidDecl())
625 InvalidDecl = true;
626 } else
627 InvalidDecl = true;
628 }
629
630 // FIXME: Deallocate dead declarations.
631 if (InvalidDecl)
632 return QualType();
633
634 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
635 assert(Proto && "Missing prototype?");
636 QualType ResultType
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000637 = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs,
Douglas Gregor5545e162009-03-24 00:38:23 +0000638 D->getLocation(), D->getDeclName());
639 if (ResultType.isNull())
640 return QualType();
641
Jay Foadbeaaccd2009-05-21 09:52:38 +0000642 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000643 Proto->isVariadic(), Proto->getTypeQuals(),
644 D->getLocation(), D->getDeclName());
645}
646
Douglas Gregore53060f2009-06-25 22:08:12 +0000647/// \brief Initializes the common fields of an instantiation function
648/// declaration (New) from the corresponding fields of its template (Tmpl).
649///
650/// \returns true if there was an error
651bool
652TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
653 FunctionDecl *Tmpl) {
654 if (Tmpl->isDeleted())
655 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000656
657 // If we are performing substituting explicitly-specified template arguments
658 // or deduced template arguments into a function template and we reach this
659 // point, we are now past the point where SFINAE applies and have committed
660 // to keeping the new function template specialization. We therefore
661 // convert the active template instantiation for the function template
662 // into a template instantiation for this specific function template
663 // specialization, which is not a SFINAE context, so that we diagnose any
664 // further errors in the declaration itself.
665 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
666 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
667 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
668 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
669 if (FunctionTemplateDecl *FunTmpl
670 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
671 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
672 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000673 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000674 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
675 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
676 }
677 }
678
Douglas Gregore53060f2009-06-25 22:08:12 +0000679 return false;
680}
681
Douglas Gregor5545e162009-03-24 00:38:23 +0000682/// \brief Initializes common fields of an instantiated method
683/// declaration (New) from the corresponding fields of its template
684/// (Tmpl).
685///
686/// \returns true if there was an error
687bool
688TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
689 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000690 if (InitFunctionInstantiation(New, Tmpl))
691 return true;
692
Douglas Gregor5545e162009-03-24 00:38:23 +0000693 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
694 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000695 if (Tmpl->isVirtualAsWritten()) {
696 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000697 Record->setAggregate(false);
698 Record->setPOD(false);
699 Record->setPolymorphic(true);
700 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000701 if (Tmpl->isPure()) {
702 New->setPure();
703 Record->setAbstract(true);
704 }
705
706 // FIXME: attributes
707 // FIXME: New needs a pointer to Tmpl
708 return false;
709}
Douglas Gregora58861f2009-05-13 20:28:22 +0000710
711/// \brief Instantiate the definition of the given function from its
712/// template.
713///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000714/// \param PointOfInstantiation the point at which the instantiation was
715/// required. Note that this is not precisely a "point of instantiation"
716/// for the function, but it's close.
717///
Douglas Gregora58861f2009-05-13 20:28:22 +0000718/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000719/// function template specialization or member function of a class template
720/// specialization.
721///
722/// \param Recursive if true, recursively instantiates any functions that
723/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000724void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000725 FunctionDecl *Function,
726 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000727 if (Function->isInvalidDecl())
728 return;
729
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000730 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000731
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000732 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000733 const FunctionDecl *PatternDecl = 0;
734 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
735 PatternDecl = Primary->getTemplatedDecl();
736 else
737 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000738 Stmt *Pattern = 0;
739 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000740 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000741
742 if (!Pattern)
743 return;
744
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000745 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
746 if (Inst)
747 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000748
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000749 // If we're performing recursive template instantiation, create our own
750 // queue of pending implicit instantiations that we will instantiate later,
751 // while we're still within our own instantiation context.
752 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
753 if (Recursive)
754 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
755
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000756 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
757
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000758 // Introduce a new scope where local variable instantiations will be
759 // recorded.
760 LocalInstantiationScope Scope(*this);
761
762 // Introduce the instantiated function parameters into the local
763 // instantiation scope.
764 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
765 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
766 Function->getParamDecl(I));
767
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000768 // Enter the scope of this instantiation. We don't use
769 // PushDeclContext because we don't have a scope.
770 DeclContext *PreviousContext = CurContext;
771 CurContext = Function;
772
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000773 // Instantiate the function body.
774 OwningStmtResult Body
775 = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function));
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000776
777 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
778 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000779
780 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000781
782 DeclGroupRef DG(Function);
783 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000784
785 if (Recursive) {
786 // Instantiate any pending implicit instantiations found during the
787 // instantiation of this template.
788 PerformPendingImplicitInstantiations();
789
790 // Restore the set of pending implicit instantiations.
791 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
792 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000793}
794
795/// \brief Instantiate the definition of the given variable from its
796/// template.
797///
Douglas Gregor7caa6822009-07-24 20:34:43 +0000798/// \param PointOfInstantiation the point at which the instantiation was
799/// required. Note that this is not precisely a "point of instantiation"
800/// for the function, but it's close.
801///
802/// \param Var the already-instantiated declaration of a static member
803/// variable of a class template specialization.
804///
805/// \param Recursive if true, recursively instantiates any functions that
806/// are required by this instantiation.
807void Sema::InstantiateStaticDataMemberDefinition(
808 SourceLocation PointOfInstantiation,
809 VarDecl *Var,
810 bool Recursive) {
811 if (Var->isInvalidDecl())
812 return;
813
814 // Find the out-of-line definition of this static data member.
815 // FIXME: Do we have to look for specializations separately?
816 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
817 bool FoundOutOfLineDef = false;
818 assert(Def && "This data member was not instantiated from a template?");
819 assert(Def->isStaticDataMember() && "Not a static data member?");
820 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
821 RDEnd = Def->redecls_end();
822 RD != RDEnd; ++RD) {
823 if (RD->getLexicalDeclContext()->isFileContext()) {
824 Def = *RD;
825 FoundOutOfLineDef = true;
826 }
827 }
828
829 if (!FoundOutOfLineDef) {
830 // We did not find an out-of-line definition of this static data member,
831 // so we won't perform any instantiation. Rather, we rely on the user to
832 // instantiate this definition (or provide a specialization for it) in
833 // another translation unit.
834 return;
835 }
836
837 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
838 if (Inst)
839 return;
840
841 // If we're performing recursive template instantiation, create our own
842 // queue of pending implicit instantiations that we will instantiate later,
843 // while we're still within our own instantiation context.
844 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
845 if (Recursive)
846 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
847
848 // Enter the scope of this instantiation. We don't use
849 // PushDeclContext because we don't have a scope.
850 DeclContext *PreviousContext = CurContext;
851 CurContext = Var->getDeclContext();
852
853#if 0
854 // Instantiate the initializer of this static data member.
855 OwningExprResult Init
856 = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
857 if (Init.isInvalid()) {
858 // If instantiation of the initializer failed, mark the declaration invalid
859 // and don't instantiate anything else that was triggered by this
860 // instantiation.
861 Var->setInvalidDecl();
862
863 // Restore the set of pending implicit instantiations.
864 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
865
866 return;
867 }
868
869 // Type-check the initializer.
870 if (Init.get())
871 AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
872 Def->hasCXXDirectInitializer());
873 else
874 ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
875#else
876 Var = cast_or_null<VarDecl>(InstantiateDecl(Def, Var->getDeclContext(),
877 getTemplateInstantiationArgs(Var)));
878#endif
879
880 CurContext = PreviousContext;
881
882 if (Var) {
883 DeclGroupRef DG(Var);
884 Consumer.HandleTopLevelDecl(DG);
885 }
886
887 if (Recursive) {
888 // Instantiate any pending implicit instantiations found during the
889 // instantiation of this template.
890 PerformPendingImplicitInstantiations();
891
892 // Restore the set of pending implicit instantiations.
893 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
894 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000895}
Douglas Gregor815215d2009-05-27 05:35:12 +0000896
897static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
898 if (D->getKind() != Other->getKind())
899 return false;
900
901 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000902 return Record->getInstantiatedFromMemberClass()->getCanonicalDecl()
903 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000904
905 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000906 return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl()
907 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000908
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000909 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000910 return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl()
911 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000912
Douglas Gregor7caa6822009-07-24 20:34:43 +0000913 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
914 if (Var->isStaticDataMember())
915 return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl()
916 == D->getCanonicalDecl();
917
Douglas Gregor815215d2009-05-27 05:35:12 +0000918 // FIXME: How can we find instantiations of anonymous unions?
919
920 return D->getDeclName() && isa<NamedDecl>(Other) &&
921 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
922}
923
924template<typename ForwardIterator>
925static NamedDecl *findInstantiationOf(ASTContext &Ctx,
926 NamedDecl *D,
927 ForwardIterator first,
928 ForwardIterator last) {
929 for (; first != last; ++first)
930 if (isInstantiationOf(Ctx, D, *first))
931 return cast<NamedDecl>(*first);
932
933 return 0;
934}
935
Douglas Gregored961e72009-05-27 17:54:46 +0000936/// \brief Find the instantiation of the given declaration within the
937/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +0000938///
939/// This routine is intended to be used when \p D is a declaration
940/// referenced from within a template, that needs to mapped into the
941/// corresponding declaration within an instantiation. For example,
942/// given:
943///
944/// \code
945/// template<typename T>
946/// struct X {
947/// enum Kind {
948/// KnownValue = sizeof(T)
949/// };
950///
951/// bool getKind() const { return KnownValue; }
952/// };
953///
954/// template struct X<int>;
955/// \endcode
956///
957/// In the instantiation of X<int>::getKind(), we need to map the
958/// EnumConstantDecl for KnownValue (which refers to
959/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +0000960/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
961/// this mapping from within the instantiation of X<int>.
962NamedDecl * Sema::InstantiateCurrentDeclRef(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +0000963 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +0000964 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
965 // D is a local of some kind. Look into the map of local
966 // declarations to their instantiations.
967 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
968 }
Douglas Gregor815215d2009-05-27 05:35:12 +0000969
Douglas Gregor2bba76b2009-05-27 17:07:49 +0000970 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
Douglas Gregored961e72009-05-27 17:54:46 +0000971 ParentDecl = InstantiateCurrentDeclRef(ParentDecl);
Douglas Gregor815215d2009-05-27 05:35:12 +0000972 if (!ParentDecl)
973 return 0;
974
975 ParentDC = cast<DeclContext>(ParentDecl);
976 }
977
Douglas Gregor815215d2009-05-27 05:35:12 +0000978 if (ParentDC != D->getDeclContext()) {
979 // We performed some kind of instantiation in the parent context,
980 // so now we need to look into the instantiated parent context to
981 // find the instantiation of the declaration D.
982 NamedDecl *Result = 0;
983 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000984 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +0000985 Result = findInstantiationOf(Context, D, Found.first, Found.second);
986 } else {
987 // Since we don't have a name for the entity we're looking for,
988 // our only option is to walk through all of the declarations to
989 // find that name. This will occur in a few cases:
990 //
991 // - anonymous struct/union within a template
992 // - unnamed class/struct/union/enum within a template
993 //
994 // FIXME: Find a better way to find these instantiations!
995 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000996 ParentDC->decls_begin(),
997 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +0000998 }
999 assert(Result && "Unable to find instantiation of declaration!");
1000 D = Result;
1001 }
1002
Douglas Gregor815215d2009-05-27 05:35:12 +00001003 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
Douglas Gregored961e72009-05-27 17:54:46 +00001004 if (ClassTemplateDecl *ClassTemplate
1005 = Record->getDescribedClassTemplate()) {
1006 // When the declaration D was parsed, it referred to the current
1007 // instantiation. Therefore, look through the current context,
1008 // which contains actual instantiations, to find the
1009 // instantiation of the "current instantiation" that D refers
1010 // to. Alternatively, we could just instantiate the
1011 // injected-class-name with the current template arguments, but
1012 // such an instantiation is far more expensive.
1013 for (DeclContext *DC = CurContext; !DC->isFileContext();
1014 DC = DC->getParent()) {
1015 if (ClassTemplateSpecializationDecl *Spec
1016 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001017 if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1018 == ClassTemplate->getCanonicalDecl())
Douglas Gregored961e72009-05-27 17:54:46 +00001019 return Spec;
1020 }
1021
1022 assert(false &&
1023 "Unable to find declaration for the current instantiation");
Douglas Gregor815215d2009-05-27 05:35:12 +00001024 }
1025
1026 return D;
1027}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001028
1029/// \brief Performs template instantiation for all implicit template
1030/// instantiations we have seen until this point.
1031void Sema::PerformPendingImplicitInstantiations() {
1032 while (!PendingImplicitInstantiations.empty()) {
1033 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001034 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001035
Douglas Gregor7caa6822009-07-24 20:34:43 +00001036 // Instantiate function definitions
1037 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001038 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001039 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001040 continue;
1041 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001042
Douglas Gregor7caa6822009-07-24 20:34:43 +00001043 // Instantiate static data member definitions.
1044 VarDecl *Var = cast<VarDecl>(Inst.first);
1045 assert(Var->isStaticDataMember() && "Not a static data member?");
1046 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001047 }
1048}