blob: 0179160835ce990ffb03aca0d270b28884cc1fab [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);
245 if (Field) {
246 if (Invalid)
247 Field->setInvalidDecl();
248
Anders Carlssond8b285f2009-09-01 04:26:58 +0000249 if (!Field->getDeclName()) {
250 // Keep track of where this decl came from.
251 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
252 }
253
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000254 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000255 }
256
257 return Field;
258}
259
John McCall02cace72009-08-28 07:59:38 +0000260Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
261 FriendDecl::FriendUnion FU;
262
263 // Handle friend type expressions by simply substituting template
264 // parameters into the pattern type.
265 if (Type *Ty = D->getFriendType()) {
266 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
267 D->getLocation(), DeclarationName());
268 if (T.isNull()) return 0;
269
270 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
271 FU = T.getTypePtr();
272
273 // Handle everything else by appropriate substitution.
274 } else {
275 NamedDecl *ND = D->getFriendDecl();
276 assert(ND && "friend decl must be a decl or a type!");
277
278 Decl *NewND = Visit(ND);
279 if (!NewND) return 0;
280
281 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000282 }
John McCall02cace72009-08-28 07:59:38 +0000283
284 FriendDecl *FD =
285 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
286 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000287 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000288 Owner->addDecl(FD);
289 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000290}
291
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000292Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
293 Expr *AssertExpr = D->getAssertExpr();
294
Douglas Gregorac7610d2009-06-22 20:57:11 +0000295 // The expression in a static assertion is not potentially evaluated.
296 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
297
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000298 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000299 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000300 if (InstantiatedAssertExpr.isInvalid())
301 return 0;
302
Douglas Gregor43d9d922009-08-08 01:41:12 +0000303 OwningExprResult Message(SemaRef, D->getMessage());
304 D->getMessage()->Retain();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000305 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000306 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
307 move(InstantiatedAssertExpr),
308 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000309 return StaticAssert;
310}
311
312Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
313 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
314 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000315 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000316 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000317 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000318 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000319 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000320 Enum->startDefinition();
321
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000322 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000323
324 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000325 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
326 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000327 EC != ECEnd; ++EC) {
328 // The specified value for the enumerator.
329 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000330 if (Expr *UninstValue = EC->getInitExpr()) {
331 // The enumerator's value expression is not potentially evaluated.
332 EnterExpressionEvaluationContext Unevaluated(SemaRef,
333 Action::Unevaluated);
334
John McCallce3ff2b2009-08-25 22:02:44 +0000335 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000336 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000337
338 // Drop the initial value and continue.
339 bool isInvalid = false;
340 if (Value.isInvalid()) {
341 Value = SemaRef.Owned((Expr *)0);
342 isInvalid = true;
343 }
344
345 EnumConstantDecl *EnumConst
346 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
347 EC->getLocation(), EC->getIdentifier(),
348 move(Value));
349
350 if (isInvalid) {
351 if (EnumConst)
352 EnumConst->setInvalidDecl();
353 Enum->setInvalidDecl();
354 }
355
356 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000357 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000358 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000359 LastEnumConst = EnumConst;
360 }
361 }
362
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000363 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000364 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000365 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
366 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000367 &Enumerators[0], Enumerators.size(),
368 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000369
370 return Enum;
371}
372
Douglas Gregor6477b692009-03-25 15:04:13 +0000373Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
374 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
375 return 0;
376}
377
John McCalle29ba202009-08-20 01:44:21 +0000378Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
379 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000380 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Douglas Gregord60e1052009-08-27 16:57:43 +0000381 if (!InstParams)
382 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000383
384 CXXRecordDecl *Pattern = D->getTemplatedDecl();
385 CXXRecordDecl *RecordInst
386 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
387 Pattern->getLocation(), Pattern->getIdentifier(),
388 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
389
390 ClassTemplateDecl *Inst
391 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
392 D->getIdentifier(), InstParams, RecordInst, 0);
393 RecordInst->setDescribedClassTemplate(Inst);
394 Inst->setAccess(D->getAccess());
395 Inst->setInstantiatedFromMemberTemplate(D);
396
397 Owner->addDecl(Inst);
398 return Inst;
399}
400
Douglas Gregord60e1052009-08-27 16:57:43 +0000401Decl *
402TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
403 TemplateParameterList *TempParams = D->getTemplateParameters();
404 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
405 if (!InstParams)
406 return NULL;
407
408 // FIXME: Handle instantiation of nested function templates that aren't
409 // member function templates. This could happen inside a FriendDecl.
410 assert(isa<CXXMethodDecl>(D->getTemplatedDecl()));
411 CXXMethodDecl *InstMethod
412 = cast_or_null<CXXMethodDecl>(
413 VisitCXXMethodDecl(cast<CXXMethodDecl>(D->getTemplatedDecl()),
414 InstParams));
415 if (!InstMethod)
416 return 0;
417
418 // Link the instantiated function template declaration to the function
419 // template from which it was instantiated.
420 FunctionTemplateDecl *InstTemplate = InstMethod->getDescribedFunctionTemplate();
421 assert(InstTemplate && "VisitCXXMethodDecl didn't create a template!");
422 InstTemplate->setInstantiatedFromMemberTemplate(D);
423 Owner->addDecl(InstTemplate);
424 return InstTemplate;
425}
426
Douglas Gregord475b8d2009-03-25 21:17:03 +0000427Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
428 CXXRecordDecl *PrevDecl = 0;
429 if (D->isInjectedClassName())
430 PrevDecl = cast<CXXRecordDecl>(Owner);
431
432 CXXRecordDecl *Record
433 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000434 D->getLocation(), D->getIdentifier(),
435 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000436 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000437 // FIXME: Check against AS_none is an ugly hack to work around the issue that
438 // the tag decls introduced by friend class declarations don't have an access
439 // specifier. Remove once this area of the code gets sorted out.
440 if (D->getAccess() != AS_none)
441 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000442 if (!D->isInjectedClassName())
443 Record->setInstantiationOfMemberClass(D);
444
John McCall02cace72009-08-28 07:59:38 +0000445 // If the original function was part of a friend declaration,
446 // inherit its namespace state.
447 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
448 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
449
Anders Carlssond8b285f2009-09-01 04:26:58 +0000450 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
451
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000452 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000453 return Record;
454}
455
John McCall02cace72009-08-28 07:59:38 +0000456/// Normal class members are of more specific types and therefore
457/// don't make it here. This function serves two purposes:
458/// 1) instantiating function templates
459/// 2) substituting friend declarations
460/// FIXME: preserve function definitions in case #2
Douglas Gregore53060f2009-06-25 22:08:12 +0000461Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000462 // Check whether there is already a function template specialization for
463 // this declaration.
464 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
465 void *InsertPos = 0;
466 if (FunctionTemplate) {
467 llvm::FoldingSetNodeID ID;
468 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000469 TemplateArgs.getInnermost().getFlatArgumentList(),
470 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000471 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000472
473 FunctionTemplateSpecializationInfo *Info
474 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
475 InsertPos);
476
477 // If we already have a function template specialization, return it.
478 if (Info)
479 return Info->Function;
480 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000481
482 Sema::LocalInstantiationScope Scope(SemaRef);
483
484 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000485 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000486 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000487 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000488
Douglas Gregore53060f2009-06-25 22:08:12 +0000489 // Build the instantiated method declaration.
John McCall02cace72009-08-28 07:59:38 +0000490 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext());
491 FunctionDecl *Function =
492 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000493 D->getDeclName(), T, D->getDeclaratorInfo(),
494 D->getStorageClass(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000495 D->isInline(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000496 Function->setLexicalDeclContext(Owner);
497
Douglas Gregore53060f2009-06-25 22:08:12 +0000498 // Attach the parameters
499 for (unsigned P = 0; P < Params.size(); ++P)
500 Params[P]->setOwningFunction(Function);
501 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000502
503 // If the original function was part of a friend declaration,
504 // inherit its namespace state and add it to the owner.
505 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) {
506 bool WasDeclared = (FOK == Decl::FOK_Declared);
507 Function->setObjectOfFriendDecl(WasDeclared);
508 if (!Owner->isDependentContext())
John McCallab88d972009-08-31 22:39:49 +0000509 DC->makeDeclVisibleInContext(Function, /* Recoverable = */ false);
John McCallf181d8a2009-08-29 03:16:09 +0000510
511 Function->setInstantiationOfMemberFunction(D);
John McCall02cace72009-08-28 07:59:38 +0000512 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000513
514 if (InitFunctionInstantiation(Function, D))
515 Function->setInvalidDecl();
516
517 bool Redeclaration = false;
518 bool OverloadableAttrRequired = false;
519 NamedDecl *PrevDecl = 0;
520 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
521 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000522
Douglas Gregor127102b2009-06-29 20:59:39 +0000523 if (FunctionTemplate) {
524 // Record this function template specialization.
525 Function->setFunctionTemplateSpecialization(SemaRef.Context,
526 FunctionTemplate,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000527 &TemplateArgs.getInnermost(),
Douglas Gregor127102b2009-06-29 20:59:39 +0000528 InsertPos);
John McCallfd810b12009-08-14 02:03:10 +0000529 }
530
Douglas Gregore53060f2009-06-25 22:08:12 +0000531 return Function;
532}
533
Douglas Gregord60e1052009-08-27 16:57:43 +0000534Decl *
535TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
536 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000537 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
538 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000539 if (FunctionTemplate && !TemplateParams) {
540 // We are creating a function template specialization from a function
541 // template. Check whether there is already a function template
542 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000543 llvm::FoldingSetNodeID ID;
544 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000545 TemplateArgs.getInnermost().getFlatArgumentList(),
546 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000547 SemaRef.Context);
548
549 FunctionTemplateSpecializationInfo *Info
550 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
551 InsertPos);
552
553 // If we already have a function template specialization, return it.
554 if (Info)
555 return Info->Function;
556 }
557
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000558 Sema::LocalInstantiationScope Scope(SemaRef);
559
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000560 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000561 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000562 if (T.isNull())
563 return 0;
564
565 // Build the instantiated method declaration.
566 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000567 CXXMethodDecl *Method = 0;
568
569 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000570 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000571 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
572 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
573 SemaRef.Context.getCanonicalType(ClassTy));
574 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000575 Constructor->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000576 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000577 Constructor->getDeclaratorInfo(),
578 Constructor->isExplicit(),
579 Constructor->isInline(), false);
580 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
581 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
582 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
583 SemaRef.Context.getCanonicalType(ClassTy));
584 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
585 Destructor->getLocation(), Name,
586 T, Destructor->isInline(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000587 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
588 CanQualType ConvTy
589 = SemaRef.Context.getCanonicalType(
590 T->getAsFunctionType()->getResultType());
591 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
592 ConvTy);
593 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
594 Conversion->getLocation(), Name,
595 T, Conversion->getDeclaratorInfo(),
596 Conversion->isInline(),
597 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000598 } else {
599 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
600 D->getDeclName(), T, D->getDeclaratorInfo(),
601 D->isStatic(), D->isInline());
602 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000603
Douglas Gregord60e1052009-08-27 16:57:43 +0000604 if (TemplateParams) {
605 // Our resulting instantiation is actually a function template, since we
606 // are substituting only the outer template parameters. For example, given
607 //
608 // template<typename T>
609 // struct X {
610 // template<typename U> void f(T, U);
611 // };
612 //
613 // X<int> x;
614 //
615 // We are instantiating the member template "f" within X<int>, which means
616 // substituting int for T, but leaving "f" as a member function template.
617 // Build the function template itself.
618 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
619 Method->getLocation(),
620 Method->getDeclName(),
621 TemplateParams, Method);
622 if (D->isOutOfLine())
623 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
624 Method->setDescribedFunctionTemplate(FunctionTemplate);
625 } else if (!FunctionTemplate)
Douglas Gregor6b906862009-08-21 00:16:32 +0000626 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000627
Douglas Gregor7caa6822009-07-24 20:34:43 +0000628 // If we are instantiating a member function defined
629 // out-of-line, the instantiation will have the same lexical
630 // context (which will be a namespace scope) as the template.
631 if (D->isOutOfLine())
632 Method->setLexicalDeclContext(D->getLexicalDeclContext());
633
Douglas Gregor5545e162009-03-24 00:38:23 +0000634 // Attach the parameters
635 for (unsigned P = 0; P < Params.size(); ++P)
636 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000637 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000638
639 if (InitMethodInstantiation(Method, D))
640 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000641
Douglas Gregordec06662009-08-21 18:42:58 +0000642 NamedDecl *PrevDecl = 0;
643
Douglas Gregord60e1052009-08-27 16:57:43 +0000644 if (!FunctionTemplate || TemplateParams) {
Douglas Gregordec06662009-08-21 18:42:58 +0000645 PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
646 Sema::LookupOrdinaryName, true);
647
648 // In C++, the previous declaration we find might be a tag type
649 // (class or enum). In this case, the new declaration will hide the
650 // tag type. Note that this does does not apply if we're declaring a
651 // typedef (C++ [dcl.typedef]p4).
652 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
653 PrevDecl = 0;
654 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000655
Douglas Gregord60e1052009-08-27 16:57:43 +0000656 if (FunctionTemplate && !TemplateParams)
Douglas Gregor6b906862009-08-21 00:16:32 +0000657 // Record this function template specialization.
658 Method->setFunctionTemplateSpecialization(SemaRef.Context,
659 FunctionTemplate,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000660 &TemplateArgs.getInnermost(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000661 InsertPos);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000662
663 bool Redeclaration = false;
664 bool OverloadableAttrRequired = false;
665 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
666 /*FIXME:*/OverloadableAttrRequired);
667
668 if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
Douglas Gregordec06662009-08-21 18:42:58 +0000669 Owner->addDecl(Method);
670
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000671 return Method;
672}
673
Douglas Gregor615c5d42009-03-24 16:43:20 +0000674Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000675 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000676}
677
Douglas Gregor03b2b072009-03-24 00:15:49 +0000678Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000679 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000680}
681
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000682Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000683 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000684}
685
Douglas Gregor6477b692009-03-25 15:04:13 +0000686ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000687 QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000688 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000689 if (OrigT.isNull())
690 return 0;
691
692 QualType T = SemaRef.adjustParameterType(OrigT);
693
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000694 // Allocate the parameter
695 ParmVarDecl *Param = 0;
696 if (T == OrigT)
697 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000698 D->getIdentifier(), T, D->getDeclaratorInfo(),
699 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000700 else
701 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
702 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000703 T, D->getDeclaratorInfo(), OrigT,
704 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000705
Anders Carlsson9351c172009-08-25 03:18:48 +0000706 // Mark the default argument as being uninstantiated.
707 if (Expr *Arg = D->getDefaultArg())
708 Param->setUninstantiatedDefaultArg(Arg);
709
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000710 // Note: we don't try to instantiate function parameters until after
711 // we've instantiated the function's type. Therefore, we don't have
712 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000713 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000714 return Param;
715}
716
717Decl *
718TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
719 // Since parameter types can decay either before or after
720 // instantiation, we simply treat OriginalParmVarDecls as
721 // ParmVarDecls the same way, and create one or the other depending
722 // on what happens after template instantiation.
723 return VisitParmVarDecl(D);
724}
725
John McCalle29ba202009-08-20 01:44:21 +0000726Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
727 TemplateTypeParmDecl *D) {
728 // TODO: don't always clone when decls are refcounted.
729 const Type* T = D->getTypeForDecl();
730 assert(T->isTemplateTypeParmType());
731 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
732
733 TemplateTypeParmDecl *Inst =
734 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
735 TTPT->getDepth(), TTPT->getIndex(),
736 TTPT->getName(),
737 D->wasDeclaredWithTypename(),
738 D->isParameterPack());
739
740 if (D->hasDefaultArgument()) {
741 QualType DefaultPattern = D->getDefaultArgument();
742 QualType DefaultInst
John McCallce3ff2b2009-08-25 22:02:44 +0000743 = SemaRef.SubstType(DefaultPattern, TemplateArgs,
744 D->getDefaultArgumentLoc(),
745 D->getDeclName());
John McCalle29ba202009-08-20 01:44:21 +0000746
747 Inst->setDefaultArgument(DefaultInst,
748 D->getDefaultArgumentLoc(),
749 D->defaultArgumentWasInherited() /* preserve? */);
750 }
751
752 return Inst;
753}
754
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000755Decl *
756TemplateDeclInstantiator::VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D) {
757 NestedNameSpecifier *NNS =
758 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
759 D->getTargetNestedNameRange(),
760 TemplateArgs);
761 if (!NNS)
762 return 0;
763
764 CXXScopeSpec SS;
765 SS.setRange(D->getTargetNestedNameRange());
766 SS.setScopeRep(NNS);
767
Anders Carlsson0d8df782009-08-29 19:37:28 +0000768 NamedDecl *UD =
769 SemaRef.BuildUsingDeclaration(D->getLocation(), SS,
770 D->getTargetNameLocation(),
771 D->getTargetName(), 0, D->isTypeName());
772 if (UD)
773 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
774 D);
775 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000776}
777
John McCallce3ff2b2009-08-25 22:02:44 +0000778Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000779 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +0000780 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000781 return Instantiator.Visit(D);
782}
783
John McCalle29ba202009-08-20 01:44:21 +0000784/// \brief Instantiates a nested template parameter list in the current
785/// instantiation context.
786///
787/// \param L The parameter list to instantiate
788///
789/// \returns NULL if there was an error
790TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000791TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +0000792 // Get errors for all the parameters before bailing out.
793 bool Invalid = false;
794
795 unsigned N = L->size();
796 typedef llvm::SmallVector<Decl*,8> ParamVector;
797 ParamVector Params;
798 Params.reserve(N);
799 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
800 PI != PE; ++PI) {
801 Decl *D = Visit(*PI);
802 Params.push_back(D);
803 Invalid = Invalid || !D;
804 }
805
806 // Clean up if we had an error.
807 if (Invalid) {
808 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
809 PI != PE; ++PI)
810 if (*PI)
811 (*PI)->Destroy(SemaRef.Context);
812 return NULL;
813 }
814
815 TemplateParameterList *InstL
816 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
817 L->getLAngleLoc(), &Params.front(), N,
818 L->getRAngleLoc());
819 return InstL;
820}
821
John McCallce3ff2b2009-08-25 22:02:44 +0000822/// \brief Does substitution on the type of the given function, including
823/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +0000824///
John McCallce3ff2b2009-08-25 22:02:44 +0000825/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +0000826///
827/// \param Params the instantiated parameter declarations
828
John McCallce3ff2b2009-08-25 22:02:44 +0000829/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +0000830/// type if there was an error.
831QualType
John McCallce3ff2b2009-08-25 22:02:44 +0000832TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +0000833 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
834 bool InvalidDecl = false;
835
John McCallce3ff2b2009-08-25 22:02:44 +0000836 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +0000837 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000838 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000839 for (FunctionDecl::param_iterator P = D->param_begin(),
840 PEnd = D->param_end();
841 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000842 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000843 if (PInst->getType()->isVoidType()) {
844 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
845 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000846 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
847 PInst->getType(),
848 diag::err_abstract_type_in_decl,
849 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000850 PInst->setInvalidDecl();
851
852 Params.push_back(PInst);
853 ParamTys.push_back(PInst->getType());
854
855 if (PInst->isInvalidDecl())
856 InvalidDecl = true;
857 } else
858 InvalidDecl = true;
859 }
860
861 // FIXME: Deallocate dead declarations.
862 if (InvalidDecl)
863 return QualType();
864
865 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
866 assert(Proto && "Missing prototype?");
867 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +0000868 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
869 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +0000870 if (ResultType.isNull())
871 return QualType();
872
Jay Foadbeaaccd2009-05-21 09:52:38 +0000873 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000874 Proto->isVariadic(), Proto->getTypeQuals(),
875 D->getLocation(), D->getDeclName());
876}
877
Douglas Gregore53060f2009-06-25 22:08:12 +0000878/// \brief Initializes the common fields of an instantiation function
879/// declaration (New) from the corresponding fields of its template (Tmpl).
880///
881/// \returns true if there was an error
882bool
883TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
884 FunctionDecl *Tmpl) {
885 if (Tmpl->isDeleted())
886 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000887
888 // If we are performing substituting explicitly-specified template arguments
889 // or deduced template arguments into a function template and we reach this
890 // point, we are now past the point where SFINAE applies and have committed
891 // to keeping the new function template specialization. We therefore
892 // convert the active template instantiation for the function template
893 // into a template instantiation for this specific function template
894 // specialization, which is not a SFINAE context, so that we diagnose any
895 // further errors in the declaration itself.
896 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
897 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
898 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
899 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
900 if (FunctionTemplateDecl *FunTmpl
901 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
902 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
903 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000904 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000905 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
906 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
907 }
908 }
909
Douglas Gregore53060f2009-06-25 22:08:12 +0000910 return false;
911}
912
Douglas Gregor5545e162009-03-24 00:38:23 +0000913/// \brief Initializes common fields of an instantiated method
914/// declaration (New) from the corresponding fields of its template
915/// (Tmpl).
916///
917/// \returns true if there was an error
918bool
919TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
920 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000921 if (InitFunctionInstantiation(New, Tmpl))
922 return true;
923
Douglas Gregor5545e162009-03-24 00:38:23 +0000924 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
925 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000926 if (Tmpl->isVirtualAsWritten()) {
927 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000928 Record->setAggregate(false);
929 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000930 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000931 Record->setPolymorphic(true);
932 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000933 if (Tmpl->isPure()) {
934 New->setPure();
935 Record->setAbstract(true);
936 }
937
938 // FIXME: attributes
939 // FIXME: New needs a pointer to Tmpl
940 return false;
941}
Douglas Gregora58861f2009-05-13 20:28:22 +0000942
943/// \brief Instantiate the definition of the given function from its
944/// template.
945///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000946/// \param PointOfInstantiation the point at which the instantiation was
947/// required. Note that this is not precisely a "point of instantiation"
948/// for the function, but it's close.
949///
Douglas Gregora58861f2009-05-13 20:28:22 +0000950/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000951/// function template specialization or member function of a class template
952/// specialization.
953///
954/// \param Recursive if true, recursively instantiates any functions that
955/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000956void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000957 FunctionDecl *Function,
958 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000959 if (Function->isInvalidDecl())
960 return;
961
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000962 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000963
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000964 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000965 const FunctionDecl *PatternDecl = 0;
Douglas Gregor5ec178f2009-08-28 21:09:48 +0000966 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate()) {
967 while (Primary->getInstantiatedFromMemberTemplate())
968 Primary = Primary->getInstantiatedFromMemberTemplate();
969
Douglas Gregor1637be72009-06-26 00:10:03 +0000970 PatternDecl = Primary->getTemplatedDecl();
Douglas Gregor5ec178f2009-08-28 21:09:48 +0000971 } else
Douglas Gregor1637be72009-06-26 00:10:03 +0000972 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000973 Stmt *Pattern = 0;
974 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000975 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000976
977 if (!Pattern)
978 return;
979
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000980 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
981 if (Inst)
982 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000983
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000984 // If we're performing recursive template instantiation, create our own
985 // queue of pending implicit instantiations that we will instantiate later,
986 // while we're still within our own instantiation context.
987 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
988 if (Recursive)
989 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
990
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000991 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
992
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000993 // Introduce a new scope where local variable instantiations will be
994 // recorded.
995 LocalInstantiationScope Scope(*this);
996
997 // Introduce the instantiated function parameters into the local
998 // instantiation scope.
999 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1000 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1001 Function->getParamDecl(I));
1002
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001003 // Enter the scope of this instantiation. We don't use
1004 // PushDeclContext because we don't have a scope.
1005 DeclContext *PreviousContext = CurContext;
1006 CurContext = Function;
1007
Anders Carlsson09025312009-08-29 05:16:22 +00001008 MultiLevelTemplateArgumentList TemplateArgs =
1009 getTemplateInstantiationArgs(Function);
1010
1011 // If this is a constructor, instantiate the member initializers.
1012 if (const CXXConstructorDecl *Ctor =
1013 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1014 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1015 TemplateArgs);
1016 }
1017
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001018 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001019 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001020
1021 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
1022 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001023
1024 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001025
1026 DeclGroupRef DG(Function);
1027 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001028
1029 if (Recursive) {
1030 // Instantiate any pending implicit instantiations found during the
1031 // instantiation of this template.
1032 PerformPendingImplicitInstantiations();
1033
1034 // Restore the set of pending implicit instantiations.
1035 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1036 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001037}
1038
1039/// \brief Instantiate the definition of the given variable from its
1040/// template.
1041///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001042/// \param PointOfInstantiation the point at which the instantiation was
1043/// required. Note that this is not precisely a "point of instantiation"
1044/// for the function, but it's close.
1045///
1046/// \param Var the already-instantiated declaration of a static member
1047/// variable of a class template specialization.
1048///
1049/// \param Recursive if true, recursively instantiates any functions that
1050/// are required by this instantiation.
1051void Sema::InstantiateStaticDataMemberDefinition(
1052 SourceLocation PointOfInstantiation,
1053 VarDecl *Var,
1054 bool Recursive) {
1055 if (Var->isInvalidDecl())
1056 return;
1057
1058 // Find the out-of-line definition of this static data member.
1059 // FIXME: Do we have to look for specializations separately?
1060 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1061 bool FoundOutOfLineDef = false;
1062 assert(Def && "This data member was not instantiated from a template?");
1063 assert(Def->isStaticDataMember() && "Not a static data member?");
1064 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
1065 RDEnd = Def->redecls_end();
1066 RD != RDEnd; ++RD) {
1067 if (RD->getLexicalDeclContext()->isFileContext()) {
1068 Def = *RD;
1069 FoundOutOfLineDef = true;
1070 }
1071 }
1072
1073 if (!FoundOutOfLineDef) {
1074 // We did not find an out-of-line definition of this static data member,
1075 // so we won't perform any instantiation. Rather, we rely on the user to
1076 // instantiate this definition (or provide a specialization for it) in
1077 // another translation unit.
1078 return;
1079 }
1080
1081 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1082 if (Inst)
1083 return;
1084
1085 // If we're performing recursive template instantiation, create our own
1086 // queue of pending implicit instantiations that we will instantiate later,
1087 // while we're still within our own instantiation context.
1088 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1089 if (Recursive)
1090 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1091
1092 // Enter the scope of this instantiation. We don't use
1093 // PushDeclContext because we don't have a scope.
1094 DeclContext *PreviousContext = CurContext;
1095 CurContext = Var->getDeclContext();
1096
John McCallce3ff2b2009-08-25 22:02:44 +00001097 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001098 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001099
1100 CurContext = PreviousContext;
1101
1102 if (Var) {
1103 DeclGroupRef DG(Var);
1104 Consumer.HandleTopLevelDecl(DG);
1105 }
1106
1107 if (Recursive) {
1108 // Instantiate any pending implicit instantiations found during the
1109 // instantiation of this template.
1110 PerformPendingImplicitInstantiations();
1111
1112 // Restore the set of pending implicit instantiations.
1113 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1114 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001115}
Douglas Gregor815215d2009-05-27 05:35:12 +00001116
Anders Carlsson09025312009-08-29 05:16:22 +00001117void
1118Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1119 const CXXConstructorDecl *Tmpl,
1120 const MultiLevelTemplateArgumentList &TemplateArgs) {
1121
1122 llvm::SmallVector<MemInitTy*, 4> NewInits;
1123
1124 // Instantiate all the initializers.
1125 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
1126 InitsEnd = Tmpl->init_end(); Inits != InitsEnd; ++Inits) {
1127 CXXBaseOrMemberInitializer *Init = *Inits;
1128
1129 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
1130
1131 // Instantiate all the arguments.
1132 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1133 Args != ArgsEnd; ++Args) {
1134 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1135
1136 if (NewArg.isInvalid())
1137 New->setInvalidDecl();
1138 else
1139 NewArgs.push_back(NewArg.takeAs<Expr>());
1140 }
1141
1142 MemInitResult NewInit;
1143
1144 if (Init->isBaseInitializer()) {
Eli Friedmanc5573a82009-08-29 22:22:07 +00001145 QualType BaseType(Init->getBaseClass(), 0);
1146 BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(),
1147 New->getDeclName());
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()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001156 FieldDecl *Member;
1157
1158 // Is this an anonymous union?
1159 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001160 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001161 else
1162 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember()));
Anders Carlsson09025312009-08-29 05:16:22 +00001163
1164 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
1165 NewArgs.size(),
1166 Init->getSourceLocation(),
1167 Init->getRParenLoc());
1168 }
1169
1170 if (NewInit.isInvalid())
1171 New->setInvalidDecl();
1172 else {
1173 // FIXME: It would be nice if ASTOwningVector had a release function.
1174 NewArgs.take();
1175
1176 NewInits.push_back((MemInitTy *)NewInit.get());
1177 }
1178 }
1179
1180 // Assign all the initializers to the new constructor.
1181 ActOnMemInitializers(DeclPtrTy::make(New),
1182 /*FIXME: ColonLoc */
1183 SourceLocation(),
1184 NewInits.data(), NewInits.size());
1185}
1186
John McCall52a575a2009-08-29 08:11:13 +00001187// TODO: this could be templated if the various decl types used the
1188// same method name.
1189static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1190 ClassTemplateDecl *Instance) {
1191 Pattern = Pattern->getCanonicalDecl();
1192
1193 do {
1194 Instance = Instance->getCanonicalDecl();
1195 if (Pattern == Instance) return true;
1196 Instance = Instance->getInstantiatedFromMemberTemplate();
1197 } while (Instance);
1198
1199 return false;
1200}
1201
1202static bool isInstantiationOf(CXXRecordDecl *Pattern,
1203 CXXRecordDecl *Instance) {
1204 Pattern = Pattern->getCanonicalDecl();
1205
1206 do {
1207 Instance = Instance->getCanonicalDecl();
1208 if (Pattern == Instance) return true;
1209 Instance = Instance->getInstantiatedFromMemberClass();
1210 } while (Instance);
1211
1212 return false;
1213}
1214
1215static bool isInstantiationOf(FunctionDecl *Pattern,
1216 FunctionDecl *Instance) {
1217 Pattern = Pattern->getCanonicalDecl();
1218
1219 do {
1220 Instance = Instance->getCanonicalDecl();
1221 if (Pattern == Instance) return true;
1222 Instance = Instance->getInstantiatedFromMemberFunction();
1223 } while (Instance);
1224
1225 return false;
1226}
1227
1228static bool isInstantiationOf(EnumDecl *Pattern,
1229 EnumDecl *Instance) {
1230 Pattern = Pattern->getCanonicalDecl();
1231
1232 do {
1233 Instance = Instance->getCanonicalDecl();
1234 if (Pattern == Instance) return true;
1235 Instance = Instance->getInstantiatedFromMemberEnum();
1236 } while (Instance);
1237
1238 return false;
1239}
1240
Anders Carlsson0d8df782009-08-29 19:37:28 +00001241static bool isInstantiationOf(UnresolvedUsingDecl *Pattern,
1242 UsingDecl *Instance,
1243 ASTContext &C) {
1244 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1245}
1246
John McCall52a575a2009-08-29 08:11:13 +00001247static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1248 VarDecl *Instance) {
1249 assert(Instance->isStaticDataMember());
1250
1251 Pattern = Pattern->getCanonicalDecl();
1252
1253 do {
1254 Instance = Instance->getCanonicalDecl();
1255 if (Pattern == Instance) return true;
1256 Instance = Instance->getInstantiatedFromStaticDataMember();
1257 } while (Instance);
1258
1259 return false;
1260}
1261
Douglas Gregor815215d2009-05-27 05:35:12 +00001262static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001263 if (D->getKind() != Other->getKind()) {
1264 if (UnresolvedUsingDecl *UUD = dyn_cast<UnresolvedUsingDecl>(D)) {
1265 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1266 return isInstantiationOf(UUD, UD, Ctx);
1267 }
1268 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001269
Anders Carlsson0d8df782009-08-29 19:37:28 +00001270 return false;
1271 }
1272
John McCall52a575a2009-08-29 08:11:13 +00001273 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1274 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001275
John McCall52a575a2009-08-29 08:11:13 +00001276 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1277 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00001278
John McCall52a575a2009-08-29 08:11:13 +00001279 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1280 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00001281
Douglas Gregor7caa6822009-07-24 20:34:43 +00001282 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00001283 if (Var->isStaticDataMember())
1284 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1285
1286 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1287 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001288
Anders Carlssond8b285f2009-09-01 04:26:58 +00001289 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
1290 if (!Field->getDeclName()) {
1291 // This is an unnamed field.
1292 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
1293 cast<FieldDecl>(D);
1294 }
1295 }
1296
Douglas Gregor815215d2009-05-27 05:35:12 +00001297 return D->getDeclName() && isa<NamedDecl>(Other) &&
1298 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1299}
1300
1301template<typename ForwardIterator>
1302static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1303 NamedDecl *D,
1304 ForwardIterator first,
1305 ForwardIterator last) {
1306 for (; first != last; ++first)
1307 if (isInstantiationOf(Ctx, D, *first))
1308 return cast<NamedDecl>(*first);
1309
1310 return 0;
1311}
1312
John McCall02cace72009-08-28 07:59:38 +00001313/// \brief Finds the instantiation of the given declaration context
1314/// within the current instantiation.
1315///
1316/// \returns NULL if there was an error
1317DeclContext *Sema::FindInstantiatedContext(DeclContext* DC) {
1318 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
1319 Decl* ID = FindInstantiatedDecl(D);
1320 return cast_or_null<DeclContext>(ID);
1321 } else return DC;
1322}
1323
Douglas Gregored961e72009-05-27 17:54:46 +00001324/// \brief Find the instantiation of the given declaration within the
1325/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001326///
1327/// This routine is intended to be used when \p D is a declaration
1328/// referenced from within a template, that needs to mapped into the
1329/// corresponding declaration within an instantiation. For example,
1330/// given:
1331///
1332/// \code
1333/// template<typename T>
1334/// struct X {
1335/// enum Kind {
1336/// KnownValue = sizeof(T)
1337/// };
1338///
1339/// bool getKind() const { return KnownValue; }
1340/// };
1341///
1342/// template struct X<int>;
1343/// \endcode
1344///
1345/// In the instantiation of X<int>::getKind(), we need to map the
1346/// EnumConstantDecl for KnownValue (which refers to
1347/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001348/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1349/// this mapping from within the instantiation of X<int>.
Douglas Gregor44c73842009-09-01 17:53:10 +00001350NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D) {
1351 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
1352 // Transform all of the elements of the overloaded function set.
1353 OverloadedFunctionDecl *Result
1354 = OverloadedFunctionDecl::Create(Context, CurContext, Ovl->getDeclName());
1355
1356 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1357 FEnd = Ovl->function_end();
1358 F != FEnd; ++F) {
1359 Result->addOverload(
1360 AnyFunctionDecl::getFromNamedDecl(FindInstantiatedDecl(*F)));
1361 }
1362
1363 return Result;
1364 }
1365
Douglas Gregor815215d2009-05-27 05:35:12 +00001366 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001367 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1368 // D is a local of some kind. Look into the map of local
1369 // declarations to their instantiations.
1370 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1371 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001372
John McCall52a575a2009-08-29 08:11:13 +00001373 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
1374 if (ClassTemplateDecl *ClassTemplate
1375 = Record->getDescribedClassTemplate()) {
1376 // When the declaration D was parsed, it referred to the current
1377 // instantiation. Therefore, look through the current context,
1378 // which contains actual instantiations, to find the
1379 // instantiation of the "current instantiation" that D refers
1380 // to. Alternatively, we could just instantiate the
1381 // injected-class-name with the current template arguments, but
1382 // such an instantiation is far more expensive.
1383 for (DeclContext *DC = CurContext; !DC->isFileContext();
1384 DC = DC->getParent()) {
1385 if (ClassTemplateSpecializationDecl *Spec
1386 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
1387 if (isInstantiationOf(ClassTemplate, Spec->getSpecializedTemplate()))
1388 return Spec;
1389 }
1390
1391 assert(false &&
1392 "Unable to find declaration for the current instantiation");
1393 }
1394
John McCall02cace72009-08-28 07:59:38 +00001395 ParentDC = FindInstantiatedContext(ParentDC);
Douglas Gregor44c73842009-09-01 17:53:10 +00001396 if (!ParentDC)
1397 return 0;
1398
Douglas Gregor815215d2009-05-27 05:35:12 +00001399 if (ParentDC != D->getDeclContext()) {
1400 // We performed some kind of instantiation in the parent context,
1401 // so now we need to look into the instantiated parent context to
1402 // find the instantiation of the declaration D.
1403 NamedDecl *Result = 0;
1404 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001405 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001406 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1407 } else {
1408 // Since we don't have a name for the entity we're looking for,
1409 // our only option is to walk through all of the declarations to
1410 // find that name. This will occur in a few cases:
1411 //
1412 // - anonymous struct/union within a template
1413 // - unnamed class/struct/union/enum within a template
1414 //
1415 // FIXME: Find a better way to find these instantiations!
1416 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001417 ParentDC->decls_begin(),
1418 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001419 }
John McCall52a575a2009-08-29 08:11:13 +00001420
Douglas Gregor815215d2009-05-27 05:35:12 +00001421 assert(Result && "Unable to find instantiation of declaration!");
1422 D = Result;
1423 }
1424
Douglas Gregor815215d2009-05-27 05:35:12 +00001425 return D;
1426}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001427
1428/// \brief Performs template instantiation for all implicit template
1429/// instantiations we have seen until this point.
1430void Sema::PerformPendingImplicitInstantiations() {
1431 while (!PendingImplicitInstantiations.empty()) {
1432 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001433 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001434
Douglas Gregor7caa6822009-07-24 20:34:43 +00001435 // Instantiate function definitions
1436 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00001437 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
1438 Function->getLocation(), *this,
1439 Context.getSourceManager(),
1440 "instantiating function definition");
1441
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001442 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001443 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001444 continue;
1445 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001446
Douglas Gregor7caa6822009-07-24 20:34:43 +00001447 // Instantiate static data member definitions.
1448 VarDecl *Var = cast<VarDecl>(Inst.first);
1449 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00001450
1451 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
1452 Var->getLocation(), *this,
1453 Context.getSourceManager(),
1454 "instantiating static data member "
1455 "definition");
1456
Douglas Gregor7caa6822009-07-24 20:34:43 +00001457 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001458 }
1459}