blob: 807115eb67017b188e887d55df5785af31044d1d [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"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000018#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000019#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000020#include "llvm/Support/Compiler.h"
21
22using namespace clang;
23
24namespace {
25 class VISIBILITY_HIDDEN TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000026 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000027 Sema &SemaRef;
28 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000029 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor8dbc2692009-03-17 21:15:40 +000030
31 public:
32 typedef Sema::OwningExprResult OwningExprResult;
33
34 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000035 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000036 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Douglas Gregor8dbc2692009-03-17 21:15:40 +000037
Mike Stump390b4cc2009-05-16 07:39:55 +000038 // FIXME: Once we get closer to completion, replace these manually-written
39 // declarations with automatically-generated ones from
40 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000041 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
42 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000043 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000044 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000045 Decl *VisitFieldDecl(FieldDecl *D);
46 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
47 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000048 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000049 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregore53060f2009-06-25 22:08:12 +000050 Decl *VisitFunctionDecl(FunctionDecl *D);
Douglas Gregord475b8d2009-03-25 21:17:03 +000051 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000052 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
53 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000054 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000055 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000056 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000057 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000058 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000059 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000060 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000061 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Anders Carlsson0dde18e2009-08-28 15:18:15 +000062 Decl *VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D);
63
Douglas Gregor8dbc2692009-03-17 21:15:40 +000064 // Base case. FIXME: Remove once we can instantiate everything.
65 Decl *VisitDecl(Decl *) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000066 assert(false && "Template instantiation of unknown declaration kind!");
Douglas Gregor8dbc2692009-03-17 21:15:40 +000067 return 0;
68 }
Douglas Gregor5545e162009-03-24 00:38:23 +000069
John McCallfd810b12009-08-14 02:03:10 +000070 const LangOptions &getLangOptions() {
71 return SemaRef.getLangOptions();
72 }
73
Douglas Gregor5545e162009-03-24 00:38:23 +000074 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000075 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000076 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000077 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000078 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000079
80 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000081 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000082 };
83}
84
Douglas Gregor4f722be2009-03-25 15:45:12 +000085Decl *
86TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
87 assert(false && "Translation units cannot be instantiated");
88 return D;
89}
90
91Decl *
92TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
93 assert(false && "Namespaces cannot be instantiated");
94 return D;
95}
96
Douglas Gregor8dbc2692009-03-17 21:15:40 +000097Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
98 bool Invalid = false;
99 QualType T = D->getUnderlyingType();
100 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000101 T = SemaRef.SubstType(T, TemplateArgs,
102 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000103 if (T.isNull()) {
104 Invalid = true;
105 T = SemaRef.Context.IntTy;
106 }
107 }
108
109 // Create the new typedef
110 TypedefDecl *Typedef
111 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
112 D->getIdentifier(), T);
113 if (Invalid)
114 Typedef->setInvalidDecl();
115
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000116 Owner->addDecl(Typedef);
Douglas Gregorbc221632009-05-28 16:34:51 +0000117
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000118 return Typedef;
119}
120
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000121Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000122 // Do substitution on the type of the declaration
123 QualType T = SemaRef.SubstType(D->getType(), TemplateArgs,
124 D->getTypeSpecStartLoc(),
125 D->getDeclName());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000126 if (T.isNull())
127 return 0;
128
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000129 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000130 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
131 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000132 T, D->getDeclaratorInfo(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000133 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000134 Var->setThreadSpecified(D->isThreadSpecified());
135 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
136 Var->setDeclaredInCondition(D->isDeclaredInCondition());
137
Douglas Gregor7caa6822009-07-24 20:34:43 +0000138 // If we are instantiating a static data member defined
139 // out-of-line, the instantiation will have the same lexical
140 // context (which will be a namespace scope) as the template.
141 if (D->isOutOfLine())
142 Var->setLexicalDeclContext(D->getLexicalDeclContext());
143
Mike Stump390b4cc2009-05-16 07:39:55 +0000144 // FIXME: In theory, we could have a previous declaration for variables that
145 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000146 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000147 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000148
149 if (D->isOutOfLine()) {
150 D->getLexicalDeclContext()->addDecl(Var);
151 Owner->makeDeclVisibleInContext(Var);
152 } else {
153 Owner->addDecl(Var);
154 }
155
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000156 if (D->getInit()) {
157 OwningExprResult Init
John McCallce3ff2b2009-08-25 22:02:44 +0000158 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000159 if (Init.isInvalid())
160 Var->setInvalidDecl();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000161 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
162 // FIXME: We're faking all of the comma locations, which is suboptimal.
163 // Do we even need these comma locations?
164 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
165 if (PLE->getNumExprs() > 0) {
166 FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
167 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
168 Expr *E = PLE->getExpr(I)->Retain();
169 FakeCommaLocs.push_back(
170 SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
171 }
Douglas Gregore9f8eb62009-08-26 23:26:04 +0000172 PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000173 }
174
175 // Add the direct initializer to the declaration.
176 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
177 PLE->getLParenLoc(),
178 Sema::MultiExprArg(SemaRef,
179 (void**)PLE->getExprs(),
180 PLE->getNumExprs()),
181 FakeCommaLocs.data(),
182 PLE->getRParenLoc());
183
184 // When Init is destroyed, it will destroy the instantiated ParenListExpr;
185 // we've explicitly retained all of its subexpressions already.
186 } else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000187 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000188 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000189 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
190 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000191
Douglas Gregor7caa6822009-07-24 20:34:43 +0000192 // Link instantiations of static data members back to the template from
193 // which they were instantiated.
194 if (Var->isStaticDataMember())
195 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
196
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000197 return Var;
198}
199
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000200Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
201 bool Invalid = false;
202 QualType T = D->getType();
203 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000204 T = SemaRef.SubstType(T, TemplateArgs,
205 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000206 if (!T.isNull() && T->isFunctionType()) {
207 // C++ [temp.arg.type]p3:
208 // If a declaration acquires a function type through a type
209 // dependent on a template-parameter and this causes a
210 // declaration that does not use the syntactic form of a
211 // function declarator to have function type, the program is
212 // ill-formed.
213 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
214 << T;
215 T = QualType();
216 Invalid = true;
217 }
218 }
219
220 Expr *BitWidth = D->getBitWidth();
221 if (Invalid)
222 BitWidth = 0;
223 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000224 // The bit-width expression is not potentially evaluated.
225 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
226
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000227 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000228 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000229 if (InstantiatedBitWidth.isInvalid()) {
230 Invalid = true;
231 BitWidth = 0;
232 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000233 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000234 }
235
236 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000237 D->getDeclaratorInfo(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000238 cast<RecordDecl>(Owner),
239 D->getLocation(),
240 D->isMutable(),
241 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000242 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000243 D->getAccess(),
244 0);
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000245 if (!Field)
246 return 0;
247
248 if (Invalid)
249 Field->setInvalidDecl();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000250
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000251 if (!Field->getDeclName()) {
252 // Keep track of where this decl came from.
253 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000254 }
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000255
256 Field->setImplicit(D->isImplicit());
257 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000258
259 return Field;
260}
261
John McCall02cace72009-08-28 07:59:38 +0000262Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
263 FriendDecl::FriendUnion FU;
264
265 // Handle friend type expressions by simply substituting template
266 // parameters into the pattern type.
267 if (Type *Ty = D->getFriendType()) {
268 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
269 D->getLocation(), DeclarationName());
270 if (T.isNull()) return 0;
271
272 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
273 FU = T.getTypePtr();
274
275 // Handle everything else by appropriate substitution.
276 } else {
277 NamedDecl *ND = D->getFriendDecl();
278 assert(ND && "friend decl must be a decl or a type!");
279
280 Decl *NewND = Visit(ND);
281 if (!NewND) return 0;
282
283 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000284 }
John McCall02cace72009-08-28 07:59:38 +0000285
286 FriendDecl *FD =
287 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
288 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000289 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000290 Owner->addDecl(FD);
291 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000292}
293
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000294Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
295 Expr *AssertExpr = D->getAssertExpr();
296
Douglas Gregorac7610d2009-06-22 20:57:11 +0000297 // The expression in a static assertion is not potentially evaluated.
298 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
299
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000300 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000301 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000302 if (InstantiatedAssertExpr.isInvalid())
303 return 0;
304
Douglas Gregor43d9d922009-08-08 01:41:12 +0000305 OwningExprResult Message(SemaRef, D->getMessage());
306 D->getMessage()->Retain();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000307 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000308 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
309 move(InstantiatedAssertExpr),
310 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000311 return StaticAssert;
312}
313
314Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
315 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
316 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000317 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000318 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000319 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000320 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000321 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000322 Enum->startDefinition();
323
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000324 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000325
326 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000327 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
328 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000329 EC != ECEnd; ++EC) {
330 // The specified value for the enumerator.
331 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000332 if (Expr *UninstValue = EC->getInitExpr()) {
333 // The enumerator's value expression is not potentially evaluated.
334 EnterExpressionEvaluationContext Unevaluated(SemaRef,
335 Action::Unevaluated);
336
John McCallce3ff2b2009-08-25 22:02:44 +0000337 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000338 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000339
340 // Drop the initial value and continue.
341 bool isInvalid = false;
342 if (Value.isInvalid()) {
343 Value = SemaRef.Owned((Expr *)0);
344 isInvalid = true;
345 }
346
347 EnumConstantDecl *EnumConst
348 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
349 EC->getLocation(), EC->getIdentifier(),
350 move(Value));
351
352 if (isInvalid) {
353 if (EnumConst)
354 EnumConst->setInvalidDecl();
355 Enum->setInvalidDecl();
356 }
357
358 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000359 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000360 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000361 LastEnumConst = EnumConst;
362 }
363 }
364
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000365 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000366 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000367 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
368 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000369 &Enumerators[0], Enumerators.size(),
370 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000371
372 return Enum;
373}
374
Douglas Gregor6477b692009-03-25 15:04:13 +0000375Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
376 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
377 return 0;
378}
379
John McCalle29ba202009-08-20 01:44:21 +0000380Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
381 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000382 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Douglas Gregord60e1052009-08-27 16:57:43 +0000383 if (!InstParams)
384 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000385
386 CXXRecordDecl *Pattern = D->getTemplatedDecl();
387 CXXRecordDecl *RecordInst
388 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
389 Pattern->getLocation(), Pattern->getIdentifier(),
390 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
391
392 ClassTemplateDecl *Inst
393 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
394 D->getIdentifier(), InstParams, RecordInst, 0);
395 RecordInst->setDescribedClassTemplate(Inst);
396 Inst->setAccess(D->getAccess());
397 Inst->setInstantiatedFromMemberTemplate(D);
398
399 Owner->addDecl(Inst);
400 return Inst;
401}
402
Douglas Gregord60e1052009-08-27 16:57:43 +0000403Decl *
404TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
405 TemplateParameterList *TempParams = D->getTemplateParameters();
406 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
407 if (!InstParams)
408 return NULL;
409
410 // FIXME: Handle instantiation of nested function templates that aren't
411 // member function templates. This could happen inside a FriendDecl.
412 assert(isa<CXXMethodDecl>(D->getTemplatedDecl()));
413 CXXMethodDecl *InstMethod
414 = cast_or_null<CXXMethodDecl>(
415 VisitCXXMethodDecl(cast<CXXMethodDecl>(D->getTemplatedDecl()),
416 InstParams));
417 if (!InstMethod)
418 return 0;
419
420 // Link the instantiated function template declaration to the function
421 // template from which it was instantiated.
422 FunctionTemplateDecl *InstTemplate = InstMethod->getDescribedFunctionTemplate();
423 assert(InstTemplate && "VisitCXXMethodDecl didn't create a template!");
424 InstTemplate->setInstantiatedFromMemberTemplate(D);
425 Owner->addDecl(InstTemplate);
426 return InstTemplate;
427}
428
Douglas Gregord475b8d2009-03-25 21:17:03 +0000429Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
430 CXXRecordDecl *PrevDecl = 0;
431 if (D->isInjectedClassName())
432 PrevDecl = cast<CXXRecordDecl>(Owner);
433
434 CXXRecordDecl *Record
435 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000436 D->getLocation(), D->getIdentifier(),
437 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000438 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000439 // FIXME: Check against AS_none is an ugly hack to work around the issue that
440 // the tag decls introduced by friend class declarations don't have an access
441 // specifier. Remove once this area of the code gets sorted out.
442 if (D->getAccess() != AS_none)
443 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000444 if (!D->isInjectedClassName())
445 Record->setInstantiationOfMemberClass(D);
446
John McCall02cace72009-08-28 07:59:38 +0000447 // If the original function was part of a friend declaration,
448 // inherit its namespace state.
449 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
450 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
451
Anders Carlssond8b285f2009-09-01 04:26:58 +0000452 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
453
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000454 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000455 return Record;
456}
457
John McCall02cace72009-08-28 07:59:38 +0000458/// Normal class members are of more specific types and therefore
459/// don't make it here. This function serves two purposes:
460/// 1) instantiating function templates
461/// 2) substituting friend declarations
462/// FIXME: preserve function definitions in case #2
Douglas Gregore53060f2009-06-25 22:08:12 +0000463Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000464 // Check whether there is already a function template specialization for
465 // this declaration.
466 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
467 void *InsertPos = 0;
468 if (FunctionTemplate) {
469 llvm::FoldingSetNodeID ID;
470 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000471 TemplateArgs.getInnermost().getFlatArgumentList(),
472 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000473 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000474
475 FunctionTemplateSpecializationInfo *Info
476 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
477 InsertPos);
478
479 // If we already have a function template specialization, return it.
480 if (Info)
481 return Info->Function;
482 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000483
484 Sema::LocalInstantiationScope Scope(SemaRef);
485
486 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000487 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000488 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000489 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000490
Douglas Gregore53060f2009-06-25 22:08:12 +0000491 // Build the instantiated method declaration.
John McCall02cace72009-08-28 07:59:38 +0000492 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext());
493 FunctionDecl *Function =
494 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000495 D->getDeclName(), T, D->getDeclaratorInfo(),
496 D->getStorageClass(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000497 D->isInline(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000498 Function->setLexicalDeclContext(Owner);
499
Douglas Gregore53060f2009-06-25 22:08:12 +0000500 // Attach the parameters
501 for (unsigned P = 0; P < Params.size(); ++P)
502 Params[P]->setOwningFunction(Function);
503 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000504
505 // If the original function was part of a friend declaration,
506 // inherit its namespace state and add it to the owner.
507 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) {
508 bool WasDeclared = (FOK == Decl::FOK_Declared);
509 Function->setObjectOfFriendDecl(WasDeclared);
510 if (!Owner->isDependentContext())
John McCallab88d972009-08-31 22:39:49 +0000511 DC->makeDeclVisibleInContext(Function, /* Recoverable = */ false);
John McCallf181d8a2009-08-29 03:16:09 +0000512
513 Function->setInstantiationOfMemberFunction(D);
John McCall02cace72009-08-28 07:59:38 +0000514 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000515
516 if (InitFunctionInstantiation(Function, D))
517 Function->setInvalidDecl();
518
519 bool Redeclaration = false;
520 bool OverloadableAttrRequired = false;
521 NamedDecl *PrevDecl = 0;
522 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
523 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000524
Douglas Gregor127102b2009-06-29 20:59:39 +0000525 if (FunctionTemplate) {
526 // Record this function template specialization.
527 Function->setFunctionTemplateSpecialization(SemaRef.Context,
528 FunctionTemplate,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000529 &TemplateArgs.getInnermost(),
Douglas Gregor127102b2009-06-29 20:59:39 +0000530 InsertPos);
John McCallfd810b12009-08-14 02:03:10 +0000531 }
532
Douglas Gregore53060f2009-06-25 22:08:12 +0000533 return Function;
534}
535
Douglas Gregord60e1052009-08-27 16:57:43 +0000536Decl *
537TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
538 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000539 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
540 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000541 if (FunctionTemplate && !TemplateParams) {
542 // We are creating a function template specialization from a function
543 // template. Check whether there is already a function template
544 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000545 llvm::FoldingSetNodeID ID;
546 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000547 TemplateArgs.getInnermost().getFlatArgumentList(),
548 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000549 SemaRef.Context);
550
551 FunctionTemplateSpecializationInfo *Info
552 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
553 InsertPos);
554
555 // If we already have a function template specialization, return it.
556 if (Info)
557 return Info->Function;
558 }
559
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000560 Sema::LocalInstantiationScope Scope(SemaRef);
561
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000562 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000563 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000564 if (T.isNull())
565 return 0;
566
567 // Build the instantiated method declaration.
568 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000569 CXXMethodDecl *Method = 0;
570
571 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000572 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000573 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
574 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
575 SemaRef.Context.getCanonicalType(ClassTy));
576 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000577 Constructor->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000578 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000579 Constructor->getDeclaratorInfo(),
580 Constructor->isExplicit(),
581 Constructor->isInline(), false);
582 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
583 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
584 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
585 SemaRef.Context.getCanonicalType(ClassTy));
586 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
587 Destructor->getLocation(), Name,
588 T, Destructor->isInline(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000589 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
590 CanQualType ConvTy
591 = SemaRef.Context.getCanonicalType(
592 T->getAsFunctionType()->getResultType());
593 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
594 ConvTy);
595 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
596 Conversion->getLocation(), Name,
597 T, Conversion->getDeclaratorInfo(),
598 Conversion->isInline(),
599 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000600 } else {
601 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
602 D->getDeclName(), T, D->getDeclaratorInfo(),
603 D->isStatic(), D->isInline());
604 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000605
Douglas Gregord60e1052009-08-27 16:57:43 +0000606 if (TemplateParams) {
607 // Our resulting instantiation is actually a function template, since we
608 // are substituting only the outer template parameters. For example, given
609 //
610 // template<typename T>
611 // struct X {
612 // template<typename U> void f(T, U);
613 // };
614 //
615 // X<int> x;
616 //
617 // We are instantiating the member template "f" within X<int>, which means
618 // substituting int for T, but leaving "f" as a member function template.
619 // Build the function template itself.
620 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
621 Method->getLocation(),
622 Method->getDeclName(),
623 TemplateParams, Method);
624 if (D->isOutOfLine())
625 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
626 Method->setDescribedFunctionTemplate(FunctionTemplate);
627 } else if (!FunctionTemplate)
Douglas Gregor6b906862009-08-21 00:16:32 +0000628 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000629
Douglas Gregor7caa6822009-07-24 20:34:43 +0000630 // If we are instantiating a member function defined
631 // out-of-line, the instantiation will have the same lexical
632 // context (which will be a namespace scope) as the template.
633 if (D->isOutOfLine())
634 Method->setLexicalDeclContext(D->getLexicalDeclContext());
635
Douglas Gregor5545e162009-03-24 00:38:23 +0000636 // Attach the parameters
637 for (unsigned P = 0; P < Params.size(); ++P)
638 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000639 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000640
641 if (InitMethodInstantiation(Method, D))
642 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000643
Douglas Gregordec06662009-08-21 18:42:58 +0000644 NamedDecl *PrevDecl = 0;
645
Douglas Gregord60e1052009-08-27 16:57:43 +0000646 if (!FunctionTemplate || TemplateParams) {
Douglas Gregordec06662009-08-21 18:42:58 +0000647 PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
648 Sema::LookupOrdinaryName, true);
649
650 // In C++, the previous declaration we find might be a tag type
651 // (class or enum). In this case, the new declaration will hide the
652 // tag type. Note that this does does not apply if we're declaring a
653 // typedef (C++ [dcl.typedef]p4).
654 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
655 PrevDecl = 0;
656 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000657
Douglas Gregord60e1052009-08-27 16:57:43 +0000658 if (FunctionTemplate && !TemplateParams)
Douglas Gregor6b906862009-08-21 00:16:32 +0000659 // Record this function template specialization.
660 Method->setFunctionTemplateSpecialization(SemaRef.Context,
661 FunctionTemplate,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000662 &TemplateArgs.getInnermost(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000663 InsertPos);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000664
665 bool Redeclaration = false;
666 bool OverloadableAttrRequired = false;
667 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
668 /*FIXME:*/OverloadableAttrRequired);
669
670 if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
Douglas Gregordec06662009-08-21 18:42:58 +0000671 Owner->addDecl(Method);
672
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000673 return Method;
674}
675
Douglas Gregor615c5d42009-03-24 16:43:20 +0000676Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000677 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000678}
679
Douglas Gregor03b2b072009-03-24 00:15:49 +0000680Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000681 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000682}
683
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000684Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000685 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000686}
687
Douglas Gregor6477b692009-03-25 15:04:13 +0000688ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000689 QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000690 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000691 if (OrigT.isNull())
692 return 0;
693
694 QualType T = SemaRef.adjustParameterType(OrigT);
695
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000696 // Allocate the parameter
697 ParmVarDecl *Param = 0;
698 if (T == OrigT)
699 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000700 D->getIdentifier(), T, D->getDeclaratorInfo(),
701 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000702 else
703 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
704 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000705 T, D->getDeclaratorInfo(), OrigT,
706 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000707
Anders Carlsson9351c172009-08-25 03:18:48 +0000708 // Mark the default argument as being uninstantiated.
709 if (Expr *Arg = D->getDefaultArg())
710 Param->setUninstantiatedDefaultArg(Arg);
711
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000712 // Note: we don't try to instantiate function parameters until after
713 // we've instantiated the function's type. Therefore, we don't have
714 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000715 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000716 return Param;
717}
718
719Decl *
720TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
721 // Since parameter types can decay either before or after
722 // instantiation, we simply treat OriginalParmVarDecls as
723 // ParmVarDecls the same way, and create one or the other depending
724 // on what happens after template instantiation.
725 return VisitParmVarDecl(D);
726}
727
John McCalle29ba202009-08-20 01:44:21 +0000728Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
729 TemplateTypeParmDecl *D) {
730 // TODO: don't always clone when decls are refcounted.
731 const Type* T = D->getTypeForDecl();
732 assert(T->isTemplateTypeParmType());
733 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
734
735 TemplateTypeParmDecl *Inst =
736 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
737 TTPT->getDepth(), TTPT->getIndex(),
738 TTPT->getName(),
739 D->wasDeclaredWithTypename(),
740 D->isParameterPack());
741
742 if (D->hasDefaultArgument()) {
743 QualType DefaultPattern = D->getDefaultArgument();
744 QualType DefaultInst
John McCallce3ff2b2009-08-25 22:02:44 +0000745 = SemaRef.SubstType(DefaultPattern, TemplateArgs,
746 D->getDefaultArgumentLoc(),
747 D->getDeclName());
John McCalle29ba202009-08-20 01:44:21 +0000748
749 Inst->setDefaultArgument(DefaultInst,
750 D->getDefaultArgumentLoc(),
751 D->defaultArgumentWasInherited() /* preserve? */);
752 }
753
754 return Inst;
755}
756
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000757Decl *
758TemplateDeclInstantiator::VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D) {
759 NestedNameSpecifier *NNS =
760 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
761 D->getTargetNestedNameRange(),
762 TemplateArgs);
763 if (!NNS)
764 return 0;
765
766 CXXScopeSpec SS;
767 SS.setRange(D->getTargetNestedNameRange());
768 SS.setScopeRep(NNS);
769
Anders Carlsson0d8df782009-08-29 19:37:28 +0000770 NamedDecl *UD =
771 SemaRef.BuildUsingDeclaration(D->getLocation(), SS,
772 D->getTargetNameLocation(),
773 D->getTargetName(), 0, D->isTypeName());
774 if (UD)
775 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
776 D);
777 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000778}
779
John McCallce3ff2b2009-08-25 22:02:44 +0000780Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000781 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +0000782 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000783 return Instantiator.Visit(D);
784}
785
John McCalle29ba202009-08-20 01:44:21 +0000786/// \brief Instantiates a nested template parameter list in the current
787/// instantiation context.
788///
789/// \param L The parameter list to instantiate
790///
791/// \returns NULL if there was an error
792TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000793TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +0000794 // Get errors for all the parameters before bailing out.
795 bool Invalid = false;
796
797 unsigned N = L->size();
798 typedef llvm::SmallVector<Decl*,8> ParamVector;
799 ParamVector Params;
800 Params.reserve(N);
801 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
802 PI != PE; ++PI) {
803 Decl *D = Visit(*PI);
804 Params.push_back(D);
805 Invalid = Invalid || !D;
806 }
807
808 // Clean up if we had an error.
809 if (Invalid) {
810 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
811 PI != PE; ++PI)
812 if (*PI)
813 (*PI)->Destroy(SemaRef.Context);
814 return NULL;
815 }
816
817 TemplateParameterList *InstL
818 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
819 L->getLAngleLoc(), &Params.front(), N,
820 L->getRAngleLoc());
821 return InstL;
822}
823
John McCallce3ff2b2009-08-25 22:02:44 +0000824/// \brief Does substitution on the type of the given function, including
825/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +0000826///
John McCallce3ff2b2009-08-25 22:02:44 +0000827/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +0000828///
829/// \param Params the instantiated parameter declarations
830
John McCallce3ff2b2009-08-25 22:02:44 +0000831/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +0000832/// type if there was an error.
833QualType
John McCallce3ff2b2009-08-25 22:02:44 +0000834TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +0000835 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
836 bool InvalidDecl = false;
837
John McCallce3ff2b2009-08-25 22:02:44 +0000838 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +0000839 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000840 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000841 for (FunctionDecl::param_iterator P = D->param_begin(),
842 PEnd = D->param_end();
843 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000844 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000845 if (PInst->getType()->isVoidType()) {
846 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
847 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000848 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
849 PInst->getType(),
850 diag::err_abstract_type_in_decl,
851 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000852 PInst->setInvalidDecl();
853
854 Params.push_back(PInst);
855 ParamTys.push_back(PInst->getType());
856
857 if (PInst->isInvalidDecl())
858 InvalidDecl = true;
859 } else
860 InvalidDecl = true;
861 }
862
863 // FIXME: Deallocate dead declarations.
864 if (InvalidDecl)
865 return QualType();
866
867 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
868 assert(Proto && "Missing prototype?");
869 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +0000870 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
871 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +0000872 if (ResultType.isNull())
873 return QualType();
874
Jay Foadbeaaccd2009-05-21 09:52:38 +0000875 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000876 Proto->isVariadic(), Proto->getTypeQuals(),
877 D->getLocation(), D->getDeclName());
878}
879
Douglas Gregore53060f2009-06-25 22:08:12 +0000880/// \brief Initializes the common fields of an instantiation function
881/// declaration (New) from the corresponding fields of its template (Tmpl).
882///
883/// \returns true if there was an error
884bool
885TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
886 FunctionDecl *Tmpl) {
887 if (Tmpl->isDeleted())
888 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000889
890 // If we are performing substituting explicitly-specified template arguments
891 // or deduced template arguments into a function template and we reach this
892 // point, we are now past the point where SFINAE applies and have committed
893 // to keeping the new function template specialization. We therefore
894 // convert the active template instantiation for the function template
895 // into a template instantiation for this specific function template
896 // specialization, which is not a SFINAE context, so that we diagnose any
897 // further errors in the declaration itself.
898 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
899 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
900 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
901 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
902 if (FunctionTemplateDecl *FunTmpl
903 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
904 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
905 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000906 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000907 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
908 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
909 }
910 }
911
Douglas Gregore53060f2009-06-25 22:08:12 +0000912 return false;
913}
914
Douglas Gregor5545e162009-03-24 00:38:23 +0000915/// \brief Initializes common fields of an instantiated method
916/// declaration (New) from the corresponding fields of its template
917/// (Tmpl).
918///
919/// \returns true if there was an error
920bool
921TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
922 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000923 if (InitFunctionInstantiation(New, Tmpl))
924 return true;
925
Douglas Gregor5545e162009-03-24 00:38:23 +0000926 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
927 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000928 if (Tmpl->isVirtualAsWritten()) {
929 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000930 Record->setAggregate(false);
931 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000932 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000933 Record->setPolymorphic(true);
934 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000935 if (Tmpl->isPure()) {
936 New->setPure();
937 Record->setAbstract(true);
938 }
939
940 // FIXME: attributes
941 // FIXME: New needs a pointer to Tmpl
942 return false;
943}
Douglas Gregora58861f2009-05-13 20:28:22 +0000944
945/// \brief Instantiate the definition of the given function from its
946/// template.
947///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000948/// \param PointOfInstantiation the point at which the instantiation was
949/// required. Note that this is not precisely a "point of instantiation"
950/// for the function, but it's close.
951///
Douglas Gregora58861f2009-05-13 20:28:22 +0000952/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000953/// function template specialization or member function of a class template
954/// specialization.
955///
956/// \param Recursive if true, recursively instantiates any functions that
957/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000958void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000959 FunctionDecl *Function,
960 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000961 if (Function->isInvalidDecl())
962 return;
963
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000964 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000965
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000966 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000967 const FunctionDecl *PatternDecl = 0;
Douglas Gregor5ec178f2009-08-28 21:09:48 +0000968 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate()) {
969 while (Primary->getInstantiatedFromMemberTemplate())
970 Primary = Primary->getInstantiatedFromMemberTemplate();
971
Douglas Gregor1637be72009-06-26 00:10:03 +0000972 PatternDecl = Primary->getTemplatedDecl();
Douglas Gregor5ec178f2009-08-28 21:09:48 +0000973 } else
Douglas Gregor1637be72009-06-26 00:10:03 +0000974 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000975 Stmt *Pattern = 0;
976 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000977 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000978
979 if (!Pattern)
980 return;
981
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000982 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
983 if (Inst)
984 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000985
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000986 // If we're performing recursive template instantiation, create our own
987 // queue of pending implicit instantiations that we will instantiate later,
988 // while we're still within our own instantiation context.
989 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
990 if (Recursive)
991 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
992
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000993 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
994
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000995 // Introduce a new scope where local variable instantiations will be
996 // recorded.
997 LocalInstantiationScope Scope(*this);
998
999 // Introduce the instantiated function parameters into the local
1000 // instantiation scope.
1001 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1002 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1003 Function->getParamDecl(I));
1004
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001005 // Enter the scope of this instantiation. We don't use
1006 // PushDeclContext because we don't have a scope.
1007 DeclContext *PreviousContext = CurContext;
1008 CurContext = Function;
1009
Anders Carlsson09025312009-08-29 05:16:22 +00001010 MultiLevelTemplateArgumentList TemplateArgs =
1011 getTemplateInstantiationArgs(Function);
1012
1013 // If this is a constructor, instantiate the member initializers.
1014 if (const CXXConstructorDecl *Ctor =
1015 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1016 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1017 TemplateArgs);
1018 }
1019
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001020 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001021 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001022
1023 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
1024 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001025
1026 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001027
1028 DeclGroupRef DG(Function);
1029 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001030
1031 if (Recursive) {
1032 // Instantiate any pending implicit instantiations found during the
1033 // instantiation of this template.
1034 PerformPendingImplicitInstantiations();
1035
1036 // Restore the set of pending implicit instantiations.
1037 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1038 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001039}
1040
1041/// \brief Instantiate the definition of the given variable from its
1042/// template.
1043///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001044/// \param PointOfInstantiation the point at which the instantiation was
1045/// required. Note that this is not precisely a "point of instantiation"
1046/// for the function, but it's close.
1047///
1048/// \param Var the already-instantiated declaration of a static member
1049/// variable of a class template specialization.
1050///
1051/// \param Recursive if true, recursively instantiates any functions that
1052/// are required by this instantiation.
1053void Sema::InstantiateStaticDataMemberDefinition(
1054 SourceLocation PointOfInstantiation,
1055 VarDecl *Var,
1056 bool Recursive) {
1057 if (Var->isInvalidDecl())
1058 return;
1059
1060 // Find the out-of-line definition of this static data member.
1061 // FIXME: Do we have to look for specializations separately?
1062 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1063 bool FoundOutOfLineDef = false;
1064 assert(Def && "This data member was not instantiated from a template?");
1065 assert(Def->isStaticDataMember() && "Not a static data member?");
1066 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
1067 RDEnd = Def->redecls_end();
1068 RD != RDEnd; ++RD) {
1069 if (RD->getLexicalDeclContext()->isFileContext()) {
1070 Def = *RD;
1071 FoundOutOfLineDef = true;
1072 }
1073 }
1074
1075 if (!FoundOutOfLineDef) {
1076 // We did not find an out-of-line definition of this static data member,
1077 // so we won't perform any instantiation. Rather, we rely on the user to
1078 // instantiate this definition (or provide a specialization for it) in
1079 // another translation unit.
1080 return;
1081 }
1082
1083 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1084 if (Inst)
1085 return;
1086
1087 // If we're performing recursive template instantiation, create our own
1088 // queue of pending implicit instantiations that we will instantiate later,
1089 // while we're still within our own instantiation context.
1090 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1091 if (Recursive)
1092 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1093
1094 // Enter the scope of this instantiation. We don't use
1095 // PushDeclContext because we don't have a scope.
1096 DeclContext *PreviousContext = CurContext;
1097 CurContext = Var->getDeclContext();
1098
John McCallce3ff2b2009-08-25 22:02:44 +00001099 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001100 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001101
1102 CurContext = PreviousContext;
1103
1104 if (Var) {
1105 DeclGroupRef DG(Var);
1106 Consumer.HandleTopLevelDecl(DG);
1107 }
1108
1109 if (Recursive) {
1110 // Instantiate any pending implicit instantiations found during the
1111 // instantiation of this template.
1112 PerformPendingImplicitInstantiations();
1113
1114 // Restore the set of pending implicit instantiations.
1115 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1116 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001117}
Douglas Gregor815215d2009-05-27 05:35:12 +00001118
Anders Carlsson09025312009-08-29 05:16:22 +00001119void
1120Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1121 const CXXConstructorDecl *Tmpl,
1122 const MultiLevelTemplateArgumentList &TemplateArgs) {
1123
1124 llvm::SmallVector<MemInitTy*, 4> NewInits;
1125
1126 // Instantiate all the initializers.
1127 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001128 InitsEnd = Tmpl->init_end();
1129 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001130 CXXBaseOrMemberInitializer *Init = *Inits;
1131
1132 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
1133
1134 // Instantiate all the arguments.
1135 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1136 Args != ArgsEnd; ++Args) {
1137 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1138
1139 if (NewArg.isInvalid())
1140 New->setInvalidDecl();
1141 else
1142 NewArgs.push_back(NewArg.takeAs<Expr>());
1143 }
1144
1145 MemInitResult NewInit;
1146
1147 if (Init->isBaseInitializer()) {
Eli Friedmanc5573a82009-08-29 22:22:07 +00001148 QualType BaseType(Init->getBaseClass(), 0);
1149 BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(),
1150 New->getDeclName());
Anders Carlsson09025312009-08-29 05:16:22 +00001151
1152 NewInit = BuildBaseInitializer(BaseType,
1153 (Expr **)NewArgs.data(),
1154 NewArgs.size(),
1155 Init->getSourceLocation(),
1156 Init->getRParenLoc(),
1157 New->getParent());
1158 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001159 FieldDecl *Member;
1160
1161 // Is this an anonymous union?
1162 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001163 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001164 else
1165 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember()));
Anders Carlsson09025312009-08-29 05:16:22 +00001166
1167 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
1168 NewArgs.size(),
1169 Init->getSourceLocation(),
1170 Init->getRParenLoc());
1171 }
1172
1173 if (NewInit.isInvalid())
1174 New->setInvalidDecl();
1175 else {
1176 // FIXME: It would be nice if ASTOwningVector had a release function.
1177 NewArgs.take();
1178
1179 NewInits.push_back((MemInitTy *)NewInit.get());
1180 }
1181 }
1182
1183 // Assign all the initializers to the new constructor.
1184 ActOnMemInitializers(DeclPtrTy::make(New),
1185 /*FIXME: ColonLoc */
1186 SourceLocation(),
1187 NewInits.data(), NewInits.size());
1188}
1189
John McCall52a575a2009-08-29 08:11:13 +00001190// TODO: this could be templated if the various decl types used the
1191// same method name.
1192static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1193 ClassTemplateDecl *Instance) {
1194 Pattern = Pattern->getCanonicalDecl();
1195
1196 do {
1197 Instance = Instance->getCanonicalDecl();
1198 if (Pattern == Instance) return true;
1199 Instance = Instance->getInstantiatedFromMemberTemplate();
1200 } while (Instance);
1201
1202 return false;
1203}
1204
1205static bool isInstantiationOf(CXXRecordDecl *Pattern,
1206 CXXRecordDecl *Instance) {
1207 Pattern = Pattern->getCanonicalDecl();
1208
1209 do {
1210 Instance = Instance->getCanonicalDecl();
1211 if (Pattern == Instance) return true;
1212 Instance = Instance->getInstantiatedFromMemberClass();
1213 } while (Instance);
1214
1215 return false;
1216}
1217
1218static bool isInstantiationOf(FunctionDecl *Pattern,
1219 FunctionDecl *Instance) {
1220 Pattern = Pattern->getCanonicalDecl();
1221
1222 do {
1223 Instance = Instance->getCanonicalDecl();
1224 if (Pattern == Instance) return true;
1225 Instance = Instance->getInstantiatedFromMemberFunction();
1226 } while (Instance);
1227
1228 return false;
1229}
1230
1231static bool isInstantiationOf(EnumDecl *Pattern,
1232 EnumDecl *Instance) {
1233 Pattern = Pattern->getCanonicalDecl();
1234
1235 do {
1236 Instance = Instance->getCanonicalDecl();
1237 if (Pattern == Instance) return true;
1238 Instance = Instance->getInstantiatedFromMemberEnum();
1239 } while (Instance);
1240
1241 return false;
1242}
1243
Anders Carlsson0d8df782009-08-29 19:37:28 +00001244static bool isInstantiationOf(UnresolvedUsingDecl *Pattern,
1245 UsingDecl *Instance,
1246 ASTContext &C) {
1247 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1248}
1249
John McCall52a575a2009-08-29 08:11:13 +00001250static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1251 VarDecl *Instance) {
1252 assert(Instance->isStaticDataMember());
1253
1254 Pattern = Pattern->getCanonicalDecl();
1255
1256 do {
1257 Instance = Instance->getCanonicalDecl();
1258 if (Pattern == Instance) return true;
1259 Instance = Instance->getInstantiatedFromStaticDataMember();
1260 } while (Instance);
1261
1262 return false;
1263}
1264
Douglas Gregor815215d2009-05-27 05:35:12 +00001265static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001266 if (D->getKind() != Other->getKind()) {
1267 if (UnresolvedUsingDecl *UUD = dyn_cast<UnresolvedUsingDecl>(D)) {
1268 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1269 return isInstantiationOf(UUD, UD, Ctx);
1270 }
1271 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001272
Anders Carlsson0d8df782009-08-29 19:37:28 +00001273 return false;
1274 }
1275
John McCall52a575a2009-08-29 08:11:13 +00001276 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1277 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001278
John McCall52a575a2009-08-29 08:11:13 +00001279 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1280 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00001281
John McCall52a575a2009-08-29 08:11:13 +00001282 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1283 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00001284
Douglas Gregor7caa6822009-07-24 20:34:43 +00001285 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00001286 if (Var->isStaticDataMember())
1287 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1288
1289 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1290 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001291
Anders Carlssond8b285f2009-09-01 04:26:58 +00001292 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
1293 if (!Field->getDeclName()) {
1294 // This is an unnamed field.
1295 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
1296 cast<FieldDecl>(D);
1297 }
1298 }
1299
Douglas Gregor815215d2009-05-27 05:35:12 +00001300 return D->getDeclName() && isa<NamedDecl>(Other) &&
1301 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1302}
1303
1304template<typename ForwardIterator>
1305static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1306 NamedDecl *D,
1307 ForwardIterator first,
1308 ForwardIterator last) {
1309 for (; first != last; ++first)
1310 if (isInstantiationOf(Ctx, D, *first))
1311 return cast<NamedDecl>(*first);
1312
1313 return 0;
1314}
1315
John McCall02cace72009-08-28 07:59:38 +00001316/// \brief Finds the instantiation of the given declaration context
1317/// within the current instantiation.
1318///
1319/// \returns NULL if there was an error
1320DeclContext *Sema::FindInstantiatedContext(DeclContext* DC) {
1321 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
1322 Decl* ID = FindInstantiatedDecl(D);
1323 return cast_or_null<DeclContext>(ID);
1324 } else return DC;
1325}
1326
Douglas Gregored961e72009-05-27 17:54:46 +00001327/// \brief Find the instantiation of the given declaration within the
1328/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001329///
1330/// This routine is intended to be used when \p D is a declaration
1331/// referenced from within a template, that needs to mapped into the
1332/// corresponding declaration within an instantiation. For example,
1333/// given:
1334///
1335/// \code
1336/// template<typename T>
1337/// struct X {
1338/// enum Kind {
1339/// KnownValue = sizeof(T)
1340/// };
1341///
1342/// bool getKind() const { return KnownValue; }
1343/// };
1344///
1345/// template struct X<int>;
1346/// \endcode
1347///
1348/// In the instantiation of X<int>::getKind(), we need to map the
1349/// EnumConstantDecl for KnownValue (which refers to
1350/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001351/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1352/// this mapping from within the instantiation of X<int>.
Douglas Gregor44c73842009-09-01 17:53:10 +00001353NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D) {
1354 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
1355 // Transform all of the elements of the overloaded function set.
1356 OverloadedFunctionDecl *Result
1357 = OverloadedFunctionDecl::Create(Context, CurContext, Ovl->getDeclName());
1358
1359 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1360 FEnd = Ovl->function_end();
1361 F != FEnd; ++F) {
1362 Result->addOverload(
1363 AnyFunctionDecl::getFromNamedDecl(FindInstantiatedDecl(*F)));
1364 }
1365
1366 return Result;
1367 }
1368
Douglas Gregor815215d2009-05-27 05:35:12 +00001369 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001370 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1371 // D is a local of some kind. Look into the map of local
1372 // declarations to their instantiations.
1373 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1374 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001375
John McCall52a575a2009-08-29 08:11:13 +00001376 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
1377 if (ClassTemplateDecl *ClassTemplate
1378 = Record->getDescribedClassTemplate()) {
1379 // When the declaration D was parsed, it referred to the current
1380 // instantiation. Therefore, look through the current context,
1381 // which contains actual instantiations, to find the
1382 // instantiation of the "current instantiation" that D refers
1383 // to. Alternatively, we could just instantiate the
1384 // injected-class-name with the current template arguments, but
1385 // such an instantiation is far more expensive.
1386 for (DeclContext *DC = CurContext; !DC->isFileContext();
1387 DC = DC->getParent()) {
1388 if (ClassTemplateSpecializationDecl *Spec
1389 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
1390 if (isInstantiationOf(ClassTemplate, Spec->getSpecializedTemplate()))
1391 return Spec;
1392 }
1393
1394 assert(false &&
1395 "Unable to find declaration for the current instantiation");
1396 }
1397
John McCall02cace72009-08-28 07:59:38 +00001398 ParentDC = FindInstantiatedContext(ParentDC);
Douglas Gregor44c73842009-09-01 17:53:10 +00001399 if (!ParentDC)
1400 return 0;
1401
Douglas Gregor815215d2009-05-27 05:35:12 +00001402 if (ParentDC != D->getDeclContext()) {
1403 // We performed some kind of instantiation in the parent context,
1404 // so now we need to look into the instantiated parent context to
1405 // find the instantiation of the declaration D.
1406 NamedDecl *Result = 0;
1407 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001408 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001409 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1410 } else {
1411 // Since we don't have a name for the entity we're looking for,
1412 // our only option is to walk through all of the declarations to
1413 // find that name. This will occur in a few cases:
1414 //
1415 // - anonymous struct/union within a template
1416 // - unnamed class/struct/union/enum within a template
1417 //
1418 // FIXME: Find a better way to find these instantiations!
1419 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001420 ParentDC->decls_begin(),
1421 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001422 }
John McCall52a575a2009-08-29 08:11:13 +00001423
Douglas Gregor815215d2009-05-27 05:35:12 +00001424 assert(Result && "Unable to find instantiation of declaration!");
1425 D = Result;
1426 }
1427
Douglas Gregor815215d2009-05-27 05:35:12 +00001428 return D;
1429}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001430
1431/// \brief Performs template instantiation for all implicit template
1432/// instantiations we have seen until this point.
1433void Sema::PerformPendingImplicitInstantiations() {
1434 while (!PendingImplicitInstantiations.empty()) {
1435 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001436 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001437
Douglas Gregor7caa6822009-07-24 20:34:43 +00001438 // Instantiate function definitions
1439 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00001440 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
1441 Function->getLocation(), *this,
1442 Context.getSourceManager(),
1443 "instantiating function definition");
1444
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001445 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001446 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001447 continue;
1448 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001449
Douglas Gregor7caa6822009-07-24 20:34:43 +00001450 // Instantiate static data member definitions.
1451 VarDecl *Var = cast<VarDecl>(Inst.first);
1452 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00001453
1454 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
1455 Var->getLocation(), *this,
1456 Context.getSourceManager(),
1457 "instantiating static data member "
1458 "definition");
1459
Douglas Gregor7caa6822009-07-24 20:34:43 +00001460 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001461 }
1462}