blob: 84e464aba300817f7eefa7e6371e075c4bb83c52 [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
Anders Carlssond8b285f2009-09-01 04:26:58 +0000248 if (!Field->getDeclName()) {
249 // Keep track of where this decl came from.
250 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
251 }
252
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000253 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000254 }
255
256 return Field;
257}
258
John McCall02cace72009-08-28 07:59:38 +0000259Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
260 FriendDecl::FriendUnion FU;
261
262 // Handle friend type expressions by simply substituting template
263 // parameters into the pattern type.
264 if (Type *Ty = D->getFriendType()) {
265 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
266 D->getLocation(), DeclarationName());
267 if (T.isNull()) return 0;
268
269 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
270 FU = T.getTypePtr();
271
272 // Handle everything else by appropriate substitution.
273 } else {
274 NamedDecl *ND = D->getFriendDecl();
275 assert(ND && "friend decl must be a decl or a type!");
276
277 Decl *NewND = Visit(ND);
278 if (!NewND) return 0;
279
280 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000281 }
John McCall02cace72009-08-28 07:59:38 +0000282
283 FriendDecl *FD =
284 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
285 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000286 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000287 Owner->addDecl(FD);
288 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000289}
290
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000291Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
292 Expr *AssertExpr = D->getAssertExpr();
293
Douglas Gregorac7610d2009-06-22 20:57:11 +0000294 // The expression in a static assertion is not potentially evaluated.
295 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
296
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000297 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000298 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000299 if (InstantiatedAssertExpr.isInvalid())
300 return 0;
301
Douglas Gregor43d9d922009-08-08 01:41:12 +0000302 OwningExprResult Message(SemaRef, D->getMessage());
303 D->getMessage()->Retain();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000304 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000305 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
306 move(InstantiatedAssertExpr),
307 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000308 return StaticAssert;
309}
310
311Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
312 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
313 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000314 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000315 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000316 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000317 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000318 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000319 Enum->startDefinition();
320
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000321 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000322
323 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000324 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
325 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000326 EC != ECEnd; ++EC) {
327 // The specified value for the enumerator.
328 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000329 if (Expr *UninstValue = EC->getInitExpr()) {
330 // The enumerator's value expression is not potentially evaluated.
331 EnterExpressionEvaluationContext Unevaluated(SemaRef,
332 Action::Unevaluated);
333
John McCallce3ff2b2009-08-25 22:02:44 +0000334 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000335 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000336
337 // Drop the initial value and continue.
338 bool isInvalid = false;
339 if (Value.isInvalid()) {
340 Value = SemaRef.Owned((Expr *)0);
341 isInvalid = true;
342 }
343
344 EnumConstantDecl *EnumConst
345 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
346 EC->getLocation(), EC->getIdentifier(),
347 move(Value));
348
349 if (isInvalid) {
350 if (EnumConst)
351 EnumConst->setInvalidDecl();
352 Enum->setInvalidDecl();
353 }
354
355 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000356 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000357 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000358 LastEnumConst = EnumConst;
359 }
360 }
361
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000362 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000363 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000364 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
365 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000366 &Enumerators[0], Enumerators.size(),
367 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000368
369 return Enum;
370}
371
Douglas Gregor6477b692009-03-25 15:04:13 +0000372Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
373 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
374 return 0;
375}
376
John McCalle29ba202009-08-20 01:44:21 +0000377Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
378 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000379 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Douglas Gregord60e1052009-08-27 16:57:43 +0000380 if (!InstParams)
381 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000382
383 CXXRecordDecl *Pattern = D->getTemplatedDecl();
384 CXXRecordDecl *RecordInst
385 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
386 Pattern->getLocation(), Pattern->getIdentifier(),
387 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
388
389 ClassTemplateDecl *Inst
390 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
391 D->getIdentifier(), InstParams, RecordInst, 0);
392 RecordInst->setDescribedClassTemplate(Inst);
393 Inst->setAccess(D->getAccess());
394 Inst->setInstantiatedFromMemberTemplate(D);
395
396 Owner->addDecl(Inst);
397 return Inst;
398}
399
Douglas Gregord60e1052009-08-27 16:57:43 +0000400Decl *
401TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
402 TemplateParameterList *TempParams = D->getTemplateParameters();
403 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
404 if (!InstParams)
405 return NULL;
406
407 // FIXME: Handle instantiation of nested function templates that aren't
408 // member function templates. This could happen inside a FriendDecl.
409 assert(isa<CXXMethodDecl>(D->getTemplatedDecl()));
410 CXXMethodDecl *InstMethod
411 = cast_or_null<CXXMethodDecl>(
412 VisitCXXMethodDecl(cast<CXXMethodDecl>(D->getTemplatedDecl()),
413 InstParams));
414 if (!InstMethod)
415 return 0;
416
417 // Link the instantiated function template declaration to the function
418 // template from which it was instantiated.
419 FunctionTemplateDecl *InstTemplate = InstMethod->getDescribedFunctionTemplate();
420 assert(InstTemplate && "VisitCXXMethodDecl didn't create a template!");
421 InstTemplate->setInstantiatedFromMemberTemplate(D);
422 Owner->addDecl(InstTemplate);
423 return InstTemplate;
424}
425
Douglas Gregord475b8d2009-03-25 21:17:03 +0000426Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
427 CXXRecordDecl *PrevDecl = 0;
428 if (D->isInjectedClassName())
429 PrevDecl = cast<CXXRecordDecl>(Owner);
430
431 CXXRecordDecl *Record
432 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000433 D->getLocation(), D->getIdentifier(),
434 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000435 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000436 // FIXME: Check against AS_none is an ugly hack to work around the issue that
437 // the tag decls introduced by friend class declarations don't have an access
438 // specifier. Remove once this area of the code gets sorted out.
439 if (D->getAccess() != AS_none)
440 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000441 if (!D->isInjectedClassName())
442 Record->setInstantiationOfMemberClass(D);
443
John McCall02cace72009-08-28 07:59:38 +0000444 // If the original function was part of a friend declaration,
445 // inherit its namespace state.
446 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
447 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
448
Anders Carlssond8b285f2009-09-01 04:26:58 +0000449 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
450
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000451 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000452 return Record;
453}
454
John McCall02cace72009-08-28 07:59:38 +0000455/// Normal class members are of more specific types and therefore
456/// don't make it here. This function serves two purposes:
457/// 1) instantiating function templates
458/// 2) substituting friend declarations
459/// FIXME: preserve function definitions in case #2
Douglas Gregore53060f2009-06-25 22:08:12 +0000460Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000461 // Check whether there is already a function template specialization for
462 // this declaration.
463 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
464 void *InsertPos = 0;
465 if (FunctionTemplate) {
466 llvm::FoldingSetNodeID ID;
467 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000468 TemplateArgs.getInnermost().getFlatArgumentList(),
469 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000470 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000471
472 FunctionTemplateSpecializationInfo *Info
473 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
474 InsertPos);
475
476 // If we already have a function template specialization, return it.
477 if (Info)
478 return Info->Function;
479 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000480
481 Sema::LocalInstantiationScope Scope(SemaRef);
482
483 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000484 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000485 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000486 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000487
Douglas Gregore53060f2009-06-25 22:08:12 +0000488 // Build the instantiated method declaration.
John McCall02cace72009-08-28 07:59:38 +0000489 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext());
490 FunctionDecl *Function =
491 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000492 D->getDeclName(), T, D->getDeclaratorInfo(),
493 D->getStorageClass(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000494 D->isInline(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000495 Function->setLexicalDeclContext(Owner);
496
Douglas Gregore53060f2009-06-25 22:08:12 +0000497 // Attach the parameters
498 for (unsigned P = 0; P < Params.size(); ++P)
499 Params[P]->setOwningFunction(Function);
500 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000501
502 // If the original function was part of a friend declaration,
503 // inherit its namespace state and add it to the owner.
504 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) {
505 bool WasDeclared = (FOK == Decl::FOK_Declared);
506 Function->setObjectOfFriendDecl(WasDeclared);
507 if (!Owner->isDependentContext())
John McCallab88d972009-08-31 22:39:49 +0000508 DC->makeDeclVisibleInContext(Function, /* Recoverable = */ false);
John McCallf181d8a2009-08-29 03:16:09 +0000509
510 Function->setInstantiationOfMemberFunction(D);
John McCall02cace72009-08-28 07:59:38 +0000511 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000512
513 if (InitFunctionInstantiation(Function, D))
514 Function->setInvalidDecl();
515
516 bool Redeclaration = false;
517 bool OverloadableAttrRequired = false;
518 NamedDecl *PrevDecl = 0;
519 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
520 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000521
Douglas Gregor127102b2009-06-29 20:59:39 +0000522 if (FunctionTemplate) {
523 // Record this function template specialization.
524 Function->setFunctionTemplateSpecialization(SemaRef.Context,
525 FunctionTemplate,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000526 &TemplateArgs.getInnermost(),
Douglas Gregor127102b2009-06-29 20:59:39 +0000527 InsertPos);
John McCallfd810b12009-08-14 02:03:10 +0000528 }
529
Douglas Gregore53060f2009-06-25 22:08:12 +0000530 return Function;
531}
532
Douglas Gregord60e1052009-08-27 16:57:43 +0000533Decl *
534TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
535 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000536 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
537 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000538 if (FunctionTemplate && !TemplateParams) {
539 // We are creating a function template specialization from a function
540 // template. Check whether there is already a function template
541 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000542 llvm::FoldingSetNodeID ID;
543 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000544 TemplateArgs.getInnermost().getFlatArgumentList(),
545 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000546 SemaRef.Context);
547
548 FunctionTemplateSpecializationInfo *Info
549 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
550 InsertPos);
551
552 // If we already have a function template specialization, return it.
553 if (Info)
554 return Info->Function;
555 }
556
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000557 Sema::LocalInstantiationScope Scope(SemaRef);
558
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000559 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000560 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000561 if (T.isNull())
562 return 0;
563
564 // Build the instantiated method declaration.
565 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000566 CXXMethodDecl *Method = 0;
567
568 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000569 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000570 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
571 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
572 SemaRef.Context.getCanonicalType(ClassTy));
573 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000574 Constructor->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000575 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000576 Constructor->getDeclaratorInfo(),
577 Constructor->isExplicit(),
578 Constructor->isInline(), false);
579 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
580 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
581 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
582 SemaRef.Context.getCanonicalType(ClassTy));
583 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
584 Destructor->getLocation(), Name,
585 T, Destructor->isInline(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000586 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
587 CanQualType ConvTy
588 = SemaRef.Context.getCanonicalType(
589 T->getAsFunctionType()->getResultType());
590 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
591 ConvTy);
592 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
593 Conversion->getLocation(), Name,
594 T, Conversion->getDeclaratorInfo(),
595 Conversion->isInline(),
596 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000597 } else {
598 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
599 D->getDeclName(), T, D->getDeclaratorInfo(),
600 D->isStatic(), D->isInline());
601 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000602
Douglas Gregord60e1052009-08-27 16:57:43 +0000603 if (TemplateParams) {
604 // Our resulting instantiation is actually a function template, since we
605 // are substituting only the outer template parameters. For example, given
606 //
607 // template<typename T>
608 // struct X {
609 // template<typename U> void f(T, U);
610 // };
611 //
612 // X<int> x;
613 //
614 // We are instantiating the member template "f" within X<int>, which means
615 // substituting int for T, but leaving "f" as a member function template.
616 // Build the function template itself.
617 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
618 Method->getLocation(),
619 Method->getDeclName(),
620 TemplateParams, Method);
621 if (D->isOutOfLine())
622 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
623 Method->setDescribedFunctionTemplate(FunctionTemplate);
624 } else if (!FunctionTemplate)
Douglas Gregor6b906862009-08-21 00:16:32 +0000625 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000626
Douglas Gregor7caa6822009-07-24 20:34:43 +0000627 // If we are instantiating a member function defined
628 // out-of-line, the instantiation will have the same lexical
629 // context (which will be a namespace scope) as the template.
630 if (D->isOutOfLine())
631 Method->setLexicalDeclContext(D->getLexicalDeclContext());
632
Douglas Gregor5545e162009-03-24 00:38:23 +0000633 // Attach the parameters
634 for (unsigned P = 0; P < Params.size(); ++P)
635 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000636 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000637
638 if (InitMethodInstantiation(Method, D))
639 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000640
Douglas Gregordec06662009-08-21 18:42:58 +0000641 NamedDecl *PrevDecl = 0;
642
Douglas Gregord60e1052009-08-27 16:57:43 +0000643 if (!FunctionTemplate || TemplateParams) {
Douglas Gregordec06662009-08-21 18:42:58 +0000644 PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
645 Sema::LookupOrdinaryName, true);
646
647 // In C++, the previous declaration we find might be a tag type
648 // (class or enum). In this case, the new declaration will hide the
649 // tag type. Note that this does does not apply if we're declaring a
650 // typedef (C++ [dcl.typedef]p4).
651 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
652 PrevDecl = 0;
653 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000654
Douglas Gregord60e1052009-08-27 16:57:43 +0000655 if (FunctionTemplate && !TemplateParams)
Douglas Gregor6b906862009-08-21 00:16:32 +0000656 // Record this function template specialization.
657 Method->setFunctionTemplateSpecialization(SemaRef.Context,
658 FunctionTemplate,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000659 &TemplateArgs.getInnermost(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000660 InsertPos);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000661
662 bool Redeclaration = false;
663 bool OverloadableAttrRequired = false;
664 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
665 /*FIXME:*/OverloadableAttrRequired);
666
667 if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
Douglas Gregordec06662009-08-21 18:42:58 +0000668 Owner->addDecl(Method);
669
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000670 return Method;
671}
672
Douglas Gregor615c5d42009-03-24 16:43:20 +0000673Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000674 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000675}
676
Douglas Gregor03b2b072009-03-24 00:15:49 +0000677Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000678 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000679}
680
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000681Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000682 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000683}
684
Douglas Gregor6477b692009-03-25 15:04:13 +0000685ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000686 QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000687 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000688 if (OrigT.isNull())
689 return 0;
690
691 QualType T = SemaRef.adjustParameterType(OrigT);
692
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000693 // Allocate the parameter
694 ParmVarDecl *Param = 0;
695 if (T == OrigT)
696 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000697 D->getIdentifier(), T, D->getDeclaratorInfo(),
698 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000699 else
700 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
701 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000702 T, D->getDeclaratorInfo(), OrigT,
703 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000704
Anders Carlsson9351c172009-08-25 03:18:48 +0000705 // Mark the default argument as being uninstantiated.
706 if (Expr *Arg = D->getDefaultArg())
707 Param->setUninstantiatedDefaultArg(Arg);
708
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000709 // Note: we don't try to instantiate function parameters until after
710 // we've instantiated the function's type. Therefore, we don't have
711 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000712 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000713 return Param;
714}
715
716Decl *
717TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
718 // Since parameter types can decay either before or after
719 // instantiation, we simply treat OriginalParmVarDecls as
720 // ParmVarDecls the same way, and create one or the other depending
721 // on what happens after template instantiation.
722 return VisitParmVarDecl(D);
723}
724
John McCalle29ba202009-08-20 01:44:21 +0000725Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
726 TemplateTypeParmDecl *D) {
727 // TODO: don't always clone when decls are refcounted.
728 const Type* T = D->getTypeForDecl();
729 assert(T->isTemplateTypeParmType());
730 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
731
732 TemplateTypeParmDecl *Inst =
733 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
734 TTPT->getDepth(), TTPT->getIndex(),
735 TTPT->getName(),
736 D->wasDeclaredWithTypename(),
737 D->isParameterPack());
738
739 if (D->hasDefaultArgument()) {
740 QualType DefaultPattern = D->getDefaultArgument();
741 QualType DefaultInst
John McCallce3ff2b2009-08-25 22:02:44 +0000742 = SemaRef.SubstType(DefaultPattern, TemplateArgs,
743 D->getDefaultArgumentLoc(),
744 D->getDeclName());
John McCalle29ba202009-08-20 01:44:21 +0000745
746 Inst->setDefaultArgument(DefaultInst,
747 D->getDefaultArgumentLoc(),
748 D->defaultArgumentWasInherited() /* preserve? */);
749 }
750
751 return Inst;
752}
753
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000754Decl *
755TemplateDeclInstantiator::VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D) {
756 NestedNameSpecifier *NNS =
757 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
758 D->getTargetNestedNameRange(),
759 TemplateArgs);
760 if (!NNS)
761 return 0;
762
763 CXXScopeSpec SS;
764 SS.setRange(D->getTargetNestedNameRange());
765 SS.setScopeRep(NNS);
766
Anders Carlsson0d8df782009-08-29 19:37:28 +0000767 NamedDecl *UD =
768 SemaRef.BuildUsingDeclaration(D->getLocation(), SS,
769 D->getTargetNameLocation(),
770 D->getTargetName(), 0, D->isTypeName());
771 if (UD)
772 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
773 D);
774 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000775}
776
John McCallce3ff2b2009-08-25 22:02:44 +0000777Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000778 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +0000779 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000780 return Instantiator.Visit(D);
781}
782
John McCalle29ba202009-08-20 01:44:21 +0000783/// \brief Instantiates a nested template parameter list in the current
784/// instantiation context.
785///
786/// \param L The parameter list to instantiate
787///
788/// \returns NULL if there was an error
789TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000790TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +0000791 // Get errors for all the parameters before bailing out.
792 bool Invalid = false;
793
794 unsigned N = L->size();
795 typedef llvm::SmallVector<Decl*,8> ParamVector;
796 ParamVector Params;
797 Params.reserve(N);
798 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
799 PI != PE; ++PI) {
800 Decl *D = Visit(*PI);
801 Params.push_back(D);
802 Invalid = Invalid || !D;
803 }
804
805 // Clean up if we had an error.
806 if (Invalid) {
807 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
808 PI != PE; ++PI)
809 if (*PI)
810 (*PI)->Destroy(SemaRef.Context);
811 return NULL;
812 }
813
814 TemplateParameterList *InstL
815 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
816 L->getLAngleLoc(), &Params.front(), N,
817 L->getRAngleLoc());
818 return InstL;
819}
820
John McCallce3ff2b2009-08-25 22:02:44 +0000821/// \brief Does substitution on the type of the given function, including
822/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +0000823///
John McCallce3ff2b2009-08-25 22:02:44 +0000824/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +0000825///
826/// \param Params the instantiated parameter declarations
827
John McCallce3ff2b2009-08-25 22:02:44 +0000828/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +0000829/// type if there was an error.
830QualType
John McCallce3ff2b2009-08-25 22:02:44 +0000831TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +0000832 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
833 bool InvalidDecl = false;
834
John McCallce3ff2b2009-08-25 22:02:44 +0000835 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +0000836 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000837 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000838 for (FunctionDecl::param_iterator P = D->param_begin(),
839 PEnd = D->param_end();
840 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000841 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000842 if (PInst->getType()->isVoidType()) {
843 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
844 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000845 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
846 PInst->getType(),
847 diag::err_abstract_type_in_decl,
848 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000849 PInst->setInvalidDecl();
850
851 Params.push_back(PInst);
852 ParamTys.push_back(PInst->getType());
853
854 if (PInst->isInvalidDecl())
855 InvalidDecl = true;
856 } else
857 InvalidDecl = true;
858 }
859
860 // FIXME: Deallocate dead declarations.
861 if (InvalidDecl)
862 return QualType();
863
864 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
865 assert(Proto && "Missing prototype?");
866 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +0000867 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
868 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +0000869 if (ResultType.isNull())
870 return QualType();
871
Jay Foadbeaaccd2009-05-21 09:52:38 +0000872 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000873 Proto->isVariadic(), Proto->getTypeQuals(),
874 D->getLocation(), D->getDeclName());
875}
876
Douglas Gregore53060f2009-06-25 22:08:12 +0000877/// \brief Initializes the common fields of an instantiation function
878/// declaration (New) from the corresponding fields of its template (Tmpl).
879///
880/// \returns true if there was an error
881bool
882TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
883 FunctionDecl *Tmpl) {
884 if (Tmpl->isDeleted())
885 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000886
887 // If we are performing substituting explicitly-specified template arguments
888 // or deduced template arguments into a function template and we reach this
889 // point, we are now past the point where SFINAE applies and have committed
890 // to keeping the new function template specialization. We therefore
891 // convert the active template instantiation for the function template
892 // into a template instantiation for this specific function template
893 // specialization, which is not a SFINAE context, so that we diagnose any
894 // further errors in the declaration itself.
895 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
896 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
897 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
898 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
899 if (FunctionTemplateDecl *FunTmpl
900 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
901 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
902 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000903 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000904 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
905 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
906 }
907 }
908
Douglas Gregore53060f2009-06-25 22:08:12 +0000909 return false;
910}
911
Douglas Gregor5545e162009-03-24 00:38:23 +0000912/// \brief Initializes common fields of an instantiated method
913/// declaration (New) from the corresponding fields of its template
914/// (Tmpl).
915///
916/// \returns true if there was an error
917bool
918TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
919 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000920 if (InitFunctionInstantiation(New, Tmpl))
921 return true;
922
Douglas Gregor5545e162009-03-24 00:38:23 +0000923 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
924 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000925 if (Tmpl->isVirtualAsWritten()) {
926 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000927 Record->setAggregate(false);
928 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000929 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000930 Record->setPolymorphic(true);
931 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000932 if (Tmpl->isPure()) {
933 New->setPure();
934 Record->setAbstract(true);
935 }
936
937 // FIXME: attributes
938 // FIXME: New needs a pointer to Tmpl
939 return false;
940}
Douglas Gregora58861f2009-05-13 20:28:22 +0000941
942/// \brief Instantiate the definition of the given function from its
943/// template.
944///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000945/// \param PointOfInstantiation the point at which the instantiation was
946/// required. Note that this is not precisely a "point of instantiation"
947/// for the function, but it's close.
948///
Douglas Gregora58861f2009-05-13 20:28:22 +0000949/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000950/// function template specialization or member function of a class template
951/// specialization.
952///
953/// \param Recursive if true, recursively instantiates any functions that
954/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000955void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000956 FunctionDecl *Function,
957 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000958 if (Function->isInvalidDecl())
959 return;
960
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000961 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000962
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000963 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000964 const FunctionDecl *PatternDecl = 0;
Douglas Gregor5ec178f2009-08-28 21:09:48 +0000965 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate()) {
966 while (Primary->getInstantiatedFromMemberTemplate())
967 Primary = Primary->getInstantiatedFromMemberTemplate();
968
Douglas Gregor1637be72009-06-26 00:10:03 +0000969 PatternDecl = Primary->getTemplatedDecl();
Douglas Gregor5ec178f2009-08-28 21:09:48 +0000970 } else
Douglas Gregor1637be72009-06-26 00:10:03 +0000971 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000972 Stmt *Pattern = 0;
973 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000974 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000975
976 if (!Pattern)
977 return;
978
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000979 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
980 if (Inst)
981 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000982
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000983 // If we're performing recursive template instantiation, create our own
984 // queue of pending implicit instantiations that we will instantiate later,
985 // while we're still within our own instantiation context.
986 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
987 if (Recursive)
988 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
989
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000990 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
991
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000992 // Introduce a new scope where local variable instantiations will be
993 // recorded.
994 LocalInstantiationScope Scope(*this);
995
996 // Introduce the instantiated function parameters into the local
997 // instantiation scope.
998 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
999 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1000 Function->getParamDecl(I));
1001
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001002 // Enter the scope of this instantiation. We don't use
1003 // PushDeclContext because we don't have a scope.
1004 DeclContext *PreviousContext = CurContext;
1005 CurContext = Function;
1006
Anders Carlsson09025312009-08-29 05:16:22 +00001007 MultiLevelTemplateArgumentList TemplateArgs =
1008 getTemplateInstantiationArgs(Function);
1009
1010 // If this is a constructor, instantiate the member initializers.
1011 if (const CXXConstructorDecl *Ctor =
1012 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1013 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1014 TemplateArgs);
1015 }
1016
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001017 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001018 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001019
1020 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
1021 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001022
1023 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001024
1025 DeclGroupRef DG(Function);
1026 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001027
1028 if (Recursive) {
1029 // Instantiate any pending implicit instantiations found during the
1030 // instantiation of this template.
1031 PerformPendingImplicitInstantiations();
1032
1033 // Restore the set of pending implicit instantiations.
1034 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1035 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001036}
1037
1038/// \brief Instantiate the definition of the given variable from its
1039/// template.
1040///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001041/// \param PointOfInstantiation the point at which the instantiation was
1042/// required. Note that this is not precisely a "point of instantiation"
1043/// for the function, but it's close.
1044///
1045/// \param Var the already-instantiated declaration of a static member
1046/// variable of a class template specialization.
1047///
1048/// \param Recursive if true, recursively instantiates any functions that
1049/// are required by this instantiation.
1050void Sema::InstantiateStaticDataMemberDefinition(
1051 SourceLocation PointOfInstantiation,
1052 VarDecl *Var,
1053 bool Recursive) {
1054 if (Var->isInvalidDecl())
1055 return;
1056
1057 // Find the out-of-line definition of this static data member.
1058 // FIXME: Do we have to look for specializations separately?
1059 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1060 bool FoundOutOfLineDef = false;
1061 assert(Def && "This data member was not instantiated from a template?");
1062 assert(Def->isStaticDataMember() && "Not a static data member?");
1063 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
1064 RDEnd = Def->redecls_end();
1065 RD != RDEnd; ++RD) {
1066 if (RD->getLexicalDeclContext()->isFileContext()) {
1067 Def = *RD;
1068 FoundOutOfLineDef = true;
1069 }
1070 }
1071
1072 if (!FoundOutOfLineDef) {
1073 // We did not find an out-of-line definition of this static data member,
1074 // so we won't perform any instantiation. Rather, we rely on the user to
1075 // instantiate this definition (or provide a specialization for it) in
1076 // another translation unit.
1077 return;
1078 }
1079
1080 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1081 if (Inst)
1082 return;
1083
1084 // If we're performing recursive template instantiation, create our own
1085 // queue of pending implicit instantiations that we will instantiate later,
1086 // while we're still within our own instantiation context.
1087 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1088 if (Recursive)
1089 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1090
1091 // Enter the scope of this instantiation. We don't use
1092 // PushDeclContext because we don't have a scope.
1093 DeclContext *PreviousContext = CurContext;
1094 CurContext = Var->getDeclContext();
1095
John McCallce3ff2b2009-08-25 22:02:44 +00001096 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001097 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001098
1099 CurContext = PreviousContext;
1100
1101 if (Var) {
1102 DeclGroupRef DG(Var);
1103 Consumer.HandleTopLevelDecl(DG);
1104 }
1105
1106 if (Recursive) {
1107 // Instantiate any pending implicit instantiations found during the
1108 // instantiation of this template.
1109 PerformPendingImplicitInstantiations();
1110
1111 // Restore the set of pending implicit instantiations.
1112 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1113 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001114}
Douglas Gregor815215d2009-05-27 05:35:12 +00001115
Anders Carlsson09025312009-08-29 05:16:22 +00001116void
1117Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1118 const CXXConstructorDecl *Tmpl,
1119 const MultiLevelTemplateArgumentList &TemplateArgs) {
1120
1121 llvm::SmallVector<MemInitTy*, 4> NewInits;
1122
1123 // Instantiate all the initializers.
1124 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
1125 InitsEnd = Tmpl->init_end(); Inits != InitsEnd; ++Inits) {
1126 CXXBaseOrMemberInitializer *Init = *Inits;
1127
1128 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
1129
1130 // Instantiate all the arguments.
1131 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1132 Args != ArgsEnd; ++Args) {
1133 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1134
1135 if (NewArg.isInvalid())
1136 New->setInvalidDecl();
1137 else
1138 NewArgs.push_back(NewArg.takeAs<Expr>());
1139 }
1140
1141 MemInitResult NewInit;
1142
1143 if (Init->isBaseInitializer()) {
Eli Friedmanc5573a82009-08-29 22:22:07 +00001144 QualType BaseType(Init->getBaseClass(), 0);
1145 BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(),
1146 New->getDeclName());
Eli Friedmanaf496ac2009-08-30 00:53:54 +00001147 BaseType = Context.getCanonicalType(BaseType);
Anders Carlsson09025312009-08-29 05:16:22 +00001148
1149 NewInit = BuildBaseInitializer(BaseType,
1150 (Expr **)NewArgs.data(),
1151 NewArgs.size(),
1152 Init->getSourceLocation(),
1153 Init->getRParenLoc(),
1154 New->getParent());
1155 } else if (Init->isMemberInitializer()) {
1156 FieldDecl *Member =
1157 cast<FieldDecl>(FindInstantiatedDecl(Init->getMember()));
1158
1159 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
1160 NewArgs.size(),
1161 Init->getSourceLocation(),
1162 Init->getRParenLoc());
1163 }
1164
1165 if (NewInit.isInvalid())
1166 New->setInvalidDecl();
1167 else {
1168 // FIXME: It would be nice if ASTOwningVector had a release function.
1169 NewArgs.take();
1170
1171 NewInits.push_back((MemInitTy *)NewInit.get());
1172 }
1173 }
1174
1175 // Assign all the initializers to the new constructor.
1176 ActOnMemInitializers(DeclPtrTy::make(New),
1177 /*FIXME: ColonLoc */
1178 SourceLocation(),
1179 NewInits.data(), NewInits.size());
1180}
1181
John McCall52a575a2009-08-29 08:11:13 +00001182// TODO: this could be templated if the various decl types used the
1183// same method name.
1184static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1185 ClassTemplateDecl *Instance) {
1186 Pattern = Pattern->getCanonicalDecl();
1187
1188 do {
1189 Instance = Instance->getCanonicalDecl();
1190 if (Pattern == Instance) return true;
1191 Instance = Instance->getInstantiatedFromMemberTemplate();
1192 } while (Instance);
1193
1194 return false;
1195}
1196
1197static bool isInstantiationOf(CXXRecordDecl *Pattern,
1198 CXXRecordDecl *Instance) {
1199 Pattern = Pattern->getCanonicalDecl();
1200
1201 do {
1202 Instance = Instance->getCanonicalDecl();
1203 if (Pattern == Instance) return true;
1204 Instance = Instance->getInstantiatedFromMemberClass();
1205 } while (Instance);
1206
1207 return false;
1208}
1209
1210static bool isInstantiationOf(FunctionDecl *Pattern,
1211 FunctionDecl *Instance) {
1212 Pattern = Pattern->getCanonicalDecl();
1213
1214 do {
1215 Instance = Instance->getCanonicalDecl();
1216 if (Pattern == Instance) return true;
1217 Instance = Instance->getInstantiatedFromMemberFunction();
1218 } while (Instance);
1219
1220 return false;
1221}
1222
1223static bool isInstantiationOf(EnumDecl *Pattern,
1224 EnumDecl *Instance) {
1225 Pattern = Pattern->getCanonicalDecl();
1226
1227 do {
1228 Instance = Instance->getCanonicalDecl();
1229 if (Pattern == Instance) return true;
1230 Instance = Instance->getInstantiatedFromMemberEnum();
1231 } while (Instance);
1232
1233 return false;
1234}
1235
Anders Carlsson0d8df782009-08-29 19:37:28 +00001236static bool isInstantiationOf(UnresolvedUsingDecl *Pattern,
1237 UsingDecl *Instance,
1238 ASTContext &C) {
1239 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1240}
1241
John McCall52a575a2009-08-29 08:11:13 +00001242static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1243 VarDecl *Instance) {
1244 assert(Instance->isStaticDataMember());
1245
1246 Pattern = Pattern->getCanonicalDecl();
1247
1248 do {
1249 Instance = Instance->getCanonicalDecl();
1250 if (Pattern == Instance) return true;
1251 Instance = Instance->getInstantiatedFromStaticDataMember();
1252 } while (Instance);
1253
1254 return false;
1255}
1256
Douglas Gregor815215d2009-05-27 05:35:12 +00001257static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001258 if (D->getKind() != Other->getKind()) {
1259 if (UnresolvedUsingDecl *UUD = dyn_cast<UnresolvedUsingDecl>(D)) {
1260 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1261 return isInstantiationOf(UUD, UD, Ctx);
1262 }
1263 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001264
Anders Carlsson0d8df782009-08-29 19:37:28 +00001265 return false;
1266 }
1267
John McCall52a575a2009-08-29 08:11:13 +00001268 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1269 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001270
John McCall52a575a2009-08-29 08:11:13 +00001271 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1272 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00001273
John McCall52a575a2009-08-29 08:11:13 +00001274 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1275 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00001276
Douglas Gregor7caa6822009-07-24 20:34:43 +00001277 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00001278 if (Var->isStaticDataMember())
1279 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1280
1281 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1282 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001283
Anders Carlssond8b285f2009-09-01 04:26:58 +00001284 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
1285 if (!Field->getDeclName()) {
1286 // This is an unnamed field.
1287 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
1288 cast<FieldDecl>(D);
1289 }
1290 }
1291
Douglas Gregor815215d2009-05-27 05:35:12 +00001292 return D->getDeclName() && isa<NamedDecl>(Other) &&
1293 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1294}
1295
1296template<typename ForwardIterator>
1297static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1298 NamedDecl *D,
1299 ForwardIterator first,
1300 ForwardIterator last) {
1301 for (; first != last; ++first)
1302 if (isInstantiationOf(Ctx, D, *first))
1303 return cast<NamedDecl>(*first);
1304
1305 return 0;
1306}
1307
John McCall02cace72009-08-28 07:59:38 +00001308/// \brief Finds the instantiation of the given declaration context
1309/// within the current instantiation.
1310///
1311/// \returns NULL if there was an error
1312DeclContext *Sema::FindInstantiatedContext(DeclContext* DC) {
1313 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
1314 Decl* ID = FindInstantiatedDecl(D);
1315 return cast_or_null<DeclContext>(ID);
1316 } else return DC;
1317}
1318
Douglas Gregored961e72009-05-27 17:54:46 +00001319/// \brief Find the instantiation of the given declaration within the
1320/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001321///
1322/// This routine is intended to be used when \p D is a declaration
1323/// referenced from within a template, that needs to mapped into the
1324/// corresponding declaration within an instantiation. For example,
1325/// given:
1326///
1327/// \code
1328/// template<typename T>
1329/// struct X {
1330/// enum Kind {
1331/// KnownValue = sizeof(T)
1332/// };
1333///
1334/// bool getKind() const { return KnownValue; }
1335/// };
1336///
1337/// template struct X<int>;
1338/// \endcode
1339///
1340/// In the instantiation of X<int>::getKind(), we need to map the
1341/// EnumConstantDecl for KnownValue (which refers to
1342/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001343/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1344/// this mapping from within the instantiation of X<int>.
John McCallce3ff2b2009-08-25 22:02:44 +00001345NamedDecl * Sema::FindInstantiatedDecl(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +00001346 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001347 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1348 // D is a local of some kind. Look into the map of local
1349 // declarations to their instantiations.
1350 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1351 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001352
John McCall52a575a2009-08-29 08:11:13 +00001353 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
1354 if (ClassTemplateDecl *ClassTemplate
1355 = Record->getDescribedClassTemplate()) {
1356 // When the declaration D was parsed, it referred to the current
1357 // instantiation. Therefore, look through the current context,
1358 // which contains actual instantiations, to find the
1359 // instantiation of the "current instantiation" that D refers
1360 // to. Alternatively, we could just instantiate the
1361 // injected-class-name with the current template arguments, but
1362 // such an instantiation is far more expensive.
1363 for (DeclContext *DC = CurContext; !DC->isFileContext();
1364 DC = DC->getParent()) {
1365 if (ClassTemplateSpecializationDecl *Spec
1366 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
1367 if (isInstantiationOf(ClassTemplate, Spec->getSpecializedTemplate()))
1368 return Spec;
1369 }
1370
1371 assert(false &&
1372 "Unable to find declaration for the current instantiation");
1373 }
1374
John McCall02cace72009-08-28 07:59:38 +00001375 ParentDC = FindInstantiatedContext(ParentDC);
1376 if (!ParentDC) return 0;
Douglas Gregor815215d2009-05-27 05:35:12 +00001377
Douglas Gregor815215d2009-05-27 05:35:12 +00001378 if (ParentDC != D->getDeclContext()) {
1379 // We performed some kind of instantiation in the parent context,
1380 // so now we need to look into the instantiated parent context to
1381 // find the instantiation of the declaration D.
1382 NamedDecl *Result = 0;
1383 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001384 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001385 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1386 } else {
1387 // Since we don't have a name for the entity we're looking for,
1388 // our only option is to walk through all of the declarations to
1389 // find that name. This will occur in a few cases:
1390 //
1391 // - anonymous struct/union within a template
1392 // - unnamed class/struct/union/enum within a template
1393 //
1394 // FIXME: Find a better way to find these instantiations!
1395 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001396 ParentDC->decls_begin(),
1397 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001398 }
John McCall52a575a2009-08-29 08:11:13 +00001399
Douglas Gregor815215d2009-05-27 05:35:12 +00001400 assert(Result && "Unable to find instantiation of declaration!");
1401 D = Result;
1402 }
1403
Douglas Gregor815215d2009-05-27 05:35:12 +00001404 return D;
1405}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001406
1407/// \brief Performs template instantiation for all implicit template
1408/// instantiations we have seen until this point.
1409void Sema::PerformPendingImplicitInstantiations() {
1410 while (!PendingImplicitInstantiations.empty()) {
1411 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001412 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001413
Douglas Gregor7caa6822009-07-24 20:34:43 +00001414 // Instantiate function definitions
1415 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001416 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001417 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001418 continue;
1419 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001420
Douglas Gregor7caa6822009-07-24 20:34:43 +00001421 // Instantiate static data member definitions.
1422 VarDecl *Var = cast<VarDecl>(Inst.first);
1423 assert(Var->isStaticDataMember() && "Not a static data member?");
1424 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001425 }
1426}