blob: 422a7bc04d7c7bda0caf81d4f295cf892f83d493 [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 {
Mike Stump1eb44332009-09-09 15:08:12 +000025 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;
Mike Stump1eb44332009-09-09 15:08:12 +000030
Douglas Gregor8dbc2692009-03-17 21:15:40 +000031 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) { }
Mike Stump1eb44332009-09-09 15:08:12 +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 Gregora735b202009-10-13 14:39:41 +000050 Decl *VisitFunctionDecl(FunctionDecl *D,
51 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000052 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000053 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
54 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000055 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000056 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000057 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000058 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000059 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000060 Decl *VisitClassTemplatePartialSpecializationDecl(
61 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000062 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000063 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000064 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Anders Carlsson0dde18e2009-08-28 15:18:15 +000065 Decl *VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000066
Douglas Gregor8dbc2692009-03-17 21:15:40 +000067 // Base case. FIXME: Remove once we can instantiate everything.
Mike Stump1eb44332009-09-09 15:08:12 +000068 Decl *VisitDecl(Decl *) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000069 assert(false && "Template instantiation of unknown declaration kind!");
Douglas Gregor8dbc2692009-03-17 21:15:40 +000070 return 0;
71 }
Douglas Gregor5545e162009-03-24 00:38:23 +000072
John McCallfd810b12009-08-14 02:03:10 +000073 const LangOptions &getLangOptions() {
74 return SemaRef.getLangOptions();
75 }
76
Douglas Gregor5545e162009-03-24 00:38:23 +000077 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000078 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000079 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000080 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000081 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000082
83 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000084 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000085 };
86}
87
Douglas Gregor4f722be2009-03-25 15:45:12 +000088Decl *
89TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
90 assert(false && "Translation units cannot be instantiated");
91 return D;
92}
93
94Decl *
95TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
96 assert(false && "Namespaces cannot be instantiated");
97 return D;
98}
99
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000100Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
101 bool Invalid = false;
John McCallba6a9bd2009-10-24 08:00:42 +0000102 DeclaratorInfo *DI = D->getTypeDeclaratorInfo();
103 if (DI->getType()->isDependentType()) {
104 DI = SemaRef.SubstType(DI, TemplateArgs,
105 D->getLocation(), D->getDeclName());
106 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000107 Invalid = true;
John McCallba6a9bd2009-10-24 08:00:42 +0000108 DI = SemaRef.Context.getTrivialDeclaratorInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000109 }
110 }
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000112 // Create the new typedef
113 TypedefDecl *Typedef
114 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000115 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000116 if (Invalid)
117 Typedef->setInvalidDecl();
118
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000119 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000121 return Typedef;
122}
123
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000124Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000125 // Do substitution on the type of the declaration
John McCall0a5fa062009-10-21 02:39:02 +0000126 DeclaratorInfo *DI = SemaRef.SubstType(D->getDeclaratorInfo(),
127 TemplateArgs,
128 D->getTypeSpecStartLoc(),
129 D->getDeclName());
130 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000131 return 0;
132
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000133 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000134 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
135 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000136 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000137 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000138 Var->setThreadSpecified(D->isThreadSpecified());
139 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
140 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000141
142 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000143 // out-of-line, the instantiation will have the same lexical
144 // context (which will be a namespace scope) as the template.
145 if (D->isOutOfLine())
146 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Mike Stump390b4cc2009-05-16 07:39:55 +0000148 // FIXME: In theory, we could have a previous declaration for variables that
149 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000150 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000151 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Douglas Gregor7caa6822009-07-24 20:34:43 +0000153 if (D->isOutOfLine()) {
154 D->getLexicalDeclContext()->addDecl(Var);
155 Owner->makeDeclVisibleInContext(Var);
156 } else {
157 Owner->addDecl(Var);
158 }
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000160 // Link instantiations of static data members back to the template from
161 // which they were instantiated.
162 if (Var->isStaticDataMember())
163 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
164 TSK_ImplicitInstantiation);
165
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000166 if (D->getInit()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000167 OwningExprResult Init
John McCallce3ff2b2009-08-25 22:02:44 +0000168 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000169 if (Init.isInvalid())
170 Var->setInvalidDecl();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000171 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000172 // FIXME: We're faking all of the comma locations, which is suboptimal.
Douglas Gregor83ddad32009-08-26 21:14:46 +0000173 // Do we even need these comma locations?
174 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
175 if (PLE->getNumExprs() > 0) {
176 FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
177 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
178 Expr *E = PLE->getExpr(I)->Retain();
179 FakeCommaLocs.push_back(
180 SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
181 }
Douglas Gregore9f8eb62009-08-26 23:26:04 +0000182 PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000183 }
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Douglas Gregor83ddad32009-08-26 21:14:46 +0000185 // Add the direct initializer to the declaration.
186 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Mike Stump1eb44332009-09-09 15:08:12 +0000187 PLE->getLParenLoc(),
Douglas Gregor83ddad32009-08-26 21:14:46 +0000188 Sema::MultiExprArg(SemaRef,
189 (void**)PLE->getExprs(),
190 PLE->getNumExprs()),
191 FakeCommaLocs.data(),
192 PLE->getRParenLoc());
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Douglas Gregor83ddad32009-08-26 21:14:46 +0000194 // When Init is destroyed, it will destroy the instantiated ParenListExpr;
195 // we've explicitly retained all of its subexpressions already.
196 } else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000197 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000198 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000199 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
200 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000201
202 return Var;
203}
204
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000205Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
206 bool Invalid = false;
John McCall07fb6be2009-10-22 23:33:21 +0000207 DeclaratorInfo *DI = D->getDeclaratorInfo();
208 if (DI->getType()->isDependentType()) {
209 DI = SemaRef.SubstType(DI, TemplateArgs,
210 D->getLocation(), D->getDeclName());
211 if (!DI) {
212 DI = D->getDeclaratorInfo();
213 Invalid = true;
214 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000215 // C++ [temp.arg.type]p3:
216 // If a declaration acquires a function type through a type
217 // dependent on a template-parameter and this causes a
218 // declaration that does not use the syntactic form of a
219 // function declarator to have function type, the program is
220 // ill-formed.
221 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000222 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000223 Invalid = true;
224 }
225 }
226
227 Expr *BitWidth = D->getBitWidth();
228 if (Invalid)
229 BitWidth = 0;
230 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000231 // The bit-width expression is not potentially evaluated.
232 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000234 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000235 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000236 if (InstantiatedBitWidth.isInvalid()) {
237 Invalid = true;
238 BitWidth = 0;
239 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000240 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000241 }
242
John McCall07fb6be2009-10-22 23:33:21 +0000243 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
244 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000245 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000246 D->getLocation(),
247 D->isMutable(),
248 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000249 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000250 D->getAccess(),
251 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000252 if (!Field) {
253 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000254 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000255 }
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000257 if (Invalid)
258 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000260 if (!Field->getDeclName()) {
261 // Keep track of where this decl came from.
262 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000263 }
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000265 Field->setImplicit(D->isImplicit());
266 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000267
268 return Field;
269}
270
John McCall02cace72009-08-28 07:59:38 +0000271Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
272 FriendDecl::FriendUnion FU;
273
274 // Handle friend type expressions by simply substituting template
275 // parameters into the pattern type.
276 if (Type *Ty = D->getFriendType()) {
277 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
278 D->getLocation(), DeclarationName());
279 if (T.isNull()) return 0;
280
281 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
282 FU = T.getTypePtr();
283
284 // Handle everything else by appropriate substitution.
285 } else {
286 NamedDecl *ND = D->getFriendDecl();
287 assert(ND && "friend decl must be a decl or a type!");
288
Douglas Gregora735b202009-10-13 14:39:41 +0000289 // FIXME: We have a problem here, because the nested call to Visit(ND)
290 // will inject the thing that the friend references into the current
291 // owner, which is wrong.
John McCall02cace72009-08-28 07:59:38 +0000292 Decl *NewND = Visit(ND);
293 if (!NewND) return 0;
294
295 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000296 }
Mike Stump1eb44332009-09-09 15:08:12 +0000297
John McCall02cace72009-08-28 07:59:38 +0000298 FriendDecl *FD =
299 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
300 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000301 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000302 Owner->addDecl(FD);
303 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000304}
305
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000306Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
307 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Douglas Gregorac7610d2009-06-22 20:57:11 +0000309 // The expression in a static assertion is not potentially evaluated.
310 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000312 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000313 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000314 if (InstantiatedAssertExpr.isInvalid())
315 return 0;
316
Douglas Gregor43d9d922009-08-08 01:41:12 +0000317 OwningExprResult Message(SemaRef, D->getMessage());
318 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000319 Decl *StaticAssert
320 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000321 move(InstantiatedAssertExpr),
322 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000323 return StaticAssert;
324}
325
326Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000327 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000328 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000329 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000330 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000331 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000332 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000333 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000334 Enum->startDefinition();
335
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000336 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000337
338 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000339 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
340 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000341 EC != ECEnd; ++EC) {
342 // The specified value for the enumerator.
343 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000344 if (Expr *UninstValue = EC->getInitExpr()) {
345 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000346 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000347 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000348
John McCallce3ff2b2009-08-25 22:02:44 +0000349 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000350 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000351
352 // Drop the initial value and continue.
353 bool isInvalid = false;
354 if (Value.isInvalid()) {
355 Value = SemaRef.Owned((Expr *)0);
356 isInvalid = true;
357 }
358
Mike Stump1eb44332009-09-09 15:08:12 +0000359 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000360 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
361 EC->getLocation(), EC->getIdentifier(),
362 move(Value));
363
364 if (isInvalid) {
365 if (EnumConst)
366 EnumConst->setInvalidDecl();
367 Enum->setInvalidDecl();
368 }
369
370 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000371 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000372 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000373 LastEnumConst = EnumConst;
374 }
375 }
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000377 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000378 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000379 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
380 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000381 &Enumerators[0], Enumerators.size(),
382 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000383
384 return Enum;
385}
386
Douglas Gregor6477b692009-03-25 15:04:13 +0000387Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
388 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
389 return 0;
390}
391
John McCalle29ba202009-08-20 01:44:21 +0000392Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
393 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000394 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000395 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000396 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000397
398 CXXRecordDecl *Pattern = D->getTemplatedDecl();
399 CXXRecordDecl *RecordInst
400 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
401 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000402 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
403 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000404
405 ClassTemplateDecl *Inst
406 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
407 D->getIdentifier(), InstParams, RecordInst, 0);
408 RecordInst->setDescribedClassTemplate(Inst);
409 Inst->setAccess(D->getAccess());
410 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000411
412 // Trigger creation of the type for the instantiation.
413 SemaRef.Context.getTypeDeclType(RecordInst);
414
John McCalle29ba202009-08-20 01:44:21 +0000415 Owner->addDecl(Inst);
416 return Inst;
417}
418
Douglas Gregord60e1052009-08-27 16:57:43 +0000419Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000420TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
421 ClassTemplatePartialSpecializationDecl *D) {
422 assert(false &&"Partial specializations of member templates are unsupported");
423 return 0;
424}
425
426Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000427TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregord0e3daf2009-09-04 22:48:11 +0000428 // FIXME: Dig out the out-of-line definition of this function template?
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Douglas Gregord60e1052009-08-27 16:57:43 +0000430 TemplateParameterList *TempParams = D->getTemplateParameters();
431 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000432 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000433 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Douglas Gregora735b202009-10-13 14:39:41 +0000435 FunctionDecl *Instantiated = 0;
436 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
437 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
438 InstParams));
439 else
440 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
441 D->getTemplatedDecl(),
442 InstParams));
443
444 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000445 return 0;
446
Mike Stump1eb44332009-09-09 15:08:12 +0000447 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000448 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000449 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000450 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000451 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000452 assert(InstTemplate &&
453 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
454 if (!InstTemplate->getInstantiatedFromMemberTemplate())
455 InstTemplate->setInstantiatedFromMemberTemplate(D);
456
457 // Add non-friends into the owner.
458 if (!InstTemplate->getFriendObjectKind())
459 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000460 return InstTemplate;
461}
462
Douglas Gregord475b8d2009-03-25 21:17:03 +0000463Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
464 CXXRecordDecl *PrevDecl = 0;
465 if (D->isInjectedClassName())
466 PrevDecl = cast<CXXRecordDecl>(Owner);
467
468 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000469 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000470 D->getLocation(), D->getIdentifier(),
471 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000472 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000473 // FIXME: Check against AS_none is an ugly hack to work around the issue that
474 // the tag decls introduced by friend class declarations don't have an access
475 // specifier. Remove once this area of the code gets sorted out.
476 if (D->getAccess() != AS_none)
477 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000478 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000479 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000480
John McCall02cace72009-08-28 07:59:38 +0000481 // If the original function was part of a friend declaration,
482 // inherit its namespace state.
483 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
484 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
485
Anders Carlssond8b285f2009-09-01 04:26:58 +0000486 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
487
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000488 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000489 return Record;
490}
491
John McCall02cace72009-08-28 07:59:38 +0000492/// Normal class members are of more specific types and therefore
493/// don't make it here. This function serves two purposes:
494/// 1) instantiating function templates
495/// 2) substituting friend declarations
496/// FIXME: preserve function definitions in case #2
Douglas Gregora735b202009-10-13 14:39:41 +0000497 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
498 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000499 // Check whether there is already a function template specialization for
500 // this declaration.
501 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
502 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000503 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000504 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000505 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000506 TemplateArgs.getInnermost().getFlatArgumentList(),
507 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000508 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000509
510 FunctionTemplateSpecializationInfo *Info
511 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000512 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Douglas Gregor127102b2009-06-29 20:59:39 +0000514 // If we already have a function template specialization, return it.
515 if (Info)
516 return Info->Function;
517 }
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Douglas Gregore53060f2009-06-25 22:08:12 +0000519 Sema::LocalInstantiationScope Scope(SemaRef);
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Douglas Gregore53060f2009-06-25 22:08:12 +0000521 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000522 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000523 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000524 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000525
Douglas Gregore53060f2009-06-25 22:08:12 +0000526 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000527 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
528 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000529 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000530 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000531 D->getDeclName(), T, D->getDeclaratorInfo(),
532 D->getStorageClass(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000533 D->isInline(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000534 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Douglas Gregore53060f2009-06-25 22:08:12 +0000536 // Attach the parameters
537 for (unsigned P = 0; P < Params.size(); ++P)
538 Params[P]->setOwningFunction(Function);
539 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000540
Douglas Gregora735b202009-10-13 14:39:41 +0000541 if (TemplateParams) {
542 // Our resulting instantiation is actually a function template, since we
543 // are substituting only the outer template parameters. For example, given
544 //
545 // template<typename T>
546 // struct X {
547 // template<typename U> friend void f(T, U);
548 // };
549 //
550 // X<int> x;
551 //
552 // We are instantiating the friend function template "f" within X<int>,
553 // which means substituting int for T, but leaving "f" as a friend function
554 // template.
555 // Build the function template itself.
556 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
557 Function->getLocation(),
558 Function->getDeclName(),
559 TemplateParams, Function);
560 Function->setDescribedFunctionTemplate(FunctionTemplate);
561 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
John McCall02cace72009-08-28 07:59:38 +0000562 }
Douglas Gregora735b202009-10-13 14:39:41 +0000563
Douglas Gregore53060f2009-06-25 22:08:12 +0000564 if (InitFunctionInstantiation(Function, D))
565 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Douglas Gregore53060f2009-06-25 22:08:12 +0000567 bool Redeclaration = false;
568 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000569
Douglas Gregore53060f2009-06-25 22:08:12 +0000570 NamedDecl *PrevDecl = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000571 if (TemplateParams || !FunctionTemplate) {
572 // Look only into the namespace where the friend would be declared to
573 // find a previous declaration. This is the innermost enclosing namespace,
574 // as described in ActOnFriendFunctionDecl.
575 Sema::LookupResult R;
576 SemaRef.LookupQualifiedName(R, DC, Function->getDeclName(),
577 Sema::LookupOrdinaryName, true);
578
579 PrevDecl = R.getAsSingleDecl(SemaRef.Context);
580
581 // In C++, the previous declaration we find might be a tag type
582 // (class or enum). In this case, the new declaration will hide the
583 // tag type. Note that this does does not apply if we're declaring a
584 // typedef (C++ [dcl.typedef]p4).
585 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
586 PrevDecl = 0;
587 }
588
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000589 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000590 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000591
Douglas Gregora735b202009-10-13 14:39:41 +0000592 // If the original function was part of a friend declaration,
593 // inherit its namespace state and add it to the owner.
594 NamedDecl *FromFriendD
595 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
596 if (FromFriendD->getFriendObjectKind()) {
597 NamedDecl *ToFriendD = 0;
598 if (TemplateParams) {
599 ToFriendD = cast<NamedDecl>(FunctionTemplate);
600 PrevDecl = FunctionTemplate->getPreviousDeclaration();
601 } else {
602 ToFriendD = Function;
603 PrevDecl = Function->getPreviousDeclaration();
604 }
605 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
606 if (!Owner->isDependentContext() && !PrevDecl)
607 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
608
609 if (!TemplateParams)
610 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
611 }
612
613 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000614 // Record this function template specialization.
615 Function->setFunctionTemplateSpecialization(SemaRef.Context,
616 FunctionTemplate,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000617 &TemplateArgs.getInnermost(),
Douglas Gregor127102b2009-06-29 20:59:39 +0000618 InsertPos);
John McCallfd810b12009-08-14 02:03:10 +0000619 }
620
Douglas Gregore53060f2009-06-25 22:08:12 +0000621 return Function;
622}
623
Douglas Gregord60e1052009-08-27 16:57:43 +0000624Decl *
625TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
626 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000627 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
628 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000629 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000630 // We are creating a function template specialization from a function
631 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000632 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000633 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000634 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000635 TemplateArgs.getInnermost().getFlatArgumentList(),
636 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000637 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
639 FunctionTemplateSpecializationInfo *Info
640 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000641 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Douglas Gregor6b906862009-08-21 00:16:32 +0000643 // If we already have a function template specialization, return it.
644 if (Info)
645 return Info->Function;
646 }
647
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000648 Sema::LocalInstantiationScope Scope(SemaRef);
649
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000650 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000651 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000652 if (T.isNull())
653 return 0;
654
655 // Build the instantiated method declaration.
656 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000657 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Douglas Gregordec06662009-08-21 18:42:58 +0000659 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000660 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000661 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
662 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
663 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000664 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
665 Constructor->getLocation(),
666 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000667 Constructor->getDeclaratorInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000668 Constructor->isExplicit(),
Douglas Gregor17e32f32009-08-21 22:43:28 +0000669 Constructor->isInline(), false);
670 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
671 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
672 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
673 SemaRef.Context.getCanonicalType(ClassTy));
674 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
675 Destructor->getLocation(), Name,
676 T, Destructor->isInline(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000677 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000678 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000679 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000680 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000681 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
682 ConvTy);
683 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
684 Conversion->getLocation(), Name,
685 T, Conversion->getDeclaratorInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000686 Conversion->isInline(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000687 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000688 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000689 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000690 D->getDeclName(), T, D->getDeclaratorInfo(),
691 D->isStatic(), D->isInline());
692 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000693
Douglas Gregord60e1052009-08-27 16:57:43 +0000694 if (TemplateParams) {
695 // Our resulting instantiation is actually a function template, since we
696 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000697 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000698 // template<typename T>
699 // struct X {
700 // template<typename U> void f(T, U);
701 // };
702 //
703 // X<int> x;
704 //
705 // We are instantiating the member template "f" within X<int>, which means
706 // substituting int for T, but leaving "f" as a member function template.
707 // Build the function template itself.
708 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
709 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000710 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000711 TemplateParams, Method);
712 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000713 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000714 Method->setDescribedFunctionTemplate(FunctionTemplate);
715 } else if (!FunctionTemplate)
Douglas Gregor2db32322009-10-07 23:56:10 +0000716 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000717
Mike Stump1eb44332009-09-09 15:08:12 +0000718 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000719 // out-of-line, the instantiation will have the same lexical
720 // context (which will be a namespace scope) as the template.
721 if (D->isOutOfLine())
722 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Douglas Gregor5545e162009-03-24 00:38:23 +0000724 // Attach the parameters
725 for (unsigned P = 0; P < Params.size(); ++P)
726 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000727 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000728
729 if (InitMethodInstantiation(Method, D))
730 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000731
Douglas Gregordec06662009-08-21 18:42:58 +0000732 NamedDecl *PrevDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Douglas Gregord60e1052009-08-27 16:57:43 +0000734 if (!FunctionTemplate || TemplateParams) {
John McCallf36e02d2009-10-09 21:13:30 +0000735 Sema::LookupResult R;
736 SemaRef.LookupQualifiedName(R, Owner, Name, Sema::LookupOrdinaryName, true);
737 PrevDecl = R.getAsSingleDecl(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Douglas Gregordec06662009-08-21 18:42:58 +0000739 // In C++, the previous declaration we find might be a tag type
740 // (class or enum). In this case, the new declaration will hide the
741 // tag type. Note that this does does not apply if we're declaring a
742 // typedef (C++ [dcl.typedef]p4).
743 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
744 PrevDecl = 0;
745 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000746
Douglas Gregord60e1052009-08-27 16:57:43 +0000747 if (FunctionTemplate && !TemplateParams)
Douglas Gregor6b906862009-08-21 00:16:32 +0000748 // Record this function template specialization.
749 Method->setFunctionTemplateSpecialization(SemaRef.Context,
750 FunctionTemplate,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000751 &TemplateArgs.getInnermost(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000752 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000753
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000754 bool Redeclaration = false;
755 bool OverloadableAttrRequired = false;
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000756 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000757 /*FIXME:*/OverloadableAttrRequired);
758
Douglas Gregora735b202009-10-13 14:39:41 +0000759 if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl) &&
760 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000761 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000763 return Method;
764}
765
Douglas Gregor615c5d42009-03-24 16:43:20 +0000766Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000767 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000768}
769
Douglas Gregor03b2b072009-03-24 00:15:49 +0000770Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000771 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000772}
773
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000774Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000775 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000776}
777
Douglas Gregor6477b692009-03-25 15:04:13 +0000778ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000779 QualType T;
780 DeclaratorInfo *DI = D->getDeclaratorInfo();
781 if (DI) {
782 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
783 D->getDeclName());
784 if (DI) T = DI->getType();
785 } else {
786 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
787 D->getDeclName());
788 DI = 0;
789 }
790
791 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000792 return 0;
793
John McCall58e46772009-10-23 21:48:59 +0000794 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000795
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000796 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +0000797 ParmVarDecl *Param
798 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
799 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000800
Anders Carlsson9351c172009-08-25 03:18:48 +0000801 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +0000802 if (D->hasUninstantiatedDefaultArg())
803 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +0000804 else if (Expr *Arg = D->getDefaultArg())
805 Param->setUninstantiatedDefaultArg(Arg);
806
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000807 // Note: we don't try to instantiate function parameters until after
808 // we've instantiated the function's type. Therefore, we don't have
809 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000810 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000811 return Param;
812}
813
John McCalle29ba202009-08-20 01:44:21 +0000814Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
815 TemplateTypeParmDecl *D) {
816 // TODO: don't always clone when decls are refcounted.
817 const Type* T = D->getTypeForDecl();
818 assert(T->isTemplateTypeParmType());
819 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +0000820
John McCalle29ba202009-08-20 01:44:21 +0000821 TemplateTypeParmDecl *Inst =
822 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
823 TTPT->getDepth(), TTPT->getIndex(),
824 TTPT->getName(),
825 D->wasDeclaredWithTypename(),
826 D->isParameterPack());
827
Douglas Gregor33642df2009-10-23 23:25:44 +0000828 // FIXME: Do we actually want to perform substitution here? I don't think
829 // we do.
John McCalle29ba202009-08-20 01:44:21 +0000830 if (D->hasDefaultArgument()) {
831 QualType DefaultPattern = D->getDefaultArgument();
832 QualType DefaultInst
John McCallce3ff2b2009-08-25 22:02:44 +0000833 = SemaRef.SubstType(DefaultPattern, TemplateArgs,
834 D->getDefaultArgumentLoc(),
835 D->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +0000836
John McCalle29ba202009-08-20 01:44:21 +0000837 Inst->setDefaultArgument(DefaultInst,
838 D->getDefaultArgumentLoc(),
839 D->defaultArgumentWasInherited() /* preserve? */);
840 }
841
842 return Inst;
843}
844
Douglas Gregor33642df2009-10-23 23:25:44 +0000845Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
846 NonTypeTemplateParmDecl *D) {
847 // Substitute into the type of the non-type template parameter.
848 QualType T;
849 DeclaratorInfo *DI = D->getDeclaratorInfo();
850 if (DI) {
851 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
852 D->getDeclName());
853 if (DI) T = DI->getType();
854 } else {
855 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
856 D->getDeclName());
857 DI = 0;
858 }
859 if (T.isNull())
860 return 0;
861
862 // Check that this type is acceptable for a non-type template parameter.
863 bool Invalid = false;
864 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
865 if (T.isNull()) {
866 T = SemaRef.Context.IntTy;
867 Invalid = true;
868 }
869
870 NonTypeTemplateParmDecl *Param
871 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
872 D->getDepth() - 1, D->getPosition(),
873 D->getIdentifier(), T, DI);
874 if (Invalid)
875 Param->setInvalidDecl();
876
877 Param->setDefaultArgument(D->getDefaultArgument());
878 return Param;
879}
880
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000881Decl *
882TemplateDeclInstantiator::VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000883 NestedNameSpecifier *NNS =
884 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
885 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000886 TemplateArgs);
887 if (!NNS)
888 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000890 CXXScopeSpec SS;
891 SS.setRange(D->getTargetNestedNameRange());
892 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +0000893
894 NamedDecl *UD =
895 SemaRef.BuildUsingDeclaration(D->getLocation(), SS,
896 D->getTargetNameLocation(),
Anders Carlsson0d8df782009-08-29 19:37:28 +0000897 D->getTargetName(), 0, D->isTypeName());
898 if (UD)
Mike Stump1eb44332009-09-09 15:08:12 +0000899 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
Anders Carlsson0d8df782009-08-29 19:37:28 +0000900 D);
901 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000902}
903
John McCallce3ff2b2009-08-25 22:02:44 +0000904Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000905 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +0000906 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000907 return Instantiator.Visit(D);
908}
909
John McCalle29ba202009-08-20 01:44:21 +0000910/// \brief Instantiates a nested template parameter list in the current
911/// instantiation context.
912///
913/// \param L The parameter list to instantiate
914///
915/// \returns NULL if there was an error
916TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000917TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +0000918 // Get errors for all the parameters before bailing out.
919 bool Invalid = false;
920
921 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000922 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +0000923 ParamVector Params;
924 Params.reserve(N);
925 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
926 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000927 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +0000928 Params.push_back(D);
929 Invalid = Invalid || !D;
930 }
931
932 // Clean up if we had an error.
933 if (Invalid) {
934 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
935 PI != PE; ++PI)
936 if (*PI)
937 (*PI)->Destroy(SemaRef.Context);
938 return NULL;
939 }
940
941 TemplateParameterList *InstL
942 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
943 L->getLAngleLoc(), &Params.front(), N,
944 L->getRAngleLoc());
945 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +0000946}
John McCalle29ba202009-08-20 01:44:21 +0000947
John McCallce3ff2b2009-08-25 22:02:44 +0000948/// \brief Does substitution on the type of the given function, including
949/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +0000950///
John McCallce3ff2b2009-08-25 22:02:44 +0000951/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +0000952///
953/// \param Params the instantiated parameter declarations
954
John McCallce3ff2b2009-08-25 22:02:44 +0000955/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +0000956/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +0000957QualType
John McCallce3ff2b2009-08-25 22:02:44 +0000958TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +0000959 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
960 bool InvalidDecl = false;
961
John McCallce3ff2b2009-08-25 22:02:44 +0000962 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +0000963 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000964 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +0000965 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000966 PEnd = D->param_end();
967 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000968 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000969 if (PInst->getType()->isVoidType()) {
970 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
971 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000972 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000973 PInst->getType(),
974 diag::err_abstract_type_in_decl,
975 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000976 PInst->setInvalidDecl();
977
978 Params.push_back(PInst);
979 ParamTys.push_back(PInst->getType());
980
981 if (PInst->isInvalidDecl())
982 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000983 } else
Douglas Gregor5545e162009-03-24 00:38:23 +0000984 InvalidDecl = true;
985 }
986
987 // FIXME: Deallocate dead declarations.
988 if (InvalidDecl)
989 return QualType();
990
John McCall183700f2009-09-21 23:43:11 +0000991 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +0000992 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +0000993 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +0000994 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
995 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +0000996 if (ResultType.isNull())
997 return QualType();
998
Jay Foadbeaaccd2009-05-21 09:52:38 +0000999 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001000 Proto->isVariadic(), Proto->getTypeQuals(),
1001 D->getLocation(), D->getDeclName());
1002}
1003
Mike Stump1eb44332009-09-09 15:08:12 +00001004/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001005/// declaration (New) from the corresponding fields of its template (Tmpl).
1006///
1007/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001008bool
1009TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001010 FunctionDecl *Tmpl) {
1011 if (Tmpl->isDeleted())
1012 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Douglas Gregorcca9e962009-07-01 22:01:06 +00001014 // If we are performing substituting explicitly-specified template arguments
1015 // or deduced template arguments into a function template and we reach this
1016 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001017 // to keeping the new function template specialization. We therefore
1018 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001019 // into a template instantiation for this specific function template
1020 // specialization, which is not a SFINAE context, so that we diagnose any
1021 // further errors in the declaration itself.
1022 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1023 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1024 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1025 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001026 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001027 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001028 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001029 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001030 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001031 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1032 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
1033 }
1034 }
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Douglas Gregore53060f2009-06-25 22:08:12 +00001036 return false;
1037}
1038
Douglas Gregor5545e162009-03-24 00:38:23 +00001039/// \brief Initializes common fields of an instantiated method
1040/// declaration (New) from the corresponding fields of its template
1041/// (Tmpl).
1042///
1043/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001044bool
1045TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001046 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001047 if (InitFunctionInstantiation(New, Tmpl))
1048 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Douglas Gregor5545e162009-03-24 00:38:23 +00001050 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1051 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +00001052 if (Tmpl->isVirtualAsWritten()) {
1053 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00001054 Record->setAggregate(false);
1055 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +00001056 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +00001057 Record->setPolymorphic(true);
1058 }
Douglas Gregor5545e162009-03-24 00:38:23 +00001059 if (Tmpl->isPure()) {
1060 New->setPure();
1061 Record->setAbstract(true);
1062 }
1063
1064 // FIXME: attributes
1065 // FIXME: New needs a pointer to Tmpl
1066 return false;
1067}
Douglas Gregora58861f2009-05-13 20:28:22 +00001068
1069/// \brief Instantiate the definition of the given function from its
1070/// template.
1071///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001072/// \param PointOfInstantiation the point at which the instantiation was
1073/// required. Note that this is not precisely a "point of instantiation"
1074/// for the function, but it's close.
1075///
Douglas Gregora58861f2009-05-13 20:28:22 +00001076/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001077/// function template specialization or member function of a class template
1078/// specialization.
1079///
1080/// \param Recursive if true, recursively instantiates any functions that
1081/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001082///
1083/// \param DefinitionRequired if true, then we are performing an explicit
1084/// instantiation where the body of the function is required. Complain if
1085/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001086void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001087 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001088 bool Recursive,
1089 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001090 if (Function->isInvalidDecl())
1091 return;
1092
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001093 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001095 // Never instantiate an explicit specialization.
1096 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1097 return;
1098
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001099 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +00001100 const FunctionDecl *PatternDecl = 0;
Douglas Gregor5ec178f2009-08-28 21:09:48 +00001101 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate()) {
Douglas Gregorfd056bc2009-10-13 16:30:37 +00001102 while (Primary->getInstantiatedFromMemberTemplate()) {
1103 // If we have hit a point where the user provided a specialization of
1104 // this template, we're done looking.
1105 if (Primary->isMemberSpecialization())
1106 break;
1107
Douglas Gregor5ec178f2009-08-28 21:09:48 +00001108 Primary = Primary->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00001109 }
1110
Douglas Gregor1637be72009-06-26 00:10:03 +00001111 PatternDecl = Primary->getTemplatedDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001112 } else
Douglas Gregor1637be72009-06-26 00:10:03 +00001113 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001114 Stmt *Pattern = 0;
1115 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001116 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001117
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001118 if (!Pattern) {
1119 if (DefinitionRequired) {
1120 if (Function->getPrimaryTemplate())
1121 Diag(PointOfInstantiation,
1122 diag::err_explicit_instantiation_undefined_func_template)
1123 << Function->getPrimaryTemplate();
1124 else
1125 Diag(PointOfInstantiation,
1126 diag::err_explicit_instantiation_undefined_member)
1127 << 1 << Function->getDeclName() << Function->getDeclContext();
1128
1129 if (PatternDecl)
1130 Diag(PatternDecl->getLocation(),
1131 diag::note_explicit_instantiation_here);
1132 }
1133
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001134 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001135 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001136
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001137 // C++0x [temp.explicit]p9:
1138 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001139 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001140 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001141 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001142 == TSK_ExplicitInstantiationDeclaration &&
1143 PatternDecl->isOutOfLine() && !PatternDecl->isInline())
1144 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001146 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1147 if (Inst)
1148 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001149
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001150 // If we're performing recursive template instantiation, create our own
1151 // queue of pending implicit instantiations that we will instantiate later,
1152 // while we're still within our own instantiation context.
1153 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1154 if (Recursive)
1155 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001157 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1158
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001159 // Introduce a new scope where local variable instantiations will be
1160 // recorded.
1161 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001163 // Introduce the instantiated function parameters into the local
1164 // instantiation scope.
1165 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1166 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1167 Function->getParamDecl(I));
1168
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001169 // Enter the scope of this instantiation. We don't use
1170 // PushDeclContext because we don't have a scope.
1171 DeclContext *PreviousContext = CurContext;
1172 CurContext = Function;
1173
Mike Stump1eb44332009-09-09 15:08:12 +00001174 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001175 getTemplateInstantiationArgs(Function);
1176
1177 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001178 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001179 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1180 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1181 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001182 }
1183
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001184 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001185 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001186
Douglas Gregor52604ab2009-09-11 21:19:12 +00001187 if (Body.isInvalid())
1188 Function->setInvalidDecl();
1189
Mike Stump1eb44332009-09-09 15:08:12 +00001190 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001191 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001192
1193 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001194
1195 DeclGroupRef DG(Function);
1196 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001198 if (Recursive) {
1199 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001200 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001201 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001203 // Restore the set of pending implicit instantiations.
1204 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1205 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001206}
1207
1208/// \brief Instantiate the definition of the given variable from its
1209/// template.
1210///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001211/// \param PointOfInstantiation the point at which the instantiation was
1212/// required. Note that this is not precisely a "point of instantiation"
1213/// for the function, but it's close.
1214///
1215/// \param Var the already-instantiated declaration of a static member
1216/// variable of a class template specialization.
1217///
1218/// \param Recursive if true, recursively instantiates any functions that
1219/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001220///
1221/// \param DefinitionRequired if true, then we are performing an explicit
1222/// instantiation where an out-of-line definition of the member variable
1223/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001224void Sema::InstantiateStaticDataMemberDefinition(
1225 SourceLocation PointOfInstantiation,
1226 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001227 bool Recursive,
1228 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001229 if (Var->isInvalidDecl())
1230 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Douglas Gregor7caa6822009-07-24 20:34:43 +00001232 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001233 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1234 bool FoundOutOfLineDef = false;
1235 assert(Def && "This data member was not instantiated from a template?");
Mike Stump1eb44332009-09-09 15:08:12 +00001236 assert(Def->isStaticDataMember() && "Not a static data member?");
1237 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001238 RDEnd = Def->redecls_end();
1239 RD != RDEnd; ++RD) {
1240 if (RD->getLexicalDeclContext()->isFileContext()) {
1241 Def = *RD;
1242 FoundOutOfLineDef = true;
1243 }
1244 }
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Douglas Gregor7caa6822009-07-24 20:34:43 +00001246 if (!FoundOutOfLineDef) {
1247 // We did not find an out-of-line definition of this static data member,
1248 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001249 // instantiate this definition (or provide a specialization for it) in
1250 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001251 if (DefinitionRequired) {
1252 Diag(PointOfInstantiation,
1253 diag::err_explicit_instantiation_undefined_member)
1254 << 2 << Var->getDeclName() << Var->getDeclContext();
1255 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1256 }
1257
Douglas Gregor7caa6822009-07-24 20:34:43 +00001258 return;
1259 }
1260
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001261 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001262 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001263 return;
1264
1265 // C++0x [temp.explicit]p9:
1266 // Except for inline functions, other explicit instantiation declarations
1267 // have the effect of suppressing the implicit instantiation of the entity
1268 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001269 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001270 == TSK_ExplicitInstantiationDeclaration)
1271 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Douglas Gregor7caa6822009-07-24 20:34:43 +00001273 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1274 if (Inst)
1275 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001276
Douglas Gregor7caa6822009-07-24 20:34:43 +00001277 // If we're performing recursive template instantiation, create our own
1278 // queue of pending implicit instantiations that we will instantiate later,
1279 // while we're still within our own instantiation context.
1280 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1281 if (Recursive)
1282 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Douglas Gregor7caa6822009-07-24 20:34:43 +00001284 // Enter the scope of this instantiation. We don't use
1285 // PushDeclContext because we don't have a scope.
1286 DeclContext *PreviousContext = CurContext;
1287 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001289 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001290 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001291 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001292 CurContext = PreviousContext;
1293
1294 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001295 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001296 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1297 assert(MSInfo && "Missing member specialization information?");
1298 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1299 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001300 DeclGroupRef DG(Var);
1301 Consumer.HandleTopLevelDecl(DG);
1302 }
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Douglas Gregor7caa6822009-07-24 20:34:43 +00001304 if (Recursive) {
1305 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001306 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001307 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001308
Douglas Gregor7caa6822009-07-24 20:34:43 +00001309 // Restore the set of pending implicit instantiations.
1310 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001311 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001312}
Douglas Gregor815215d2009-05-27 05:35:12 +00001313
Anders Carlsson09025312009-08-29 05:16:22 +00001314void
1315Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1316 const CXXConstructorDecl *Tmpl,
1317 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Anders Carlsson09025312009-08-29 05:16:22 +00001319 llvm::SmallVector<MemInitTy*, 4> NewInits;
1320
1321 // Instantiate all the initializers.
1322 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001323 InitsEnd = Tmpl->init_end();
1324 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001325 CXXBaseOrMemberInitializer *Init = *Inits;
1326
1327 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Anders Carlsson09025312009-08-29 05:16:22 +00001329 // Instantiate all the arguments.
1330 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1331 Args != ArgsEnd; ++Args) {
1332 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1333
1334 if (NewArg.isInvalid())
1335 New->setInvalidDecl();
1336 else
1337 NewArgs.push_back(NewArg.takeAs<Expr>());
1338 }
1339
1340 MemInitResult NewInit;
1341
1342 if (Init->isBaseInitializer()) {
Eli Friedmanc5573a82009-08-29 22:22:07 +00001343 QualType BaseType(Init->getBaseClass(), 0);
1344 BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(),
1345 New->getDeclName());
Anders Carlsson09025312009-08-29 05:16:22 +00001346
1347 NewInit = BuildBaseInitializer(BaseType,
Mike Stump1eb44332009-09-09 15:08:12 +00001348 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001349 NewArgs.size(),
1350 Init->getSourceLocation(),
1351 Init->getRParenLoc(),
1352 New->getParent());
1353 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001354 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001356 // Is this an anonymous union?
1357 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001358 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001359 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001360 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1361 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001362
1363 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001364 NewArgs.size(),
1365 Init->getSourceLocation(),
1366 Init->getRParenLoc());
1367 }
1368
1369 if (NewInit.isInvalid())
1370 New->setInvalidDecl();
1371 else {
1372 // FIXME: It would be nice if ASTOwningVector had a release function.
1373 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Anders Carlsson09025312009-08-29 05:16:22 +00001375 NewInits.push_back((MemInitTy *)NewInit.get());
1376 }
1377 }
Mike Stump1eb44332009-09-09 15:08:12 +00001378
Anders Carlsson09025312009-08-29 05:16:22 +00001379 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001380 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001381 /*FIXME: ColonLoc */
1382 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001383 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001384}
1385
John McCall52a575a2009-08-29 08:11:13 +00001386// TODO: this could be templated if the various decl types used the
1387// same method name.
1388static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1389 ClassTemplateDecl *Instance) {
1390 Pattern = Pattern->getCanonicalDecl();
1391
1392 do {
1393 Instance = Instance->getCanonicalDecl();
1394 if (Pattern == Instance) return true;
1395 Instance = Instance->getInstantiatedFromMemberTemplate();
1396 } while (Instance);
1397
1398 return false;
1399}
1400
Douglas Gregor0d696532009-09-28 06:34:35 +00001401static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1402 FunctionTemplateDecl *Instance) {
1403 Pattern = Pattern->getCanonicalDecl();
1404
1405 do {
1406 Instance = Instance->getCanonicalDecl();
1407 if (Pattern == Instance) return true;
1408 Instance = Instance->getInstantiatedFromMemberTemplate();
1409 } while (Instance);
1410
1411 return false;
1412}
1413
John McCall52a575a2009-08-29 08:11:13 +00001414static bool isInstantiationOf(CXXRecordDecl *Pattern,
1415 CXXRecordDecl *Instance) {
1416 Pattern = Pattern->getCanonicalDecl();
1417
1418 do {
1419 Instance = Instance->getCanonicalDecl();
1420 if (Pattern == Instance) return true;
1421 Instance = Instance->getInstantiatedFromMemberClass();
1422 } while (Instance);
1423
1424 return false;
1425}
1426
1427static bool isInstantiationOf(FunctionDecl *Pattern,
1428 FunctionDecl *Instance) {
1429 Pattern = Pattern->getCanonicalDecl();
1430
1431 do {
1432 Instance = Instance->getCanonicalDecl();
1433 if (Pattern == Instance) return true;
1434 Instance = Instance->getInstantiatedFromMemberFunction();
1435 } while (Instance);
1436
1437 return false;
1438}
1439
1440static bool isInstantiationOf(EnumDecl *Pattern,
1441 EnumDecl *Instance) {
1442 Pattern = Pattern->getCanonicalDecl();
1443
1444 do {
1445 Instance = Instance->getCanonicalDecl();
1446 if (Pattern == Instance) return true;
1447 Instance = Instance->getInstantiatedFromMemberEnum();
1448 } while (Instance);
1449
1450 return false;
1451}
1452
Anders Carlsson0d8df782009-08-29 19:37:28 +00001453static bool isInstantiationOf(UnresolvedUsingDecl *Pattern,
1454 UsingDecl *Instance,
1455 ASTContext &C) {
1456 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1457}
1458
John McCall52a575a2009-08-29 08:11:13 +00001459static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1460 VarDecl *Instance) {
1461 assert(Instance->isStaticDataMember());
1462
1463 Pattern = Pattern->getCanonicalDecl();
1464
1465 do {
1466 Instance = Instance->getCanonicalDecl();
1467 if (Pattern == Instance) return true;
1468 Instance = Instance->getInstantiatedFromStaticDataMember();
1469 } while (Instance);
1470
1471 return false;
1472}
1473
Douglas Gregor815215d2009-05-27 05:35:12 +00001474static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001475 if (D->getKind() != Other->getKind()) {
1476 if (UnresolvedUsingDecl *UUD = dyn_cast<UnresolvedUsingDecl>(D)) {
1477 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1478 return isInstantiationOf(UUD, UD, Ctx);
1479 }
1480 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001481
Anders Carlsson0d8df782009-08-29 19:37:28 +00001482 return false;
1483 }
Mike Stump1eb44332009-09-09 15:08:12 +00001484
John McCall52a575a2009-08-29 08:11:13 +00001485 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1486 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
John McCall52a575a2009-08-29 08:11:13 +00001488 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1489 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00001490
John McCall52a575a2009-08-29 08:11:13 +00001491 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1492 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00001493
Douglas Gregor7caa6822009-07-24 20:34:43 +00001494 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00001495 if (Var->isStaticDataMember())
1496 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1497
1498 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1499 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001500
Douglas Gregor0d696532009-09-28 06:34:35 +00001501 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
1502 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
1503
Anders Carlssond8b285f2009-09-01 04:26:58 +00001504 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
1505 if (!Field->getDeclName()) {
1506 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00001507 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00001508 cast<FieldDecl>(D);
1509 }
1510 }
Mike Stump1eb44332009-09-09 15:08:12 +00001511
Douglas Gregor815215d2009-05-27 05:35:12 +00001512 return D->getDeclName() && isa<NamedDecl>(Other) &&
1513 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1514}
1515
1516template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00001517static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00001518 NamedDecl *D,
1519 ForwardIterator first,
1520 ForwardIterator last) {
1521 for (; first != last; ++first)
1522 if (isInstantiationOf(Ctx, D, *first))
1523 return cast<NamedDecl>(*first);
1524
1525 return 0;
1526}
1527
John McCall02cace72009-08-28 07:59:38 +00001528/// \brief Finds the instantiation of the given declaration context
1529/// within the current instantiation.
1530///
1531/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00001532DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
1533 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00001534 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00001535 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00001536 return cast_or_null<DeclContext>(ID);
1537 } else return DC;
1538}
1539
Douglas Gregored961e72009-05-27 17:54:46 +00001540/// \brief Find the instantiation of the given declaration within the
1541/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001542///
1543/// This routine is intended to be used when \p D is a declaration
1544/// referenced from within a template, that needs to mapped into the
1545/// corresponding declaration within an instantiation. For example,
1546/// given:
1547///
1548/// \code
1549/// template<typename T>
1550/// struct X {
1551/// enum Kind {
1552/// KnownValue = sizeof(T)
1553/// };
1554///
1555/// bool getKind() const { return KnownValue; }
1556/// };
1557///
1558/// template struct X<int>;
1559/// \endcode
1560///
1561/// In the instantiation of X<int>::getKind(), we need to map the
1562/// EnumConstantDecl for KnownValue (which refers to
1563/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001564/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1565/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00001566NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
1567 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor44c73842009-09-01 17:53:10 +00001568 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
1569 // Transform all of the elements of the overloaded function set.
Mike Stump1eb44332009-09-09 15:08:12 +00001570 OverloadedFunctionDecl *Result
Douglas Gregor44c73842009-09-01 17:53:10 +00001571 = OverloadedFunctionDecl::Create(Context, CurContext, Ovl->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Douglas Gregor44c73842009-09-01 17:53:10 +00001573 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1574 FEnd = Ovl->function_end();
1575 F != FEnd; ++F) {
1576 Result->addOverload(
Douglas Gregore95b4092009-09-16 18:34:49 +00001577 AnyFunctionDecl::getFromNamedDecl(FindInstantiatedDecl(*F,
1578 TemplateArgs)));
Douglas Gregor44c73842009-09-01 17:53:10 +00001579 }
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Douglas Gregor44c73842009-09-01 17:53:10 +00001581 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001582 }
1583
Douglas Gregor815215d2009-05-27 05:35:12 +00001584 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001585 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1586 // D is a local of some kind. Look into the map of local
1587 // declarations to their instantiations.
1588 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1589 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001590
Douglas Gregore95b4092009-09-16 18:34:49 +00001591 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
1592 if (!Record->isDependentContext())
1593 return D;
1594
1595 // If the RecordDecl is actually the injected-class-name or a "templated"
1596 // declaration for a class template or class template partial
1597 // specialization, substitute into the injected-class-name of the
1598 // class template or partial specialization to find the new DeclContext.
1599 QualType T;
1600 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
1601
1602 if (ClassTemplate) {
1603 T = ClassTemplate->getInjectedClassNameType(Context);
1604 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1605 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1606 T = Context.getTypeDeclType(Record);
1607 ClassTemplate = PartialSpec->getSpecializedTemplate();
1608 }
1609
1610 if (!T.isNull()) {
1611 // Substitute into the injected-class-name to get the type corresponding
1612 // to the instantiation we want. This substitution should never fail,
1613 // since we know we can instantiate the injected-class-name or we wouldn't
1614 // have gotten to the injected-class-name!
1615 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
1616 // instantiation in the common case?
1617 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
1618 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
1619
1620 if (!T->isDependentType()) {
1621 assert(T->isRecordType() && "Instantiation must produce a record type");
1622 return T->getAs<RecordType>()->getDecl();
1623 }
1624
1625 // We are performing "partial" template instantiation to create the
1626 // member declarations for the members of a class template
1627 // specialization. Therefore, D is actually referring to something in
1628 // the current instantiation. Look through the current context,
1629 // which contains actual instantiations, to find the instantiation of
1630 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00001631 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00001632 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001633 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00001634 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00001635 if (isInstantiationOf(ClassTemplate,
1636 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00001637 return Spec;
1638 }
1639
Mike Stump1eb44332009-09-09 15:08:12 +00001640 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00001641 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00001642 return Record;
John McCall52a575a2009-08-29 08:11:13 +00001643 }
Douglas Gregore95b4092009-09-16 18:34:49 +00001644
1645 // Fall through to deal with other dependent record types (e.g.,
1646 // anonymous unions in class templates).
1647 }
John McCall52a575a2009-08-29 08:11:13 +00001648
Douglas Gregore95b4092009-09-16 18:34:49 +00001649 if (!ParentDC->isDependentContext())
1650 return D;
1651
1652 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001653 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00001654 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Douglas Gregor815215d2009-05-27 05:35:12 +00001656 if (ParentDC != D->getDeclContext()) {
1657 // We performed some kind of instantiation in the parent context,
1658 // so now we need to look into the instantiated parent context to
1659 // find the instantiation of the declaration D.
1660 NamedDecl *Result = 0;
1661 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001662 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001663 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1664 } else {
1665 // Since we don't have a name for the entity we're looking for,
1666 // our only option is to walk through all of the declarations to
1667 // find that name. This will occur in a few cases:
1668 //
1669 // - anonymous struct/union within a template
1670 // - unnamed class/struct/union/enum within a template
1671 //
1672 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00001673 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001674 ParentDC->decls_begin(),
1675 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Douglas Gregor815215d2009-05-27 05:35:12 +00001678 assert(Result && "Unable to find instantiation of declaration!");
1679 D = Result;
1680 }
1681
Douglas Gregor815215d2009-05-27 05:35:12 +00001682 return D;
1683}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001684
Mike Stump1eb44332009-09-09 15:08:12 +00001685/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001686/// instantiations we have seen until this point.
1687void Sema::PerformPendingImplicitInstantiations() {
1688 while (!PendingImplicitInstantiations.empty()) {
1689 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001690 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Douglas Gregor7caa6822009-07-24 20:34:43 +00001692 // Instantiate function definitions
1693 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001694 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00001695 Function->getLocation(), *this,
1696 Context.getSourceManager(),
1697 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001699 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001700 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001701 continue;
1702 }
Mike Stump1eb44332009-09-09 15:08:12 +00001703
Douglas Gregor7caa6822009-07-24 20:34:43 +00001704 // Instantiate static data member definitions.
1705 VarDecl *Var = cast<VarDecl>(Inst.first);
1706 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00001707
Mike Stump1eb44332009-09-09 15:08:12 +00001708 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00001709 Var->getLocation(), *this,
1710 Context.getSourceManager(),
1711 "instantiating static data member "
1712 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Douglas Gregor7caa6822009-07-24 20:34:43 +00001714 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001715 }
1716}