blob: 7995def332248b414a7ef1ac48ec53effd9d2840 [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"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/DeclTemplate.h"
15#include "clang/AST/DeclVisitor.h"
16#include "clang/AST/Expr.h"
17#include "llvm/Support/Compiler.h"
18
19using namespace clang;
20
21namespace {
22 class VISIBILITY_HIDDEN TemplateDeclInstantiator
23 : public DeclVisitor<TemplateDeclInstantiator, Decl *>
24 {
25 Sema &SemaRef;
26 DeclContext *Owner;
27 const TemplateArgument *TemplateArgs;
28 unsigned NumTemplateArgs;
29
30 public:
31 typedef Sema::OwningExprResult OwningExprResult;
32
33 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
34 const TemplateArgument *TemplateArgs,
35 unsigned NumTemplateArgs)
36 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs),
37 NumTemplateArgs(NumTemplateArgs) { }
38
39 // FIXME: Once we get closer to completion, replace these
40 // manually-written declarations with automatically-generated ones
41 // from clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000042 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
43 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000044 Decl *VisitTypedefDecl(TypedefDecl *D);
45 Decl *VisitFieldDecl(FieldDecl *D);
46 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
47 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000048 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000049 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
Douglas Gregor615c5d42009-03-24 16:43:20 +000050 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000051 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000052 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000053 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000054 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
Douglas Gregor5545e162009-03-24 00:38:23 +000055
Douglas Gregor8dbc2692009-03-17 21:15:40 +000056 // Base case. FIXME: Remove once we can instantiate everything.
57 Decl *VisitDecl(Decl *) {
58 return 0;
59 }
Douglas Gregor5545e162009-03-24 00:38:23 +000060
61 // Helper functions for instantiating methods.
62 QualType InstantiateFunctionType(FunctionDecl *D,
63 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
64 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000065 };
66}
67
Douglas Gregor4f722be2009-03-25 15:45:12 +000068Decl *
69TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
70 assert(false && "Translation units cannot be instantiated");
71 return D;
72}
73
74Decl *
75TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
76 assert(false && "Namespaces cannot be instantiated");
77 return D;
78}
79
Douglas Gregor8dbc2692009-03-17 21:15:40 +000080Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
81 bool Invalid = false;
82 QualType T = D->getUnderlyingType();
83 if (T->isDependentType()) {
84 T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs,
85 D->getLocation(),
86 D->getDeclName());
87 if (T.isNull()) {
88 Invalid = true;
89 T = SemaRef.Context.IntTy;
90 }
91 }
92
93 // Create the new typedef
94 TypedefDecl *Typedef
95 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
96 D->getIdentifier(), T);
97 if (Invalid)
98 Typedef->setInvalidDecl();
99
100 Owner->addDecl(Typedef);
101 return Typedef;
102}
103
104Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
105 bool Invalid = false;
106 QualType T = D->getType();
107 if (T->isDependentType()) {
108 T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs,
109 D->getLocation(),
110 D->getDeclName());
111 if (!T.isNull() && T->isFunctionType()) {
112 // C++ [temp.arg.type]p3:
113 // If a declaration acquires a function type through a type
114 // dependent on a template-parameter and this causes a
115 // declaration that does not use the syntactic form of a
116 // function declarator to have function type, the program is
117 // ill-formed.
118 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
119 << T;
120 T = QualType();
121 Invalid = true;
122 }
123 }
124
125 Expr *BitWidth = D->getBitWidth();
126 if (Invalid)
127 BitWidth = 0;
128 else if (BitWidth) {
129 OwningExprResult InstantiatedBitWidth
130 = SemaRef.InstantiateExpr(BitWidth, TemplateArgs, NumTemplateArgs);
131 if (InstantiatedBitWidth.isInvalid()) {
132 Invalid = true;
133 BitWidth = 0;
134 } else
135 BitWidth = (Expr *)InstantiatedBitWidth.release();
136 }
137
138 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
139 cast<RecordDecl>(Owner),
140 D->getLocation(),
141 D->isMutable(),
142 BitWidth,
143 D->getAccess(),
144 0);
145 if (Field) {
146 if (Invalid)
147 Field->setInvalidDecl();
148
149 Owner->addDecl(Field);
150 }
151
152 return Field;
153}
154
155Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
156 Expr *AssertExpr = D->getAssertExpr();
157
158 OwningExprResult InstantiatedAssertExpr
159 = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs, NumTemplateArgs);
160 if (InstantiatedAssertExpr.isInvalid())
161 return 0;
162
163 OwningExprResult Message = SemaRef.Clone(D->getMessage());
164 Decl *StaticAssert
165 = (Decl *)SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
166 move(InstantiatedAssertExpr),
167 move(Message));
168 return StaticAssert;
169}
170
171Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
172 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
173 D->getLocation(), D->getIdentifier(),
174 /*PrevDecl=*/0);
175 Owner->addDecl(Enum);
176 Enum->startDefinition();
177
178 llvm::SmallVector<Sema::DeclTy *, 16> Enumerators;
179
180 EnumConstantDecl *LastEnumConst = 0;
181 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
182 ECEnd = D->enumerator_end();
183 EC != ECEnd; ++EC) {
184 // The specified value for the enumerator.
185 OwningExprResult Value = SemaRef.Owned((Expr *)0);
186 if (Expr *UninstValue = EC->getInitExpr())
187 Value = SemaRef.InstantiateExpr(UninstValue,
188 TemplateArgs, NumTemplateArgs);
189
190 // Drop the initial value and continue.
191 bool isInvalid = false;
192 if (Value.isInvalid()) {
193 Value = SemaRef.Owned((Expr *)0);
194 isInvalid = true;
195 }
196
197 EnumConstantDecl *EnumConst
198 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
199 EC->getLocation(), EC->getIdentifier(),
200 move(Value));
201
202 if (isInvalid) {
203 if (EnumConst)
204 EnumConst->setInvalidDecl();
205 Enum->setInvalidDecl();
206 }
207
208 if (EnumConst) {
209 Enum->addDecl(EnumConst);
210 Enumerators.push_back(EnumConst);
211 LastEnumConst = EnumConst;
212 }
213 }
214
215 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum,
216 &Enumerators[0], Enumerators.size());
217
218 return Enum;
219}
220
Douglas Gregor6477b692009-03-25 15:04:13 +0000221Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
222 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
223 return 0;
224}
225
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000226Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
227 // Only handle actual methods; we'll deal with constructors,
228 // destructors, etc. separately.
229 if (D->getKind() != Decl::CXXMethod)
230 return 0;
231
Douglas Gregor5545e162009-03-24 00:38:23 +0000232 llvm::SmallVector<ParmVarDecl *, 16> Params;
233 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000234 if (T.isNull())
235 return 0;
236
237 // Build the instantiated method declaration.
238 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
239 CXXMethodDecl *Method
240 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
241 D->getDeclName(), T, D->isStatic(),
242 D->isInline());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000243
Douglas Gregor5545e162009-03-24 00:38:23 +0000244 // Attach the parameters
245 for (unsigned P = 0; P < Params.size(); ++P)
246 Params[P]->setOwningFunction(Method);
247 Method->setParams(SemaRef.Context, &Params[0], Params.size());
248
249 if (InitMethodInstantiation(Method, D))
250 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000251
252 NamedDecl *PrevDecl
253 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
254 Sema::LookupOrdinaryName, true);
255 // In C++, the previous declaration we find might be a tag type
256 // (class or enum). In this case, the new declaration will hide the
257 // tag type. Note that this does does not apply if we're declaring a
258 // typedef (C++ [dcl.typedef]p4).
259 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
260 PrevDecl = 0;
261 bool Redeclaration = false;
262 bool OverloadableAttrRequired = false;
263 if (SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
264 /*FIXME:*/OverloadableAttrRequired))
265 Method->setInvalidDecl();
266
267 if (!Method->isInvalidDecl() || !PrevDecl)
268 Owner->addDecl(Method);
269 return Method;
270}
271
Douglas Gregor615c5d42009-03-24 16:43:20 +0000272Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
273 llvm::SmallVector<ParmVarDecl *, 16> Params;
274 QualType T = InstantiateFunctionType(D, Params);
275 if (T.isNull())
276 return 0;
277
278 // Build the instantiated method declaration.
279 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
280 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
281 DeclarationName Name
282 = SemaRef.Context.DeclarationNames.getCXXConstructorName(ClassTy);
283 CXXConstructorDecl *Constructor
284 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
285 Name, T, D->isExplicit(), D->isInline(),
286 false);
287
288 // Attach the parameters
289 for (unsigned P = 0; P < Params.size(); ++P)
290 Params[P]->setOwningFunction(Constructor);
291 Constructor->setParams(SemaRef.Context, &Params[0], Params.size());
292
293 if (InitMethodInstantiation(Constructor, D))
294 Constructor->setInvalidDecl();
295
296 NamedDecl *PrevDecl
297 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
298
299 // In C++, the previous declaration we find might be a tag type
300 // (class or enum). In this case, the new declaration will hide the
301 // tag type. Note that this does does not apply if we're declaring a
302 // typedef (C++ [dcl.typedef]p4).
303 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
304 PrevDecl = 0;
305 bool Redeclaration = false;
306 bool OverloadableAttrRequired = false;
307 if (SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
308 /*FIXME:*/OverloadableAttrRequired))
309 Constructor->setInvalidDecl();
310
311 if (!Constructor->isInvalidDecl())
312 Owner->addDecl(Constructor);
313 return Constructor;
314}
315
Douglas Gregor03b2b072009-03-24 00:15:49 +0000316Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000317 llvm::SmallVector<ParmVarDecl *, 16> Params;
318 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000319 if (T.isNull())
320 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +0000321 assert(Params.size() == 0 && "Destructor with parameters?");
322
Douglas Gregor03b2b072009-03-24 00:15:49 +0000323 // Build the instantiated destructor declaration.
324 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
325 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
326 CXXDestructorDecl *Destructor
327 = CXXDestructorDecl::Create(SemaRef.Context, Record,
328 D->getLocation(),
329 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
330 T, D->isInline(), false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000331 if (InitMethodInstantiation(Destructor, D))
332 Destructor->setInvalidDecl();
Douglas Gregor03b2b072009-03-24 00:15:49 +0000333
334 bool Redeclaration = false;
335 bool OverloadableAttrRequired = false;
336 NamedDecl *PrevDecl = 0;
337 if (SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
338 /*FIXME:*/OverloadableAttrRequired))
339 Destructor->setInvalidDecl();
340 Owner->addDecl(Destructor);
341 return Destructor;
342}
343
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000344Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
345 llvm::SmallVector<ParmVarDecl *, 16> Params;
346 QualType T = InstantiateFunctionType(D, Params);
347 if (T.isNull())
348 return 0;
349 assert(Params.size() == 0 && "Destructor with parameters?");
350
351 // Build the instantiated conversion declaration.
352 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
353 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
354 QualType ConvTy
355 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
356 CXXConversionDecl *Conversion
357 = CXXConversionDecl::Create(SemaRef.Context, Record,
358 D->getLocation(),
359 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
360 T, D->isInline(), D->isExplicit());
361 if (InitMethodInstantiation(Conversion, D))
362 Conversion->setInvalidDecl();
363
364 bool Redeclaration = false;
365 bool OverloadableAttrRequired = false;
366 NamedDecl *PrevDecl = 0;
367 if (SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
368 /*FIXME:*/OverloadableAttrRequired))
369 Conversion->setInvalidDecl();
370 Owner->addDecl(Conversion);
371 return Conversion;
372}
373
Douglas Gregor6477b692009-03-25 15:04:13 +0000374ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000375 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
376 NumTemplateArgs, D->getLocation(),
377 D->getDeclName());
378 if (OrigT.isNull())
379 return 0;
380
381 QualType T = SemaRef.adjustParameterType(OrigT);
382
383 if (D->getDefaultArg()) {
384 // FIXME: Leave a marker for "uninstantiated" default
385 // arguments. They only get instantiated on demand at the call
386 // site.
387 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
388 "sorry, dropping default argument during template instantiation");
389 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
390 << D->getDefaultArg()->getSourceRange();
391 }
392
393 // Allocate the parameter
394 ParmVarDecl *Param = 0;
395 if (T == OrigT)
396 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
397 D->getIdentifier(), T, D->getStorageClass(),
398 0);
399 else
400 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
401 D->getLocation(), D->getIdentifier(),
402 T, OrigT, D->getStorageClass(), 0);
403
404 // Note: we don't try to instantiate function parameters until after
405 // we've instantiated the function's type. Therefore, we don't have
406 // to check for 'void' parameter types here.
407 return Param;
408}
409
410Decl *
411TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
412 // Since parameter types can decay either before or after
413 // instantiation, we simply treat OriginalParmVarDecls as
414 // ParmVarDecls the same way, and create one or the other depending
415 // on what happens after template instantiation.
416 return VisitParmVarDecl(D);
417}
418
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000419Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
420 const TemplateArgument *TemplateArgs,
421 unsigned NumTemplateArgs) {
422 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs,
423 NumTemplateArgs);
424 return Instantiator.Visit(D);
425}
426
Douglas Gregor5545e162009-03-24 00:38:23 +0000427/// \brief Instantiates the type of the given function, including
428/// instantiating all of the function parameters.
429///
430/// \param D The function that we will be instantiated
431///
432/// \param Params the instantiated parameter declarations
433
434/// \returns the instantiated function's type if successfull, a NULL
435/// type if there was an error.
436QualType
437TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
438 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
439 bool InvalidDecl = false;
440
441 // Instantiate the function parameters
442 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0,
443 TemplateArgs, NumTemplateArgs);
444 llvm::SmallVector<QualType, 16> ParamTys;
445 for (FunctionDecl::param_iterator P = D->param_begin(),
446 PEnd = D->param_end();
447 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000448 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000449 if (PInst->getType()->isVoidType()) {
450 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
451 PInst->setInvalidDecl();
452 }
453 else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
454 PInst->getType(),
455 diag::err_abstract_type_in_decl,
Anders Carlsson8211eff2009-03-24 01:19:16 +0000456 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000457 PInst->setInvalidDecl();
458
459 Params.push_back(PInst);
460 ParamTys.push_back(PInst->getType());
461
462 if (PInst->isInvalidDecl())
463 InvalidDecl = true;
464 } else
465 InvalidDecl = true;
466 }
467
468 // FIXME: Deallocate dead declarations.
469 if (InvalidDecl)
470 return QualType();
471
472 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
473 assert(Proto && "Missing prototype?");
474 QualType ResultType
475 = SemaRef.InstantiateType(Proto->getResultType(),
476 TemplateArgs, NumTemplateArgs,
477 D->getLocation(), D->getDeclName());
478 if (ResultType.isNull())
479 return QualType();
480
481 return SemaRef.BuildFunctionType(ResultType, &ParamTys[0], ParamTys.size(),
482 Proto->isVariadic(), Proto->getTypeQuals(),
483 D->getLocation(), D->getDeclName());
484}
485
486/// \brief Initializes common fields of an instantiated method
487/// declaration (New) from the corresponding fields of its template
488/// (Tmpl).
489///
490/// \returns true if there was an error
491bool
492TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
493 CXXMethodDecl *Tmpl) {
494 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
495 New->setAccess(Tmpl->getAccess());
496 if (Tmpl->isVirtual()) {
497 New->setVirtual();
498 Record->setAggregate(false);
499 Record->setPOD(false);
500 Record->setPolymorphic(true);
501 }
502 if (Tmpl->isDeleted())
503 New->setDeleted();
504 if (Tmpl->isPure()) {
505 New->setPure();
506 Record->setAbstract(true);
507 }
508
509 // FIXME: attributes
510 // FIXME: New needs a pointer to Tmpl
511 return false;
512}