blob: 8d75ac463ab78ac180bff071d8b14dd8c3c60407 [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) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000460 // Check whether there is already a function template specialization for
461 // this declaration.
462 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
463 void *InsertPos = 0;
464 if (FunctionTemplate) {
465 llvm::FoldingSetNodeID ID;
466 FunctionTemplateSpecializationInfo::Profile(ID,
467 TemplateArgs.getFlatArgumentList(),
468 TemplateArgs.flat_size(),
469 SemaRef.Context);
470
471 FunctionTemplateSpecializationInfo *Info
472 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
473 InsertPos);
474
475 // If we already have a function template specialization, return it.
476 if (Info)
477 return Info->Function;
478 }
479
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000480 Sema::LocalInstantiationScope Scope(SemaRef);
481
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000482 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000483 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000484 if (T.isNull())
485 return 0;
486
487 // Build the instantiated method declaration.
488 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
489 CXXMethodDecl *Method
490 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000491 D->getDeclName(), T, D->getDeclaratorInfo(),
492 D->isStatic(), D->isInline());
Douglas Gregor6b906862009-08-21 00:16:32 +0000493
494 if (!FunctionTemplate)
495 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000496
Douglas Gregor7caa6822009-07-24 20:34:43 +0000497 // If we are instantiating a member function defined
498 // out-of-line, the instantiation will have the same lexical
499 // context (which will be a namespace scope) as the template.
500 if (D->isOutOfLine())
501 Method->setLexicalDeclContext(D->getLexicalDeclContext());
502
Douglas Gregor5545e162009-03-24 00:38:23 +0000503 // Attach the parameters
504 for (unsigned P = 0; P < Params.size(); ++P)
505 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000506 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000507
508 if (InitMethodInstantiation(Method, D))
509 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000510
511 NamedDecl *PrevDecl
512 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
513 Sema::LookupOrdinaryName, true);
514 // In C++, the previous declaration we find might be a tag type
515 // (class or enum). In this case, the new declaration will hide the
516 // tag type. Note that this does does not apply if we're declaring a
517 // typedef (C++ [dcl.typedef]p4).
518 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
519 PrevDecl = 0;
520 bool Redeclaration = false;
521 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000522 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
523 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000524
Douglas Gregor6b906862009-08-21 00:16:32 +0000525 if (FunctionTemplate)
526 // Record this function template specialization.
527 Method->setFunctionTemplateSpecialization(SemaRef.Context,
528 FunctionTemplate,
529 &TemplateArgs,
530 InsertPos);
531 else if (!Method->isInvalidDecl() || !PrevDecl)
532 Owner->addDecl(Method);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000533 return Method;
534}
535
Douglas Gregor615c5d42009-03-24 16:43:20 +0000536Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000537 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000538 Sema::LocalInstantiationScope Scope(SemaRef);
539
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000540 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor615c5d42009-03-24 16:43:20 +0000541 QualType T = InstantiateFunctionType(D, Params);
542 if (T.isNull())
543 return 0;
544
545 // Build the instantiated method declaration.
546 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
547 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
548 DeclarationName Name
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000549 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
550 SemaRef.Context.getCanonicalType(ClassTy));
Douglas Gregor615c5d42009-03-24 16:43:20 +0000551 CXXConstructorDecl *Constructor
552 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000553 Name, T, D->getDeclaratorInfo(),
554 D->isExplicit(), D->isInline(), false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000555 Constructor->setInstantiationOfMemberFunction(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000556
557 // Attach the parameters
558 for (unsigned P = 0; P < Params.size(); ++P)
559 Params[P]->setOwningFunction(Constructor);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000560 Constructor->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor615c5d42009-03-24 16:43:20 +0000561
562 if (InitMethodInstantiation(Constructor, D))
563 Constructor->setInvalidDecl();
564
565 NamedDecl *PrevDecl
566 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
567
568 // In C++, the previous declaration we find might be a tag type
569 // (class or enum). In this case, the new declaration will hide the
570 // tag type. Note that this does does not apply if we're declaring a
571 // typedef (C++ [dcl.typedef]p4).
572 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
573 PrevDecl = 0;
574 bool Redeclaration = false;
575 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000576 SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
577 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000578
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000579 Record->addedConstructor(SemaRef.Context, Constructor);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000580 Owner->addDecl(Constructor);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000581 return Constructor;
582}
583
Douglas Gregor03b2b072009-03-24 00:15:49 +0000584Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000585 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000586 Sema::LocalInstantiationScope Scope(SemaRef);
587
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000588 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000589 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000590 if (T.isNull())
591 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +0000592 assert(Params.size() == 0 && "Destructor with parameters?");
593
Douglas Gregor03b2b072009-03-24 00:15:49 +0000594 // Build the instantiated destructor declaration.
595 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregor50d62d12009-08-05 05:36:45 +0000596 CanQualType ClassTy =
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000597 SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record));
Douglas Gregor03b2b072009-03-24 00:15:49 +0000598 CXXDestructorDecl *Destructor
599 = CXXDestructorDecl::Create(SemaRef.Context, Record,
600 D->getLocation(),
601 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
602 T, D->isInline(), false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000603 Destructor->setInstantiationOfMemberFunction(D);
Douglas Gregor5545e162009-03-24 00:38:23 +0000604 if (InitMethodInstantiation(Destructor, D))
605 Destructor->setInvalidDecl();
Douglas Gregor03b2b072009-03-24 00:15:49 +0000606
607 bool Redeclaration = false;
608 bool OverloadableAttrRequired = false;
609 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000610 SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
611 /*FIXME:*/OverloadableAttrRequired);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000612 Owner->addDecl(Destructor);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000613 return Destructor;
614}
615
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000616Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000617 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000618 Sema::LocalInstantiationScope Scope(SemaRef);
619
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000620 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000621 QualType T = InstantiateFunctionType(D, Params);
622 if (T.isNull())
623 return 0;
624 assert(Params.size() == 0 && "Destructor with parameters?");
625
626 // Build the instantiated conversion declaration.
627 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
628 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
Douglas Gregor50d62d12009-08-05 05:36:45 +0000629 CanQualType ConvTy
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000630 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
631 CXXConversionDecl *Conversion
632 = CXXConversionDecl::Create(SemaRef.Context, Record,
633 D->getLocation(),
634 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000635 T, D->getDeclaratorInfo(),
636 D->isInline(), D->isExplicit());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000637 Conversion->setInstantiationOfMemberFunction(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000638 if (InitMethodInstantiation(Conversion, D))
639 Conversion->setInvalidDecl();
640
641 bool Redeclaration = false;
642 bool OverloadableAttrRequired = false;
643 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000644 SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
645 /*FIXME:*/OverloadableAttrRequired);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000646 Owner->addDecl(Conversion);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000647 return Conversion;
648}
649
Douglas Gregor6477b692009-03-25 15:04:13 +0000650ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000651 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000652 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000653 if (OrigT.isNull())
654 return 0;
655
656 QualType T = SemaRef.adjustParameterType(OrigT);
657
658 if (D->getDefaultArg()) {
659 // FIXME: Leave a marker for "uninstantiated" default
660 // arguments. They only get instantiated on demand at the call
661 // site.
662 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
663 "sorry, dropping default argument during template instantiation");
664 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
665 << D->getDefaultArg()->getSourceRange();
666 }
667
668 // Allocate the parameter
669 ParmVarDecl *Param = 0;
670 if (T == OrigT)
671 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000672 D->getIdentifier(), T, D->getDeclaratorInfo(),
673 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000674 else
675 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
676 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000677 T, D->getDeclaratorInfo(), OrigT,
678 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000679
680 // Note: we don't try to instantiate function parameters until after
681 // we've instantiated the function's type. Therefore, we don't have
682 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000683 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000684 return Param;
685}
686
687Decl *
688TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
689 // Since parameter types can decay either before or after
690 // instantiation, we simply treat OriginalParmVarDecls as
691 // ParmVarDecls the same way, and create one or the other depending
692 // on what happens after template instantiation.
693 return VisitParmVarDecl(D);
694}
695
John McCalle29ba202009-08-20 01:44:21 +0000696Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
697 TemplateTypeParmDecl *D) {
698 // TODO: don't always clone when decls are refcounted.
699 const Type* T = D->getTypeForDecl();
700 assert(T->isTemplateTypeParmType());
701 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
702
703 TemplateTypeParmDecl *Inst =
704 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
705 TTPT->getDepth(), TTPT->getIndex(),
706 TTPT->getName(),
707 D->wasDeclaredWithTypename(),
708 D->isParameterPack());
709
710 if (D->hasDefaultArgument()) {
711 QualType DefaultPattern = D->getDefaultArgument();
712 QualType DefaultInst
713 = SemaRef.InstantiateType(DefaultPattern, TemplateArgs,
714 D->getDefaultArgumentLoc(),
715 D->getDeclName());
716
717 Inst->setDefaultArgument(DefaultInst,
718 D->getDefaultArgumentLoc(),
719 D->defaultArgumentWasInherited() /* preserve? */);
720 }
721
722 return Inst;
723}
724
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000725Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
Douglas Gregor7e063902009-05-11 23:53:27 +0000726 const TemplateArgumentList &TemplateArgs) {
727 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000728 return Instantiator.Visit(D);
729}
730
John McCalle29ba202009-08-20 01:44:21 +0000731/// \brief Instantiates a nested template parameter list in the current
732/// instantiation context.
733///
734/// \param L The parameter list to instantiate
735///
736/// \returns NULL if there was an error
737TemplateParameterList *
738TemplateDeclInstantiator::InstantiateTemplateParams(TemplateParameterList *L) {
739 // Get errors for all the parameters before bailing out.
740 bool Invalid = false;
741
742 unsigned N = L->size();
743 typedef llvm::SmallVector<Decl*,8> ParamVector;
744 ParamVector Params;
745 Params.reserve(N);
746 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
747 PI != PE; ++PI) {
748 Decl *D = Visit(*PI);
749 Params.push_back(D);
750 Invalid = Invalid || !D;
751 }
752
753 // Clean up if we had an error.
754 if (Invalid) {
755 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
756 PI != PE; ++PI)
757 if (*PI)
758 (*PI)->Destroy(SemaRef.Context);
759 return NULL;
760 }
761
762 TemplateParameterList *InstL
763 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
764 L->getLAngleLoc(), &Params.front(), N,
765 L->getRAngleLoc());
766 return InstL;
767}
768
Douglas Gregor5545e162009-03-24 00:38:23 +0000769/// \brief Instantiates the type of the given function, including
770/// instantiating all of the function parameters.
771///
772/// \param D The function that we will be instantiated
773///
774/// \param Params the instantiated parameter declarations
775
776/// \returns the instantiated function's type if successfull, a NULL
777/// type if there was an error.
778QualType
779TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
780 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
781 bool InvalidDecl = false;
782
783 // Instantiate the function parameters
Douglas Gregor7e063902009-05-11 23:53:27 +0000784 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000785 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000786 for (FunctionDecl::param_iterator P = D->param_begin(),
787 PEnd = D->param_end();
788 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000789 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000790 if (PInst->getType()->isVoidType()) {
791 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
792 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000793 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
794 PInst->getType(),
795 diag::err_abstract_type_in_decl,
796 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000797 PInst->setInvalidDecl();
798
799 Params.push_back(PInst);
800 ParamTys.push_back(PInst->getType());
801
802 if (PInst->isInvalidDecl())
803 InvalidDecl = true;
804 } else
805 InvalidDecl = true;
806 }
807
808 // FIXME: Deallocate dead declarations.
809 if (InvalidDecl)
810 return QualType();
811
812 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
813 assert(Proto && "Missing prototype?");
814 QualType ResultType
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000815 = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs,
Douglas Gregor5545e162009-03-24 00:38:23 +0000816 D->getLocation(), D->getDeclName());
817 if (ResultType.isNull())
818 return QualType();
819
Jay Foadbeaaccd2009-05-21 09:52:38 +0000820 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000821 Proto->isVariadic(), Proto->getTypeQuals(),
822 D->getLocation(), D->getDeclName());
823}
824
Douglas Gregore53060f2009-06-25 22:08:12 +0000825/// \brief Initializes the common fields of an instantiation function
826/// declaration (New) from the corresponding fields of its template (Tmpl).
827///
828/// \returns true if there was an error
829bool
830TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
831 FunctionDecl *Tmpl) {
832 if (Tmpl->isDeleted())
833 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000834
835 // If we are performing substituting explicitly-specified template arguments
836 // or deduced template arguments into a function template and we reach this
837 // point, we are now past the point where SFINAE applies and have committed
838 // to keeping the new function template specialization. We therefore
839 // convert the active template instantiation for the function template
840 // into a template instantiation for this specific function template
841 // specialization, which is not a SFINAE context, so that we diagnose any
842 // further errors in the declaration itself.
843 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
844 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
845 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
846 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
847 if (FunctionTemplateDecl *FunTmpl
848 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
849 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
850 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000851 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000852 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
853 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
854 }
855 }
856
Douglas Gregore53060f2009-06-25 22:08:12 +0000857 return false;
858}
859
Douglas Gregor5545e162009-03-24 00:38:23 +0000860/// \brief Initializes common fields of an instantiated method
861/// declaration (New) from the corresponding fields of its template
862/// (Tmpl).
863///
864/// \returns true if there was an error
865bool
866TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
867 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000868 if (InitFunctionInstantiation(New, Tmpl))
869 return true;
870
Douglas Gregor5545e162009-03-24 00:38:23 +0000871 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
872 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000873 if (Tmpl->isVirtualAsWritten()) {
874 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000875 Record->setAggregate(false);
876 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000877 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000878 Record->setPolymorphic(true);
879 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000880 if (Tmpl->isPure()) {
881 New->setPure();
882 Record->setAbstract(true);
883 }
884
885 // FIXME: attributes
886 // FIXME: New needs a pointer to Tmpl
887 return false;
888}
Douglas Gregora58861f2009-05-13 20:28:22 +0000889
890/// \brief Instantiate the definition of the given function from its
891/// template.
892///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000893/// \param PointOfInstantiation the point at which the instantiation was
894/// required. Note that this is not precisely a "point of instantiation"
895/// for the function, but it's close.
896///
Douglas Gregora58861f2009-05-13 20:28:22 +0000897/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000898/// function template specialization or member function of a class template
899/// specialization.
900///
901/// \param Recursive if true, recursively instantiates any functions that
902/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000903void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000904 FunctionDecl *Function,
905 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000906 if (Function->isInvalidDecl())
907 return;
908
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000909 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000910
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000911 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000912 const FunctionDecl *PatternDecl = 0;
913 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
914 PatternDecl = Primary->getTemplatedDecl();
915 else
916 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000917 Stmt *Pattern = 0;
918 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000919 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000920
921 if (!Pattern)
922 return;
923
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000924 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
925 if (Inst)
926 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000927
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000928 // If we're performing recursive template instantiation, create our own
929 // queue of pending implicit instantiations that we will instantiate later,
930 // while we're still within our own instantiation context.
931 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
932 if (Recursive)
933 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
934
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000935 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
936
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000937 // Introduce a new scope where local variable instantiations will be
938 // recorded.
939 LocalInstantiationScope Scope(*this);
940
941 // Introduce the instantiated function parameters into the local
942 // instantiation scope.
943 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
944 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
945 Function->getParamDecl(I));
946
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000947 // Enter the scope of this instantiation. We don't use
948 // PushDeclContext because we don't have a scope.
949 DeclContext *PreviousContext = CurContext;
950 CurContext = Function;
951
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000952 // Instantiate the function body.
953 OwningStmtResult Body
954 = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function));
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000955
956 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
957 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000958
959 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000960
961 DeclGroupRef DG(Function);
962 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000963
964 if (Recursive) {
965 // Instantiate any pending implicit instantiations found during the
966 // instantiation of this template.
967 PerformPendingImplicitInstantiations();
968
969 // Restore the set of pending implicit instantiations.
970 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
971 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000972}
973
974/// \brief Instantiate the definition of the given variable from its
975/// template.
976///
Douglas Gregor7caa6822009-07-24 20:34:43 +0000977/// \param PointOfInstantiation the point at which the instantiation was
978/// required. Note that this is not precisely a "point of instantiation"
979/// for the function, but it's close.
980///
981/// \param Var the already-instantiated declaration of a static member
982/// variable of a class template specialization.
983///
984/// \param Recursive if true, recursively instantiates any functions that
985/// are required by this instantiation.
986void Sema::InstantiateStaticDataMemberDefinition(
987 SourceLocation PointOfInstantiation,
988 VarDecl *Var,
989 bool Recursive) {
990 if (Var->isInvalidDecl())
991 return;
992
993 // Find the out-of-line definition of this static data member.
994 // FIXME: Do we have to look for specializations separately?
995 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
996 bool FoundOutOfLineDef = false;
997 assert(Def && "This data member was not instantiated from a template?");
998 assert(Def->isStaticDataMember() && "Not a static data member?");
999 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
1000 RDEnd = Def->redecls_end();
1001 RD != RDEnd; ++RD) {
1002 if (RD->getLexicalDeclContext()->isFileContext()) {
1003 Def = *RD;
1004 FoundOutOfLineDef = true;
1005 }
1006 }
1007
1008 if (!FoundOutOfLineDef) {
1009 // We did not find an out-of-line definition of this static data member,
1010 // so we won't perform any instantiation. Rather, we rely on the user to
1011 // instantiate this definition (or provide a specialization for it) in
1012 // another translation unit.
1013 return;
1014 }
1015
1016 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1017 if (Inst)
1018 return;
1019
1020 // If we're performing recursive template instantiation, create our own
1021 // queue of pending implicit instantiations that we will instantiate later,
1022 // while we're still within our own instantiation context.
1023 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1024 if (Recursive)
1025 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1026
1027 // Enter the scope of this instantiation. We don't use
1028 // PushDeclContext because we don't have a scope.
1029 DeclContext *PreviousContext = CurContext;
1030 CurContext = Var->getDeclContext();
1031
1032#if 0
1033 // Instantiate the initializer of this static data member.
1034 OwningExprResult Init
1035 = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
1036 if (Init.isInvalid()) {
1037 // If instantiation of the initializer failed, mark the declaration invalid
1038 // and don't instantiate anything else that was triggered by this
1039 // instantiation.
1040 Var->setInvalidDecl();
1041
1042 // Restore the set of pending implicit instantiations.
1043 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1044
1045 return;
1046 }
1047
1048 // Type-check the initializer.
1049 if (Init.get())
1050 AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
1051 Def->hasCXXDirectInitializer());
1052 else
1053 ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
1054#else
1055 Var = cast_or_null<VarDecl>(InstantiateDecl(Def, Var->getDeclContext(),
1056 getTemplateInstantiationArgs(Var)));
1057#endif
1058
1059 CurContext = PreviousContext;
1060
1061 if (Var) {
1062 DeclGroupRef DG(Var);
1063 Consumer.HandleTopLevelDecl(DG);
1064 }
1065
1066 if (Recursive) {
1067 // Instantiate any pending implicit instantiations found during the
1068 // instantiation of this template.
1069 PerformPendingImplicitInstantiations();
1070
1071 // Restore the set of pending implicit instantiations.
1072 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1073 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001074}
Douglas Gregor815215d2009-05-27 05:35:12 +00001075
1076static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1077 if (D->getKind() != Other->getKind())
1078 return false;
1079
1080 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001081 return Record->getInstantiatedFromMemberClass()->getCanonicalDecl()
1082 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001083
1084 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001085 return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl()
1086 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001087
Douglas Gregor8dbc3c62009-05-27 17:20:35 +00001088 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001089 return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl()
1090 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001091
Douglas Gregor7caa6822009-07-24 20:34:43 +00001092 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
1093 if (Var->isStaticDataMember())
1094 return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl()
1095 == D->getCanonicalDecl();
1096
Douglas Gregor815215d2009-05-27 05:35:12 +00001097 // FIXME: How can we find instantiations of anonymous unions?
1098
1099 return D->getDeclName() && isa<NamedDecl>(Other) &&
1100 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1101}
1102
1103template<typename ForwardIterator>
1104static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1105 NamedDecl *D,
1106 ForwardIterator first,
1107 ForwardIterator last) {
1108 for (; first != last; ++first)
1109 if (isInstantiationOf(Ctx, D, *first))
1110 return cast<NamedDecl>(*first);
1111
1112 return 0;
1113}
1114
Douglas Gregored961e72009-05-27 17:54:46 +00001115/// \brief Find the instantiation of the given declaration within the
1116/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001117///
1118/// This routine is intended to be used when \p D is a declaration
1119/// referenced from within a template, that needs to mapped into the
1120/// corresponding declaration within an instantiation. For example,
1121/// given:
1122///
1123/// \code
1124/// template<typename T>
1125/// struct X {
1126/// enum Kind {
1127/// KnownValue = sizeof(T)
1128/// };
1129///
1130/// bool getKind() const { return KnownValue; }
1131/// };
1132///
1133/// template struct X<int>;
1134/// \endcode
1135///
1136/// In the instantiation of X<int>::getKind(), we need to map the
1137/// EnumConstantDecl for KnownValue (which refers to
1138/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001139/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1140/// this mapping from within the instantiation of X<int>.
1141NamedDecl * Sema::InstantiateCurrentDeclRef(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +00001142 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001143 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1144 // D is a local of some kind. Look into the map of local
1145 // declarations to their instantiations.
1146 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1147 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001148
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001149 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
Douglas Gregored961e72009-05-27 17:54:46 +00001150 ParentDecl = InstantiateCurrentDeclRef(ParentDecl);
Douglas Gregor815215d2009-05-27 05:35:12 +00001151 if (!ParentDecl)
1152 return 0;
1153
1154 ParentDC = cast<DeclContext>(ParentDecl);
1155 }
1156
Douglas Gregor815215d2009-05-27 05:35:12 +00001157 if (ParentDC != D->getDeclContext()) {
1158 // We performed some kind of instantiation in the parent context,
1159 // so now we need to look into the instantiated parent context to
1160 // find the instantiation of the declaration D.
1161 NamedDecl *Result = 0;
1162 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001163 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001164 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1165 } else {
1166 // Since we don't have a name for the entity we're looking for,
1167 // our only option is to walk through all of the declarations to
1168 // find that name. This will occur in a few cases:
1169 //
1170 // - anonymous struct/union within a template
1171 // - unnamed class/struct/union/enum within a template
1172 //
1173 // FIXME: Find a better way to find these instantiations!
1174 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001175 ParentDC->decls_begin(),
1176 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001177 }
1178 assert(Result && "Unable to find instantiation of declaration!");
1179 D = Result;
1180 }
1181
Douglas Gregor815215d2009-05-27 05:35:12 +00001182 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
Douglas Gregored961e72009-05-27 17:54:46 +00001183 if (ClassTemplateDecl *ClassTemplate
1184 = Record->getDescribedClassTemplate()) {
1185 // When the declaration D was parsed, it referred to the current
1186 // instantiation. Therefore, look through the current context,
1187 // which contains actual instantiations, to find the
1188 // instantiation of the "current instantiation" that D refers
1189 // to. Alternatively, we could just instantiate the
1190 // injected-class-name with the current template arguments, but
1191 // such an instantiation is far more expensive.
1192 for (DeclContext *DC = CurContext; !DC->isFileContext();
1193 DC = DC->getParent()) {
1194 if (ClassTemplateSpecializationDecl *Spec
1195 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001196 if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1197 == ClassTemplate->getCanonicalDecl())
Douglas Gregored961e72009-05-27 17:54:46 +00001198 return Spec;
1199 }
1200
1201 assert(false &&
1202 "Unable to find declaration for the current instantiation");
Douglas Gregor815215d2009-05-27 05:35:12 +00001203 }
1204
1205 return D;
1206}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001207
1208/// \brief Performs template instantiation for all implicit template
1209/// instantiations we have seen until this point.
1210void Sema::PerformPendingImplicitInstantiations() {
1211 while (!PendingImplicitInstantiations.empty()) {
1212 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001213 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001214
Douglas Gregor7caa6822009-07-24 20:34:43 +00001215 // Instantiate function definitions
1216 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001217 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001218 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001219 continue;
1220 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001221
Douglas Gregor7caa6822009-07-24 20:34:43 +00001222 // Instantiate static data member definitions.
1223 VarDecl *Var = cast<VarDecl>(Inst.first);
1224 assert(Var->isStaticDataMember() && "Not a static data member?");
1225 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001226 }
1227}