blob: ba5c7863668415878949cb9c22bee388912eac5a [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 Gregord6350ae2009-08-28 20:31:08 +000028 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor8dbc2692009-03-17 21:15:40 +000029
30 public:
31 typedef Sema::OwningExprResult OwningExprResult;
32
33 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000034 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000035 : 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 McCall02cace72009-08-28 07:59:38 +000048 Decl *VisitFriendDecl(FriendDecl *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);
Anders Carlsson0dde18e2009-08-28 15:18:15 +000061 Decl *VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D);
62
Douglas Gregor8dbc2692009-03-17 21:15:40 +000063 // Base case. FIXME: Remove once we can instantiate everything.
64 Decl *VisitDecl(Decl *) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000065 assert(false && "Template instantiation of unknown declaration kind!");
Douglas Gregor8dbc2692009-03-17 21:15:40 +000066 return 0;
67 }
Douglas Gregor5545e162009-03-24 00:38:23 +000068
John McCallfd810b12009-08-14 02:03:10 +000069 const LangOptions &getLangOptions() {
70 return SemaRef.getLangOptions();
71 }
72
Douglas Gregor5545e162009-03-24 00:38:23 +000073 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000074 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000075 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000076 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000077 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000078
79 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000080 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000081 };
82}
83
Douglas Gregor4f722be2009-03-25 15:45:12 +000084Decl *
85TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
86 assert(false && "Translation units cannot be instantiated");
87 return D;
88}
89
90Decl *
91TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
92 assert(false && "Namespaces cannot be instantiated");
93 return D;
94}
95
Douglas Gregor8dbc2692009-03-17 21:15:40 +000096Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
97 bool Invalid = false;
98 QualType T = D->getUnderlyingType();
99 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000100 T = SemaRef.SubstType(T, TemplateArgs,
101 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000102 if (T.isNull()) {
103 Invalid = true;
104 T = SemaRef.Context.IntTy;
105 }
106 }
107
108 // Create the new typedef
109 TypedefDecl *Typedef
110 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
111 D->getIdentifier(), T);
112 if (Invalid)
113 Typedef->setInvalidDecl();
114
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000115 Owner->addDecl(Typedef);
Douglas Gregorbc221632009-05-28 16:34:51 +0000116
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000117 return Typedef;
118}
119
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000120Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000121 // Do substitution on the type of the declaration
122 QualType T = SemaRef.SubstType(D->getType(), TemplateArgs,
123 D->getTypeSpecStartLoc(),
124 D->getDeclName());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000125 if (T.isNull())
126 return 0;
127
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000128 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000129 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
130 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000131 T, D->getDeclaratorInfo(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000132 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000133 Var->setThreadSpecified(D->isThreadSpecified());
134 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
135 Var->setDeclaredInCondition(D->isDeclaredInCondition());
136
Douglas Gregor7caa6822009-07-24 20:34:43 +0000137 // If we are instantiating a static data member defined
138 // out-of-line, the instantiation will have the same lexical
139 // context (which will be a namespace scope) as the template.
140 if (D->isOutOfLine())
141 Var->setLexicalDeclContext(D->getLexicalDeclContext());
142
Mike Stump390b4cc2009-05-16 07:39:55 +0000143 // FIXME: In theory, we could have a previous declaration for variables that
144 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000145 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000146 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000147
148 if (D->isOutOfLine()) {
149 D->getLexicalDeclContext()->addDecl(Var);
150 Owner->makeDeclVisibleInContext(Var);
151 } else {
152 Owner->addDecl(Var);
153 }
154
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000155 if (D->getInit()) {
156 OwningExprResult Init
John McCallce3ff2b2009-08-25 22:02:44 +0000157 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000158 if (Init.isInvalid())
159 Var->setInvalidDecl();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000160 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
161 // FIXME: We're faking all of the comma locations, which is suboptimal.
162 // Do we even need these comma locations?
163 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
164 if (PLE->getNumExprs() > 0) {
165 FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
166 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
167 Expr *E = PLE->getExpr(I)->Retain();
168 FakeCommaLocs.push_back(
169 SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
170 }
Douglas Gregore9f8eb62009-08-26 23:26:04 +0000171 PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000172 }
173
174 // Add the direct initializer to the declaration.
175 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
176 PLE->getLParenLoc(),
177 Sema::MultiExprArg(SemaRef,
178 (void**)PLE->getExprs(),
179 PLE->getNumExprs()),
180 FakeCommaLocs.data(),
181 PLE->getRParenLoc());
182
183 // When Init is destroyed, it will destroy the instantiated ParenListExpr;
184 // we've explicitly retained all of its subexpressions already.
185 } else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000186 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000187 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000188 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
189 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000190
Douglas Gregor7caa6822009-07-24 20:34:43 +0000191 // Link instantiations of static data members back to the template from
192 // which they were instantiated.
193 if (Var->isStaticDataMember())
194 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
195
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000196 return Var;
197}
198
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000199Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
200 bool Invalid = false;
201 QualType T = D->getType();
202 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000203 T = SemaRef.SubstType(T, TemplateArgs,
204 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000205 if (!T.isNull() && T->isFunctionType()) {
206 // C++ [temp.arg.type]p3:
207 // If a declaration acquires a function type through a type
208 // dependent on a template-parameter and this causes a
209 // declaration that does not use the syntactic form of a
210 // function declarator to have function type, the program is
211 // ill-formed.
212 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
213 << T;
214 T = QualType();
215 Invalid = true;
216 }
217 }
218
219 Expr *BitWidth = D->getBitWidth();
220 if (Invalid)
221 BitWidth = 0;
222 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000223 // The bit-width expression is not potentially evaluated.
224 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
225
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000226 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000227 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000228 if (InstantiatedBitWidth.isInvalid()) {
229 Invalid = true;
230 BitWidth = 0;
231 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000232 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000233 }
234
235 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000236 D->getDeclaratorInfo(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000237 cast<RecordDecl>(Owner),
238 D->getLocation(),
239 D->isMutable(),
240 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000241 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000242 D->getAccess(),
243 0);
244 if (Field) {
245 if (Invalid)
246 Field->setInvalidDecl();
247
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000248 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000249 }
250
251 return Field;
252}
253
John McCall02cace72009-08-28 07:59:38 +0000254Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
255 FriendDecl::FriendUnion FU;
256
257 // Handle friend type expressions by simply substituting template
258 // parameters into the pattern type.
259 if (Type *Ty = D->getFriendType()) {
260 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
261 D->getLocation(), DeclarationName());
262 if (T.isNull()) return 0;
263
264 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
265 FU = T.getTypePtr();
266
267 // Handle everything else by appropriate substitution.
268 } else {
269 NamedDecl *ND = D->getFriendDecl();
270 assert(ND && "friend decl must be a decl or a type!");
271
272 Decl *NewND = Visit(ND);
273 if (!NewND) return 0;
274
275 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000276 }
John McCall02cace72009-08-28 07:59:38 +0000277
278 FriendDecl *FD =
279 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
280 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000281 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000282 Owner->addDecl(FD);
283 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000284}
285
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000286Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
287 Expr *AssertExpr = D->getAssertExpr();
288
Douglas Gregorac7610d2009-06-22 20:57:11 +0000289 // The expression in a static assertion is not potentially evaluated.
290 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
291
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000292 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000293 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000294 if (InstantiatedAssertExpr.isInvalid())
295 return 0;
296
Douglas Gregor43d9d922009-08-08 01:41:12 +0000297 OwningExprResult Message(SemaRef, D->getMessage());
298 D->getMessage()->Retain();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000299 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000300 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
301 move(InstantiatedAssertExpr),
302 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000303 return StaticAssert;
304}
305
306Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
307 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
308 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000309 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000310 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000311 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000312 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000313 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000314 Enum->startDefinition();
315
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000316 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000317
318 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000319 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
320 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000321 EC != ECEnd; ++EC) {
322 // The specified value for the enumerator.
323 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000324 if (Expr *UninstValue = EC->getInitExpr()) {
325 // The enumerator's value expression is not potentially evaluated.
326 EnterExpressionEvaluationContext Unevaluated(SemaRef,
327 Action::Unevaluated);
328
John McCallce3ff2b2009-08-25 22:02:44 +0000329 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000330 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000331
332 // Drop the initial value and continue.
333 bool isInvalid = false;
334 if (Value.isInvalid()) {
335 Value = SemaRef.Owned((Expr *)0);
336 isInvalid = true;
337 }
338
339 EnumConstantDecl *EnumConst
340 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
341 EC->getLocation(), EC->getIdentifier(),
342 move(Value));
343
344 if (isInvalid) {
345 if (EnumConst)
346 EnumConst->setInvalidDecl();
347 Enum->setInvalidDecl();
348 }
349
350 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000351 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000352 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000353 LastEnumConst = EnumConst;
354 }
355 }
356
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000357 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000358 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000359 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
360 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000361 &Enumerators[0], Enumerators.size(),
362 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000363
364 return Enum;
365}
366
Douglas Gregor6477b692009-03-25 15:04:13 +0000367Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
368 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
369 return 0;
370}
371
John McCalle29ba202009-08-20 01:44:21 +0000372Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
373 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000374 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Douglas Gregord60e1052009-08-27 16:57:43 +0000375 if (!InstParams)
376 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000377
378 CXXRecordDecl *Pattern = D->getTemplatedDecl();
379 CXXRecordDecl *RecordInst
380 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
381 Pattern->getLocation(), Pattern->getIdentifier(),
382 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
383
384 ClassTemplateDecl *Inst
385 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
386 D->getIdentifier(), InstParams, RecordInst, 0);
387 RecordInst->setDescribedClassTemplate(Inst);
388 Inst->setAccess(D->getAccess());
389 Inst->setInstantiatedFromMemberTemplate(D);
390
391 Owner->addDecl(Inst);
392 return Inst;
393}
394
Douglas Gregord60e1052009-08-27 16:57:43 +0000395Decl *
396TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
397 TemplateParameterList *TempParams = D->getTemplateParameters();
398 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
399 if (!InstParams)
400 return NULL;
401
402 // FIXME: Handle instantiation of nested function templates that aren't
403 // member function templates. This could happen inside a FriendDecl.
404 assert(isa<CXXMethodDecl>(D->getTemplatedDecl()));
405 CXXMethodDecl *InstMethod
406 = cast_or_null<CXXMethodDecl>(
407 VisitCXXMethodDecl(cast<CXXMethodDecl>(D->getTemplatedDecl()),
408 InstParams));
409 if (!InstMethod)
410 return 0;
411
412 // Link the instantiated function template declaration to the function
413 // template from which it was instantiated.
414 FunctionTemplateDecl *InstTemplate = InstMethod->getDescribedFunctionTemplate();
415 assert(InstTemplate && "VisitCXXMethodDecl didn't create a template!");
416 InstTemplate->setInstantiatedFromMemberTemplate(D);
417 Owner->addDecl(InstTemplate);
418 return InstTemplate;
419}
420
Douglas Gregord475b8d2009-03-25 21:17:03 +0000421Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
422 CXXRecordDecl *PrevDecl = 0;
423 if (D->isInjectedClassName())
424 PrevDecl = cast<CXXRecordDecl>(Owner);
425
426 CXXRecordDecl *Record
427 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000428 D->getLocation(), D->getIdentifier(),
429 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000430 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000431 // FIXME: Check against AS_none is an ugly hack to work around the issue that
432 // the tag decls introduced by friend class declarations don't have an access
433 // specifier. Remove once this area of the code gets sorted out.
434 if (D->getAccess() != AS_none)
435 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000436 if (!D->isInjectedClassName())
437 Record->setInstantiationOfMemberClass(D);
438
John McCall02cace72009-08-28 07:59:38 +0000439 // If the original function was part of a friend declaration,
440 // inherit its namespace state.
441 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
442 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
443
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000444 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000445 return Record;
446}
447
John McCall02cace72009-08-28 07:59:38 +0000448/// Normal class members are of more specific types and therefore
449/// don't make it here. This function serves two purposes:
450/// 1) instantiating function templates
451/// 2) substituting friend declarations
452/// FIXME: preserve function definitions in case #2
Douglas Gregore53060f2009-06-25 22:08:12 +0000453Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000454 // Check whether there is already a function template specialization for
455 // this declaration.
456 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
457 void *InsertPos = 0;
458 if (FunctionTemplate) {
459 llvm::FoldingSetNodeID ID;
460 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000461 TemplateArgs.getInnermost().getFlatArgumentList(),
462 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000463 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000464
465 FunctionTemplateSpecializationInfo *Info
466 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
467 InsertPos);
468
469 // If we already have a function template specialization, return it.
470 if (Info)
471 return Info->Function;
472 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000473
474 Sema::LocalInstantiationScope Scope(SemaRef);
475
476 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000477 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000478 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000479 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000480
Douglas Gregore53060f2009-06-25 22:08:12 +0000481 // Build the instantiated method declaration.
John McCall02cace72009-08-28 07:59:38 +0000482 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext());
483 FunctionDecl *Function =
484 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000485 D->getDeclName(), T, D->getDeclaratorInfo(),
486 D->getStorageClass(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000487 D->isInline(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000488 Function->setLexicalDeclContext(Owner);
489
Douglas Gregore53060f2009-06-25 22:08:12 +0000490 // Attach the parameters
491 for (unsigned P = 0; P < Params.size(); ++P)
492 Params[P]->setOwningFunction(Function);
493 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000494
495 // If the original function was part of a friend declaration,
496 // inherit its namespace state and add it to the owner.
497 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) {
498 bool WasDeclared = (FOK == Decl::FOK_Declared);
499 Function->setObjectOfFriendDecl(WasDeclared);
500 if (!Owner->isDependentContext())
501 DC->makeDeclVisibleInContext(Function);
John McCallf181d8a2009-08-29 03:16:09 +0000502
503 Function->setInstantiationOfMemberFunction(D);
John McCall02cace72009-08-28 07:59:38 +0000504 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000505
506 if (InitFunctionInstantiation(Function, D))
507 Function->setInvalidDecl();
508
509 bool Redeclaration = false;
510 bool OverloadableAttrRequired = false;
511 NamedDecl *PrevDecl = 0;
512 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
513 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000514
Douglas Gregor127102b2009-06-29 20:59:39 +0000515 if (FunctionTemplate) {
516 // Record this function template specialization.
517 Function->setFunctionTemplateSpecialization(SemaRef.Context,
518 FunctionTemplate,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000519 &TemplateArgs.getInnermost(),
Douglas Gregor127102b2009-06-29 20:59:39 +0000520 InsertPos);
John McCallfd810b12009-08-14 02:03:10 +0000521 }
522
Douglas Gregore53060f2009-06-25 22:08:12 +0000523 return Function;
524}
525
Douglas Gregord60e1052009-08-27 16:57:43 +0000526Decl *
527TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
528 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000529 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
530 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000531 if (FunctionTemplate && !TemplateParams) {
532 // We are creating a function template specialization from a function
533 // template. Check whether there is already a function template
534 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000535 llvm::FoldingSetNodeID ID;
536 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000537 TemplateArgs.getInnermost().getFlatArgumentList(),
538 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000539 SemaRef.Context);
540
541 FunctionTemplateSpecializationInfo *Info
542 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
543 InsertPos);
544
545 // If we already have a function template specialization, return it.
546 if (Info)
547 return Info->Function;
548 }
549
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000550 Sema::LocalInstantiationScope Scope(SemaRef);
551
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000552 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000553 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000554 if (T.isNull())
555 return 0;
556
557 // Build the instantiated method declaration.
558 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000559 CXXMethodDecl *Method = 0;
560
561 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000562 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000563 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
564 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
565 SemaRef.Context.getCanonicalType(ClassTy));
566 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000567 Constructor->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000568 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000569 Constructor->getDeclaratorInfo(),
570 Constructor->isExplicit(),
571 Constructor->isInline(), false);
572 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
573 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
574 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
575 SemaRef.Context.getCanonicalType(ClassTy));
576 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
577 Destructor->getLocation(), Name,
578 T, Destructor->isInline(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000579 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
580 CanQualType ConvTy
581 = SemaRef.Context.getCanonicalType(
582 T->getAsFunctionType()->getResultType());
583 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
584 ConvTy);
585 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
586 Conversion->getLocation(), Name,
587 T, Conversion->getDeclaratorInfo(),
588 Conversion->isInline(),
589 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000590 } else {
591 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
592 D->getDeclName(), T, D->getDeclaratorInfo(),
593 D->isStatic(), D->isInline());
594 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000595
Douglas Gregord60e1052009-08-27 16:57:43 +0000596 if (TemplateParams) {
597 // Our resulting instantiation is actually a function template, since we
598 // are substituting only the outer template parameters. For example, given
599 //
600 // template<typename T>
601 // struct X {
602 // template<typename U> void f(T, U);
603 // };
604 //
605 // X<int> x;
606 //
607 // We are instantiating the member template "f" within X<int>, which means
608 // substituting int for T, but leaving "f" as a member function template.
609 // Build the function template itself.
610 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
611 Method->getLocation(),
612 Method->getDeclName(),
613 TemplateParams, Method);
614 if (D->isOutOfLine())
615 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
616 Method->setDescribedFunctionTemplate(FunctionTemplate);
617 } else if (!FunctionTemplate)
Douglas Gregor6b906862009-08-21 00:16:32 +0000618 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000619
Douglas Gregor7caa6822009-07-24 20:34:43 +0000620 // If we are instantiating a member function defined
621 // out-of-line, the instantiation will have the same lexical
622 // context (which will be a namespace scope) as the template.
623 if (D->isOutOfLine())
624 Method->setLexicalDeclContext(D->getLexicalDeclContext());
625
Douglas Gregor5545e162009-03-24 00:38:23 +0000626 // Attach the parameters
627 for (unsigned P = 0; P < Params.size(); ++P)
628 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000629 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000630
631 if (InitMethodInstantiation(Method, D))
632 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000633
Douglas Gregordec06662009-08-21 18:42:58 +0000634 NamedDecl *PrevDecl = 0;
635
Douglas Gregord60e1052009-08-27 16:57:43 +0000636 if (!FunctionTemplate || TemplateParams) {
Douglas Gregordec06662009-08-21 18:42:58 +0000637 PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
638 Sema::LookupOrdinaryName, true);
639
640 // In C++, the previous declaration we find might be a tag type
641 // (class or enum). In this case, the new declaration will hide the
642 // tag type. Note that this does does not apply if we're declaring a
643 // typedef (C++ [dcl.typedef]p4).
644 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
645 PrevDecl = 0;
646 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000647
Douglas Gregord60e1052009-08-27 16:57:43 +0000648 if (FunctionTemplate && !TemplateParams)
Douglas Gregor6b906862009-08-21 00:16:32 +0000649 // Record this function template specialization.
650 Method->setFunctionTemplateSpecialization(SemaRef.Context,
651 FunctionTemplate,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000652 &TemplateArgs.getInnermost(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000653 InsertPos);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000654
655 bool Redeclaration = false;
656 bool OverloadableAttrRequired = false;
657 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
658 /*FIXME:*/OverloadableAttrRequired);
659
660 if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
Douglas Gregordec06662009-08-21 18:42:58 +0000661 Owner->addDecl(Method);
662
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000663 return Method;
664}
665
Douglas Gregor615c5d42009-03-24 16:43:20 +0000666Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000667 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000668}
669
Douglas Gregor03b2b072009-03-24 00:15:49 +0000670Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000671 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000672}
673
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000674Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000675 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000676}
677
Douglas Gregor6477b692009-03-25 15:04:13 +0000678ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000679 QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000680 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000681 if (OrigT.isNull())
682 return 0;
683
684 QualType T = SemaRef.adjustParameterType(OrigT);
685
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000686 // Allocate the parameter
687 ParmVarDecl *Param = 0;
688 if (T == OrigT)
689 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000690 D->getIdentifier(), T, D->getDeclaratorInfo(),
691 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000692 else
693 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
694 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000695 T, D->getDeclaratorInfo(), OrigT,
696 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000697
Anders Carlsson9351c172009-08-25 03:18:48 +0000698 // Mark the default argument as being uninstantiated.
699 if (Expr *Arg = D->getDefaultArg())
700 Param->setUninstantiatedDefaultArg(Arg);
701
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000702 // Note: we don't try to instantiate function parameters until after
703 // we've instantiated the function's type. Therefore, we don't have
704 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000705 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000706 return Param;
707}
708
709Decl *
710TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
711 // Since parameter types can decay either before or after
712 // instantiation, we simply treat OriginalParmVarDecls as
713 // ParmVarDecls the same way, and create one or the other depending
714 // on what happens after template instantiation.
715 return VisitParmVarDecl(D);
716}
717
John McCalle29ba202009-08-20 01:44:21 +0000718Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
719 TemplateTypeParmDecl *D) {
720 // TODO: don't always clone when decls are refcounted.
721 const Type* T = D->getTypeForDecl();
722 assert(T->isTemplateTypeParmType());
723 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
724
725 TemplateTypeParmDecl *Inst =
726 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
727 TTPT->getDepth(), TTPT->getIndex(),
728 TTPT->getName(),
729 D->wasDeclaredWithTypename(),
730 D->isParameterPack());
731
732 if (D->hasDefaultArgument()) {
733 QualType DefaultPattern = D->getDefaultArgument();
734 QualType DefaultInst
John McCallce3ff2b2009-08-25 22:02:44 +0000735 = SemaRef.SubstType(DefaultPattern, TemplateArgs,
736 D->getDefaultArgumentLoc(),
737 D->getDeclName());
John McCalle29ba202009-08-20 01:44:21 +0000738
739 Inst->setDefaultArgument(DefaultInst,
740 D->getDefaultArgumentLoc(),
741 D->defaultArgumentWasInherited() /* preserve? */);
742 }
743
744 return Inst;
745}
746
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000747Decl *
748TemplateDeclInstantiator::VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D) {
749 NestedNameSpecifier *NNS =
750 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
751 D->getTargetNestedNameRange(),
752 TemplateArgs);
753 if (!NNS)
754 return 0;
755
756 CXXScopeSpec SS;
757 SS.setRange(D->getTargetNestedNameRange());
758 SS.setScopeRep(NNS);
759
760 return SemaRef.BuildUsingDeclaration(D->getLocation(), SS,
761 D->getTargetNameLocation(),
762 D->getTargetName(), 0, D->isTypeName());
763}
764
John McCallce3ff2b2009-08-25 22:02:44 +0000765Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000766 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +0000767 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000768 return Instantiator.Visit(D);
769}
770
John McCalle29ba202009-08-20 01:44:21 +0000771/// \brief Instantiates a nested template parameter list in the current
772/// instantiation context.
773///
774/// \param L The parameter list to instantiate
775///
776/// \returns NULL if there was an error
777TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000778TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +0000779 // Get errors for all the parameters before bailing out.
780 bool Invalid = false;
781
782 unsigned N = L->size();
783 typedef llvm::SmallVector<Decl*,8> ParamVector;
784 ParamVector Params;
785 Params.reserve(N);
786 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
787 PI != PE; ++PI) {
788 Decl *D = Visit(*PI);
789 Params.push_back(D);
790 Invalid = Invalid || !D;
791 }
792
793 // Clean up if we had an error.
794 if (Invalid) {
795 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
796 PI != PE; ++PI)
797 if (*PI)
798 (*PI)->Destroy(SemaRef.Context);
799 return NULL;
800 }
801
802 TemplateParameterList *InstL
803 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
804 L->getLAngleLoc(), &Params.front(), N,
805 L->getRAngleLoc());
806 return InstL;
807}
808
John McCallce3ff2b2009-08-25 22:02:44 +0000809/// \brief Does substitution on the type of the given function, including
810/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +0000811///
John McCallce3ff2b2009-08-25 22:02:44 +0000812/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +0000813///
814/// \param Params the instantiated parameter declarations
815
John McCallce3ff2b2009-08-25 22:02:44 +0000816/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +0000817/// type if there was an error.
818QualType
John McCallce3ff2b2009-08-25 22:02:44 +0000819TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +0000820 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
821 bool InvalidDecl = false;
822
John McCallce3ff2b2009-08-25 22:02:44 +0000823 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +0000824 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000825 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000826 for (FunctionDecl::param_iterator P = D->param_begin(),
827 PEnd = D->param_end();
828 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000829 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000830 if (PInst->getType()->isVoidType()) {
831 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
832 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000833 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
834 PInst->getType(),
835 diag::err_abstract_type_in_decl,
836 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000837 PInst->setInvalidDecl();
838
839 Params.push_back(PInst);
840 ParamTys.push_back(PInst->getType());
841
842 if (PInst->isInvalidDecl())
843 InvalidDecl = true;
844 } else
845 InvalidDecl = true;
846 }
847
848 // FIXME: Deallocate dead declarations.
849 if (InvalidDecl)
850 return QualType();
851
852 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
853 assert(Proto && "Missing prototype?");
854 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +0000855 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
856 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +0000857 if (ResultType.isNull())
858 return QualType();
859
Jay Foadbeaaccd2009-05-21 09:52:38 +0000860 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000861 Proto->isVariadic(), Proto->getTypeQuals(),
862 D->getLocation(), D->getDeclName());
863}
864
Douglas Gregore53060f2009-06-25 22:08:12 +0000865/// \brief Initializes the common fields of an instantiation function
866/// declaration (New) from the corresponding fields of its template (Tmpl).
867///
868/// \returns true if there was an error
869bool
870TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
871 FunctionDecl *Tmpl) {
872 if (Tmpl->isDeleted())
873 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000874
875 // If we are performing substituting explicitly-specified template arguments
876 // or deduced template arguments into a function template and we reach this
877 // point, we are now past the point where SFINAE applies and have committed
878 // to keeping the new function template specialization. We therefore
879 // convert the active template instantiation for the function template
880 // into a template instantiation for this specific function template
881 // specialization, which is not a SFINAE context, so that we diagnose any
882 // further errors in the declaration itself.
883 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
884 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
885 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
886 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
887 if (FunctionTemplateDecl *FunTmpl
888 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
889 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
890 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000891 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000892 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
893 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
894 }
895 }
896
Douglas Gregore53060f2009-06-25 22:08:12 +0000897 return false;
898}
899
Douglas Gregor5545e162009-03-24 00:38:23 +0000900/// \brief Initializes common fields of an instantiated method
901/// declaration (New) from the corresponding fields of its template
902/// (Tmpl).
903///
904/// \returns true if there was an error
905bool
906TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
907 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000908 if (InitFunctionInstantiation(New, Tmpl))
909 return true;
910
Douglas Gregor5545e162009-03-24 00:38:23 +0000911 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
912 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000913 if (Tmpl->isVirtualAsWritten()) {
914 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000915 Record->setAggregate(false);
916 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000917 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000918 Record->setPolymorphic(true);
919 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000920 if (Tmpl->isPure()) {
921 New->setPure();
922 Record->setAbstract(true);
923 }
924
925 // FIXME: attributes
926 // FIXME: New needs a pointer to Tmpl
927 return false;
928}
Douglas Gregora58861f2009-05-13 20:28:22 +0000929
930/// \brief Instantiate the definition of the given function from its
931/// template.
932///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000933/// \param PointOfInstantiation the point at which the instantiation was
934/// required. Note that this is not precisely a "point of instantiation"
935/// for the function, but it's close.
936///
Douglas Gregora58861f2009-05-13 20:28:22 +0000937/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000938/// function template specialization or member function of a class template
939/// specialization.
940///
941/// \param Recursive if true, recursively instantiates any functions that
942/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000943void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000944 FunctionDecl *Function,
945 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000946 if (Function->isInvalidDecl())
947 return;
948
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000949 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000950
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000951 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000952 const FunctionDecl *PatternDecl = 0;
Douglas Gregor5ec178f2009-08-28 21:09:48 +0000953 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate()) {
954 while (Primary->getInstantiatedFromMemberTemplate())
955 Primary = Primary->getInstantiatedFromMemberTemplate();
956
Douglas Gregor1637be72009-06-26 00:10:03 +0000957 PatternDecl = Primary->getTemplatedDecl();
Douglas Gregor5ec178f2009-08-28 21:09:48 +0000958 } else
Douglas Gregor1637be72009-06-26 00:10:03 +0000959 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000960 Stmt *Pattern = 0;
961 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000962 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000963
964 if (!Pattern)
965 return;
966
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000967 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
968 if (Inst)
969 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000970
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000971 // If we're performing recursive template instantiation, create our own
972 // queue of pending implicit instantiations that we will instantiate later,
973 // while we're still within our own instantiation context.
974 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
975 if (Recursive)
976 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
977
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000978 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
979
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000980 // Introduce a new scope where local variable instantiations will be
981 // recorded.
982 LocalInstantiationScope Scope(*this);
983
984 // Introduce the instantiated function parameters into the local
985 // instantiation scope.
986 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
987 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
988 Function->getParamDecl(I));
989
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000990 // Enter the scope of this instantiation. We don't use
991 // PushDeclContext because we don't have a scope.
992 DeclContext *PreviousContext = CurContext;
993 CurContext = Function;
994
Anders Carlsson09025312009-08-29 05:16:22 +0000995 MultiLevelTemplateArgumentList TemplateArgs =
996 getTemplateInstantiationArgs(Function);
997
998 // If this is a constructor, instantiate the member initializers.
999 if (const CXXConstructorDecl *Ctor =
1000 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1001 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1002 TemplateArgs);
1003 }
1004
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001005 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001006 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001007
1008 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
1009 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001010
1011 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001012
1013 DeclGroupRef DG(Function);
1014 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001015
1016 if (Recursive) {
1017 // Instantiate any pending implicit instantiations found during the
1018 // instantiation of this template.
1019 PerformPendingImplicitInstantiations();
1020
1021 // Restore the set of pending implicit instantiations.
1022 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1023 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001024}
1025
1026/// \brief Instantiate the definition of the given variable from its
1027/// template.
1028///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001029/// \param PointOfInstantiation the point at which the instantiation was
1030/// required. Note that this is not precisely a "point of instantiation"
1031/// for the function, but it's close.
1032///
1033/// \param Var the already-instantiated declaration of a static member
1034/// variable of a class template specialization.
1035///
1036/// \param Recursive if true, recursively instantiates any functions that
1037/// are required by this instantiation.
1038void Sema::InstantiateStaticDataMemberDefinition(
1039 SourceLocation PointOfInstantiation,
1040 VarDecl *Var,
1041 bool Recursive) {
1042 if (Var->isInvalidDecl())
1043 return;
1044
1045 // Find the out-of-line definition of this static data member.
1046 // FIXME: Do we have to look for specializations separately?
1047 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1048 bool FoundOutOfLineDef = false;
1049 assert(Def && "This data member was not instantiated from a template?");
1050 assert(Def->isStaticDataMember() && "Not a static data member?");
1051 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
1052 RDEnd = Def->redecls_end();
1053 RD != RDEnd; ++RD) {
1054 if (RD->getLexicalDeclContext()->isFileContext()) {
1055 Def = *RD;
1056 FoundOutOfLineDef = true;
1057 }
1058 }
1059
1060 if (!FoundOutOfLineDef) {
1061 // We did not find an out-of-line definition of this static data member,
1062 // so we won't perform any instantiation. Rather, we rely on the user to
1063 // instantiate this definition (or provide a specialization for it) in
1064 // another translation unit.
1065 return;
1066 }
1067
1068 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1069 if (Inst)
1070 return;
1071
1072 // If we're performing recursive template instantiation, create our own
1073 // queue of pending implicit instantiations that we will instantiate later,
1074 // while we're still within our own instantiation context.
1075 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1076 if (Recursive)
1077 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1078
1079 // Enter the scope of this instantiation. We don't use
1080 // PushDeclContext because we don't have a scope.
1081 DeclContext *PreviousContext = CurContext;
1082 CurContext = Var->getDeclContext();
1083
John McCallce3ff2b2009-08-25 22:02:44 +00001084 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001085 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001086
1087 CurContext = PreviousContext;
1088
1089 if (Var) {
1090 DeclGroupRef DG(Var);
1091 Consumer.HandleTopLevelDecl(DG);
1092 }
1093
1094 if (Recursive) {
1095 // Instantiate any pending implicit instantiations found during the
1096 // instantiation of this template.
1097 PerformPendingImplicitInstantiations();
1098
1099 // Restore the set of pending implicit instantiations.
1100 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1101 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001102}
Douglas Gregor815215d2009-05-27 05:35:12 +00001103
Anders Carlsson09025312009-08-29 05:16:22 +00001104void
1105Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1106 const CXXConstructorDecl *Tmpl,
1107 const MultiLevelTemplateArgumentList &TemplateArgs) {
1108
1109 llvm::SmallVector<MemInitTy*, 4> NewInits;
1110
1111 // Instantiate all the initializers.
1112 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
1113 InitsEnd = Tmpl->init_end(); Inits != InitsEnd; ++Inits) {
1114 CXXBaseOrMemberInitializer *Init = *Inits;
1115
1116 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
1117
1118 // Instantiate all the arguments.
1119 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1120 Args != ArgsEnd; ++Args) {
1121 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1122
1123 if (NewArg.isInvalid())
1124 New->setInvalidDecl();
1125 else
1126 NewArgs.push_back(NewArg.takeAs<Expr>());
1127 }
1128
1129 MemInitResult NewInit;
1130
1131 if (Init->isBaseInitializer()) {
1132 // FIXME: Type needs to be instantiated.
1133 QualType BaseType =
1134 Context.getCanonicalType(QualType(Init->getBaseClass(), 0));
1135
1136 NewInit = BuildBaseInitializer(BaseType,
1137 (Expr **)NewArgs.data(),
1138 NewArgs.size(),
1139 Init->getSourceLocation(),
1140 Init->getRParenLoc(),
1141 New->getParent());
1142 } else if (Init->isMemberInitializer()) {
1143 FieldDecl *Member =
1144 cast<FieldDecl>(FindInstantiatedDecl(Init->getMember()));
1145
1146 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
1147 NewArgs.size(),
1148 Init->getSourceLocation(),
1149 Init->getRParenLoc());
1150 }
1151
1152 if (NewInit.isInvalid())
1153 New->setInvalidDecl();
1154 else {
1155 // FIXME: It would be nice if ASTOwningVector had a release function.
1156 NewArgs.take();
1157
1158 NewInits.push_back((MemInitTy *)NewInit.get());
1159 }
1160 }
1161
1162 // Assign all the initializers to the new constructor.
1163 ActOnMemInitializers(DeclPtrTy::make(New),
1164 /*FIXME: ColonLoc */
1165 SourceLocation(),
1166 NewInits.data(), NewInits.size());
1167}
1168
Douglas Gregor815215d2009-05-27 05:35:12 +00001169static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1170 if (D->getKind() != Other->getKind())
1171 return false;
1172
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001173 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) {
1174 if (CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass())
1175 return Pattern->getCanonicalDecl() == D->getCanonicalDecl();
1176 else
1177 return false;
1178 }
1179
1180 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) {
1181 if (FunctionDecl *Pattern = Function->getInstantiatedFromMemberFunction())
1182 return Pattern->getCanonicalDecl() == D->getCanonicalDecl();
1183 else
1184 return false;
1185 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001186
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001187 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) {
1188 if (EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum())
1189 return Pattern->getCanonicalDecl() == D->getCanonicalDecl();
1190 else
1191 return false;
1192 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001193
Douglas Gregor7caa6822009-07-24 20:34:43 +00001194 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001195 if (Var->isStaticDataMember()) {
1196 if (VarDecl *Pattern = Var->getInstantiatedFromStaticDataMember())
1197 return Pattern->getCanonicalDecl() == D->getCanonicalDecl();
1198 else
1199 return false;
1200 }
1201
Douglas Gregor815215d2009-05-27 05:35:12 +00001202 // FIXME: How can we find instantiations of anonymous unions?
1203
1204 return D->getDeclName() && isa<NamedDecl>(Other) &&
1205 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1206}
1207
1208template<typename ForwardIterator>
1209static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1210 NamedDecl *D,
1211 ForwardIterator first,
1212 ForwardIterator last) {
1213 for (; first != last; ++first)
1214 if (isInstantiationOf(Ctx, D, *first))
1215 return cast<NamedDecl>(*first);
1216
1217 return 0;
1218}
1219
John McCall02cace72009-08-28 07:59:38 +00001220/// \brief Finds the instantiation of the given declaration context
1221/// within the current instantiation.
1222///
1223/// \returns NULL if there was an error
1224DeclContext *Sema::FindInstantiatedContext(DeclContext* DC) {
1225 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
1226 Decl* ID = FindInstantiatedDecl(D);
1227 return cast_or_null<DeclContext>(ID);
1228 } else return DC;
1229}
1230
Douglas Gregored961e72009-05-27 17:54:46 +00001231/// \brief Find the instantiation of the given declaration within the
1232/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001233///
1234/// This routine is intended to be used when \p D is a declaration
1235/// referenced from within a template, that needs to mapped into the
1236/// corresponding declaration within an instantiation. For example,
1237/// given:
1238///
1239/// \code
1240/// template<typename T>
1241/// struct X {
1242/// enum Kind {
1243/// KnownValue = sizeof(T)
1244/// };
1245///
1246/// bool getKind() const { return KnownValue; }
1247/// };
1248///
1249/// template struct X<int>;
1250/// \endcode
1251///
1252/// In the instantiation of X<int>::getKind(), we need to map the
1253/// EnumConstantDecl for KnownValue (which refers to
1254/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001255/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1256/// this mapping from within the instantiation of X<int>.
John McCallce3ff2b2009-08-25 22:02:44 +00001257NamedDecl * Sema::FindInstantiatedDecl(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +00001258 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001259 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1260 // D is a local of some kind. Look into the map of local
1261 // declarations to their instantiations.
1262 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1263 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001264
John McCall02cace72009-08-28 07:59:38 +00001265 ParentDC = FindInstantiatedContext(ParentDC);
1266 if (!ParentDC) return 0;
Douglas Gregor815215d2009-05-27 05:35:12 +00001267
Douglas Gregor815215d2009-05-27 05:35:12 +00001268 if (ParentDC != D->getDeclContext()) {
1269 // We performed some kind of instantiation in the parent context,
1270 // so now we need to look into the instantiated parent context to
1271 // find the instantiation of the declaration D.
1272 NamedDecl *Result = 0;
1273 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001274 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001275 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1276 } else {
1277 // Since we don't have a name for the entity we're looking for,
1278 // our only option is to walk through all of the declarations to
1279 // find that name. This will occur in a few cases:
1280 //
1281 // - anonymous struct/union within a template
1282 // - unnamed class/struct/union/enum within a template
1283 //
1284 // FIXME: Find a better way to find these instantiations!
1285 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001286 ParentDC->decls_begin(),
1287 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001288 }
1289 assert(Result && "Unable to find instantiation of declaration!");
1290 D = Result;
1291 }
1292
Douglas Gregor815215d2009-05-27 05:35:12 +00001293 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
Douglas Gregored961e72009-05-27 17:54:46 +00001294 if (ClassTemplateDecl *ClassTemplate
1295 = Record->getDescribedClassTemplate()) {
1296 // When the declaration D was parsed, it referred to the current
1297 // instantiation. Therefore, look through the current context,
1298 // which contains actual instantiations, to find the
1299 // instantiation of the "current instantiation" that D refers
1300 // to. Alternatively, we could just instantiate the
1301 // injected-class-name with the current template arguments, but
1302 // such an instantiation is far more expensive.
1303 for (DeclContext *DC = CurContext; !DC->isFileContext();
1304 DC = DC->getParent()) {
1305 if (ClassTemplateSpecializationDecl *Spec
1306 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001307 if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1308 == ClassTemplate->getCanonicalDecl())
Douglas Gregored961e72009-05-27 17:54:46 +00001309 return Spec;
1310 }
1311
1312 assert(false &&
1313 "Unable to find declaration for the current instantiation");
Douglas Gregor815215d2009-05-27 05:35:12 +00001314 }
1315
1316 return D;
1317}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001318
1319/// \brief Performs template instantiation for all implicit template
1320/// instantiations we have seen until this point.
1321void Sema::PerformPendingImplicitInstantiations() {
1322 while (!PendingImplicitInstantiations.empty()) {
1323 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001324 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001325
Douglas Gregor7caa6822009-07-24 20:34:43 +00001326 // Instantiate function definitions
1327 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001328 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001329 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001330 continue;
1331 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001332
Douglas Gregor7caa6822009-07-24 20:34:43 +00001333 // Instantiate static data member definitions.
1334 VarDecl *Var = cast<VarDecl>(Inst.first);
1335 assert(Var->isStaticDataMember() && "Not a static data member?");
1336 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001337 }
1338}