blob: a0353e3c539ebeaa52015eb82f919db653da4ae8 [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"
Douglas Gregor83ddad32009-08-26 21:14:46 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000019#include "llvm/Support/Compiler.h"
20
21using namespace clang;
22
23namespace {
24 class VISIBILITY_HIDDEN TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000025 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000026 Sema &SemaRef;
27 DeclContext *Owner;
Douglas Gregor7e063902009-05-11 23:53:27 +000028 const TemplateArgumentList &TemplateArgs;
Douglas Gregor8dbc2692009-03-17 21:15:40 +000029
30 public:
31 typedef Sema::OwningExprResult OwningExprResult;
32
33 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregor7e063902009-05-11 23:53:27 +000034 const TemplateArgumentList &TemplateArgs)
35 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Douglas Gregor8dbc2692009-03-17 21:15:40 +000036
Mike Stump390b4cc2009-05-16 07:39:55 +000037 // FIXME: Once we get closer to completion, replace these manually-written
38 // declarations with automatically-generated ones from
39 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000040 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
41 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000042 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000043 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000044 Decl *VisitFieldDecl(FieldDecl *D);
45 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
46 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000047 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCallfd810b12009-08-14 02:03:10 +000048 Decl *VisitFriendClassDecl(FriendClassDecl *D);
Douglas Gregore53060f2009-06-25 22:08:12 +000049 Decl *VisitFunctionDecl(FunctionDecl *D);
Douglas Gregord475b8d2009-03-25 21:17:03 +000050 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000051 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
52 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000053 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000054 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000055 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000056 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000057 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000058 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000059 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000060 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor5545e162009-03-24 00:38:23 +000061
Douglas Gregor8dbc2692009-03-17 21:15:40 +000062 // Base case. FIXME: Remove once we can instantiate everything.
63 Decl *VisitDecl(Decl *) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000064 assert(false && "Template instantiation of unknown declaration kind!");
Douglas Gregor8dbc2692009-03-17 21:15:40 +000065 return 0;
66 }
Douglas Gregor5545e162009-03-24 00:38:23 +000067
John McCallfd810b12009-08-14 02:03:10 +000068 const LangOptions &getLangOptions() {
69 return SemaRef.getLangOptions();
70 }
71
Douglas Gregor5545e162009-03-24 00:38:23 +000072 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000073 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000074 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000075 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000076 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000077
78 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000079 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000080 };
81}
82
Douglas Gregor4f722be2009-03-25 15:45:12 +000083Decl *
84TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
85 assert(false && "Translation units cannot be instantiated");
86 return D;
87}
88
89Decl *
90TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
91 assert(false && "Namespaces cannot be instantiated");
92 return D;
93}
94
Douglas Gregor8dbc2692009-03-17 21:15:40 +000095Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
96 bool Invalid = false;
97 QualType T = D->getUnderlyingType();
98 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +000099 T = SemaRef.SubstType(T, TemplateArgs,
100 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000101 if (T.isNull()) {
102 Invalid = true;
103 T = SemaRef.Context.IntTy;
104 }
105 }
106
107 // Create the new typedef
108 TypedefDecl *Typedef
109 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
110 D->getIdentifier(), T);
111 if (Invalid)
112 Typedef->setInvalidDecl();
113
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000114 Owner->addDecl(Typedef);
Douglas Gregorbc221632009-05-28 16:34:51 +0000115
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000116 return Typedef;
117}
118
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000119Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000120 // Do substitution on the type of the declaration
121 QualType T = SemaRef.SubstType(D->getType(), TemplateArgs,
122 D->getTypeSpecStartLoc(),
123 D->getDeclName());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000124 if (T.isNull())
125 return 0;
126
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000127 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000128 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
129 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000130 T, D->getDeclaratorInfo(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000131 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000132 Var->setThreadSpecified(D->isThreadSpecified());
133 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
134 Var->setDeclaredInCondition(D->isDeclaredInCondition());
135
Douglas Gregor7caa6822009-07-24 20:34:43 +0000136 // If we are instantiating a static data member defined
137 // out-of-line, the instantiation will have the same lexical
138 // context (which will be a namespace scope) as the template.
139 if (D->isOutOfLine())
140 Var->setLexicalDeclContext(D->getLexicalDeclContext());
141
Mike Stump390b4cc2009-05-16 07:39:55 +0000142 // FIXME: In theory, we could have a previous declaration for variables that
143 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000144 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000145 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000146
147 if (D->isOutOfLine()) {
148 D->getLexicalDeclContext()->addDecl(Var);
149 Owner->makeDeclVisibleInContext(Var);
150 } else {
151 Owner->addDecl(Var);
152 }
153
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000154 if (D->getInit()) {
155 OwningExprResult Init
John McCallce3ff2b2009-08-25 22:02:44 +0000156 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000157 if (Init.isInvalid())
158 Var->setInvalidDecl();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000159 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
160 // FIXME: We're faking all of the comma locations, which is suboptimal.
161 // Do we even need these comma locations?
162 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
163 if (PLE->getNumExprs() > 0) {
164 FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
165 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
166 Expr *E = PLE->getExpr(I)->Retain();
167 FakeCommaLocs.push_back(
168 SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
169 }
Douglas Gregore9f8eb62009-08-26 23:26:04 +0000170 PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000171 }
172
173 // Add the direct initializer to the declaration.
174 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
175 PLE->getLParenLoc(),
176 Sema::MultiExprArg(SemaRef,
177 (void**)PLE->getExprs(),
178 PLE->getNumExprs()),
179 FakeCommaLocs.data(),
180 PLE->getRParenLoc());
181
182 // When Init is destroyed, it will destroy the instantiated ParenListExpr;
183 // we've explicitly retained all of its subexpressions already.
184 } else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000185 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000186 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000187 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
188 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000189
Douglas Gregor7caa6822009-07-24 20:34:43 +0000190 // Link instantiations of static data members back to the template from
191 // which they were instantiated.
192 if (Var->isStaticDataMember())
193 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
194
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000195 return Var;
196}
197
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000198Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
199 bool Invalid = false;
200 QualType T = D->getType();
201 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000202 T = SemaRef.SubstType(T, TemplateArgs,
203 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000204 if (!T.isNull() && T->isFunctionType()) {
205 // C++ [temp.arg.type]p3:
206 // If a declaration acquires a function type through a type
207 // dependent on a template-parameter and this causes a
208 // declaration that does not use the syntactic form of a
209 // function declarator to have function type, the program is
210 // ill-formed.
211 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
212 << T;
213 T = QualType();
214 Invalid = true;
215 }
216 }
217
218 Expr *BitWidth = D->getBitWidth();
219 if (Invalid)
220 BitWidth = 0;
221 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000222 // The bit-width expression is not potentially evaluated.
223 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
224
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000225 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000226 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000227 if (InstantiatedBitWidth.isInvalid()) {
228 Invalid = true;
229 BitWidth = 0;
230 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000231 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000232 }
233
234 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000235 D->getDeclaratorInfo(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000236 cast<RecordDecl>(Owner),
237 D->getLocation(),
238 D->isMutable(),
239 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000240 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000241 D->getAccess(),
242 0);
243 if (Field) {
244 if (Invalid)
245 Field->setInvalidDecl();
246
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000247 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000248 }
249
250 return Field;
251}
252
John McCallfd810b12009-08-14 02:03:10 +0000253Decl *TemplateDeclInstantiator::VisitFriendClassDecl(FriendClassDecl *D) {
254 QualType T = D->getFriendType();
255 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000256 T = SemaRef.SubstType(T, TemplateArgs, D->getLocation(),
257 DeclarationName());
John McCallfd810b12009-08-14 02:03:10 +0000258 assert(T.isNull() || getLangOptions().CPlusPlus0x || T->isRecordType());
259 }
260
261 // FIXME: the target context might be dependent.
262 DeclContext *DC = D->getDeclContext();
263 assert(DC->isFileContext());
264
265 FriendClassDecl *NewD =
266 FriendClassDecl::Create(SemaRef.Context, DC, D->getLocation(), T,
267 D->getFriendLoc());
Eli Friedmanc5c54f22009-08-27 18:38:56 +0000268 NewD->setLexicalDeclContext(Owner);
269
John McCallfd810b12009-08-14 02:03:10 +0000270 Owner->addDecl(NewD);
271 return NewD;
272}
273
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000274Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
275 Expr *AssertExpr = D->getAssertExpr();
276
Douglas Gregorac7610d2009-06-22 20:57:11 +0000277 // The expression in a static assertion is not potentially evaluated.
278 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
279
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000280 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000281 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000282 if (InstantiatedAssertExpr.isInvalid())
283 return 0;
284
Douglas Gregor43d9d922009-08-08 01:41:12 +0000285 OwningExprResult Message(SemaRef, D->getMessage());
286 D->getMessage()->Retain();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000287 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000288 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
289 move(InstantiatedAssertExpr),
290 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000291 return StaticAssert;
292}
293
294Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
295 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
296 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000297 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000298 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000299 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000300 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000301 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000302 Enum->startDefinition();
303
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000304 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000305
306 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000307 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
308 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000309 EC != ECEnd; ++EC) {
310 // The specified value for the enumerator.
311 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000312 if (Expr *UninstValue = EC->getInitExpr()) {
313 // The enumerator's value expression is not potentially evaluated.
314 EnterExpressionEvaluationContext Unevaluated(SemaRef,
315 Action::Unevaluated);
316
John McCallce3ff2b2009-08-25 22:02:44 +0000317 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000318 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000319
320 // Drop the initial value and continue.
321 bool isInvalid = false;
322 if (Value.isInvalid()) {
323 Value = SemaRef.Owned((Expr *)0);
324 isInvalid = true;
325 }
326
327 EnumConstantDecl *EnumConst
328 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
329 EC->getLocation(), EC->getIdentifier(),
330 move(Value));
331
332 if (isInvalid) {
333 if (EnumConst)
334 EnumConst->setInvalidDecl();
335 Enum->setInvalidDecl();
336 }
337
338 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000339 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000340 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000341 LastEnumConst = EnumConst;
342 }
343 }
344
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000345 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000346 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000347 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
348 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000349 &Enumerators[0], Enumerators.size(),
350 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000351
352 return Enum;
353}
354
Douglas Gregor6477b692009-03-25 15:04:13 +0000355Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
356 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
357 return 0;
358}
359
John McCalle29ba202009-08-20 01:44:21 +0000360Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
361 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000362 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Douglas Gregord60e1052009-08-27 16:57:43 +0000363 if (!InstParams)
364 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000365
366 CXXRecordDecl *Pattern = D->getTemplatedDecl();
367 CXXRecordDecl *RecordInst
368 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
369 Pattern->getLocation(), Pattern->getIdentifier(),
370 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
371
372 ClassTemplateDecl *Inst
373 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
374 D->getIdentifier(), InstParams, RecordInst, 0);
375 RecordInst->setDescribedClassTemplate(Inst);
376 Inst->setAccess(D->getAccess());
377 Inst->setInstantiatedFromMemberTemplate(D);
378
379 Owner->addDecl(Inst);
380 return Inst;
381}
382
Douglas Gregord60e1052009-08-27 16:57:43 +0000383Decl *
384TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
385 TemplateParameterList *TempParams = D->getTemplateParameters();
386 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
387 if (!InstParams)
388 return NULL;
389
390 // FIXME: Handle instantiation of nested function templates that aren't
391 // member function templates. This could happen inside a FriendDecl.
392 assert(isa<CXXMethodDecl>(D->getTemplatedDecl()));
393 CXXMethodDecl *InstMethod
394 = cast_or_null<CXXMethodDecl>(
395 VisitCXXMethodDecl(cast<CXXMethodDecl>(D->getTemplatedDecl()),
396 InstParams));
397 if (!InstMethod)
398 return 0;
399
400 // Link the instantiated function template declaration to the function
401 // template from which it was instantiated.
402 FunctionTemplateDecl *InstTemplate = InstMethod->getDescribedFunctionTemplate();
403 assert(InstTemplate && "VisitCXXMethodDecl didn't create a template!");
404 InstTemplate->setInstantiatedFromMemberTemplate(D);
405 Owner->addDecl(InstTemplate);
406 return InstTemplate;
407}
408
Douglas Gregord475b8d2009-03-25 21:17:03 +0000409Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
410 CXXRecordDecl *PrevDecl = 0;
411 if (D->isInjectedClassName())
412 PrevDecl = cast<CXXRecordDecl>(Owner);
413
414 CXXRecordDecl *Record
415 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000416 D->getLocation(), D->getIdentifier(),
417 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000418 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000419 // FIXME: Check against AS_none is an ugly hack to work around the issue that
420 // the tag decls introduced by friend class declarations don't have an access
421 // specifier. Remove once this area of the code gets sorted out.
422 if (D->getAccess() != AS_none)
423 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000424 if (!D->isInjectedClassName())
425 Record->setInstantiationOfMemberClass(D);
426
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000427 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000428 return Record;
429}
430
Douglas Gregore53060f2009-06-25 22:08:12 +0000431Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000432 // Check whether there is already a function template specialization for
433 // this declaration.
434 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
435 void *InsertPos = 0;
436 if (FunctionTemplate) {
437 llvm::FoldingSetNodeID ID;
438 FunctionTemplateSpecializationInfo::Profile(ID,
439 TemplateArgs.getFlatArgumentList(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000440 TemplateArgs.flat_size(),
441 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000442
443 FunctionTemplateSpecializationInfo *Info
444 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
445 InsertPos);
446
447 // If we already have a function template specialization, return it.
448 if (Info)
449 return Info->Function;
450 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000451
452 Sema::LocalInstantiationScope Scope(SemaRef);
453
454 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000455 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000456 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000457 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000458
Douglas Gregore53060f2009-06-25 22:08:12 +0000459 // Build the instantiated method declaration.
John McCallfd810b12009-08-14 02:03:10 +0000460 FunctionDecl *Function;
461 if (FriendFunctionDecl* FFD = dyn_cast<FriendFunctionDecl>(D)) {
462 // The new decl's semantic context. FIXME: this might need
463 // to be instantiated.
464 DeclContext *DC = D->getDeclContext();
465
466 // This assert is bogus and exists only to catch cases we don't
467 // handle yet.
468 assert(!DC->isDependentContext());
469
470 Function =
471 FriendFunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000472 D->getDeclName(), T, D->getDeclaratorInfo(),
473 D->isInline(), FFD->getFriendLoc());
John McCallfd810b12009-08-14 02:03:10 +0000474 Function->setLexicalDeclContext(Owner);
475 } else {
476 Function =
477 FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000478 D->getDeclName(), T, D->getDeclaratorInfo(),
479 D->getStorageClass(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000480 D->isInline(), D->hasWrittenPrototype());
John McCallfd810b12009-08-14 02:03:10 +0000481 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000482
483 // Attach the parameters
484 for (unsigned P = 0; P < Params.size(); ++P)
485 Params[P]->setOwningFunction(Function);
486 Function->setParams(SemaRef.Context, Params.data(), Params.size());
487
488 if (InitFunctionInstantiation(Function, D))
489 Function->setInvalidDecl();
490
491 bool Redeclaration = false;
492 bool OverloadableAttrRequired = false;
493 NamedDecl *PrevDecl = 0;
494 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
495 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000496
Douglas Gregor127102b2009-06-29 20:59:39 +0000497 if (FunctionTemplate) {
498 // Record this function template specialization.
499 Function->setFunctionTemplateSpecialization(SemaRef.Context,
500 FunctionTemplate,
501 &TemplateArgs,
502 InsertPos);
John McCallfd810b12009-08-14 02:03:10 +0000503 }
504
505 // If this was a friend function decl, it's a member which
506 // needs to be added.
507 if (isa<FriendFunctionDecl>(Function)) {
508 // If the new context is still dependent, this declaration
509 // needs to remain hidden.
510 if (Owner->isDependentContext())
511 Owner->addHiddenDecl(Function);
512 else
513 Owner->addDecl(Function);
514 }
Douglas Gregor127102b2009-06-29 20:59:39 +0000515
Douglas Gregore53060f2009-06-25 22:08:12 +0000516 return Function;
517}
518
Douglas Gregord60e1052009-08-27 16:57:43 +0000519Decl *
520TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
521 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000522 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
523 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000524 if (FunctionTemplate && !TemplateParams) {
525 // We are creating a function template specialization from a function
526 // template. Check whether there is already a function template
527 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000528 llvm::FoldingSetNodeID ID;
529 FunctionTemplateSpecializationInfo::Profile(ID,
530 TemplateArgs.getFlatArgumentList(),
531 TemplateArgs.flat_size(),
532 SemaRef.Context);
533
534 FunctionTemplateSpecializationInfo *Info
535 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
536 InsertPos);
537
538 // If we already have a function template specialization, return it.
539 if (Info)
540 return Info->Function;
541 }
542
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000543 Sema::LocalInstantiationScope Scope(SemaRef);
544
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000545 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000546 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000547 if (T.isNull())
548 return 0;
549
550 // Build the instantiated method declaration.
551 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000552 CXXMethodDecl *Method = 0;
553
554 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000555 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000556 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
557 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
558 SemaRef.Context.getCanonicalType(ClassTy));
559 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000560 Constructor->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000561 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000562 Constructor->getDeclaratorInfo(),
563 Constructor->isExplicit(),
564 Constructor->isInline(), false);
565 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
566 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
567 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
568 SemaRef.Context.getCanonicalType(ClassTy));
569 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
570 Destructor->getLocation(), Name,
571 T, Destructor->isInline(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000572 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
573 CanQualType ConvTy
574 = SemaRef.Context.getCanonicalType(
575 T->getAsFunctionType()->getResultType());
576 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
577 ConvTy);
578 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
579 Conversion->getLocation(), Name,
580 T, Conversion->getDeclaratorInfo(),
581 Conversion->isInline(),
582 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000583 } else {
584 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
585 D->getDeclName(), T, D->getDeclaratorInfo(),
586 D->isStatic(), D->isInline());
587 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000588
Douglas Gregord60e1052009-08-27 16:57:43 +0000589 if (TemplateParams) {
590 // Our resulting instantiation is actually a function template, since we
591 // are substituting only the outer template parameters. For example, given
592 //
593 // template<typename T>
594 // struct X {
595 // template<typename U> void f(T, U);
596 // };
597 //
598 // X<int> x;
599 //
600 // We are instantiating the member template "f" within X<int>, which means
601 // substituting int for T, but leaving "f" as a member function template.
602 // Build the function template itself.
603 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
604 Method->getLocation(),
605 Method->getDeclName(),
606 TemplateParams, Method);
607 if (D->isOutOfLine())
608 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
609 Method->setDescribedFunctionTemplate(FunctionTemplate);
610 } else if (!FunctionTemplate)
Douglas Gregor6b906862009-08-21 00:16:32 +0000611 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000612
Douglas Gregor7caa6822009-07-24 20:34:43 +0000613 // If we are instantiating a member function defined
614 // out-of-line, the instantiation will have the same lexical
615 // context (which will be a namespace scope) as the template.
616 if (D->isOutOfLine())
617 Method->setLexicalDeclContext(D->getLexicalDeclContext());
618
Douglas Gregor5545e162009-03-24 00:38:23 +0000619 // Attach the parameters
620 for (unsigned P = 0; P < Params.size(); ++P)
621 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000622 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000623
624 if (InitMethodInstantiation(Method, D))
625 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000626
Douglas Gregordec06662009-08-21 18:42:58 +0000627 NamedDecl *PrevDecl = 0;
628
Douglas Gregord60e1052009-08-27 16:57:43 +0000629 if (!FunctionTemplate || TemplateParams) {
Douglas Gregordec06662009-08-21 18:42:58 +0000630 PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
631 Sema::LookupOrdinaryName, true);
632
633 // In C++, the previous declaration we find might be a tag type
634 // (class or enum). In this case, the new declaration will hide the
635 // tag type. Note that this does does not apply if we're declaring a
636 // typedef (C++ [dcl.typedef]p4).
637 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
638 PrevDecl = 0;
639 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000640
Douglas Gregord60e1052009-08-27 16:57:43 +0000641 if (FunctionTemplate && !TemplateParams)
Douglas Gregor6b906862009-08-21 00:16:32 +0000642 // Record this function template specialization.
643 Method->setFunctionTemplateSpecialization(SemaRef.Context,
644 FunctionTemplate,
645 &TemplateArgs,
646 InsertPos);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000647
648 bool Redeclaration = false;
649 bool OverloadableAttrRequired = false;
650 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
651 /*FIXME:*/OverloadableAttrRequired);
652
653 if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
Douglas Gregordec06662009-08-21 18:42:58 +0000654 Owner->addDecl(Method);
655
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000656 return Method;
657}
658
Douglas Gregor615c5d42009-03-24 16:43:20 +0000659Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000660 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000661}
662
Douglas Gregor03b2b072009-03-24 00:15:49 +0000663Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000664 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000665}
666
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000667Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000668 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000669}
670
Douglas Gregor6477b692009-03-25 15:04:13 +0000671ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000672 QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000673 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000674 if (OrigT.isNull())
675 return 0;
676
677 QualType T = SemaRef.adjustParameterType(OrigT);
678
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000679 // Allocate the parameter
680 ParmVarDecl *Param = 0;
681 if (T == OrigT)
682 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000683 D->getIdentifier(), T, D->getDeclaratorInfo(),
684 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000685 else
686 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
687 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000688 T, D->getDeclaratorInfo(), OrigT,
689 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000690
Anders Carlsson9351c172009-08-25 03:18:48 +0000691 // Mark the default argument as being uninstantiated.
692 if (Expr *Arg = D->getDefaultArg())
693 Param->setUninstantiatedDefaultArg(Arg);
694
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000695 // Note: we don't try to instantiate function parameters until after
696 // we've instantiated the function's type. Therefore, we don't have
697 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000698 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000699 return Param;
700}
701
702Decl *
703TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
704 // Since parameter types can decay either before or after
705 // instantiation, we simply treat OriginalParmVarDecls as
706 // ParmVarDecls the same way, and create one or the other depending
707 // on what happens after template instantiation.
708 return VisitParmVarDecl(D);
709}
710
John McCalle29ba202009-08-20 01:44:21 +0000711Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
712 TemplateTypeParmDecl *D) {
713 // TODO: don't always clone when decls are refcounted.
714 const Type* T = D->getTypeForDecl();
715 assert(T->isTemplateTypeParmType());
716 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
717
718 TemplateTypeParmDecl *Inst =
719 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
720 TTPT->getDepth(), TTPT->getIndex(),
721 TTPT->getName(),
722 D->wasDeclaredWithTypename(),
723 D->isParameterPack());
724
725 if (D->hasDefaultArgument()) {
726 QualType DefaultPattern = D->getDefaultArgument();
727 QualType DefaultInst
John McCallce3ff2b2009-08-25 22:02:44 +0000728 = SemaRef.SubstType(DefaultPattern, TemplateArgs,
729 D->getDefaultArgumentLoc(),
730 D->getDeclName());
John McCalle29ba202009-08-20 01:44:21 +0000731
732 Inst->setDefaultArgument(DefaultInst,
733 D->getDefaultArgumentLoc(),
734 D->defaultArgumentWasInherited() /* preserve? */);
735 }
736
737 return Inst;
738}
739
John McCallce3ff2b2009-08-25 22:02:44 +0000740Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
741 const TemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +0000742 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000743 return Instantiator.Visit(D);
744}
745
John McCalle29ba202009-08-20 01:44:21 +0000746/// \brief Instantiates a nested template parameter list in the current
747/// instantiation context.
748///
749/// \param L The parameter list to instantiate
750///
751/// \returns NULL if there was an error
752TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000753TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +0000754 // Get errors for all the parameters before bailing out.
755 bool Invalid = false;
756
757 unsigned N = L->size();
758 typedef llvm::SmallVector<Decl*,8> ParamVector;
759 ParamVector Params;
760 Params.reserve(N);
761 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
762 PI != PE; ++PI) {
763 Decl *D = Visit(*PI);
764 Params.push_back(D);
765 Invalid = Invalid || !D;
766 }
767
768 // Clean up if we had an error.
769 if (Invalid) {
770 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
771 PI != PE; ++PI)
772 if (*PI)
773 (*PI)->Destroy(SemaRef.Context);
774 return NULL;
775 }
776
777 TemplateParameterList *InstL
778 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
779 L->getLAngleLoc(), &Params.front(), N,
780 L->getRAngleLoc());
781 return InstL;
782}
783
John McCallce3ff2b2009-08-25 22:02:44 +0000784/// \brief Does substitution on the type of the given function, including
785/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +0000786///
John McCallce3ff2b2009-08-25 22:02:44 +0000787/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +0000788///
789/// \param Params the instantiated parameter declarations
790
John McCallce3ff2b2009-08-25 22:02:44 +0000791/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +0000792/// type if there was an error.
793QualType
John McCallce3ff2b2009-08-25 22:02:44 +0000794TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +0000795 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
796 bool InvalidDecl = false;
797
John McCallce3ff2b2009-08-25 22:02:44 +0000798 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +0000799 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000800 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000801 for (FunctionDecl::param_iterator P = D->param_begin(),
802 PEnd = D->param_end();
803 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000804 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000805 if (PInst->getType()->isVoidType()) {
806 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
807 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000808 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
809 PInst->getType(),
810 diag::err_abstract_type_in_decl,
811 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000812 PInst->setInvalidDecl();
813
814 Params.push_back(PInst);
815 ParamTys.push_back(PInst->getType());
816
817 if (PInst->isInvalidDecl())
818 InvalidDecl = true;
819 } else
820 InvalidDecl = true;
821 }
822
823 // FIXME: Deallocate dead declarations.
824 if (InvalidDecl)
825 return QualType();
826
827 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
828 assert(Proto && "Missing prototype?");
829 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +0000830 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
831 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +0000832 if (ResultType.isNull())
833 return QualType();
834
Jay Foadbeaaccd2009-05-21 09:52:38 +0000835 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000836 Proto->isVariadic(), Proto->getTypeQuals(),
837 D->getLocation(), D->getDeclName());
838}
839
Douglas Gregore53060f2009-06-25 22:08:12 +0000840/// \brief Initializes the common fields of an instantiation function
841/// declaration (New) from the corresponding fields of its template (Tmpl).
842///
843/// \returns true if there was an error
844bool
845TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
846 FunctionDecl *Tmpl) {
847 if (Tmpl->isDeleted())
848 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000849
850 // If we are performing substituting explicitly-specified template arguments
851 // or deduced template arguments into a function template and we reach this
852 // point, we are now past the point where SFINAE applies and have committed
853 // to keeping the new function template specialization. We therefore
854 // convert the active template instantiation for the function template
855 // into a template instantiation for this specific function template
856 // specialization, which is not a SFINAE context, so that we diagnose any
857 // further errors in the declaration itself.
858 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
859 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
860 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
861 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
862 if (FunctionTemplateDecl *FunTmpl
863 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
864 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
865 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000866 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000867 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
868 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
869 }
870 }
871
Douglas Gregore53060f2009-06-25 22:08:12 +0000872 return false;
873}
874
Douglas Gregor5545e162009-03-24 00:38:23 +0000875/// \brief Initializes common fields of an instantiated method
876/// declaration (New) from the corresponding fields of its template
877/// (Tmpl).
878///
879/// \returns true if there was an error
880bool
881TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
882 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000883 if (InitFunctionInstantiation(New, Tmpl))
884 return true;
885
Douglas Gregor5545e162009-03-24 00:38:23 +0000886 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
887 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000888 if (Tmpl->isVirtualAsWritten()) {
889 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000890 Record->setAggregate(false);
891 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000892 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000893 Record->setPolymorphic(true);
894 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000895 if (Tmpl->isPure()) {
896 New->setPure();
897 Record->setAbstract(true);
898 }
899
900 // FIXME: attributes
901 // FIXME: New needs a pointer to Tmpl
902 return false;
903}
Douglas Gregora58861f2009-05-13 20:28:22 +0000904
905/// \brief Instantiate the definition of the given function from its
906/// template.
907///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000908/// \param PointOfInstantiation the point at which the instantiation was
909/// required. Note that this is not precisely a "point of instantiation"
910/// for the function, but it's close.
911///
Douglas Gregora58861f2009-05-13 20:28:22 +0000912/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000913/// function template specialization or member function of a class template
914/// specialization.
915///
916/// \param Recursive if true, recursively instantiates any functions that
917/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000918void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000919 FunctionDecl *Function,
920 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000921 if (Function->isInvalidDecl())
922 return;
923
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000924 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000925
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000926 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000927 const FunctionDecl *PatternDecl = 0;
928 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
929 PatternDecl = Primary->getTemplatedDecl();
930 else
931 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000932 Stmt *Pattern = 0;
933 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000934 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000935
936 if (!Pattern)
937 return;
938
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000939 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
940 if (Inst)
941 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000942
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000943 // If we're performing recursive template instantiation, create our own
944 // queue of pending implicit instantiations that we will instantiate later,
945 // while we're still within our own instantiation context.
946 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
947 if (Recursive)
948 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
949
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000950 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
951
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000952 // Introduce a new scope where local variable instantiations will be
953 // recorded.
954 LocalInstantiationScope Scope(*this);
955
956 // Introduce the instantiated function parameters into the local
957 // instantiation scope.
958 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
959 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
960 Function->getParamDecl(I));
961
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000962 // Enter the scope of this instantiation. We don't use
963 // PushDeclContext because we don't have a scope.
964 DeclContext *PreviousContext = CurContext;
965 CurContext = Function;
966
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000967 // Instantiate the function body.
968 OwningStmtResult Body
John McCallce3ff2b2009-08-25 22:02:44 +0000969 = SubstStmt(Pattern, getTemplateInstantiationArgs(Function));
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000970
971 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
972 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000973
974 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000975
976 DeclGroupRef DG(Function);
977 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000978
979 if (Recursive) {
980 // Instantiate any pending implicit instantiations found during the
981 // instantiation of this template.
982 PerformPendingImplicitInstantiations();
983
984 // Restore the set of pending implicit instantiations.
985 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
986 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000987}
988
989/// \brief Instantiate the definition of the given variable from its
990/// template.
991///
Douglas Gregor7caa6822009-07-24 20:34:43 +0000992/// \param PointOfInstantiation the point at which the instantiation was
993/// required. Note that this is not precisely a "point of instantiation"
994/// for the function, but it's close.
995///
996/// \param Var the already-instantiated declaration of a static member
997/// variable of a class template specialization.
998///
999/// \param Recursive if true, recursively instantiates any functions that
1000/// are required by this instantiation.
1001void Sema::InstantiateStaticDataMemberDefinition(
1002 SourceLocation PointOfInstantiation,
1003 VarDecl *Var,
1004 bool Recursive) {
1005 if (Var->isInvalidDecl())
1006 return;
1007
1008 // Find the out-of-line definition of this static data member.
1009 // FIXME: Do we have to look for specializations separately?
1010 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1011 bool FoundOutOfLineDef = false;
1012 assert(Def && "This data member was not instantiated from a template?");
1013 assert(Def->isStaticDataMember() && "Not a static data member?");
1014 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
1015 RDEnd = Def->redecls_end();
1016 RD != RDEnd; ++RD) {
1017 if (RD->getLexicalDeclContext()->isFileContext()) {
1018 Def = *RD;
1019 FoundOutOfLineDef = true;
1020 }
1021 }
1022
1023 if (!FoundOutOfLineDef) {
1024 // We did not find an out-of-line definition of this static data member,
1025 // so we won't perform any instantiation. Rather, we rely on the user to
1026 // instantiate this definition (or provide a specialization for it) in
1027 // another translation unit.
1028 return;
1029 }
1030
1031 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1032 if (Inst)
1033 return;
1034
1035 // If we're performing recursive template instantiation, create our own
1036 // queue of pending implicit instantiations that we will instantiate later,
1037 // while we're still within our own instantiation context.
1038 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1039 if (Recursive)
1040 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1041
1042 // Enter the scope of this instantiation. We don't use
1043 // PushDeclContext because we don't have a scope.
1044 DeclContext *PreviousContext = CurContext;
1045 CurContext = Var->getDeclContext();
1046
1047#if 0
1048 // Instantiate the initializer of this static data member.
1049 OwningExprResult Init
1050 = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
1051 if (Init.isInvalid()) {
1052 // If instantiation of the initializer failed, mark the declaration invalid
1053 // and don't instantiate anything else that was triggered by this
1054 // instantiation.
1055 Var->setInvalidDecl();
1056
1057 // Restore the set of pending implicit instantiations.
1058 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1059
1060 return;
1061 }
1062
1063 // Type-check the initializer.
1064 if (Init.get())
1065 AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
1066 Def->hasCXXDirectInitializer());
1067 else
1068 ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
1069#else
John McCallce3ff2b2009-08-25 22:02:44 +00001070 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001071 getTemplateInstantiationArgs(Var)));
1072#endif
1073
1074 CurContext = PreviousContext;
1075
1076 if (Var) {
1077 DeclGroupRef DG(Var);
1078 Consumer.HandleTopLevelDecl(DG);
1079 }
1080
1081 if (Recursive) {
1082 // Instantiate any pending implicit instantiations found during the
1083 // instantiation of this template.
1084 PerformPendingImplicitInstantiations();
1085
1086 // Restore the set of pending implicit instantiations.
1087 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1088 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001089}
Douglas Gregor815215d2009-05-27 05:35:12 +00001090
1091static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1092 if (D->getKind() != Other->getKind())
1093 return false;
1094
1095 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001096 return Record->getInstantiatedFromMemberClass()->getCanonicalDecl()
1097 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001098
1099 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001100 return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl()
1101 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001102
Douglas Gregor8dbc3c62009-05-27 17:20:35 +00001103 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001104 return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl()
1105 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001106
Douglas Gregor7caa6822009-07-24 20:34:43 +00001107 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
1108 if (Var->isStaticDataMember())
1109 return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl()
1110 == D->getCanonicalDecl();
1111
Douglas Gregor815215d2009-05-27 05:35:12 +00001112 // FIXME: How can we find instantiations of anonymous unions?
1113
1114 return D->getDeclName() && isa<NamedDecl>(Other) &&
1115 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1116}
1117
1118template<typename ForwardIterator>
1119static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1120 NamedDecl *D,
1121 ForwardIterator first,
1122 ForwardIterator last) {
1123 for (; first != last; ++first)
1124 if (isInstantiationOf(Ctx, D, *first))
1125 return cast<NamedDecl>(*first);
1126
1127 return 0;
1128}
1129
Douglas Gregored961e72009-05-27 17:54:46 +00001130/// \brief Find the instantiation of the given declaration within the
1131/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001132///
1133/// This routine is intended to be used when \p D is a declaration
1134/// referenced from within a template, that needs to mapped into the
1135/// corresponding declaration within an instantiation. For example,
1136/// given:
1137///
1138/// \code
1139/// template<typename T>
1140/// struct X {
1141/// enum Kind {
1142/// KnownValue = sizeof(T)
1143/// };
1144///
1145/// bool getKind() const { return KnownValue; }
1146/// };
1147///
1148/// template struct X<int>;
1149/// \endcode
1150///
1151/// In the instantiation of X<int>::getKind(), we need to map the
1152/// EnumConstantDecl for KnownValue (which refers to
1153/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001154/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1155/// this mapping from within the instantiation of X<int>.
John McCallce3ff2b2009-08-25 22:02:44 +00001156NamedDecl * Sema::FindInstantiatedDecl(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +00001157 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001158 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1159 // D is a local of some kind. Look into the map of local
1160 // declarations to their instantiations.
1161 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1162 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001163
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001164 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
John McCallce3ff2b2009-08-25 22:02:44 +00001165 ParentDecl = FindInstantiatedDecl(ParentDecl);
Douglas Gregor815215d2009-05-27 05:35:12 +00001166 if (!ParentDecl)
1167 return 0;
1168
1169 ParentDC = cast<DeclContext>(ParentDecl);
1170 }
1171
Douglas Gregor815215d2009-05-27 05:35:12 +00001172 if (ParentDC != D->getDeclContext()) {
1173 // We performed some kind of instantiation in the parent context,
1174 // so now we need to look into the instantiated parent context to
1175 // find the instantiation of the declaration D.
1176 NamedDecl *Result = 0;
1177 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001178 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001179 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1180 } else {
1181 // Since we don't have a name for the entity we're looking for,
1182 // our only option is to walk through all of the declarations to
1183 // find that name. This will occur in a few cases:
1184 //
1185 // - anonymous struct/union within a template
1186 // - unnamed class/struct/union/enum within a template
1187 //
1188 // FIXME: Find a better way to find these instantiations!
1189 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001190 ParentDC->decls_begin(),
1191 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001192 }
1193 assert(Result && "Unable to find instantiation of declaration!");
1194 D = Result;
1195 }
1196
Douglas Gregor815215d2009-05-27 05:35:12 +00001197 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
Douglas Gregored961e72009-05-27 17:54:46 +00001198 if (ClassTemplateDecl *ClassTemplate
1199 = Record->getDescribedClassTemplate()) {
1200 // When the declaration D was parsed, it referred to the current
1201 // instantiation. Therefore, look through the current context,
1202 // which contains actual instantiations, to find the
1203 // instantiation of the "current instantiation" that D refers
1204 // to. Alternatively, we could just instantiate the
1205 // injected-class-name with the current template arguments, but
1206 // such an instantiation is far more expensive.
1207 for (DeclContext *DC = CurContext; !DC->isFileContext();
1208 DC = DC->getParent()) {
1209 if (ClassTemplateSpecializationDecl *Spec
1210 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001211 if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1212 == ClassTemplate->getCanonicalDecl())
Douglas Gregored961e72009-05-27 17:54:46 +00001213 return Spec;
1214 }
1215
1216 assert(false &&
1217 "Unable to find declaration for the current instantiation");
Douglas Gregor815215d2009-05-27 05:35:12 +00001218 }
1219
1220 return D;
1221}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001222
1223/// \brief Performs template instantiation for all implicit template
1224/// instantiations we have seen until this point.
1225void Sema::PerformPendingImplicitInstantiations() {
1226 while (!PendingImplicitInstantiations.empty()) {
1227 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001228 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001229
Douglas Gregor7caa6822009-07-24 20:34:43 +00001230 // Instantiate function definitions
1231 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001232 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001233 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001234 continue;
1235 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001236
Douglas Gregor7caa6822009-07-24 20:34:43 +00001237 // Instantiate static data member definitions.
1238 VarDecl *Var = cast<VarDecl>(Inst.first);
1239 assert(Var->isStaticDataMember() && "Not a static data member?");
1240 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001241 }
1242}