blob: 321292319452cbfbf20370f5317583909518497f [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);
John McCallfd810b12009-08-14 02:03:10 +000047 Decl *VisitFriendClassDecl(FriendClassDecl *D);
Douglas Gregore53060f2009-06-25 22:08:12 +000048 Decl *VisitFunctionDecl(FunctionDecl *D);
Douglas Gregord475b8d2009-03-25 21:17:03 +000049 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000050 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
Douglas Gregor615c5d42009-03-24 16:43:20 +000051 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000052 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000053 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000054 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000055 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
Douglas Gregor5545e162009-03-24 00:38:23 +000056
Douglas Gregor8dbc2692009-03-17 21:15:40 +000057 // Base case. FIXME: Remove once we can instantiate everything.
58 Decl *VisitDecl(Decl *) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000059 assert(false && "Template instantiation of unknown declaration kind!");
Douglas Gregor8dbc2692009-03-17 21:15:40 +000060 return 0;
61 }
Douglas Gregor5545e162009-03-24 00:38:23 +000062
John McCallfd810b12009-08-14 02:03:10 +000063 const LangOptions &getLangOptions() {
64 return SemaRef.getLangOptions();
65 }
66
Douglas Gregor5545e162009-03-24 00:38:23 +000067 // Helper functions for instantiating methods.
68 QualType InstantiateFunctionType(FunctionDecl *D,
69 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000070 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000071 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000072 };
73}
74
Douglas Gregor4f722be2009-03-25 15:45:12 +000075Decl *
76TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
77 assert(false && "Translation units cannot be instantiated");
78 return D;
79}
80
81Decl *
82TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
83 assert(false && "Namespaces cannot be instantiated");
84 return D;
85}
86
Douglas Gregor8dbc2692009-03-17 21:15:40 +000087Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
88 bool Invalid = false;
89 QualType T = D->getUnderlyingType();
90 if (T->isDependentType()) {
Douglas Gregor1eee0e72009-05-14 21:06:31 +000091 T = SemaRef.InstantiateType(T, TemplateArgs,
92 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +000093 if (T.isNull()) {
94 Invalid = true;
95 T = SemaRef.Context.IntTy;
96 }
97 }
98
99 // Create the new typedef
100 TypedefDecl *Typedef
101 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
102 D->getIdentifier(), T);
103 if (Invalid)
104 Typedef->setInvalidDecl();
105
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000106 Owner->addDecl(Typedef);
Douglas Gregorbc221632009-05-28 16:34:51 +0000107
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000108 return Typedef;
109}
110
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000111Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
112 // Instantiate the type of the declaration
113 QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs,
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000114 D->getTypeSpecStartLoc(),
115 D->getDeclName());
116 if (T.isNull())
117 return 0;
118
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000119 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000120 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
121 D->getLocation(), D->getIdentifier(),
122 T, D->getStorageClass(),
123 D->getTypeSpecStartLoc());
124 Var->setThreadSpecified(D->isThreadSpecified());
125 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
126 Var->setDeclaredInCondition(D->isDeclaredInCondition());
127
Douglas Gregor7caa6822009-07-24 20:34:43 +0000128 // If we are instantiating a static data member defined
129 // out-of-line, the instantiation will have the same lexical
130 // context (which will be a namespace scope) as the template.
131 if (D->isOutOfLine())
132 Var->setLexicalDeclContext(D->getLexicalDeclContext());
133
Mike Stump390b4cc2009-05-16 07:39:55 +0000134 // FIXME: In theory, we could have a previous declaration for variables that
135 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000136 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000137 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000138
139 if (D->isOutOfLine()) {
140 D->getLexicalDeclContext()->addDecl(Var);
141 Owner->makeDeclVisibleInContext(Var);
142 } else {
143 Owner->addDecl(Var);
144 }
145
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000146 if (D->getInit()) {
147 OwningExprResult Init
Douglas Gregor7e063902009-05-11 23:53:27 +0000148 = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000149 if (Init.isInvalid())
150 Var->setInvalidDecl();
151 else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000152 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000153 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000154 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
155 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000156
Douglas Gregor7caa6822009-07-24 20:34:43 +0000157 // Link instantiations of static data members back to the template from
158 // which they were instantiated.
159 if (Var->isStaticDataMember())
160 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
161
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000162 return Var;
163}
164
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000165Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
166 bool Invalid = false;
167 QualType T = D->getType();
168 if (T->isDependentType()) {
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000169 T = SemaRef.InstantiateType(T, TemplateArgs,
170 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000171 if (!T.isNull() && T->isFunctionType()) {
172 // C++ [temp.arg.type]p3:
173 // If a declaration acquires a function type through a type
174 // dependent on a template-parameter and this causes a
175 // declaration that does not use the syntactic form of a
176 // function declarator to have function type, the program is
177 // ill-formed.
178 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
179 << T;
180 T = QualType();
181 Invalid = true;
182 }
183 }
184
185 Expr *BitWidth = D->getBitWidth();
186 if (Invalid)
187 BitWidth = 0;
188 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000189 // The bit-width expression is not potentially evaluated.
190 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
191
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000192 OwningExprResult InstantiatedBitWidth
Douglas Gregor7e063902009-05-11 23:53:27 +0000193 = SemaRef.InstantiateExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000194 if (InstantiatedBitWidth.isInvalid()) {
195 Invalid = true;
196 BitWidth = 0;
197 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000198 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000199 }
200
201 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
202 cast<RecordDecl>(Owner),
203 D->getLocation(),
204 D->isMutable(),
205 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000206 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000207 D->getAccess(),
208 0);
209 if (Field) {
210 if (Invalid)
211 Field->setInvalidDecl();
212
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000213 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000214 }
215
216 return Field;
217}
218
John McCallfd810b12009-08-14 02:03:10 +0000219Decl *TemplateDeclInstantiator::VisitFriendClassDecl(FriendClassDecl *D) {
220 QualType T = D->getFriendType();
221 if (T->isDependentType()) {
222 T = SemaRef.InstantiateType(T, TemplateArgs, D->getLocation(),
223 DeclarationName());
224 assert(T.isNull() || getLangOptions().CPlusPlus0x || T->isRecordType());
225 }
226
227 // FIXME: the target context might be dependent.
228 DeclContext *DC = D->getDeclContext();
229 assert(DC->isFileContext());
230
231 FriendClassDecl *NewD =
232 FriendClassDecl::Create(SemaRef.Context, DC, D->getLocation(), T,
233 D->getFriendLoc());
234 Owner->addDecl(NewD);
235 return NewD;
236}
237
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000238Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
239 Expr *AssertExpr = D->getAssertExpr();
240
Douglas Gregorac7610d2009-06-22 20:57:11 +0000241 // The expression in a static assertion is not potentially evaluated.
242 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
243
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000244 OwningExprResult InstantiatedAssertExpr
Douglas Gregor7e063902009-05-11 23:53:27 +0000245 = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000246 if (InstantiatedAssertExpr.isInvalid())
247 return 0;
248
Douglas Gregor43d9d922009-08-08 01:41:12 +0000249 OwningExprResult Message(SemaRef, D->getMessage());
250 D->getMessage()->Retain();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000251 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000252 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
253 move(InstantiatedAssertExpr),
254 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000255 return StaticAssert;
256}
257
258Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
259 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
260 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000261 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000262 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000263 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000264 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000265 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000266 Enum->startDefinition();
267
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000268 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000269
270 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000271 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
272 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000273 EC != ECEnd; ++EC) {
274 // The specified value for the enumerator.
275 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000276 if (Expr *UninstValue = EC->getInitExpr()) {
277 // The enumerator's value expression is not potentially evaluated.
278 EnterExpressionEvaluationContext Unevaluated(SemaRef,
279 Action::Unevaluated);
280
Douglas Gregor7e063902009-05-11 23:53:27 +0000281 Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000282 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000283
284 // Drop the initial value and continue.
285 bool isInvalid = false;
286 if (Value.isInvalid()) {
287 Value = SemaRef.Owned((Expr *)0);
288 isInvalid = true;
289 }
290
291 EnumConstantDecl *EnumConst
292 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
293 EC->getLocation(), EC->getIdentifier(),
294 move(Value));
295
296 if (isInvalid) {
297 if (EnumConst)
298 EnumConst->setInvalidDecl();
299 Enum->setInvalidDecl();
300 }
301
302 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000303 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000304 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000305 LastEnumConst = EnumConst;
306 }
307 }
308
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000309 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000310 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000311 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
312 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000313 &Enumerators[0], Enumerators.size(),
314 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000315
316 return Enum;
317}
318
Douglas Gregor6477b692009-03-25 15:04:13 +0000319Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
320 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
321 return 0;
322}
323
Douglas Gregord475b8d2009-03-25 21:17:03 +0000324Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
325 CXXRecordDecl *PrevDecl = 0;
326 if (D->isInjectedClassName())
327 PrevDecl = cast<CXXRecordDecl>(Owner);
328
329 CXXRecordDecl *Record
330 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000331 D->getLocation(), D->getIdentifier(),
332 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000333 Record->setImplicit(D->isImplicit());
334 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000335 if (!D->isInjectedClassName())
336 Record->setInstantiationOfMemberClass(D);
337
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000338 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000339 return Record;
340}
341
Douglas Gregore53060f2009-06-25 22:08:12 +0000342Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000343 // Check whether there is already a function template specialization for
344 // this declaration.
345 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
346 void *InsertPos = 0;
347 if (FunctionTemplate) {
348 llvm::FoldingSetNodeID ID;
349 FunctionTemplateSpecializationInfo::Profile(ID,
350 TemplateArgs.getFlatArgumentList(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000351 TemplateArgs.flat_size(),
352 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000353
354 FunctionTemplateSpecializationInfo *Info
355 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
356 InsertPos);
357
358 // If we already have a function template specialization, return it.
359 if (Info)
360 return Info->Function;
361 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000362
363 Sema::LocalInstantiationScope Scope(SemaRef);
364
365 llvm::SmallVector<ParmVarDecl *, 4> Params;
366 QualType T = InstantiateFunctionType(D, Params);
367 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000368 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000369
Douglas Gregore53060f2009-06-25 22:08:12 +0000370 // Build the instantiated method declaration.
John McCallfd810b12009-08-14 02:03:10 +0000371 FunctionDecl *Function;
372 if (FriendFunctionDecl* FFD = dyn_cast<FriendFunctionDecl>(D)) {
373 // The new decl's semantic context. FIXME: this might need
374 // to be instantiated.
375 DeclContext *DC = D->getDeclContext();
376
377 // This assert is bogus and exists only to catch cases we don't
378 // handle yet.
379 assert(!DC->isDependentContext());
380
381 Function =
382 FriendFunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
383 D->getDeclName(), T, D->isInline(),
384 FFD->getFriendLoc());
385 Function->setLexicalDeclContext(Owner);
386 } else {
387 Function =
388 FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregore53060f2009-06-25 22:08:12 +0000389 D->getDeclName(), T, D->getStorageClass(),
390 D->isInline(), D->hasWrittenPrototype(),
391 D->getTypeSpecStartLoc());
John McCallfd810b12009-08-14 02:03:10 +0000392 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000393
394 // Attach the parameters
395 for (unsigned P = 0; P < Params.size(); ++P)
396 Params[P]->setOwningFunction(Function);
397 Function->setParams(SemaRef.Context, Params.data(), Params.size());
398
399 if (InitFunctionInstantiation(Function, D))
400 Function->setInvalidDecl();
401
402 bool Redeclaration = false;
403 bool OverloadableAttrRequired = false;
404 NamedDecl *PrevDecl = 0;
405 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
406 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000407
Douglas Gregor127102b2009-06-29 20:59:39 +0000408 if (FunctionTemplate) {
409 // Record this function template specialization.
410 Function->setFunctionTemplateSpecialization(SemaRef.Context,
411 FunctionTemplate,
412 &TemplateArgs,
413 InsertPos);
John McCallfd810b12009-08-14 02:03:10 +0000414 }
415
416 // If this was a friend function decl, it's a member which
417 // needs to be added.
418 if (isa<FriendFunctionDecl>(Function)) {
419 // If the new context is still dependent, this declaration
420 // needs to remain hidden.
421 if (Owner->isDependentContext())
422 Owner->addHiddenDecl(Function);
423 else
424 Owner->addDecl(Function);
425 }
Douglas Gregor127102b2009-06-29 20:59:39 +0000426
Douglas Gregore53060f2009-06-25 22:08:12 +0000427 return Function;
428}
429
430Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
431 // 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 Gregor5545e162009-03-24 00:38:23 +0000435 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000436 if (T.isNull())
437 return 0;
438
439 // Build the instantiated method declaration.
440 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
441 CXXMethodDecl *Method
442 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
443 D->getDeclName(), T, D->isStatic(),
444 D->isInline());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000445 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000446
Douglas Gregor7caa6822009-07-24 20:34:43 +0000447 // If we are instantiating a member function defined
448 // out-of-line, the instantiation will have the same lexical
449 // context (which will be a namespace scope) as the template.
450 if (D->isOutOfLine())
451 Method->setLexicalDeclContext(D->getLexicalDeclContext());
452
Douglas Gregor5545e162009-03-24 00:38:23 +0000453 // Attach the parameters
454 for (unsigned P = 0; P < Params.size(); ++P)
455 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000456 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000457
458 if (InitMethodInstantiation(Method, D))
459 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000460
461 NamedDecl *PrevDecl
462 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
463 Sema::LookupOrdinaryName, true);
464 // In C++, the previous declaration we find might be a tag type
465 // (class or enum). In this case, the new declaration will hide the
466 // tag type. Note that this does does not apply if we're declaring a
467 // typedef (C++ [dcl.typedef]p4).
468 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
469 PrevDecl = 0;
470 bool Redeclaration = false;
471 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000472 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
473 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000474
475 if (!Method->isInvalidDecl() || !PrevDecl)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000476 Owner->addDecl(Method);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000477 return Method;
478}
479
Douglas Gregor615c5d42009-03-24 16:43:20 +0000480Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000481 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000482 Sema::LocalInstantiationScope Scope(SemaRef);
483
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000484 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor615c5d42009-03-24 16:43:20 +0000485 QualType T = InstantiateFunctionType(D, Params);
486 if (T.isNull())
487 return 0;
488
489 // Build the instantiated method declaration.
490 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
491 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
492 DeclarationName Name
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000493 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
494 SemaRef.Context.getCanonicalType(ClassTy));
Douglas Gregor615c5d42009-03-24 16:43:20 +0000495 CXXConstructorDecl *Constructor
496 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
497 Name, T, D->isExplicit(), D->isInline(),
498 false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000499 Constructor->setInstantiationOfMemberFunction(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000500
501 // Attach the parameters
502 for (unsigned P = 0; P < Params.size(); ++P)
503 Params[P]->setOwningFunction(Constructor);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000504 Constructor->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor615c5d42009-03-24 16:43:20 +0000505
506 if (InitMethodInstantiation(Constructor, D))
507 Constructor->setInvalidDecl();
508
509 NamedDecl *PrevDecl
510 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
511
512 // In C++, the previous declaration we find might be a tag type
513 // (class or enum). In this case, the new declaration will hide the
514 // tag type. Note that this does does not apply if we're declaring a
515 // typedef (C++ [dcl.typedef]p4).
516 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
517 PrevDecl = 0;
518 bool Redeclaration = false;
519 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000520 SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
521 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000522
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000523 Record->addedConstructor(SemaRef.Context, Constructor);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000524 Owner->addDecl(Constructor);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000525 return Constructor;
526}
527
Douglas Gregor03b2b072009-03-24 00:15:49 +0000528Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000529 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000530 Sema::LocalInstantiationScope Scope(SemaRef);
531
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000532 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000533 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000534 if (T.isNull())
535 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +0000536 assert(Params.size() == 0 && "Destructor with parameters?");
537
Douglas Gregor03b2b072009-03-24 00:15:49 +0000538 // Build the instantiated destructor declaration.
539 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregor50d62d12009-08-05 05:36:45 +0000540 CanQualType ClassTy =
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000541 SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record));
Douglas Gregor03b2b072009-03-24 00:15:49 +0000542 CXXDestructorDecl *Destructor
543 = CXXDestructorDecl::Create(SemaRef.Context, Record,
544 D->getLocation(),
545 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
546 T, D->isInline(), false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000547 Destructor->setInstantiationOfMemberFunction(D);
Douglas Gregor5545e162009-03-24 00:38:23 +0000548 if (InitMethodInstantiation(Destructor, D))
549 Destructor->setInvalidDecl();
Douglas Gregor03b2b072009-03-24 00:15:49 +0000550
551 bool Redeclaration = false;
552 bool OverloadableAttrRequired = false;
553 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000554 SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
555 /*FIXME:*/OverloadableAttrRequired);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000556 Owner->addDecl(Destructor);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000557 return Destructor;
558}
559
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000560Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000561 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000562 Sema::LocalInstantiationScope Scope(SemaRef);
563
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000564 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000565 QualType T = InstantiateFunctionType(D, Params);
566 if (T.isNull())
567 return 0;
568 assert(Params.size() == 0 && "Destructor with parameters?");
569
570 // Build the instantiated conversion declaration.
571 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
572 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
Douglas Gregor50d62d12009-08-05 05:36:45 +0000573 CanQualType ConvTy
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000574 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
575 CXXConversionDecl *Conversion
576 = CXXConversionDecl::Create(SemaRef.Context, Record,
577 D->getLocation(),
578 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
579 T, D->isInline(), D->isExplicit());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000580 Conversion->setInstantiationOfMemberFunction(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000581 if (InitMethodInstantiation(Conversion, D))
582 Conversion->setInvalidDecl();
583
584 bool Redeclaration = false;
585 bool OverloadableAttrRequired = false;
586 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000587 SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
588 /*FIXME:*/OverloadableAttrRequired);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000589 Owner->addDecl(Conversion);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000590 return Conversion;
591}
592
Douglas Gregor6477b692009-03-25 15:04:13 +0000593ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000594 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000595 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000596 if (OrigT.isNull())
597 return 0;
598
599 QualType T = SemaRef.adjustParameterType(OrigT);
600
601 if (D->getDefaultArg()) {
602 // FIXME: Leave a marker for "uninstantiated" default
603 // arguments. They only get instantiated on demand at the call
604 // site.
605 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
606 "sorry, dropping default argument during template instantiation");
607 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
608 << D->getDefaultArg()->getSourceRange();
609 }
610
611 // Allocate the parameter
612 ParmVarDecl *Param = 0;
613 if (T == OrigT)
614 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
615 D->getIdentifier(), T, D->getStorageClass(),
616 0);
617 else
618 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
619 D->getLocation(), D->getIdentifier(),
620 T, OrigT, D->getStorageClass(), 0);
621
622 // Note: we don't try to instantiate function parameters until after
623 // we've instantiated the function's type. Therefore, we don't have
624 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000625 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000626 return Param;
627}
628
629Decl *
630TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
631 // Since parameter types can decay either before or after
632 // instantiation, we simply treat OriginalParmVarDecls as
633 // ParmVarDecls the same way, and create one or the other depending
634 // on what happens after template instantiation.
635 return VisitParmVarDecl(D);
636}
637
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000638Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
Douglas Gregor7e063902009-05-11 23:53:27 +0000639 const TemplateArgumentList &TemplateArgs) {
640 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000641 return Instantiator.Visit(D);
642}
643
Douglas Gregor5545e162009-03-24 00:38:23 +0000644/// \brief Instantiates the type of the given function, including
645/// instantiating all of the function parameters.
646///
647/// \param D The function that we will be instantiated
648///
649/// \param Params the instantiated parameter declarations
650
651/// \returns the instantiated function's type if successfull, a NULL
652/// type if there was an error.
653QualType
654TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
655 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
656 bool InvalidDecl = false;
657
658 // Instantiate the function parameters
Douglas Gregor7e063902009-05-11 23:53:27 +0000659 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000660 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000661 for (FunctionDecl::param_iterator P = D->param_begin(),
662 PEnd = D->param_end();
663 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000664 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000665 if (PInst->getType()->isVoidType()) {
666 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
667 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000668 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
669 PInst->getType(),
670 diag::err_abstract_type_in_decl,
671 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000672 PInst->setInvalidDecl();
673
674 Params.push_back(PInst);
675 ParamTys.push_back(PInst->getType());
676
677 if (PInst->isInvalidDecl())
678 InvalidDecl = true;
679 } else
680 InvalidDecl = true;
681 }
682
683 // FIXME: Deallocate dead declarations.
684 if (InvalidDecl)
685 return QualType();
686
687 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
688 assert(Proto && "Missing prototype?");
689 QualType ResultType
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000690 = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs,
Douglas Gregor5545e162009-03-24 00:38:23 +0000691 D->getLocation(), D->getDeclName());
692 if (ResultType.isNull())
693 return QualType();
694
Jay Foadbeaaccd2009-05-21 09:52:38 +0000695 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000696 Proto->isVariadic(), Proto->getTypeQuals(),
697 D->getLocation(), D->getDeclName());
698}
699
Douglas Gregore53060f2009-06-25 22:08:12 +0000700/// \brief Initializes the common fields of an instantiation function
701/// declaration (New) from the corresponding fields of its template (Tmpl).
702///
703/// \returns true if there was an error
704bool
705TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
706 FunctionDecl *Tmpl) {
707 if (Tmpl->isDeleted())
708 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000709
710 // If we are performing substituting explicitly-specified template arguments
711 // or deduced template arguments into a function template and we reach this
712 // point, we are now past the point where SFINAE applies and have committed
713 // to keeping the new function template specialization. We therefore
714 // convert the active template instantiation for the function template
715 // into a template instantiation for this specific function template
716 // specialization, which is not a SFINAE context, so that we diagnose any
717 // further errors in the declaration itself.
718 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
719 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
720 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
721 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
722 if (FunctionTemplateDecl *FunTmpl
723 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
724 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
725 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000726 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000727 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
728 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
729 }
730 }
731
Douglas Gregore53060f2009-06-25 22:08:12 +0000732 return false;
733}
734
Douglas Gregor5545e162009-03-24 00:38:23 +0000735/// \brief Initializes common fields of an instantiated method
736/// declaration (New) from the corresponding fields of its template
737/// (Tmpl).
738///
739/// \returns true if there was an error
740bool
741TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
742 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000743 if (InitFunctionInstantiation(New, Tmpl))
744 return true;
745
Douglas Gregor5545e162009-03-24 00:38:23 +0000746 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
747 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000748 if (Tmpl->isVirtualAsWritten()) {
749 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000750 Record->setAggregate(false);
751 Record->setPOD(false);
752 Record->setPolymorphic(true);
753 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000754 if (Tmpl->isPure()) {
755 New->setPure();
756 Record->setAbstract(true);
757 }
758
759 // FIXME: attributes
760 // FIXME: New needs a pointer to Tmpl
761 return false;
762}
Douglas Gregora58861f2009-05-13 20:28:22 +0000763
764/// \brief Instantiate the definition of the given function from its
765/// template.
766///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000767/// \param PointOfInstantiation the point at which the instantiation was
768/// required. Note that this is not precisely a "point of instantiation"
769/// for the function, but it's close.
770///
Douglas Gregora58861f2009-05-13 20:28:22 +0000771/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000772/// function template specialization or member function of a class template
773/// specialization.
774///
775/// \param Recursive if true, recursively instantiates any functions that
776/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000777void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000778 FunctionDecl *Function,
779 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000780 if (Function->isInvalidDecl())
781 return;
782
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000783 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000784
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000785 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000786 const FunctionDecl *PatternDecl = 0;
787 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
788 PatternDecl = Primary->getTemplatedDecl();
789 else
790 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000791 Stmt *Pattern = 0;
792 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000793 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000794
795 if (!Pattern)
796 return;
797
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000798 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
799 if (Inst)
800 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000801
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000802 // If we're performing recursive template instantiation, create our own
803 // queue of pending implicit instantiations that we will instantiate later,
804 // while we're still within our own instantiation context.
805 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
806 if (Recursive)
807 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
808
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000809 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
810
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000811 // Introduce a new scope where local variable instantiations will be
812 // recorded.
813 LocalInstantiationScope Scope(*this);
814
815 // Introduce the instantiated function parameters into the local
816 // instantiation scope.
817 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
818 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
819 Function->getParamDecl(I));
820
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000821 // Enter the scope of this instantiation. We don't use
822 // PushDeclContext because we don't have a scope.
823 DeclContext *PreviousContext = CurContext;
824 CurContext = Function;
825
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000826 // Instantiate the function body.
827 OwningStmtResult Body
828 = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function));
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000829
830 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
831 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000832
833 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000834
835 DeclGroupRef DG(Function);
836 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000837
838 if (Recursive) {
839 // Instantiate any pending implicit instantiations found during the
840 // instantiation of this template.
841 PerformPendingImplicitInstantiations();
842
843 // Restore the set of pending implicit instantiations.
844 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
845 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000846}
847
848/// \brief Instantiate the definition of the given variable from its
849/// template.
850///
Douglas Gregor7caa6822009-07-24 20:34:43 +0000851/// \param PointOfInstantiation the point at which the instantiation was
852/// required. Note that this is not precisely a "point of instantiation"
853/// for the function, but it's close.
854///
855/// \param Var the already-instantiated declaration of a static member
856/// variable of a class template specialization.
857///
858/// \param Recursive if true, recursively instantiates any functions that
859/// are required by this instantiation.
860void Sema::InstantiateStaticDataMemberDefinition(
861 SourceLocation PointOfInstantiation,
862 VarDecl *Var,
863 bool Recursive) {
864 if (Var->isInvalidDecl())
865 return;
866
867 // Find the out-of-line definition of this static data member.
868 // FIXME: Do we have to look for specializations separately?
869 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
870 bool FoundOutOfLineDef = false;
871 assert(Def && "This data member was not instantiated from a template?");
872 assert(Def->isStaticDataMember() && "Not a static data member?");
873 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
874 RDEnd = Def->redecls_end();
875 RD != RDEnd; ++RD) {
876 if (RD->getLexicalDeclContext()->isFileContext()) {
877 Def = *RD;
878 FoundOutOfLineDef = true;
879 }
880 }
881
882 if (!FoundOutOfLineDef) {
883 // We did not find an out-of-line definition of this static data member,
884 // so we won't perform any instantiation. Rather, we rely on the user to
885 // instantiate this definition (or provide a specialization for it) in
886 // another translation unit.
887 return;
888 }
889
890 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
891 if (Inst)
892 return;
893
894 // If we're performing recursive template instantiation, create our own
895 // queue of pending implicit instantiations that we will instantiate later,
896 // while we're still within our own instantiation context.
897 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
898 if (Recursive)
899 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
900
901 // Enter the scope of this instantiation. We don't use
902 // PushDeclContext because we don't have a scope.
903 DeclContext *PreviousContext = CurContext;
904 CurContext = Var->getDeclContext();
905
906#if 0
907 // Instantiate the initializer of this static data member.
908 OwningExprResult Init
909 = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
910 if (Init.isInvalid()) {
911 // If instantiation of the initializer failed, mark the declaration invalid
912 // and don't instantiate anything else that was triggered by this
913 // instantiation.
914 Var->setInvalidDecl();
915
916 // Restore the set of pending implicit instantiations.
917 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
918
919 return;
920 }
921
922 // Type-check the initializer.
923 if (Init.get())
924 AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
925 Def->hasCXXDirectInitializer());
926 else
927 ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
928#else
929 Var = cast_or_null<VarDecl>(InstantiateDecl(Def, Var->getDeclContext(),
930 getTemplateInstantiationArgs(Var)));
931#endif
932
933 CurContext = PreviousContext;
934
935 if (Var) {
936 DeclGroupRef DG(Var);
937 Consumer.HandleTopLevelDecl(DG);
938 }
939
940 if (Recursive) {
941 // Instantiate any pending implicit instantiations found during the
942 // instantiation of this template.
943 PerformPendingImplicitInstantiations();
944
945 // Restore the set of pending implicit instantiations.
946 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
947 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000948}
Douglas Gregor815215d2009-05-27 05:35:12 +0000949
950static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
951 if (D->getKind() != Other->getKind())
952 return false;
953
954 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000955 return Record->getInstantiatedFromMemberClass()->getCanonicalDecl()
956 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000957
958 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000959 return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl()
960 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000961
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000962 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000963 return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl()
964 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000965
Douglas Gregor7caa6822009-07-24 20:34:43 +0000966 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
967 if (Var->isStaticDataMember())
968 return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl()
969 == D->getCanonicalDecl();
970
Douglas Gregor815215d2009-05-27 05:35:12 +0000971 // FIXME: How can we find instantiations of anonymous unions?
972
973 return D->getDeclName() && isa<NamedDecl>(Other) &&
974 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
975}
976
977template<typename ForwardIterator>
978static NamedDecl *findInstantiationOf(ASTContext &Ctx,
979 NamedDecl *D,
980 ForwardIterator first,
981 ForwardIterator last) {
982 for (; first != last; ++first)
983 if (isInstantiationOf(Ctx, D, *first))
984 return cast<NamedDecl>(*first);
985
986 return 0;
987}
988
Douglas Gregored961e72009-05-27 17:54:46 +0000989/// \brief Find the instantiation of the given declaration within the
990/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +0000991///
992/// This routine is intended to be used when \p D is a declaration
993/// referenced from within a template, that needs to mapped into the
994/// corresponding declaration within an instantiation. For example,
995/// given:
996///
997/// \code
998/// template<typename T>
999/// struct X {
1000/// enum Kind {
1001/// KnownValue = sizeof(T)
1002/// };
1003///
1004/// bool getKind() const { return KnownValue; }
1005/// };
1006///
1007/// template struct X<int>;
1008/// \endcode
1009///
1010/// In the instantiation of X<int>::getKind(), we need to map the
1011/// EnumConstantDecl for KnownValue (which refers to
1012/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001013/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1014/// this mapping from within the instantiation of X<int>.
1015NamedDecl * Sema::InstantiateCurrentDeclRef(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +00001016 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001017 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1018 // D is a local of some kind. Look into the map of local
1019 // declarations to their instantiations.
1020 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1021 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001022
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001023 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
Douglas Gregored961e72009-05-27 17:54:46 +00001024 ParentDecl = InstantiateCurrentDeclRef(ParentDecl);
Douglas Gregor815215d2009-05-27 05:35:12 +00001025 if (!ParentDecl)
1026 return 0;
1027
1028 ParentDC = cast<DeclContext>(ParentDecl);
1029 }
1030
Douglas Gregor815215d2009-05-27 05:35:12 +00001031 if (ParentDC != D->getDeclContext()) {
1032 // We performed some kind of instantiation in the parent context,
1033 // so now we need to look into the instantiated parent context to
1034 // find the instantiation of the declaration D.
1035 NamedDecl *Result = 0;
1036 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001037 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001038 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1039 } else {
1040 // Since we don't have a name for the entity we're looking for,
1041 // our only option is to walk through all of the declarations to
1042 // find that name. This will occur in a few cases:
1043 //
1044 // - anonymous struct/union within a template
1045 // - unnamed class/struct/union/enum within a template
1046 //
1047 // FIXME: Find a better way to find these instantiations!
1048 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001049 ParentDC->decls_begin(),
1050 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001051 }
1052 assert(Result && "Unable to find instantiation of declaration!");
1053 D = Result;
1054 }
1055
Douglas Gregor815215d2009-05-27 05:35:12 +00001056 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
Douglas Gregored961e72009-05-27 17:54:46 +00001057 if (ClassTemplateDecl *ClassTemplate
1058 = Record->getDescribedClassTemplate()) {
1059 // When the declaration D was parsed, it referred to the current
1060 // instantiation. Therefore, look through the current context,
1061 // which contains actual instantiations, to find the
1062 // instantiation of the "current instantiation" that D refers
1063 // to. Alternatively, we could just instantiate the
1064 // injected-class-name with the current template arguments, but
1065 // such an instantiation is far more expensive.
1066 for (DeclContext *DC = CurContext; !DC->isFileContext();
1067 DC = DC->getParent()) {
1068 if (ClassTemplateSpecializationDecl *Spec
1069 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001070 if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1071 == ClassTemplate->getCanonicalDecl())
Douglas Gregored961e72009-05-27 17:54:46 +00001072 return Spec;
1073 }
1074
1075 assert(false &&
1076 "Unable to find declaration for the current instantiation");
Douglas Gregor815215d2009-05-27 05:35:12 +00001077 }
1078
1079 return D;
1080}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001081
1082/// \brief Performs template instantiation for all implicit template
1083/// instantiations we have seen until this point.
1084void Sema::PerformPendingImplicitInstantiations() {
1085 while (!PendingImplicitInstantiations.empty()) {
1086 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001087 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001088
Douglas Gregor7caa6822009-07-24 20:34:43 +00001089 // Instantiate function definitions
1090 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001091 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001092 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001093 continue;
1094 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001095
Douglas Gregor7caa6822009-07-24 20:34:43 +00001096 // Instantiate static data member definitions.
1097 VarDecl *Var = cast<VarDecl>(Inst.first);
1098 assert(Var->isStaticDataMember() && "Not a static data member?");
1099 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001100 }
1101}