1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
9 // This file implements C++ template instantiation for declarations.
11 //===----------------------------------------------------------------------===/
13 #include "clang/AST/ASTConsumer.h"
14 #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"
20 using namespace clang;
23 class VISIBILITY_HIDDEN TemplateDeclInstantiator
24 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
27 const TemplateArgumentList &TemplateArgs;
30 typedef Sema::OwningExprResult OwningExprResult;
32 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
33 const TemplateArgumentList &TemplateArgs)
34 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
36 // FIXME: Once we get closer to completion, replace these manually-written
37 // declarations with automatically-generated ones from
38 // clang/AST/DeclNodes.def.
39 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
40 Decl *VisitNamespaceDecl(NamespaceDecl *D);
41 Decl *VisitTypedefDecl(TypedefDecl *D);
42 Decl *VisitVarDecl(VarDecl *D);
43 Decl *VisitFieldDecl(FieldDecl *D);
44 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
45 Decl *VisitEnumDecl(EnumDecl *D);
46 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
47 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
48 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
49 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
50 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
51 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
52 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
53 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
55 // Base case. FIXME: Remove once we can instantiate everything.
56 Decl *VisitDecl(Decl *) {
57 assert(false && "Template instantiation of unknown declaration kind!");
61 // Helper functions for instantiating methods.
62 QualType InstantiateFunctionType(FunctionDecl *D,
63 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
64 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
69 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
70 assert(false && "Translation units cannot be instantiated");
75 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
76 assert(false && "Namespaces cannot be instantiated");
80 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
82 QualType T = D->getUnderlyingType();
83 if (T->isDependentType()) {
84 T = SemaRef.InstantiateType(T, TemplateArgs,
85 D->getLocation(), D->getDeclName());
88 T = SemaRef.Context.IntTy;
92 // Create the new typedef
94 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
95 D->getIdentifier(), T);
97 Typedef->setInvalidDecl();
99 Owner->addDecl(SemaRef.Context, Typedef);
104 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
105 // Instantiate the type of the declaration
106 QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs,
107 D->getTypeSpecStartLoc(),
112 // Build the instantiated declaration
113 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
114 D->getLocation(), D->getIdentifier(),
115 T, D->getStorageClass(),
116 D->getTypeSpecStartLoc());
117 Var->setThreadSpecified(D->isThreadSpecified());
118 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
119 Var->setDeclaredInCondition(D->isDeclaredInCondition());
121 // FIXME: In theory, we could have a previous declaration for variables that
122 // are not static data members.
123 bool Redeclaration = false;
124 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
125 Owner->addDecl(SemaRef.Context, Var);
128 OwningExprResult Init
129 = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs);
130 if (Init.isInvalid())
131 Var->setInvalidDecl();
133 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
134 D->hasCXXDirectInitializer());
136 // FIXME: Call ActOnUninitializedDecl? (Not always)
142 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
143 bool Invalid = false;
144 QualType T = D->getType();
145 if (T->isDependentType()) {
146 T = SemaRef.InstantiateType(T, TemplateArgs,
147 D->getLocation(), D->getDeclName());
148 if (!T.isNull() && T->isFunctionType()) {
149 // C++ [temp.arg.type]p3:
150 // If a declaration acquires a function type through a type
151 // dependent on a template-parameter and this causes a
152 // declaration that does not use the syntactic form of a
153 // function declarator to have function type, the program is
155 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
162 Expr *BitWidth = D->getBitWidth();
166 OwningExprResult InstantiatedBitWidth
167 = SemaRef.InstantiateExpr(BitWidth, TemplateArgs);
168 if (InstantiatedBitWidth.isInvalid()) {
172 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
175 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
176 cast<RecordDecl>(Owner),
184 Field->setInvalidDecl();
186 Owner->addDecl(SemaRef.Context, Field);
192 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
193 Expr *AssertExpr = D->getAssertExpr();
195 OwningExprResult InstantiatedAssertExpr
196 = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs);
197 if (InstantiatedAssertExpr.isInvalid())
200 OwningExprResult Message = SemaRef.Clone(D->getMessage());
202 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
203 move(InstantiatedAssertExpr),
204 move(Message)).getAs<Decl>();
208 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
209 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
210 D->getLocation(), D->getIdentifier(),
212 Enum->setInstantiationOfMemberEnum(D);
213 Enum->setAccess(D->getAccess());
214 Owner->addDecl(SemaRef.Context, Enum);
215 Enum->startDefinition();
217 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
219 EnumConstantDecl *LastEnumConst = 0;
220 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(SemaRef.Context),
221 ECEnd = D->enumerator_end(SemaRef.Context);
223 // The specified value for the enumerator.
224 OwningExprResult Value = SemaRef.Owned((Expr *)0);
225 if (Expr *UninstValue = EC->getInitExpr())
226 Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs);
228 // Drop the initial value and continue.
229 bool isInvalid = false;
230 if (Value.isInvalid()) {
231 Value = SemaRef.Owned((Expr *)0);
235 EnumConstantDecl *EnumConst
236 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
237 EC->getLocation(), EC->getIdentifier(),
242 EnumConst->setInvalidDecl();
243 Enum->setInvalidDecl();
247 Enum->addDecl(SemaRef.Context, EnumConst);
248 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
249 LastEnumConst = EnumConst;
253 // FIXME: Fixup LBraceLoc and RBraceLoc
254 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
255 Sema::DeclPtrTy::make(Enum),
256 &Enumerators[0], Enumerators.size());
261 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
262 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
266 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
267 CXXRecordDecl *PrevDecl = 0;
268 if (D->isInjectedClassName())
269 PrevDecl = cast<CXXRecordDecl>(Owner);
271 CXXRecordDecl *Record
272 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
273 D->getLocation(), D->getIdentifier(), PrevDecl);
274 Record->setImplicit(D->isImplicit());
275 Record->setAccess(D->getAccess());
276 if (!D->isInjectedClassName())
277 Record->setInstantiationOfMemberClass(D);
279 Owner->addDecl(SemaRef.Context, Record);
283 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
284 // Only handle actual methods; we'll deal with constructors,
285 // destructors, etc. separately.
286 if (D->getKind() != Decl::CXXMethod)
289 Sema::LocalInstantiationScope Scope(SemaRef);
291 llvm::SmallVector<ParmVarDecl *, 4> Params;
292 QualType T = InstantiateFunctionType(D, Params);
296 // Build the instantiated method declaration.
297 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
298 CXXMethodDecl *Method
299 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
300 D->getDeclName(), T, D->isStatic(),
302 Method->setInstantiationOfMemberFunction(D);
304 // Attach the parameters
305 for (unsigned P = 0; P < Params.size(); ++P)
306 Params[P]->setOwningFunction(Method);
307 Method->setParams(SemaRef.Context, Params.data(), Params.size());
309 if (InitMethodInstantiation(Method, D))
310 Method->setInvalidDecl();
313 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
314 Sema::LookupOrdinaryName, true);
315 // In C++, the previous declaration we find might be a tag type
316 // (class or enum). In this case, the new declaration will hide the
317 // tag type. Note that this does does not apply if we're declaring a
318 // typedef (C++ [dcl.typedef]p4).
319 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
321 bool Redeclaration = false;
322 bool OverloadableAttrRequired = false;
323 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
324 /*FIXME:*/OverloadableAttrRequired);
326 if (!Method->isInvalidDecl() || !PrevDecl)
327 Owner->addDecl(SemaRef.Context, Method);
331 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
332 Sema::LocalInstantiationScope Scope(SemaRef);
334 llvm::SmallVector<ParmVarDecl *, 4> Params;
335 QualType T = InstantiateFunctionType(D, Params);
339 // Build the instantiated method declaration.
340 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
341 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
343 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
344 SemaRef.Context.getCanonicalType(ClassTy));
345 CXXConstructorDecl *Constructor
346 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
347 Name, T, D->isExplicit(), D->isInline(),
349 Constructor->setInstantiationOfMemberFunction(D);
351 // Attach the parameters
352 for (unsigned P = 0; P < Params.size(); ++P)
353 Params[P]->setOwningFunction(Constructor);
354 Constructor->setParams(SemaRef.Context, Params.data(), Params.size());
356 if (InitMethodInstantiation(Constructor, D))
357 Constructor->setInvalidDecl();
360 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
362 // In C++, the previous declaration we find might be a tag type
363 // (class or enum). In this case, the new declaration will hide the
364 // tag type. Note that this does does not apply if we're declaring a
365 // typedef (C++ [dcl.typedef]p4).
366 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
368 bool Redeclaration = false;
369 bool OverloadableAttrRequired = false;
370 SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
371 /*FIXME:*/OverloadableAttrRequired);
373 Record->addedConstructor(SemaRef.Context, Constructor);
374 Owner->addDecl(SemaRef.Context, Constructor);
378 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
379 Sema::LocalInstantiationScope Scope(SemaRef);
381 llvm::SmallVector<ParmVarDecl *, 4> Params;
382 QualType T = InstantiateFunctionType(D, Params);
385 assert(Params.size() == 0 && "Destructor with parameters?");
387 // Build the instantiated destructor declaration.
388 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
390 SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record));
391 CXXDestructorDecl *Destructor
392 = CXXDestructorDecl::Create(SemaRef.Context, Record,
394 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
395 T, D->isInline(), false);
396 Destructor->setInstantiationOfMemberFunction(D);
397 if (InitMethodInstantiation(Destructor, D))
398 Destructor->setInvalidDecl();
400 bool Redeclaration = false;
401 bool OverloadableAttrRequired = false;
402 NamedDecl *PrevDecl = 0;
403 SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
404 /*FIXME:*/OverloadableAttrRequired);
405 Owner->addDecl(SemaRef.Context, Destructor);
409 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
410 Sema::LocalInstantiationScope Scope(SemaRef);
412 llvm::SmallVector<ParmVarDecl *, 4> Params;
413 QualType T = InstantiateFunctionType(D, Params);
416 assert(Params.size() == 0 && "Destructor with parameters?");
418 // Build the instantiated conversion declaration.
419 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
420 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
422 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
423 CXXConversionDecl *Conversion
424 = CXXConversionDecl::Create(SemaRef.Context, Record,
426 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
427 T, D->isInline(), D->isExplicit());
428 Conversion->setInstantiationOfMemberFunction(D);
429 if (InitMethodInstantiation(Conversion, D))
430 Conversion->setInvalidDecl();
432 bool Redeclaration = false;
433 bool OverloadableAttrRequired = false;
434 NamedDecl *PrevDecl = 0;
435 SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
436 /*FIXME:*/OverloadableAttrRequired);
437 Owner->addDecl(SemaRef.Context, Conversion);
441 ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
442 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
443 D->getLocation(), D->getDeclName());
447 QualType T = SemaRef.adjustParameterType(OrigT);
449 if (D->getDefaultArg()) {
450 // FIXME: Leave a marker for "uninstantiated" default
451 // arguments. They only get instantiated on demand at the call
453 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
454 "sorry, dropping default argument during template instantiation");
455 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
456 << D->getDefaultArg()->getSourceRange();
459 // Allocate the parameter
460 ParmVarDecl *Param = 0;
462 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
463 D->getIdentifier(), T, D->getStorageClass(),
466 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
467 D->getLocation(), D->getIdentifier(),
468 T, OrigT, D->getStorageClass(), 0);
470 // Note: we don't try to instantiate function parameters until after
471 // we've instantiated the function's type. Therefore, we don't have
472 // to check for 'void' parameter types here.
473 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
478 TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
479 // Since parameter types can decay either before or after
480 // instantiation, we simply treat OriginalParmVarDecls as
481 // ParmVarDecls the same way, and create one or the other depending
482 // on what happens after template instantiation.
483 return VisitParmVarDecl(D);
486 Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
487 const TemplateArgumentList &TemplateArgs) {
488 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
489 return Instantiator.Visit(D);
492 /// \brief Instantiates the type of the given function, including
493 /// instantiating all of the function parameters.
495 /// \param D The function that we will be instantiated
497 /// \param Params the instantiated parameter declarations
499 /// \returns the instantiated function's type if successfull, a NULL
500 /// type if there was an error.
502 TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
503 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
504 bool InvalidDecl = false;
506 // Instantiate the function parameters
507 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
508 llvm::SmallVector<QualType, 4> ParamTys;
509 for (FunctionDecl::param_iterator P = D->param_begin(),
510 PEnd = D->param_end();
512 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
513 if (PInst->getType()->isVoidType()) {
514 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
515 PInst->setInvalidDecl();
517 else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
519 diag::err_abstract_type_in_decl,
520 Sema::AbstractParamType))
521 PInst->setInvalidDecl();
523 Params.push_back(PInst);
524 ParamTys.push_back(PInst->getType());
526 if (PInst->isInvalidDecl())
532 // FIXME: Deallocate dead declarations.
536 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
537 assert(Proto && "Missing prototype?");
539 = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs,
540 D->getLocation(), D->getDeclName());
541 if (ResultType.isNull())
544 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
545 Proto->isVariadic(), Proto->getTypeQuals(),
546 D->getLocation(), D->getDeclName());
549 /// \brief Initializes common fields of an instantiated method
550 /// declaration (New) from the corresponding fields of its template
553 /// \returns true if there was an error
555 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
556 CXXMethodDecl *Tmpl) {
557 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
558 New->setAccess(Tmpl->getAccess());
559 if (Tmpl->isVirtualAsWritten()) {
560 New->setVirtualAsWritten(true);
561 Record->setAggregate(false);
562 Record->setPOD(false);
563 Record->setPolymorphic(true);
565 if (Tmpl->isDeleted())
567 if (Tmpl->isPure()) {
569 Record->setAbstract(true);
573 // FIXME: New needs a pointer to Tmpl
577 /// \brief Instantiate the definition of the given function from its
580 /// \param Function the already-instantiated declaration of a
582 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
583 FunctionDecl *Function) {
584 // FIXME: make this work for function template specializations, too.
586 if (Function->isInvalidDecl())
589 // Find the function body that we'll be substituting.
590 const FunctionDecl *PatternDecl
591 = Function->getInstantiatedFromMemberFunction();
594 Pattern = PatternDecl->getBody(Context, PatternDecl);
599 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
603 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
605 // Introduce a new scope where local variable instantiations will be
607 LocalInstantiationScope Scope(*this);
609 // Introduce the instantiated function parameters into the local
610 // instantiation scope.
611 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
612 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
613 Function->getParamDecl(I));
615 // Enter the scope of this instantiation. We don't use
616 // PushDeclContext because we don't have a scope.
617 DeclContext *PreviousContext = CurContext;
618 CurContext = Function;
620 // Instantiate the function body.
621 OwningStmtResult Body
622 = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function));
624 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
625 /*IsInstantiation=*/true);
627 CurContext = PreviousContext;
629 DeclGroupRef DG(Function);
630 Consumer.HandleTopLevelDecl(DG);
633 /// \brief Instantiate the definition of the given variable from its
636 /// \param Var the already-instantiated declaration of a variable.
637 void Sema::InstantiateVariableDefinition(VarDecl *Var) {
638 // FIXME: Implement this!
641 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
642 if (D->getKind() != Other->getKind())
645 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
646 return Ctx.getCanonicalDecl(Record->getInstantiatedFromMemberClass())
647 == Ctx.getCanonicalDecl(D);
649 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
650 return Ctx.getCanonicalDecl(Function->getInstantiatedFromMemberFunction())
651 == Ctx.getCanonicalDecl(D);
653 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
654 return Ctx.getCanonicalDecl(Enum->getInstantiatedFromMemberEnum())
655 == Ctx.getCanonicalDecl(D);
657 // FIXME: How can we find instantiations of anonymous unions?
659 return D->getDeclName() && isa<NamedDecl>(Other) &&
660 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
663 template<typename ForwardIterator>
664 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
666 ForwardIterator first,
667 ForwardIterator last) {
668 for (; first != last; ++first)
669 if (isInstantiationOf(Ctx, D, *first))
670 return cast<NamedDecl>(*first);
675 /// \brief Find the instantiation of the given declaration within the
676 /// current instantiation.
678 /// This routine is intended to be used when \p D is a declaration
679 /// referenced from within a template, that needs to mapped into the
680 /// corresponding declaration within an instantiation. For example,
684 /// template<typename T>
687 /// KnownValue = sizeof(T)
690 /// bool getKind() const { return KnownValue; }
693 /// template struct X<int>;
696 /// In the instantiation of X<int>::getKind(), we need to map the
697 /// EnumConstantDecl for KnownValue (which refers to
698 /// X<T>::<Kind>::KnownValue) to its instantiation
699 /// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
700 /// this mapping from within the instantiation of X<int>.
701 NamedDecl * Sema::InstantiateCurrentDeclRef(NamedDecl *D) {
702 DeclContext *ParentDC = D->getDeclContext();
703 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
704 // D is a local of some kind. Look into the map of local
705 // declarations to their instantiations.
706 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
709 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
710 ParentDecl = InstantiateCurrentDeclRef(ParentDecl);
714 ParentDC = cast<DeclContext>(ParentDecl);
717 if (ParentDC != D->getDeclContext()) {
718 // We performed some kind of instantiation in the parent context,
719 // so now we need to look into the instantiated parent context to
720 // find the instantiation of the declaration D.
721 NamedDecl *Result = 0;
722 if (D->getDeclName()) {
723 DeclContext::lookup_result Found
724 = ParentDC->lookup(Context, D->getDeclName());
725 Result = findInstantiationOf(Context, D, Found.first, Found.second);
727 // Since we don't have a name for the entity we're looking for,
728 // our only option is to walk through all of the declarations to
729 // find that name. This will occur in a few cases:
731 // - anonymous struct/union within a template
732 // - unnamed class/struct/union/enum within a template
734 // FIXME: Find a better way to find these instantiations!
735 Result = findInstantiationOf(Context, D,
736 ParentDC->decls_begin(Context),
737 ParentDC->decls_end(Context));
739 assert(Result && "Unable to find instantiation of declaration!");
743 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
744 if (ClassTemplateDecl *ClassTemplate
745 = Record->getDescribedClassTemplate()) {
746 // When the declaration D was parsed, it referred to the current
747 // instantiation. Therefore, look through the current context,
748 // which contains actual instantiations, to find the
749 // instantiation of the "current instantiation" that D refers
750 // to. Alternatively, we could just instantiate the
751 // injected-class-name with the current template arguments, but
752 // such an instantiation is far more expensive.
753 for (DeclContext *DC = CurContext; !DC->isFileContext();
754 DC = DC->getParent()) {
755 if (ClassTemplateSpecializationDecl *Spec
756 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
757 if (Context.getCanonicalDecl(Spec->getSpecializedTemplate())
758 == Context.getCanonicalDecl(ClassTemplate))
763 "Unable to find declaration for the current instantiation");