blob: 23256a853cd1148dbbf834ae5b876245e52459d4 [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"
18#include "llvm/Support/Compiler.h"
19
20using namespace clang;
21
22namespace {
23 class VISIBILITY_HIDDEN TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000024 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000025 Sema &SemaRef;
26 DeclContext *Owner;
Douglas Gregor7e063902009-05-11 23:53:27 +000027 const TemplateArgumentList &TemplateArgs;
Douglas Gregor8dbc2692009-03-17 21:15:40 +000028
29 public:
30 typedef Sema::OwningExprResult OwningExprResult;
31
32 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregor7e063902009-05-11 23:53:27 +000033 const TemplateArgumentList &TemplateArgs)
34 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Douglas Gregor8dbc2692009-03-17 21:15:40 +000035
Mike Stump390b4cc2009-05-16 07:39:55 +000036 // FIXME: Once we get closer to completion, replace these manually-written
37 // declarations with automatically-generated ones from
38 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000039 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
40 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000041 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000042 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000043 Decl *VisitFieldDecl(FieldDecl *D);
44 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
45 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000046 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCallfd810b12009-08-14 02:03:10 +000047 Decl *VisitFriendClassDecl(FriendClassDecl *D);
Douglas Gregore53060f2009-06-25 22:08:12 +000048 Decl *VisitFunctionDecl(FunctionDecl *D);
Douglas Gregord475b8d2009-03-25 21:17:03 +000049 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000050 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
Douglas Gregor615c5d42009-03-24 16:43:20 +000051 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000052 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000053 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000054 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000055 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000056 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
57 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor5545e162009-03-24 00:38:23 +000058
Douglas Gregor8dbc2692009-03-17 21:15:40 +000059 // Base case. FIXME: Remove once we can instantiate everything.
60 Decl *VisitDecl(Decl *) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000061 assert(false && "Template instantiation of unknown declaration kind!");
Douglas Gregor8dbc2692009-03-17 21:15:40 +000062 return 0;
63 }
Douglas Gregor5545e162009-03-24 00:38:23 +000064
John McCallfd810b12009-08-14 02:03:10 +000065 const LangOptions &getLangOptions() {
66 return SemaRef.getLangOptions();
67 }
68
Douglas Gregor5545e162009-03-24 00:38:23 +000069 // Helper functions for instantiating methods.
70 QualType InstantiateFunctionType(FunctionDecl *D,
71 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000072 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000073 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000074
75 TemplateParameterList *
76 InstantiateTemplateParams(TemplateParameterList *List);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000077 };
78}
79
Douglas Gregor4f722be2009-03-25 15:45:12 +000080Decl *
81TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
82 assert(false && "Translation units cannot be instantiated");
83 return D;
84}
85
86Decl *
87TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
88 assert(false && "Namespaces cannot be instantiated");
89 return D;
90}
91
Douglas Gregor8dbc2692009-03-17 21:15:40 +000092Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
93 bool Invalid = false;
94 QualType T = D->getUnderlyingType();
95 if (T->isDependentType()) {
Douglas Gregor1eee0e72009-05-14 21:06:31 +000096 T = SemaRef.InstantiateType(T, TemplateArgs,
97 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +000098 if (T.isNull()) {
99 Invalid = true;
100 T = SemaRef.Context.IntTy;
101 }
102 }
103
104 // Create the new typedef
105 TypedefDecl *Typedef
106 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
107 D->getIdentifier(), T);
108 if (Invalid)
109 Typedef->setInvalidDecl();
110
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000111 Owner->addDecl(Typedef);
Douglas Gregorbc221632009-05-28 16:34:51 +0000112
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000113 return Typedef;
114}
115
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000116Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
117 // Instantiate the type of the declaration
118 QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs,
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000119 D->getTypeSpecStartLoc(),
120 D->getDeclName());
121 if (T.isNull())
122 return 0;
123
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000124 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000125 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
126 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000127 T, D->getDeclaratorInfo(),
128 D->getStorageClass(),D->getTypeSpecStartLoc());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000129 Var->setThreadSpecified(D->isThreadSpecified());
130 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
131 Var->setDeclaredInCondition(D->isDeclaredInCondition());
132
Douglas Gregor7caa6822009-07-24 20:34:43 +0000133 // If we are instantiating a static data member defined
134 // out-of-line, the instantiation will have the same lexical
135 // context (which will be a namespace scope) as the template.
136 if (D->isOutOfLine())
137 Var->setLexicalDeclContext(D->getLexicalDeclContext());
138
Mike Stump390b4cc2009-05-16 07:39:55 +0000139 // FIXME: In theory, we could have a previous declaration for variables that
140 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000141 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000142 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000143
144 if (D->isOutOfLine()) {
145 D->getLexicalDeclContext()->addDecl(Var);
146 Owner->makeDeclVisibleInContext(Var);
147 } else {
148 Owner->addDecl(Var);
149 }
150
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000151 if (D->getInit()) {
152 OwningExprResult Init
Douglas Gregor7e063902009-05-11 23:53:27 +0000153 = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000154 if (Init.isInvalid())
155 Var->setInvalidDecl();
156 else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000157 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000158 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000159 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
160 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000161
Douglas Gregor7caa6822009-07-24 20:34:43 +0000162 // Link instantiations of static data members back to the template from
163 // which they were instantiated.
164 if (Var->isStaticDataMember())
165 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
166
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000167 return Var;
168}
169
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000170Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
171 bool Invalid = false;
172 QualType T = D->getType();
173 if (T->isDependentType()) {
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000174 T = SemaRef.InstantiateType(T, TemplateArgs,
175 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000176 if (!T.isNull() && T->isFunctionType()) {
177 // C++ [temp.arg.type]p3:
178 // If a declaration acquires a function type through a type
179 // dependent on a template-parameter and this causes a
180 // declaration that does not use the syntactic form of a
181 // function declarator to have function type, the program is
182 // ill-formed.
183 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
184 << T;
185 T = QualType();
186 Invalid = true;
187 }
188 }
189
190 Expr *BitWidth = D->getBitWidth();
191 if (Invalid)
192 BitWidth = 0;
193 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000194 // The bit-width expression is not potentially evaluated.
195 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
196
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000197 OwningExprResult InstantiatedBitWidth
Douglas Gregor7e063902009-05-11 23:53:27 +0000198 = SemaRef.InstantiateExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000199 if (InstantiatedBitWidth.isInvalid()) {
200 Invalid = true;
201 BitWidth = 0;
202 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000203 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000204 }
205
206 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000207 D->getDeclaratorInfo(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000208 cast<RecordDecl>(Owner),
209 D->getLocation(),
210 D->isMutable(),
211 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000212 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000213 D->getAccess(),
214 0);
215 if (Field) {
216 if (Invalid)
217 Field->setInvalidDecl();
218
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000219 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000220 }
221
222 return Field;
223}
224
John McCallfd810b12009-08-14 02:03:10 +0000225Decl *TemplateDeclInstantiator::VisitFriendClassDecl(FriendClassDecl *D) {
226 QualType T = D->getFriendType();
227 if (T->isDependentType()) {
228 T = SemaRef.InstantiateType(T, TemplateArgs, D->getLocation(),
229 DeclarationName());
230 assert(T.isNull() || getLangOptions().CPlusPlus0x || T->isRecordType());
231 }
232
233 // FIXME: the target context might be dependent.
234 DeclContext *DC = D->getDeclContext();
235 assert(DC->isFileContext());
236
237 FriendClassDecl *NewD =
238 FriendClassDecl::Create(SemaRef.Context, DC, D->getLocation(), T,
239 D->getFriendLoc());
240 Owner->addDecl(NewD);
241 return NewD;
242}
243
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000244Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
245 Expr *AssertExpr = D->getAssertExpr();
246
Douglas Gregorac7610d2009-06-22 20:57:11 +0000247 // The expression in a static assertion is not potentially evaluated.
248 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
249
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000250 OwningExprResult InstantiatedAssertExpr
Douglas Gregor7e063902009-05-11 23:53:27 +0000251 = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000252 if (InstantiatedAssertExpr.isInvalid())
253 return 0;
254
Douglas Gregor43d9d922009-08-08 01:41:12 +0000255 OwningExprResult Message(SemaRef, D->getMessage());
256 D->getMessage()->Retain();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000257 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000258 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
259 move(InstantiatedAssertExpr),
260 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000261 return StaticAssert;
262}
263
264Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
265 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
266 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000267 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000268 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000269 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000270 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000271 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000272 Enum->startDefinition();
273
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000274 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000275
276 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000277 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
278 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000279 EC != ECEnd; ++EC) {
280 // The specified value for the enumerator.
281 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000282 if (Expr *UninstValue = EC->getInitExpr()) {
283 // The enumerator's value expression is not potentially evaluated.
284 EnterExpressionEvaluationContext Unevaluated(SemaRef,
285 Action::Unevaluated);
286
Douglas Gregor7e063902009-05-11 23:53:27 +0000287 Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000288 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000289
290 // Drop the initial value and continue.
291 bool isInvalid = false;
292 if (Value.isInvalid()) {
293 Value = SemaRef.Owned((Expr *)0);
294 isInvalid = true;
295 }
296
297 EnumConstantDecl *EnumConst
298 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
299 EC->getLocation(), EC->getIdentifier(),
300 move(Value));
301
302 if (isInvalid) {
303 if (EnumConst)
304 EnumConst->setInvalidDecl();
305 Enum->setInvalidDecl();
306 }
307
308 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000309 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000310 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000311 LastEnumConst = EnumConst;
312 }
313 }
314
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000315 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000316 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000317 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
318 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000319 &Enumerators[0], Enumerators.size(),
320 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000321
322 return Enum;
323}
324
Douglas Gregor6477b692009-03-25 15:04:13 +0000325Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
326 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
327 return 0;
328}
329
John McCalle29ba202009-08-20 01:44:21 +0000330Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
331 TemplateParameterList *TempParams = D->getTemplateParameters();
332 TemplateParameterList *InstParams = InstantiateTemplateParams(TempParams);
333 if (!InstParams) return NULL;
334
335 CXXRecordDecl *Pattern = D->getTemplatedDecl();
336 CXXRecordDecl *RecordInst
337 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
338 Pattern->getLocation(), Pattern->getIdentifier(),
339 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
340
341 ClassTemplateDecl *Inst
342 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
343 D->getIdentifier(), InstParams, RecordInst, 0);
344 RecordInst->setDescribedClassTemplate(Inst);
345 Inst->setAccess(D->getAccess());
346 Inst->setInstantiatedFromMemberTemplate(D);
347
348 Owner->addDecl(Inst);
349 return Inst;
350}
351
Douglas Gregord475b8d2009-03-25 21:17:03 +0000352Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
353 CXXRecordDecl *PrevDecl = 0;
354 if (D->isInjectedClassName())
355 PrevDecl = cast<CXXRecordDecl>(Owner);
356
357 CXXRecordDecl *Record
358 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000359 D->getLocation(), D->getIdentifier(),
360 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000361 Record->setImplicit(D->isImplicit());
362 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000363 if (!D->isInjectedClassName())
364 Record->setInstantiationOfMemberClass(D);
365
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000366 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000367 return Record;
368}
369
Douglas Gregore53060f2009-06-25 22:08:12 +0000370Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000371 // Check whether there is already a function template specialization for
372 // this declaration.
373 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
374 void *InsertPos = 0;
375 if (FunctionTemplate) {
376 llvm::FoldingSetNodeID ID;
377 FunctionTemplateSpecializationInfo::Profile(ID,
378 TemplateArgs.getFlatArgumentList(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000379 TemplateArgs.flat_size(),
380 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000381
382 FunctionTemplateSpecializationInfo *Info
383 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
384 InsertPos);
385
386 // If we already have a function template specialization, return it.
387 if (Info)
388 return Info->Function;
389 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000390
391 Sema::LocalInstantiationScope Scope(SemaRef);
392
393 llvm::SmallVector<ParmVarDecl *, 4> Params;
394 QualType T = InstantiateFunctionType(D, Params);
395 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000396 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000397
Douglas Gregore53060f2009-06-25 22:08:12 +0000398 // Build the instantiated method declaration.
John McCallfd810b12009-08-14 02:03:10 +0000399 FunctionDecl *Function;
400 if (FriendFunctionDecl* FFD = dyn_cast<FriendFunctionDecl>(D)) {
401 // The new decl's semantic context. FIXME: this might need
402 // to be instantiated.
403 DeclContext *DC = D->getDeclContext();
404
405 // This assert is bogus and exists only to catch cases we don't
406 // handle yet.
407 assert(!DC->isDependentContext());
408
409 Function =
410 FriendFunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000411 D->getDeclName(), T, D->getDeclaratorInfo(),
412 D->isInline(), FFD->getFriendLoc());
John McCallfd810b12009-08-14 02:03:10 +0000413 Function->setLexicalDeclContext(Owner);
414 } else {
415 Function =
416 FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000417 D->getDeclName(), T, D->getDeclaratorInfo(),
418 D->getStorageClass(),
Douglas Gregore53060f2009-06-25 22:08:12 +0000419 D->isInline(), D->hasWrittenPrototype(),
420 D->getTypeSpecStartLoc());
John McCallfd810b12009-08-14 02:03:10 +0000421 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000422
423 // Attach the parameters
424 for (unsigned P = 0; P < Params.size(); ++P)
425 Params[P]->setOwningFunction(Function);
426 Function->setParams(SemaRef.Context, Params.data(), Params.size());
427
428 if (InitFunctionInstantiation(Function, D))
429 Function->setInvalidDecl();
430
431 bool Redeclaration = false;
432 bool OverloadableAttrRequired = false;
433 NamedDecl *PrevDecl = 0;
434 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
435 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000436
Douglas Gregor127102b2009-06-29 20:59:39 +0000437 if (FunctionTemplate) {
438 // Record this function template specialization.
439 Function->setFunctionTemplateSpecialization(SemaRef.Context,
440 FunctionTemplate,
441 &TemplateArgs,
442 InsertPos);
John McCallfd810b12009-08-14 02:03:10 +0000443 }
444
445 // If this was a friend function decl, it's a member which
446 // needs to be added.
447 if (isa<FriendFunctionDecl>(Function)) {
448 // If the new context is still dependent, this declaration
449 // needs to remain hidden.
450 if (Owner->isDependentContext())
451 Owner->addHiddenDecl(Function);
452 else
453 Owner->addDecl(Function);
454 }
Douglas Gregor127102b2009-06-29 20:59:39 +0000455
Douglas Gregore53060f2009-06-25 22:08:12 +0000456 return Function;
457}
458
459Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
460 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000461 Sema::LocalInstantiationScope Scope(SemaRef);
462
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000463 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000464 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000465 if (T.isNull())
466 return 0;
467
468 // Build the instantiated method declaration.
469 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
470 CXXMethodDecl *Method
471 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000472 D->getDeclName(), T, D->getDeclaratorInfo(),
473 D->isStatic(), D->isInline());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000474 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000475
Douglas Gregor7caa6822009-07-24 20:34:43 +0000476 // If we are instantiating a member function defined
477 // out-of-line, the instantiation will have the same lexical
478 // context (which will be a namespace scope) as the template.
479 if (D->isOutOfLine())
480 Method->setLexicalDeclContext(D->getLexicalDeclContext());
481
Douglas Gregor5545e162009-03-24 00:38:23 +0000482 // Attach the parameters
483 for (unsigned P = 0; P < Params.size(); ++P)
484 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000485 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000486
487 if (InitMethodInstantiation(Method, D))
488 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000489
490 NamedDecl *PrevDecl
491 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
492 Sema::LookupOrdinaryName, true);
493 // In C++, the previous declaration we find might be a tag type
494 // (class or enum). In this case, the new declaration will hide the
495 // tag type. Note that this does does not apply if we're declaring a
496 // typedef (C++ [dcl.typedef]p4).
497 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
498 PrevDecl = 0;
499 bool Redeclaration = false;
500 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000501 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
502 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000503
504 if (!Method->isInvalidDecl() || !PrevDecl)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000505 Owner->addDecl(Method);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000506 return Method;
507}
508
Douglas Gregor615c5d42009-03-24 16:43:20 +0000509Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000510 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000511 Sema::LocalInstantiationScope Scope(SemaRef);
512
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000513 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor615c5d42009-03-24 16:43:20 +0000514 QualType T = InstantiateFunctionType(D, Params);
515 if (T.isNull())
516 return 0;
517
518 // Build the instantiated method declaration.
519 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
520 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
521 DeclarationName Name
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000522 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
523 SemaRef.Context.getCanonicalType(ClassTy));
Douglas Gregor615c5d42009-03-24 16:43:20 +0000524 CXXConstructorDecl *Constructor
525 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000526 Name, T, D->getDeclaratorInfo(),
527 D->isExplicit(), D->isInline(), false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000528 Constructor->setInstantiationOfMemberFunction(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000529
530 // Attach the parameters
531 for (unsigned P = 0; P < Params.size(); ++P)
532 Params[P]->setOwningFunction(Constructor);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000533 Constructor->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor615c5d42009-03-24 16:43:20 +0000534
535 if (InitMethodInstantiation(Constructor, D))
536 Constructor->setInvalidDecl();
537
538 NamedDecl *PrevDecl
539 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
540
541 // In C++, the previous declaration we find might be a tag type
542 // (class or enum). In this case, the new declaration will hide the
543 // tag type. Note that this does does not apply if we're declaring a
544 // typedef (C++ [dcl.typedef]p4).
545 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
546 PrevDecl = 0;
547 bool Redeclaration = false;
548 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000549 SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
550 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000551
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000552 Record->addedConstructor(SemaRef.Context, Constructor);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000553 Owner->addDecl(Constructor);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000554 return Constructor;
555}
556
Douglas Gregor03b2b072009-03-24 00:15:49 +0000557Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000558 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000559 Sema::LocalInstantiationScope Scope(SemaRef);
560
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000561 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000562 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000563 if (T.isNull())
564 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +0000565 assert(Params.size() == 0 && "Destructor with parameters?");
566
Douglas Gregor03b2b072009-03-24 00:15:49 +0000567 // Build the instantiated destructor declaration.
568 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregor50d62d12009-08-05 05:36:45 +0000569 CanQualType ClassTy =
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000570 SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record));
Douglas Gregor03b2b072009-03-24 00:15:49 +0000571 CXXDestructorDecl *Destructor
572 = CXXDestructorDecl::Create(SemaRef.Context, Record,
573 D->getLocation(),
574 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
575 T, D->isInline(), false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000576 Destructor->setInstantiationOfMemberFunction(D);
Douglas Gregor5545e162009-03-24 00:38:23 +0000577 if (InitMethodInstantiation(Destructor, D))
578 Destructor->setInvalidDecl();
Douglas Gregor03b2b072009-03-24 00:15:49 +0000579
580 bool Redeclaration = false;
581 bool OverloadableAttrRequired = false;
582 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000583 SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
584 /*FIXME:*/OverloadableAttrRequired);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000585 Owner->addDecl(Destructor);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000586 return Destructor;
587}
588
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000589Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000590 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000591 Sema::LocalInstantiationScope Scope(SemaRef);
592
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000593 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000594 QualType T = InstantiateFunctionType(D, Params);
595 if (T.isNull())
596 return 0;
597 assert(Params.size() == 0 && "Destructor with parameters?");
598
599 // Build the instantiated conversion declaration.
600 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
601 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
Douglas Gregor50d62d12009-08-05 05:36:45 +0000602 CanQualType ConvTy
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000603 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
604 CXXConversionDecl *Conversion
605 = CXXConversionDecl::Create(SemaRef.Context, Record,
606 D->getLocation(),
607 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000608 T, D->getDeclaratorInfo(),
609 D->isInline(), D->isExplicit());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000610 Conversion->setInstantiationOfMemberFunction(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000611 if (InitMethodInstantiation(Conversion, D))
612 Conversion->setInvalidDecl();
613
614 bool Redeclaration = false;
615 bool OverloadableAttrRequired = false;
616 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000617 SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
618 /*FIXME:*/OverloadableAttrRequired);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000619 Owner->addDecl(Conversion);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000620 return Conversion;
621}
622
Douglas Gregor6477b692009-03-25 15:04:13 +0000623ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000624 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000625 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000626 if (OrigT.isNull())
627 return 0;
628
629 QualType T = SemaRef.adjustParameterType(OrigT);
630
631 if (D->getDefaultArg()) {
632 // FIXME: Leave a marker for "uninstantiated" default
633 // arguments. They only get instantiated on demand at the call
634 // site.
635 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
636 "sorry, dropping default argument during template instantiation");
637 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
638 << D->getDefaultArg()->getSourceRange();
639 }
640
641 // Allocate the parameter
642 ParmVarDecl *Param = 0;
643 if (T == OrigT)
644 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000645 D->getIdentifier(), T, D->getDeclaratorInfo(),
646 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000647 else
648 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
649 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000650 T, D->getDeclaratorInfo(), OrigT,
651 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000652
653 // Note: we don't try to instantiate function parameters until after
654 // we've instantiated the function's type. Therefore, we don't have
655 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000656 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000657 return Param;
658}
659
660Decl *
661TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
662 // Since parameter types can decay either before or after
663 // instantiation, we simply treat OriginalParmVarDecls as
664 // ParmVarDecls the same way, and create one or the other depending
665 // on what happens after template instantiation.
666 return VisitParmVarDecl(D);
667}
668
John McCalle29ba202009-08-20 01:44:21 +0000669Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
670 TemplateTypeParmDecl *D) {
671 // TODO: don't always clone when decls are refcounted.
672 const Type* T = D->getTypeForDecl();
673 assert(T->isTemplateTypeParmType());
674 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
675
676 TemplateTypeParmDecl *Inst =
677 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
678 TTPT->getDepth(), TTPT->getIndex(),
679 TTPT->getName(),
680 D->wasDeclaredWithTypename(),
681 D->isParameterPack());
682
683 if (D->hasDefaultArgument()) {
684 QualType DefaultPattern = D->getDefaultArgument();
685 QualType DefaultInst
686 = SemaRef.InstantiateType(DefaultPattern, TemplateArgs,
687 D->getDefaultArgumentLoc(),
688 D->getDeclName());
689
690 Inst->setDefaultArgument(DefaultInst,
691 D->getDefaultArgumentLoc(),
692 D->defaultArgumentWasInherited() /* preserve? */);
693 }
694
695 return Inst;
696}
697
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000698Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
Douglas Gregor7e063902009-05-11 23:53:27 +0000699 const TemplateArgumentList &TemplateArgs) {
700 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000701 return Instantiator.Visit(D);
702}
703
John McCalle29ba202009-08-20 01:44:21 +0000704/// \brief Instantiates a nested template parameter list in the current
705/// instantiation context.
706///
707/// \param L The parameter list to instantiate
708///
709/// \returns NULL if there was an error
710TemplateParameterList *
711TemplateDeclInstantiator::InstantiateTemplateParams(TemplateParameterList *L) {
712 // Get errors for all the parameters before bailing out.
713 bool Invalid = false;
714
715 unsigned N = L->size();
716 typedef llvm::SmallVector<Decl*,8> ParamVector;
717 ParamVector Params;
718 Params.reserve(N);
719 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
720 PI != PE; ++PI) {
721 Decl *D = Visit(*PI);
722 Params.push_back(D);
723 Invalid = Invalid || !D;
724 }
725
726 // Clean up if we had an error.
727 if (Invalid) {
728 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
729 PI != PE; ++PI)
730 if (*PI)
731 (*PI)->Destroy(SemaRef.Context);
732 return NULL;
733 }
734
735 TemplateParameterList *InstL
736 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
737 L->getLAngleLoc(), &Params.front(), N,
738 L->getRAngleLoc());
739 return InstL;
740}
741
Douglas Gregor5545e162009-03-24 00:38:23 +0000742/// \brief Instantiates the type of the given function, including
743/// instantiating all of the function parameters.
744///
745/// \param D The function that we will be instantiated
746///
747/// \param Params the instantiated parameter declarations
748
749/// \returns the instantiated function's type if successfull, a NULL
750/// type if there was an error.
751QualType
752TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
753 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
754 bool InvalidDecl = false;
755
756 // Instantiate the function parameters
Douglas Gregor7e063902009-05-11 23:53:27 +0000757 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000758 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000759 for (FunctionDecl::param_iterator P = D->param_begin(),
760 PEnd = D->param_end();
761 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000762 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000763 if (PInst->getType()->isVoidType()) {
764 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
765 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000766 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
767 PInst->getType(),
768 diag::err_abstract_type_in_decl,
769 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000770 PInst->setInvalidDecl();
771
772 Params.push_back(PInst);
773 ParamTys.push_back(PInst->getType());
774
775 if (PInst->isInvalidDecl())
776 InvalidDecl = true;
777 } else
778 InvalidDecl = true;
779 }
780
781 // FIXME: Deallocate dead declarations.
782 if (InvalidDecl)
783 return QualType();
784
785 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
786 assert(Proto && "Missing prototype?");
787 QualType ResultType
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000788 = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs,
Douglas Gregor5545e162009-03-24 00:38:23 +0000789 D->getLocation(), D->getDeclName());
790 if (ResultType.isNull())
791 return QualType();
792
Jay Foadbeaaccd2009-05-21 09:52:38 +0000793 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000794 Proto->isVariadic(), Proto->getTypeQuals(),
795 D->getLocation(), D->getDeclName());
796}
797
Douglas Gregore53060f2009-06-25 22:08:12 +0000798/// \brief Initializes the common fields of an instantiation function
799/// declaration (New) from the corresponding fields of its template (Tmpl).
800///
801/// \returns true if there was an error
802bool
803TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
804 FunctionDecl *Tmpl) {
805 if (Tmpl->isDeleted())
806 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000807
808 // If we are performing substituting explicitly-specified template arguments
809 // or deduced template arguments into a function template and we reach this
810 // point, we are now past the point where SFINAE applies and have committed
811 // to keeping the new function template specialization. We therefore
812 // convert the active template instantiation for the function template
813 // into a template instantiation for this specific function template
814 // specialization, which is not a SFINAE context, so that we diagnose any
815 // further errors in the declaration itself.
816 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
817 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
818 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
819 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
820 if (FunctionTemplateDecl *FunTmpl
821 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
822 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
823 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000824 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000825 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
826 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
827 }
828 }
829
Douglas Gregore53060f2009-06-25 22:08:12 +0000830 return false;
831}
832
Douglas Gregor5545e162009-03-24 00:38:23 +0000833/// \brief Initializes common fields of an instantiated method
834/// declaration (New) from the corresponding fields of its template
835/// (Tmpl).
836///
837/// \returns true if there was an error
838bool
839TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
840 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000841 if (InitFunctionInstantiation(New, Tmpl))
842 return true;
843
Douglas Gregor5545e162009-03-24 00:38:23 +0000844 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
845 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000846 if (Tmpl->isVirtualAsWritten()) {
847 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000848 Record->setAggregate(false);
849 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000850 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000851 Record->setPolymorphic(true);
852 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000853 if (Tmpl->isPure()) {
854 New->setPure();
855 Record->setAbstract(true);
856 }
857
858 // FIXME: attributes
859 // FIXME: New needs a pointer to Tmpl
860 return false;
861}
Douglas Gregora58861f2009-05-13 20:28:22 +0000862
863/// \brief Instantiate the definition of the given function from its
864/// template.
865///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000866/// \param PointOfInstantiation the point at which the instantiation was
867/// required. Note that this is not precisely a "point of instantiation"
868/// for the function, but it's close.
869///
Douglas Gregora58861f2009-05-13 20:28:22 +0000870/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000871/// function template specialization or member function of a class template
872/// specialization.
873///
874/// \param Recursive if true, recursively instantiates any functions that
875/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000876void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000877 FunctionDecl *Function,
878 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000879 if (Function->isInvalidDecl())
880 return;
881
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000882 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000883
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000884 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000885 const FunctionDecl *PatternDecl = 0;
886 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
887 PatternDecl = Primary->getTemplatedDecl();
888 else
889 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000890 Stmt *Pattern = 0;
891 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000892 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000893
894 if (!Pattern)
895 return;
896
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000897 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
898 if (Inst)
899 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000900
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000901 // If we're performing recursive template instantiation, create our own
902 // queue of pending implicit instantiations that we will instantiate later,
903 // while we're still within our own instantiation context.
904 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
905 if (Recursive)
906 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
907
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000908 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
909
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000910 // Introduce a new scope where local variable instantiations will be
911 // recorded.
912 LocalInstantiationScope Scope(*this);
913
914 // Introduce the instantiated function parameters into the local
915 // instantiation scope.
916 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
917 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
918 Function->getParamDecl(I));
919
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000920 // Enter the scope of this instantiation. We don't use
921 // PushDeclContext because we don't have a scope.
922 DeclContext *PreviousContext = CurContext;
923 CurContext = Function;
924
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000925 // Instantiate the function body.
926 OwningStmtResult Body
927 = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function));
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000928
929 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
930 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000931
932 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000933
934 DeclGroupRef DG(Function);
935 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000936
937 if (Recursive) {
938 // Instantiate any pending implicit instantiations found during the
939 // instantiation of this template.
940 PerformPendingImplicitInstantiations();
941
942 // Restore the set of pending implicit instantiations.
943 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
944 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000945}
946
947/// \brief Instantiate the definition of the given variable from its
948/// template.
949///
Douglas Gregor7caa6822009-07-24 20:34:43 +0000950/// \param PointOfInstantiation the point at which the instantiation was
951/// required. Note that this is not precisely a "point of instantiation"
952/// for the function, but it's close.
953///
954/// \param Var the already-instantiated declaration of a static member
955/// variable of a class template specialization.
956///
957/// \param Recursive if true, recursively instantiates any functions that
958/// are required by this instantiation.
959void Sema::InstantiateStaticDataMemberDefinition(
960 SourceLocation PointOfInstantiation,
961 VarDecl *Var,
962 bool Recursive) {
963 if (Var->isInvalidDecl())
964 return;
965
966 // Find the out-of-line definition of this static data member.
967 // FIXME: Do we have to look for specializations separately?
968 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
969 bool FoundOutOfLineDef = false;
970 assert(Def && "This data member was not instantiated from a template?");
971 assert(Def->isStaticDataMember() && "Not a static data member?");
972 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
973 RDEnd = Def->redecls_end();
974 RD != RDEnd; ++RD) {
975 if (RD->getLexicalDeclContext()->isFileContext()) {
976 Def = *RD;
977 FoundOutOfLineDef = true;
978 }
979 }
980
981 if (!FoundOutOfLineDef) {
982 // We did not find an out-of-line definition of this static data member,
983 // so we won't perform any instantiation. Rather, we rely on the user to
984 // instantiate this definition (or provide a specialization for it) in
985 // another translation unit.
986 return;
987 }
988
989 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
990 if (Inst)
991 return;
992
993 // If we're performing recursive template instantiation, create our own
994 // queue of pending implicit instantiations that we will instantiate later,
995 // while we're still within our own instantiation context.
996 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
997 if (Recursive)
998 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
999
1000 // Enter the scope of this instantiation. We don't use
1001 // PushDeclContext because we don't have a scope.
1002 DeclContext *PreviousContext = CurContext;
1003 CurContext = Var->getDeclContext();
1004
1005#if 0
1006 // Instantiate the initializer of this static data member.
1007 OwningExprResult Init
1008 = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
1009 if (Init.isInvalid()) {
1010 // If instantiation of the initializer failed, mark the declaration invalid
1011 // and don't instantiate anything else that was triggered by this
1012 // instantiation.
1013 Var->setInvalidDecl();
1014
1015 // Restore the set of pending implicit instantiations.
1016 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1017
1018 return;
1019 }
1020
1021 // Type-check the initializer.
1022 if (Init.get())
1023 AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
1024 Def->hasCXXDirectInitializer());
1025 else
1026 ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
1027#else
1028 Var = cast_or_null<VarDecl>(InstantiateDecl(Def, Var->getDeclContext(),
1029 getTemplateInstantiationArgs(Var)));
1030#endif
1031
1032 CurContext = PreviousContext;
1033
1034 if (Var) {
1035 DeclGroupRef DG(Var);
1036 Consumer.HandleTopLevelDecl(DG);
1037 }
1038
1039 if (Recursive) {
1040 // Instantiate any pending implicit instantiations found during the
1041 // instantiation of this template.
1042 PerformPendingImplicitInstantiations();
1043
1044 // Restore the set of pending implicit instantiations.
1045 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1046 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001047}
Douglas Gregor815215d2009-05-27 05:35:12 +00001048
1049static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1050 if (D->getKind() != Other->getKind())
1051 return false;
1052
1053 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001054 return Record->getInstantiatedFromMemberClass()->getCanonicalDecl()
1055 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001056
1057 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001058 return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl()
1059 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001060
Douglas Gregor8dbc3c62009-05-27 17:20:35 +00001061 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001062 return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl()
1063 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001064
Douglas Gregor7caa6822009-07-24 20:34:43 +00001065 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
1066 if (Var->isStaticDataMember())
1067 return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl()
1068 == D->getCanonicalDecl();
1069
Douglas Gregor815215d2009-05-27 05:35:12 +00001070 // FIXME: How can we find instantiations of anonymous unions?
1071
1072 return D->getDeclName() && isa<NamedDecl>(Other) &&
1073 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1074}
1075
1076template<typename ForwardIterator>
1077static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1078 NamedDecl *D,
1079 ForwardIterator first,
1080 ForwardIterator last) {
1081 for (; first != last; ++first)
1082 if (isInstantiationOf(Ctx, D, *first))
1083 return cast<NamedDecl>(*first);
1084
1085 return 0;
1086}
1087
Douglas Gregored961e72009-05-27 17:54:46 +00001088/// \brief Find the instantiation of the given declaration within the
1089/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001090///
1091/// This routine is intended to be used when \p D is a declaration
1092/// referenced from within a template, that needs to mapped into the
1093/// corresponding declaration within an instantiation. For example,
1094/// given:
1095///
1096/// \code
1097/// template<typename T>
1098/// struct X {
1099/// enum Kind {
1100/// KnownValue = sizeof(T)
1101/// };
1102///
1103/// bool getKind() const { return KnownValue; }
1104/// };
1105///
1106/// template struct X<int>;
1107/// \endcode
1108///
1109/// In the instantiation of X<int>::getKind(), we need to map the
1110/// EnumConstantDecl for KnownValue (which refers to
1111/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001112/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1113/// this mapping from within the instantiation of X<int>.
1114NamedDecl * Sema::InstantiateCurrentDeclRef(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +00001115 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001116 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1117 // D is a local of some kind. Look into the map of local
1118 // declarations to their instantiations.
1119 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1120 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001121
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001122 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
Douglas Gregored961e72009-05-27 17:54:46 +00001123 ParentDecl = InstantiateCurrentDeclRef(ParentDecl);
Douglas Gregor815215d2009-05-27 05:35:12 +00001124 if (!ParentDecl)
1125 return 0;
1126
1127 ParentDC = cast<DeclContext>(ParentDecl);
1128 }
1129
Douglas Gregor815215d2009-05-27 05:35:12 +00001130 if (ParentDC != D->getDeclContext()) {
1131 // We performed some kind of instantiation in the parent context,
1132 // so now we need to look into the instantiated parent context to
1133 // find the instantiation of the declaration D.
1134 NamedDecl *Result = 0;
1135 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001136 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001137 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1138 } else {
1139 // Since we don't have a name for the entity we're looking for,
1140 // our only option is to walk through all of the declarations to
1141 // find that name. This will occur in a few cases:
1142 //
1143 // - anonymous struct/union within a template
1144 // - unnamed class/struct/union/enum within a template
1145 //
1146 // FIXME: Find a better way to find these instantiations!
1147 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001148 ParentDC->decls_begin(),
1149 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001150 }
1151 assert(Result && "Unable to find instantiation of declaration!");
1152 D = Result;
1153 }
1154
Douglas Gregor815215d2009-05-27 05:35:12 +00001155 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
Douglas Gregored961e72009-05-27 17:54:46 +00001156 if (ClassTemplateDecl *ClassTemplate
1157 = Record->getDescribedClassTemplate()) {
1158 // When the declaration D was parsed, it referred to the current
1159 // instantiation. Therefore, look through the current context,
1160 // which contains actual instantiations, to find the
1161 // instantiation of the "current instantiation" that D refers
1162 // to. Alternatively, we could just instantiate the
1163 // injected-class-name with the current template arguments, but
1164 // such an instantiation is far more expensive.
1165 for (DeclContext *DC = CurContext; !DC->isFileContext();
1166 DC = DC->getParent()) {
1167 if (ClassTemplateSpecializationDecl *Spec
1168 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001169 if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1170 == ClassTemplate->getCanonicalDecl())
Douglas Gregored961e72009-05-27 17:54:46 +00001171 return Spec;
1172 }
1173
1174 assert(false &&
1175 "Unable to find declaration for the current instantiation");
Douglas Gregor815215d2009-05-27 05:35:12 +00001176 }
1177
1178 return D;
1179}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001180
1181/// \brief Performs template instantiation for all implicit template
1182/// instantiations we have seen until this point.
1183void Sema::PerformPendingImplicitInstantiations() {
1184 while (!PendingImplicitInstantiations.empty()) {
1185 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001186 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001187
Douglas Gregor7caa6822009-07-24 20:34:43 +00001188 // Instantiate function definitions
1189 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001190 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001191 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001192 continue;
1193 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001194
Douglas Gregor7caa6822009-07-24 20:34:43 +00001195 // Instantiate static data member definitions.
1196 VarDecl *Var = cast<VarDecl>(Inst.first);
1197 assert(Var->isStaticDataMember() && "Not a static data member?");
1198 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001199 }
1200}