blob: 86505ee8b0d6fcb514f792f82aa744744025dec9 [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
Douglas Gregor43d9d922009-08-08 01:41:12 +0000225 OwningExprResult Message(SemaRef, D->getMessage());
226 D->getMessage()->Retain();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000227 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000228 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
229 move(InstantiatedAssertExpr),
230 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000231 return StaticAssert;
232}
233
234Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
235 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
236 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000237 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000238 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000239 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000240 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000241 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000242 Enum->startDefinition();
243
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000244 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000245
246 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000247 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
248 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000249 EC != ECEnd; ++EC) {
250 // The specified value for the enumerator.
251 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000252 if (Expr *UninstValue = EC->getInitExpr()) {
253 // The enumerator's value expression is not potentially evaluated.
254 EnterExpressionEvaluationContext Unevaluated(SemaRef,
255 Action::Unevaluated);
256
Douglas Gregor7e063902009-05-11 23:53:27 +0000257 Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000258 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000259
260 // Drop the initial value and continue.
261 bool isInvalid = false;
262 if (Value.isInvalid()) {
263 Value = SemaRef.Owned((Expr *)0);
264 isInvalid = true;
265 }
266
267 EnumConstantDecl *EnumConst
268 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
269 EC->getLocation(), EC->getIdentifier(),
270 move(Value));
271
272 if (isInvalid) {
273 if (EnumConst)
274 EnumConst->setInvalidDecl();
275 Enum->setInvalidDecl();
276 }
277
278 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000279 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000280 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000281 LastEnumConst = EnumConst;
282 }
283 }
284
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000285 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000286 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000287 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
288 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000289 &Enumerators[0], Enumerators.size(),
290 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000291
292 return Enum;
293}
294
Douglas Gregor6477b692009-03-25 15:04:13 +0000295Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
296 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
297 return 0;
298}
299
Douglas Gregord475b8d2009-03-25 21:17:03 +0000300Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
301 CXXRecordDecl *PrevDecl = 0;
302 if (D->isInjectedClassName())
303 PrevDecl = cast<CXXRecordDecl>(Owner);
304
305 CXXRecordDecl *Record
306 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000307 D->getLocation(), D->getIdentifier(),
308 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000309 Record->setImplicit(D->isImplicit());
310 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000311 if (!D->isInjectedClassName())
312 Record->setInstantiationOfMemberClass(D);
313
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000314 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000315 return Record;
316}
317
Douglas Gregore53060f2009-06-25 22:08:12 +0000318Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000319 // Check whether there is already a function template specialization for
320 // this declaration.
321 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
322 void *InsertPos = 0;
323 if (FunctionTemplate) {
324 llvm::FoldingSetNodeID ID;
325 FunctionTemplateSpecializationInfo::Profile(ID,
326 TemplateArgs.getFlatArgumentList(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000327 TemplateArgs.flat_size(),
328 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000329
330 FunctionTemplateSpecializationInfo *Info
331 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
332 InsertPos);
333
334 // If we already have a function template specialization, return it.
335 if (Info)
336 return Info->Function;
337 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000338
339 Sema::LocalInstantiationScope Scope(SemaRef);
340
341 llvm::SmallVector<ParmVarDecl *, 4> Params;
342 QualType T = InstantiateFunctionType(D, Params);
343 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000344 return 0;
Douglas Gregore53060f2009-06-25 22:08:12 +0000345
346 // Build the instantiated method declaration.
347 FunctionDecl *Function
348 = FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(),
349 D->getDeclName(), T, D->getStorageClass(),
350 D->isInline(), D->hasWrittenPrototype(),
351 D->getTypeSpecStartLoc());
352
353 // FIXME: friend functions
354
355 // Attach the parameters
356 for (unsigned P = 0; P < Params.size(); ++P)
357 Params[P]->setOwningFunction(Function);
358 Function->setParams(SemaRef.Context, Params.data(), Params.size());
359
360 if (InitFunctionInstantiation(Function, D))
361 Function->setInvalidDecl();
362
363 bool Redeclaration = false;
364 bool OverloadableAttrRequired = false;
365 NamedDecl *PrevDecl = 0;
366 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
367 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000368
Douglas Gregor127102b2009-06-29 20:59:39 +0000369 if (FunctionTemplate) {
370 // Record this function template specialization.
371 Function->setFunctionTemplateSpecialization(SemaRef.Context,
372 FunctionTemplate,
373 &TemplateArgs,
374 InsertPos);
375 }
376
Douglas Gregore53060f2009-06-25 22:08:12 +0000377 return Function;
378}
379
380Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
381 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000382 Sema::LocalInstantiationScope Scope(SemaRef);
383
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000384 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000385 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000386 if (T.isNull())
387 return 0;
388
389 // Build the instantiated method declaration.
390 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
391 CXXMethodDecl *Method
392 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
393 D->getDeclName(), T, D->isStatic(),
394 D->isInline());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000395 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000396
Douglas Gregor7caa6822009-07-24 20:34:43 +0000397 // If we are instantiating a member function defined
398 // out-of-line, the instantiation will have the same lexical
399 // context (which will be a namespace scope) as the template.
400 if (D->isOutOfLine())
401 Method->setLexicalDeclContext(D->getLexicalDeclContext());
402
Douglas Gregor5545e162009-03-24 00:38:23 +0000403 // Attach the parameters
404 for (unsigned P = 0; P < Params.size(); ++P)
405 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000406 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000407
408 if (InitMethodInstantiation(Method, D))
409 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000410
411 NamedDecl *PrevDecl
412 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
413 Sema::LookupOrdinaryName, true);
414 // In C++, the previous declaration we find might be a tag type
415 // (class or enum). In this case, the new declaration will hide the
416 // tag type. Note that this does does not apply if we're declaring a
417 // typedef (C++ [dcl.typedef]p4).
418 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
419 PrevDecl = 0;
420 bool Redeclaration = false;
421 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000422 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
423 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000424
425 if (!Method->isInvalidDecl() || !PrevDecl)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000426 Owner->addDecl(Method);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000427 return Method;
428}
429
Douglas Gregor615c5d42009-03-24 16:43:20 +0000430Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000431 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000432 Sema::LocalInstantiationScope Scope(SemaRef);
433
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000434 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor615c5d42009-03-24 16:43:20 +0000435 QualType T = InstantiateFunctionType(D, Params);
436 if (T.isNull())
437 return 0;
438
439 // Build the instantiated method declaration.
440 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
441 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
442 DeclarationName Name
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000443 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
444 SemaRef.Context.getCanonicalType(ClassTy));
Douglas Gregor615c5d42009-03-24 16:43:20 +0000445 CXXConstructorDecl *Constructor
446 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
447 Name, T, D->isExplicit(), D->isInline(),
448 false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000449 Constructor->setInstantiationOfMemberFunction(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000450
451 // Attach the parameters
452 for (unsigned P = 0; P < Params.size(); ++P)
453 Params[P]->setOwningFunction(Constructor);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000454 Constructor->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor615c5d42009-03-24 16:43:20 +0000455
456 if (InitMethodInstantiation(Constructor, D))
457 Constructor->setInvalidDecl();
458
459 NamedDecl *PrevDecl
460 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
461
462 // In C++, the previous declaration we find might be a tag type
463 // (class or enum). In this case, the new declaration will hide the
464 // tag type. Note that this does does not apply if we're declaring a
465 // typedef (C++ [dcl.typedef]p4).
466 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
467 PrevDecl = 0;
468 bool Redeclaration = false;
469 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000470 SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
471 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000472
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000473 Record->addedConstructor(SemaRef.Context, Constructor);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000474 Owner->addDecl(Constructor);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000475 return Constructor;
476}
477
Douglas Gregor03b2b072009-03-24 00:15:49 +0000478Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000479 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000480 Sema::LocalInstantiationScope Scope(SemaRef);
481
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000482 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000483 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000484 if (T.isNull())
485 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +0000486 assert(Params.size() == 0 && "Destructor with parameters?");
487
Douglas Gregor03b2b072009-03-24 00:15:49 +0000488 // Build the instantiated destructor declaration.
489 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregor50d62d12009-08-05 05:36:45 +0000490 CanQualType ClassTy =
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000491 SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record));
Douglas Gregor03b2b072009-03-24 00:15:49 +0000492 CXXDestructorDecl *Destructor
493 = CXXDestructorDecl::Create(SemaRef.Context, Record,
494 D->getLocation(),
495 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
496 T, D->isInline(), false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000497 Destructor->setInstantiationOfMemberFunction(D);
Douglas Gregor5545e162009-03-24 00:38:23 +0000498 if (InitMethodInstantiation(Destructor, D))
499 Destructor->setInvalidDecl();
Douglas Gregor03b2b072009-03-24 00:15:49 +0000500
501 bool Redeclaration = false;
502 bool OverloadableAttrRequired = false;
503 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000504 SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
505 /*FIXME:*/OverloadableAttrRequired);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000506 Owner->addDecl(Destructor);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000507 return Destructor;
508}
509
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000510Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000511 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000512 Sema::LocalInstantiationScope Scope(SemaRef);
513
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000514 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000515 QualType T = InstantiateFunctionType(D, Params);
516 if (T.isNull())
517 return 0;
518 assert(Params.size() == 0 && "Destructor with parameters?");
519
520 // Build the instantiated conversion declaration.
521 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
522 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
Douglas Gregor50d62d12009-08-05 05:36:45 +0000523 CanQualType ConvTy
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000524 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
525 CXXConversionDecl *Conversion
526 = CXXConversionDecl::Create(SemaRef.Context, Record,
527 D->getLocation(),
528 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
529 T, D->isInline(), D->isExplicit());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000530 Conversion->setInstantiationOfMemberFunction(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000531 if (InitMethodInstantiation(Conversion, D))
532 Conversion->setInvalidDecl();
533
534 bool Redeclaration = false;
535 bool OverloadableAttrRequired = false;
536 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000537 SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
538 /*FIXME:*/OverloadableAttrRequired);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000539 Owner->addDecl(Conversion);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000540 return Conversion;
541}
542
Douglas Gregor6477b692009-03-25 15:04:13 +0000543ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000544 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000545 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000546 if (OrigT.isNull())
547 return 0;
548
549 QualType T = SemaRef.adjustParameterType(OrigT);
550
551 if (D->getDefaultArg()) {
552 // FIXME: Leave a marker for "uninstantiated" default
553 // arguments. They only get instantiated on demand at the call
554 // site.
555 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
556 "sorry, dropping default argument during template instantiation");
557 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
558 << D->getDefaultArg()->getSourceRange();
559 }
560
561 // Allocate the parameter
562 ParmVarDecl *Param = 0;
563 if (T == OrigT)
564 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
565 D->getIdentifier(), T, D->getStorageClass(),
566 0);
567 else
568 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
569 D->getLocation(), D->getIdentifier(),
570 T, OrigT, D->getStorageClass(), 0);
571
572 // Note: we don't try to instantiate function parameters until after
573 // we've instantiated the function's type. Therefore, we don't have
574 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000575 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000576 return Param;
577}
578
579Decl *
580TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
581 // Since parameter types can decay either before or after
582 // instantiation, we simply treat OriginalParmVarDecls as
583 // ParmVarDecls the same way, and create one or the other depending
584 // on what happens after template instantiation.
585 return VisitParmVarDecl(D);
586}
587
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000588Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
Douglas Gregor7e063902009-05-11 23:53:27 +0000589 const TemplateArgumentList &TemplateArgs) {
590 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000591 return Instantiator.Visit(D);
592}
593
Douglas Gregor5545e162009-03-24 00:38:23 +0000594/// \brief Instantiates the type of the given function, including
595/// instantiating all of the function parameters.
596///
597/// \param D The function that we will be instantiated
598///
599/// \param Params the instantiated parameter declarations
600
601/// \returns the instantiated function's type if successfull, a NULL
602/// type if there was an error.
603QualType
604TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
605 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
606 bool InvalidDecl = false;
607
608 // Instantiate the function parameters
Douglas Gregor7e063902009-05-11 23:53:27 +0000609 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000610 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000611 for (FunctionDecl::param_iterator P = D->param_begin(),
612 PEnd = D->param_end();
613 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000614 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000615 if (PInst->getType()->isVoidType()) {
616 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
617 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000618 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
619 PInst->getType(),
620 diag::err_abstract_type_in_decl,
621 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000622 PInst->setInvalidDecl();
623
624 Params.push_back(PInst);
625 ParamTys.push_back(PInst->getType());
626
627 if (PInst->isInvalidDecl())
628 InvalidDecl = true;
629 } else
630 InvalidDecl = true;
631 }
632
633 // FIXME: Deallocate dead declarations.
634 if (InvalidDecl)
635 return QualType();
636
637 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
638 assert(Proto && "Missing prototype?");
639 QualType ResultType
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000640 = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs,
Douglas Gregor5545e162009-03-24 00:38:23 +0000641 D->getLocation(), D->getDeclName());
642 if (ResultType.isNull())
643 return QualType();
644
Jay Foadbeaaccd2009-05-21 09:52:38 +0000645 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000646 Proto->isVariadic(), Proto->getTypeQuals(),
647 D->getLocation(), D->getDeclName());
648}
649
Douglas Gregore53060f2009-06-25 22:08:12 +0000650/// \brief Initializes the common fields of an instantiation function
651/// declaration (New) from the corresponding fields of its template (Tmpl).
652///
653/// \returns true if there was an error
654bool
655TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
656 FunctionDecl *Tmpl) {
657 if (Tmpl->isDeleted())
658 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000659
660 // If we are performing substituting explicitly-specified template arguments
661 // or deduced template arguments into a function template and we reach this
662 // point, we are now past the point where SFINAE applies and have committed
663 // to keeping the new function template specialization. We therefore
664 // convert the active template instantiation for the function template
665 // into a template instantiation for this specific function template
666 // specialization, which is not a SFINAE context, so that we diagnose any
667 // further errors in the declaration itself.
668 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
669 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
670 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
671 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
672 if (FunctionTemplateDecl *FunTmpl
673 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
674 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
675 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000676 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000677 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
678 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
679 }
680 }
681
Douglas Gregore53060f2009-06-25 22:08:12 +0000682 return false;
683}
684
Douglas Gregor5545e162009-03-24 00:38:23 +0000685/// \brief Initializes common fields of an instantiated method
686/// declaration (New) from the corresponding fields of its template
687/// (Tmpl).
688///
689/// \returns true if there was an error
690bool
691TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
692 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000693 if (InitFunctionInstantiation(New, Tmpl))
694 return true;
695
Douglas Gregor5545e162009-03-24 00:38:23 +0000696 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
697 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000698 if (Tmpl->isVirtualAsWritten()) {
699 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000700 Record->setAggregate(false);
701 Record->setPOD(false);
702 Record->setPolymorphic(true);
703 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000704 if (Tmpl->isPure()) {
705 New->setPure();
706 Record->setAbstract(true);
707 }
708
709 // FIXME: attributes
710 // FIXME: New needs a pointer to Tmpl
711 return false;
712}
Douglas Gregora58861f2009-05-13 20:28:22 +0000713
714/// \brief Instantiate the definition of the given function from its
715/// template.
716///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000717/// \param PointOfInstantiation the point at which the instantiation was
718/// required. Note that this is not precisely a "point of instantiation"
719/// for the function, but it's close.
720///
Douglas Gregora58861f2009-05-13 20:28:22 +0000721/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000722/// function template specialization or member function of a class template
723/// specialization.
724///
725/// \param Recursive if true, recursively instantiates any functions that
726/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000727void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000728 FunctionDecl *Function,
729 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000730 if (Function->isInvalidDecl())
731 return;
732
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000733 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000734
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000735 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000736 const FunctionDecl *PatternDecl = 0;
737 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
738 PatternDecl = Primary->getTemplatedDecl();
739 else
740 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000741 Stmt *Pattern = 0;
742 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000743 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000744
745 if (!Pattern)
746 return;
747
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000748 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
749 if (Inst)
750 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000751
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000752 // If we're performing recursive template instantiation, create our own
753 // queue of pending implicit instantiations that we will instantiate later,
754 // while we're still within our own instantiation context.
755 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
756 if (Recursive)
757 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
758
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000759 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
760
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000761 // Introduce a new scope where local variable instantiations will be
762 // recorded.
763 LocalInstantiationScope Scope(*this);
764
765 // Introduce the instantiated function parameters into the local
766 // instantiation scope.
767 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
768 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
769 Function->getParamDecl(I));
770
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000771 // Enter the scope of this instantiation. We don't use
772 // PushDeclContext because we don't have a scope.
773 DeclContext *PreviousContext = CurContext;
774 CurContext = Function;
775
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000776 // Instantiate the function body.
777 OwningStmtResult Body
778 = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function));
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000779
780 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
781 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000782
783 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000784
785 DeclGroupRef DG(Function);
786 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000787
788 if (Recursive) {
789 // Instantiate any pending implicit instantiations found during the
790 // instantiation of this template.
791 PerformPendingImplicitInstantiations();
792
793 // Restore the set of pending implicit instantiations.
794 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
795 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000796}
797
798/// \brief Instantiate the definition of the given variable from its
799/// template.
800///
Douglas Gregor7caa6822009-07-24 20:34:43 +0000801/// \param PointOfInstantiation the point at which the instantiation was
802/// required. Note that this is not precisely a "point of instantiation"
803/// for the function, but it's close.
804///
805/// \param Var the already-instantiated declaration of a static member
806/// variable of a class template specialization.
807///
808/// \param Recursive if true, recursively instantiates any functions that
809/// are required by this instantiation.
810void Sema::InstantiateStaticDataMemberDefinition(
811 SourceLocation PointOfInstantiation,
812 VarDecl *Var,
813 bool Recursive) {
814 if (Var->isInvalidDecl())
815 return;
816
817 // Find the out-of-line definition of this static data member.
818 // FIXME: Do we have to look for specializations separately?
819 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
820 bool FoundOutOfLineDef = false;
821 assert(Def && "This data member was not instantiated from a template?");
822 assert(Def->isStaticDataMember() && "Not a static data member?");
823 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
824 RDEnd = Def->redecls_end();
825 RD != RDEnd; ++RD) {
826 if (RD->getLexicalDeclContext()->isFileContext()) {
827 Def = *RD;
828 FoundOutOfLineDef = true;
829 }
830 }
831
832 if (!FoundOutOfLineDef) {
833 // We did not find an out-of-line definition of this static data member,
834 // so we won't perform any instantiation. Rather, we rely on the user to
835 // instantiate this definition (or provide a specialization for it) in
836 // another translation unit.
837 return;
838 }
839
840 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
841 if (Inst)
842 return;
843
844 // If we're performing recursive template instantiation, create our own
845 // queue of pending implicit instantiations that we will instantiate later,
846 // while we're still within our own instantiation context.
847 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
848 if (Recursive)
849 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
850
851 // Enter the scope of this instantiation. We don't use
852 // PushDeclContext because we don't have a scope.
853 DeclContext *PreviousContext = CurContext;
854 CurContext = Var->getDeclContext();
855
856#if 0
857 // Instantiate the initializer of this static data member.
858 OwningExprResult Init
859 = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
860 if (Init.isInvalid()) {
861 // If instantiation of the initializer failed, mark the declaration invalid
862 // and don't instantiate anything else that was triggered by this
863 // instantiation.
864 Var->setInvalidDecl();
865
866 // Restore the set of pending implicit instantiations.
867 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
868
869 return;
870 }
871
872 // Type-check the initializer.
873 if (Init.get())
874 AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
875 Def->hasCXXDirectInitializer());
876 else
877 ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
878#else
879 Var = cast_or_null<VarDecl>(InstantiateDecl(Def, Var->getDeclContext(),
880 getTemplateInstantiationArgs(Var)));
881#endif
882
883 CurContext = PreviousContext;
884
885 if (Var) {
886 DeclGroupRef DG(Var);
887 Consumer.HandleTopLevelDecl(DG);
888 }
889
890 if (Recursive) {
891 // Instantiate any pending implicit instantiations found during the
892 // instantiation of this template.
893 PerformPendingImplicitInstantiations();
894
895 // Restore the set of pending implicit instantiations.
896 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
897 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000898}
Douglas Gregor815215d2009-05-27 05:35:12 +0000899
900static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
901 if (D->getKind() != Other->getKind())
902 return false;
903
904 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000905 return Record->getInstantiatedFromMemberClass()->getCanonicalDecl()
906 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000907
908 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000909 return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl()
910 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000911
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000912 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000913 return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl()
914 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000915
Douglas Gregor7caa6822009-07-24 20:34:43 +0000916 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
917 if (Var->isStaticDataMember())
918 return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl()
919 == D->getCanonicalDecl();
920
Douglas Gregor815215d2009-05-27 05:35:12 +0000921 // FIXME: How can we find instantiations of anonymous unions?
922
923 return D->getDeclName() && isa<NamedDecl>(Other) &&
924 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
925}
926
927template<typename ForwardIterator>
928static NamedDecl *findInstantiationOf(ASTContext &Ctx,
929 NamedDecl *D,
930 ForwardIterator first,
931 ForwardIterator last) {
932 for (; first != last; ++first)
933 if (isInstantiationOf(Ctx, D, *first))
934 return cast<NamedDecl>(*first);
935
936 return 0;
937}
938
Douglas Gregored961e72009-05-27 17:54:46 +0000939/// \brief Find the instantiation of the given declaration within the
940/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +0000941///
942/// This routine is intended to be used when \p D is a declaration
943/// referenced from within a template, that needs to mapped into the
944/// corresponding declaration within an instantiation. For example,
945/// given:
946///
947/// \code
948/// template<typename T>
949/// struct X {
950/// enum Kind {
951/// KnownValue = sizeof(T)
952/// };
953///
954/// bool getKind() const { return KnownValue; }
955/// };
956///
957/// template struct X<int>;
958/// \endcode
959///
960/// In the instantiation of X<int>::getKind(), we need to map the
961/// EnumConstantDecl for KnownValue (which refers to
962/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +0000963/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
964/// this mapping from within the instantiation of X<int>.
965NamedDecl * Sema::InstantiateCurrentDeclRef(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +0000966 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +0000967 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
968 // D is a local of some kind. Look into the map of local
969 // declarations to their instantiations.
970 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
971 }
Douglas Gregor815215d2009-05-27 05:35:12 +0000972
Douglas Gregor2bba76b2009-05-27 17:07:49 +0000973 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
Douglas Gregored961e72009-05-27 17:54:46 +0000974 ParentDecl = InstantiateCurrentDeclRef(ParentDecl);
Douglas Gregor815215d2009-05-27 05:35:12 +0000975 if (!ParentDecl)
976 return 0;
977
978 ParentDC = cast<DeclContext>(ParentDecl);
979 }
980
Douglas Gregor815215d2009-05-27 05:35:12 +0000981 if (ParentDC != D->getDeclContext()) {
982 // We performed some kind of instantiation in the parent context,
983 // so now we need to look into the instantiated parent context to
984 // find the instantiation of the declaration D.
985 NamedDecl *Result = 0;
986 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000987 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +0000988 Result = findInstantiationOf(Context, D, Found.first, Found.second);
989 } else {
990 // Since we don't have a name for the entity we're looking for,
991 // our only option is to walk through all of the declarations to
992 // find that name. This will occur in a few cases:
993 //
994 // - anonymous struct/union within a template
995 // - unnamed class/struct/union/enum within a template
996 //
997 // FIXME: Find a better way to find these instantiations!
998 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000999 ParentDC->decls_begin(),
1000 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001001 }
1002 assert(Result && "Unable to find instantiation of declaration!");
1003 D = Result;
1004 }
1005
Douglas Gregor815215d2009-05-27 05:35:12 +00001006 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
Douglas Gregored961e72009-05-27 17:54:46 +00001007 if (ClassTemplateDecl *ClassTemplate
1008 = Record->getDescribedClassTemplate()) {
1009 // When the declaration D was parsed, it referred to the current
1010 // instantiation. Therefore, look through the current context,
1011 // which contains actual instantiations, to find the
1012 // instantiation of the "current instantiation" that D refers
1013 // to. Alternatively, we could just instantiate the
1014 // injected-class-name with the current template arguments, but
1015 // such an instantiation is far more expensive.
1016 for (DeclContext *DC = CurContext; !DC->isFileContext();
1017 DC = DC->getParent()) {
1018 if (ClassTemplateSpecializationDecl *Spec
1019 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001020 if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1021 == ClassTemplate->getCanonicalDecl())
Douglas Gregored961e72009-05-27 17:54:46 +00001022 return Spec;
1023 }
1024
1025 assert(false &&
1026 "Unable to find declaration for the current instantiation");
Douglas Gregor815215d2009-05-27 05:35:12 +00001027 }
1028
1029 return D;
1030}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001031
1032/// \brief Performs template instantiation for all implicit template
1033/// instantiations we have seen until this point.
1034void Sema::PerformPendingImplicitInstantiations() {
1035 while (!PendingImplicitInstantiations.empty()) {
1036 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001037 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001038
Douglas Gregor7caa6822009-07-24 20:34:43 +00001039 // Instantiate function definitions
1040 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001041 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001042 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001043 continue;
1044 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001045
Douglas Gregor7caa6822009-07-24 20:34:43 +00001046 // Instantiate static data member definitions.
1047 VarDecl *Var = cast<VarDecl>(Inst.first);
1048 assert(Var->isStaticDataMember() && "Not a static data member?");
1049 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001050 }
1051}