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 //===----------------------------------------------------------------------===/
12 #include "clang/Sema/SemaInternal.h"
13 #include "clang/Sema/Lookup.h"
14 #include "clang/Sema/PrettyDeclStackTrace.h"
15 #include "clang/Sema/Template.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/DependentDiagnostic.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/Lex/Preprocessor.h"
26 using namespace clang
;
28 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl
*OldDecl
,
29 DeclaratorDecl
*NewDecl
) {
30 NestedNameSpecifier
*OldQual
= OldDecl
->getQualifier();
31 if (!OldQual
) return false;
33 SourceRange QualRange
= OldDecl
->getQualifierRange();
35 NestedNameSpecifier
*NewQual
36 = SemaRef
.SubstNestedNameSpecifier(OldQual
, QualRange
, TemplateArgs
);
40 NewDecl
->setQualifierInfo(NewQual
, QualRange
);
44 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl
*OldDecl
,
46 NestedNameSpecifier
*OldQual
= OldDecl
->getQualifier();
47 if (!OldQual
) return false;
49 SourceRange QualRange
= OldDecl
->getQualifierRange();
51 NestedNameSpecifier
*NewQual
52 = SemaRef
.SubstNestedNameSpecifier(OldQual
, QualRange
, TemplateArgs
);
56 NewDecl
->setQualifierInfo(NewQual
, QualRange
);
60 // FIXME: Is this still too simple?
61 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList
&TemplateArgs
,
62 Decl
*Tmpl
, Decl
*New
) {
63 for (AttrVec::const_iterator i
= Tmpl
->attr_begin(), e
= Tmpl
->attr_end();
65 const Attr
*TmplAttr
= *i
;
66 // FIXME: This should be generalized to more than just the AlignedAttr.
67 if (const AlignedAttr
*Aligned
= dyn_cast
<AlignedAttr
>(TmplAttr
)) {
68 if (Aligned
->isAlignmentDependent()) {
69 // The alignment expression is not potentially evaluated.
70 EnterExpressionEvaluationContext
Unevaluated(*this,
73 if (Aligned
->isAlignmentExpr()) {
74 ExprResult Result
= SubstExpr(Aligned
->getAlignmentExpr(),
76 if (!Result
.isInvalid())
77 AddAlignedAttr(Aligned
->getLocation(), New
, Result
.takeAs
<Expr
>());
80 TypeSourceInfo
*Result
= SubstType(Aligned
->getAlignmentType(),
82 Aligned
->getLocation(),
85 AddAlignedAttr(Aligned
->getLocation(), New
, Result
);
91 // FIXME: Is cloning correct for all attributes?
92 Attr
*NewAttr
= TmplAttr
->clone(Context
);
93 New
->addAttr(NewAttr
);
98 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl
*D
) {
99 assert(false && "Translation units cannot be instantiated");
104 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl
*D
) {
105 LabelDecl
*Inst
= LabelDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
107 Owner
->addDecl(Inst
);
112 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl
*D
) {
113 assert(false && "Namespaces cannot be instantiated");
118 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl
*D
) {
119 NamespaceAliasDecl
*Inst
120 = NamespaceAliasDecl::Create(SemaRef
.Context
, Owner
,
121 D
->getNamespaceLoc(),
123 D
->getNamespace()->getIdentifier(),
124 D
->getQualifierRange(),
126 D
->getTargetNameLoc(),
128 Owner
->addDecl(Inst
);
132 Decl
*TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl
*D
) {
133 bool Invalid
= false;
134 TypeSourceInfo
*DI
= D
->getTypeSourceInfo();
135 if (DI
->getType()->isDependentType() ||
136 DI
->getType()->isVariablyModifiedType()) {
137 DI
= SemaRef
.SubstType(DI
, TemplateArgs
,
138 D
->getLocation(), D
->getDeclName());
141 DI
= SemaRef
.Context
.getTrivialTypeSourceInfo(SemaRef
.Context
.IntTy
);
144 SemaRef
.MarkDeclarationsReferencedInType(D
->getLocation(), DI
->getType());
147 // Create the new typedef
149 = TypedefDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
150 D
->getIdentifier(), DI
);
152 Typedef
->setInvalidDecl();
154 // If the old typedef was the name for linkage purposes of an anonymous
155 // tag decl, re-establish that relationship for the new typedef.
156 if (const TagType
*oldTagType
= D
->getUnderlyingType()->getAs
<TagType
>()) {
157 TagDecl
*oldTag
= oldTagType
->getDecl();
158 if (oldTag
->getTypedefForAnonDecl() == D
) {
159 TagDecl
*newTag
= DI
->getType()->castAs
<TagType
>()->getDecl();
160 assert(!newTag
->getIdentifier() && !newTag
->getTypedefForAnonDecl());
161 newTag
->setTypedefForAnonDecl(Typedef
);
165 if (TypedefDecl
*Prev
= D
->getPreviousDeclaration()) {
166 NamedDecl
*InstPrev
= SemaRef
.FindInstantiatedDecl(D
->getLocation(), Prev
,
168 Typedef
->setPreviousDeclaration(cast
<TypedefDecl
>(InstPrev
));
171 SemaRef
.InstantiateAttrs(TemplateArgs
, D
, Typedef
);
173 Typedef
->setAccess(D
->getAccess());
174 Owner
->addDecl(Typedef
);
179 /// \brief Instantiate an initializer, breaking it into separate
180 /// initialization arguments.
182 /// \param S The semantic analysis object.
184 /// \param Init The initializer to instantiate.
186 /// \param TemplateArgs Template arguments to be substituted into the
189 /// \param NewArgs Will be filled in with the instantiation arguments.
191 /// \returns true if an error occurred, false otherwise
192 static bool InstantiateInitializer(Sema
&S
, Expr
*Init
,
193 const MultiLevelTemplateArgumentList
&TemplateArgs
,
194 SourceLocation
&LParenLoc
,
195 ASTOwningVector
<Expr
*> &NewArgs
,
196 SourceLocation
&RParenLoc
) {
198 LParenLoc
= SourceLocation();
199 RParenLoc
= SourceLocation();
204 if (ExprWithCleanups
*ExprTemp
= dyn_cast
<ExprWithCleanups
>(Init
))
205 Init
= ExprTemp
->getSubExpr();
207 while (CXXBindTemporaryExpr
*Binder
= dyn_cast
<CXXBindTemporaryExpr
>(Init
))
208 Init
= Binder
->getSubExpr();
210 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(Init
))
211 Init
= ICE
->getSubExprAsWritten();
213 if (ParenListExpr
*ParenList
= dyn_cast
<ParenListExpr
>(Init
)) {
214 LParenLoc
= ParenList
->getLParenLoc();
215 RParenLoc
= ParenList
->getRParenLoc();
216 return S
.SubstExprs(ParenList
->getExprs(), ParenList
->getNumExprs(),
217 true, TemplateArgs
, NewArgs
);
220 if (CXXConstructExpr
*Construct
= dyn_cast
<CXXConstructExpr
>(Init
)) {
221 if (!isa
<CXXTemporaryObjectExpr
>(Construct
)) {
222 if (S
.SubstExprs(Construct
->getArgs(), Construct
->getNumArgs(), true,
223 TemplateArgs
, NewArgs
))
226 // FIXME: Fake locations!
227 LParenLoc
= S
.PP
.getLocForEndOfToken(Init
->getLocStart());
228 RParenLoc
= LParenLoc
;
233 ExprResult Result
= S
.SubstExpr(Init
, TemplateArgs
);
234 if (Result
.isInvalid())
237 NewArgs
.push_back(Result
.takeAs
<Expr
>());
241 Decl
*TemplateDeclInstantiator::VisitVarDecl(VarDecl
*D
) {
242 // If this is the variable for an anonymous struct or union,
243 // instantiate the anonymous struct/union type first.
244 if (const RecordType
*RecordTy
= D
->getType()->getAs
<RecordType
>())
245 if (RecordTy
->getDecl()->isAnonymousStructOrUnion())
246 if (!VisitCXXRecordDecl(cast
<CXXRecordDecl
>(RecordTy
->getDecl())))
249 // Do substitution on the type of the declaration
250 TypeSourceInfo
*DI
= SemaRef
.SubstType(D
->getTypeSourceInfo(),
252 D
->getTypeSpecStartLoc(),
257 if (DI
->getType()->isFunctionType()) {
258 SemaRef
.Diag(D
->getLocation(), diag::err_variable_instantiates_to_function
)
259 << D
->isStaticDataMember() << DI
->getType();
263 // Build the instantiated declaration
264 VarDecl
*Var
= VarDecl::Create(SemaRef
.Context
, Owner
,
265 D
->getLocation(), D
->getIdentifier(),
267 D
->getStorageClass(),
268 D
->getStorageClassAsWritten());
269 Var
->setThreadSpecified(D
->isThreadSpecified());
270 Var
->setCXXDirectInitializer(D
->hasCXXDirectInitializer());
272 // Substitute the nested name specifier, if any.
273 if (SubstQualifier(D
, Var
))
276 // If we are instantiating a static data member defined
277 // out-of-line, the instantiation will have the same lexical
278 // context (which will be a namespace scope) as the template.
279 if (D
->isOutOfLine())
280 Var
->setLexicalDeclContext(D
->getLexicalDeclContext());
282 Var
->setAccess(D
->getAccess());
284 if (!D
->isStaticDataMember())
285 Var
->setUsed(D
->isUsed(false));
287 // FIXME: In theory, we could have a previous declaration for variables that
288 // are not static data members.
289 bool Redeclaration
= false;
290 // FIXME: having to fake up a LookupResult is dumb.
291 LookupResult
Previous(SemaRef
, Var
->getDeclName(), Var
->getLocation(),
292 Sema::LookupOrdinaryName
, Sema::ForRedeclaration
);
293 if (D
->isStaticDataMember())
294 SemaRef
.LookupQualifiedName(Previous
, Owner
, false);
295 SemaRef
.CheckVariableDeclaration(Var
, Previous
, Redeclaration
);
297 if (D
->isOutOfLine()) {
298 if (!D
->isStaticDataMember())
299 D
->getLexicalDeclContext()->addDecl(Var
);
300 Owner
->makeDeclVisibleInContext(Var
);
303 if (Owner
->isFunctionOrMethod())
304 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Var
);
306 SemaRef
.InstantiateAttrs(TemplateArgs
, D
, Var
);
308 // Link instantiations of static data members back to the template from
309 // which they were instantiated.
310 if (Var
->isStaticDataMember())
311 SemaRef
.Context
.setInstantiatedFromStaticDataMember(Var
, D
,
312 TSK_ImplicitInstantiation
);
314 if (Var
->getAnyInitializer()) {
315 // We already have an initializer in the class.
316 } else if (D
->getInit()) {
317 if (Var
->isStaticDataMember() && !D
->isOutOfLine())
318 SemaRef
.PushExpressionEvaluationContext(Sema::Unevaluated
);
320 SemaRef
.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated
);
322 // Instantiate the initializer.
323 SourceLocation LParenLoc
, RParenLoc
;
324 ASTOwningVector
<Expr
*> InitArgs(SemaRef
);
325 if (!InstantiateInitializer(SemaRef
, D
->getInit(), TemplateArgs
, LParenLoc
,
326 InitArgs
, RParenLoc
)) {
327 // Attach the initializer to the declaration, if we have one.
328 if (InitArgs
.size() == 0)
329 SemaRef
.ActOnUninitializedDecl(Var
, false);
330 else if (D
->hasCXXDirectInitializer()) {
331 // Add the direct initializer to the declaration.
332 SemaRef
.AddCXXDirectInitializerToDecl(Var
,
337 assert(InitArgs
.size() == 1);
338 Expr
*Init
= InitArgs
.take()[0];
339 SemaRef
.AddInitializerToDecl(Var
, Init
, false);
342 // FIXME: Not too happy about invalidating the declaration
343 // because of a bogus initializer.
344 Var
->setInvalidDecl();
347 SemaRef
.PopExpressionEvaluationContext();
348 } else if (!Var
->isStaticDataMember() || Var
->isOutOfLine())
349 SemaRef
.ActOnUninitializedDecl(Var
, false);
351 // Diagnose unused local variables.
352 if (!Var
->isInvalidDecl() && Owner
->isFunctionOrMethod() && !Var
->isUsed())
353 SemaRef
.DiagnoseUnusedDecl(Var
);
358 Decl
*TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl
*D
) {
360 = AccessSpecDecl::Create(SemaRef
.Context
, D
->getAccess(), Owner
,
361 D
->getAccessSpecifierLoc(), D
->getColonLoc());
362 Owner
->addHiddenDecl(AD
);
366 Decl
*TemplateDeclInstantiator::VisitFieldDecl(FieldDecl
*D
) {
367 bool Invalid
= false;
368 TypeSourceInfo
*DI
= D
->getTypeSourceInfo();
369 if (DI
->getType()->isDependentType() ||
370 DI
->getType()->isVariablyModifiedType()) {
371 DI
= SemaRef
.SubstType(DI
, TemplateArgs
,
372 D
->getLocation(), D
->getDeclName());
374 DI
= D
->getTypeSourceInfo();
376 } else if (DI
->getType()->isFunctionType()) {
377 // C++ [temp.arg.type]p3:
378 // If a declaration acquires a function type through a type
379 // dependent on a template-parameter and this causes a
380 // declaration that does not use the syntactic form of a
381 // function declarator to have function type, the program is
383 SemaRef
.Diag(D
->getLocation(), diag::err_field_instantiates_to_function
)
388 SemaRef
.MarkDeclarationsReferencedInType(D
->getLocation(), DI
->getType());
391 Expr
*BitWidth
= D
->getBitWidth();
395 // The bit-width expression is not potentially evaluated.
396 EnterExpressionEvaluationContext
Unevaluated(SemaRef
, Sema::Unevaluated
);
398 ExprResult InstantiatedBitWidth
399 = SemaRef
.SubstExpr(BitWidth
, TemplateArgs
);
400 if (InstantiatedBitWidth
.isInvalid()) {
404 BitWidth
= InstantiatedBitWidth
.takeAs
<Expr
>();
407 FieldDecl
*Field
= SemaRef
.CheckFieldDecl(D
->getDeclName(),
409 cast
<RecordDecl
>(Owner
),
413 D
->getTypeSpecStartLoc(),
417 cast
<Decl
>(Owner
)->setInvalidDecl();
421 SemaRef
.InstantiateAttrs(TemplateArgs
, D
, Field
);
424 Field
->setInvalidDecl();
426 if (!Field
->getDeclName()) {
427 // Keep track of where this decl came from.
428 SemaRef
.Context
.setInstantiatedFromUnnamedFieldDecl(Field
, D
);
430 if (CXXRecordDecl
*Parent
= dyn_cast
<CXXRecordDecl
>(Field
->getDeclContext())) {
431 if (Parent
->isAnonymousStructOrUnion() &&
432 Parent
->getRedeclContext()->isFunctionOrMethod())
433 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Field
);
436 Field
->setImplicit(D
->isImplicit());
437 Field
->setAccess(D
->getAccess());
438 Owner
->addDecl(Field
);
443 Decl
*TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl
*D
) {
444 NamedDecl
**NamedChain
=
445 new (SemaRef
.Context
)NamedDecl
*[D
->getChainingSize()];
448 for (IndirectFieldDecl::chain_iterator PI
=
449 D
->chain_begin(), PE
= D
->chain_end();
451 NamedChain
[i
++] = (SemaRef
.FindInstantiatedDecl(D
->getLocation(),
454 QualType T
= cast
<FieldDecl
>(NamedChain
[i
-1])->getType();
455 IndirectFieldDecl
* IndirectField
456 = IndirectFieldDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
457 D
->getIdentifier(), T
,
458 NamedChain
, D
->getChainingSize());
461 IndirectField
->setImplicit(D
->isImplicit());
462 IndirectField
->setAccess(D
->getAccess());
463 Owner
->addDecl(IndirectField
);
464 return IndirectField
;
467 Decl
*TemplateDeclInstantiator::VisitFriendDecl(FriendDecl
*D
) {
468 // Handle friend type expressions by simply substituting template
469 // parameters into the pattern type and checking the result.
470 if (TypeSourceInfo
*Ty
= D
->getFriendType()) {
471 TypeSourceInfo
*InstTy
=
472 SemaRef
.SubstType(Ty
, TemplateArgs
,
473 D
->getLocation(), DeclarationName());
477 FriendDecl
*FD
= SemaRef
.CheckFriendTypeDecl(D
->getFriendLoc(), InstTy
);
481 FD
->setAccess(AS_public
);
482 FD
->setUnsupportedFriend(D
->isUnsupportedFriend());
487 NamedDecl
*ND
= D
->getFriendDecl();
488 assert(ND
&& "friend decl must be a decl or a type!");
490 // All of the Visit implementations for the various potential friend
491 // declarations have to be carefully written to work for friend
492 // objects, with the most important detail being that the target
493 // decl should almost certainly not be placed in Owner.
494 Decl
*NewND
= Visit(ND
);
495 if (!NewND
) return 0;
498 FriendDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
499 cast
<NamedDecl
>(NewND
), D
->getFriendLoc());
500 FD
->setAccess(AS_public
);
501 FD
->setUnsupportedFriend(D
->isUnsupportedFriend());
506 Decl
*TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl
*D
) {
507 Expr
*AssertExpr
= D
->getAssertExpr();
509 // The expression in a static assertion is not potentially evaluated.
510 EnterExpressionEvaluationContext
Unevaluated(SemaRef
, Sema::Unevaluated
);
512 ExprResult InstantiatedAssertExpr
513 = SemaRef
.SubstExpr(AssertExpr
, TemplateArgs
);
514 if (InstantiatedAssertExpr
.isInvalid())
517 ExprResult
Message(D
->getMessage());
519 return SemaRef
.ActOnStaticAssertDeclaration(D
->getLocation(),
520 InstantiatedAssertExpr
.get(),
524 Decl
*TemplateDeclInstantiator::VisitEnumDecl(EnumDecl
*D
) {
525 EnumDecl
*Enum
= EnumDecl::Create(SemaRef
.Context
, Owner
,
526 D
->getLocation(), D
->getIdentifier(),
527 D
->getTagKeywordLoc(),
528 /*PrevDecl=*/0, D
->isScoped(),
529 D
->isScopedUsingClassTag(), D
->isFixed());
531 if (TypeSourceInfo
* TI
= D
->getIntegerTypeSourceInfo()) {
532 // If we have type source information for the underlying type, it means it
533 // has been explicitly set by the user. Perform substitution on it before
535 SourceLocation UnderlyingLoc
= TI
->getTypeLoc().getBeginLoc();
536 Enum
->setIntegerTypeSourceInfo(SemaRef
.SubstType(TI
,
541 if (!Enum
->getIntegerTypeSourceInfo())
542 Enum
->setIntegerType(SemaRef
.Context
.IntTy
);
545 assert(!D
->getIntegerType()->isDependentType()
546 && "Dependent type without type source info");
547 Enum
->setIntegerType(D
->getIntegerType());
551 SemaRef
.InstantiateAttrs(TemplateArgs
, D
, Enum
);
553 Enum
->setInstantiationOfMemberEnum(D
);
554 Enum
->setAccess(D
->getAccess());
555 if (SubstQualifier(D
, Enum
)) return 0;
556 Owner
->addDecl(Enum
);
557 Enum
->startDefinition();
559 if (D
->getDeclContext()->isFunctionOrMethod())
560 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Enum
);
562 llvm::SmallVector
<Decl
*, 4> Enumerators
;
564 EnumConstantDecl
*LastEnumConst
= 0;
565 for (EnumDecl::enumerator_iterator EC
= D
->enumerator_begin(),
566 ECEnd
= D
->enumerator_end();
568 // The specified value for the enumerator.
569 ExprResult Value
= SemaRef
.Owned((Expr
*)0);
570 if (Expr
*UninstValue
= EC
->getInitExpr()) {
571 // The enumerator's value expression is not potentially evaluated.
572 EnterExpressionEvaluationContext
Unevaluated(SemaRef
,
575 Value
= SemaRef
.SubstExpr(UninstValue
, TemplateArgs
);
578 // Drop the initial value and continue.
579 bool isInvalid
= false;
580 if (Value
.isInvalid()) {
581 Value
= SemaRef
.Owned((Expr
*)0);
585 EnumConstantDecl
*EnumConst
586 = SemaRef
.CheckEnumConstant(Enum
, LastEnumConst
,
587 EC
->getLocation(), EC
->getIdentifier(),
592 EnumConst
->setInvalidDecl();
593 Enum
->setInvalidDecl();
597 SemaRef
.InstantiateAttrs(TemplateArgs
, *EC
, EnumConst
);
599 EnumConst
->setAccess(Enum
->getAccess());
600 Enum
->addDecl(EnumConst
);
601 Enumerators
.push_back(EnumConst
);
602 LastEnumConst
= EnumConst
;
604 if (D
->getDeclContext()->isFunctionOrMethod()) {
605 // If the enumeration is within a function or method, record the enum
606 // constant as a local.
607 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(*EC
, EnumConst
);
612 // FIXME: Fixup LBraceLoc and RBraceLoc
613 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
614 SemaRef
.ActOnEnumBody(Enum
->getLocation(), SourceLocation(), SourceLocation(),
616 Enumerators
.data(), Enumerators
.size(),
622 Decl
*TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl
*D
) {
623 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
627 Decl
*TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl
*D
) {
628 bool isFriend
= (D
->getFriendObjectKind() != Decl::FOK_None
);
630 // Create a local instantiation scope for this class template, which
631 // will contain the instantiations of the template parameters.
632 LocalInstantiationScope
Scope(SemaRef
);
633 TemplateParameterList
*TempParams
= D
->getTemplateParameters();
634 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
638 CXXRecordDecl
*Pattern
= D
->getTemplatedDecl();
640 // Instantiate the qualifier. We have to do this first in case
641 // we're a friend declaration, because if we are then we need to put
642 // the new declaration in the appropriate context.
643 NestedNameSpecifier
*Qualifier
= Pattern
->getQualifier();
645 Qualifier
= SemaRef
.SubstNestedNameSpecifier(Qualifier
,
646 Pattern
->getQualifierRange(),
648 if (!Qualifier
) return 0;
651 CXXRecordDecl
*PrevDecl
= 0;
652 ClassTemplateDecl
*PrevClassTemplate
= 0;
654 if (!isFriend
&& Pattern
->getPreviousDeclaration()) {
655 DeclContext::lookup_result Found
= Owner
->lookup(Pattern
->getDeclName());
656 if (Found
.first
!= Found
.second
) {
657 PrevClassTemplate
= dyn_cast
<ClassTemplateDecl
>(*Found
.first
);
658 if (PrevClassTemplate
)
659 PrevDecl
= PrevClassTemplate
->getTemplatedDecl();
663 // If this isn't a friend, then it's a member template, in which
664 // case we just want to build the instantiation in the
665 // specialization. If it is a friend, we want to build it in
666 // the appropriate context.
667 DeclContext
*DC
= Owner
;
671 SS
.setScopeRep(Qualifier
);
672 SS
.setRange(Pattern
->getQualifierRange());
673 DC
= SemaRef
.computeDeclContext(SS
);
676 DC
= SemaRef
.FindInstantiatedContext(Pattern
->getLocation(),
677 Pattern
->getDeclContext(),
681 // Look for a previous declaration of the template in the owning
683 LookupResult
R(SemaRef
, Pattern
->getDeclName(), Pattern
->getLocation(),
684 Sema::LookupOrdinaryName
, Sema::ForRedeclaration
);
685 SemaRef
.LookupQualifiedName(R
, DC
);
687 if (R
.isSingleResult()) {
688 PrevClassTemplate
= R
.getAsSingle
<ClassTemplateDecl
>();
689 if (PrevClassTemplate
)
690 PrevDecl
= PrevClassTemplate
->getTemplatedDecl();
693 if (!PrevClassTemplate
&& Qualifier
) {
694 SemaRef
.Diag(Pattern
->getLocation(), diag::err_not_tag_in_scope
)
695 << D
->getTemplatedDecl()->getTagKind() << Pattern
->getDeclName() << DC
696 << Pattern
->getQualifierRange();
700 bool AdoptedPreviousTemplateParams
= false;
701 if (PrevClassTemplate
) {
702 bool Complain
= true;
704 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
705 // template for struct std::tr1::__detail::_Map_base, where the
706 // template parameters of the friend declaration don't match the
707 // template parameters of the original declaration. In this one
708 // case, we don't complain about the ill-formed friend
710 if (isFriend
&& Pattern
->getIdentifier() &&
711 Pattern
->getIdentifier()->isStr("_Map_base") &&
713 cast
<NamespaceDecl
>(DC
)->getIdentifier() &&
714 cast
<NamespaceDecl
>(DC
)->getIdentifier()->isStr("__detail")) {
715 DeclContext
*DCParent
= DC
->getParent();
716 if (DCParent
->isNamespace() &&
717 cast
<NamespaceDecl
>(DCParent
)->getIdentifier() &&
718 cast
<NamespaceDecl
>(DCParent
)->getIdentifier()->isStr("tr1")) {
719 DeclContext
*DCParent2
= DCParent
->getParent();
720 if (DCParent2
->isNamespace() &&
721 cast
<NamespaceDecl
>(DCParent2
)->getIdentifier() &&
722 cast
<NamespaceDecl
>(DCParent2
)->getIdentifier()->isStr("std") &&
723 DCParent2
->getParent()->isTranslationUnit())
728 TemplateParameterList
*PrevParams
729 = PrevClassTemplate
->getTemplateParameters();
731 // Make sure the parameter lists match.
732 if (!SemaRef
.TemplateParameterListsAreEqual(InstParams
, PrevParams
,
734 Sema::TPL_TemplateMatch
)) {
738 AdoptedPreviousTemplateParams
= true;
739 InstParams
= PrevParams
;
742 // Do some additional validation, then merge default arguments
743 // from the existing declarations.
744 if (!AdoptedPreviousTemplateParams
&&
745 SemaRef
.CheckTemplateParameterList(InstParams
, PrevParams
,
746 Sema::TPC_ClassTemplate
))
751 CXXRecordDecl
*RecordInst
752 = CXXRecordDecl::Create(SemaRef
.Context
, Pattern
->getTagKind(), DC
,
753 Pattern
->getLocation(), Pattern
->getIdentifier(),
754 Pattern
->getTagKeywordLoc(), PrevDecl
,
755 /*DelayTypeCreation=*/true);
758 RecordInst
->setQualifierInfo(Qualifier
, Pattern
->getQualifierRange());
760 ClassTemplateDecl
*Inst
761 = ClassTemplateDecl::Create(SemaRef
.Context
, DC
, D
->getLocation(),
762 D
->getIdentifier(), InstParams
, RecordInst
,
764 RecordInst
->setDescribedClassTemplate(Inst
);
767 if (PrevClassTemplate
)
768 Inst
->setAccess(PrevClassTemplate
->getAccess());
770 Inst
->setAccess(D
->getAccess());
772 Inst
->setObjectOfFriendDecl(PrevClassTemplate
!= 0);
773 // TODO: do we want to track the instantiation progeny of this
774 // friend target decl?
776 Inst
->setAccess(D
->getAccess());
777 if (!PrevClassTemplate
)
778 Inst
->setInstantiatedFromMemberTemplate(D
);
781 // Trigger creation of the type for the instantiation.
782 SemaRef
.Context
.getInjectedClassNameType(RecordInst
,
783 Inst
->getInjectedClassNameSpecialization());
785 // Finish handling of friends.
787 DC
->makeDeclVisibleInContext(Inst
, /*Recoverable*/ false);
791 Owner
->addDecl(Inst
);
793 if (!PrevClassTemplate
) {
794 // Queue up any out-of-line partial specializations of this member
795 // class template; the client will force their instantiation once
796 // the enclosing class has been instantiated.
797 llvm::SmallVector
<ClassTemplatePartialSpecializationDecl
*, 4> PartialSpecs
;
798 D
->getPartialSpecializations(PartialSpecs
);
799 for (unsigned I
= 0, N
= PartialSpecs
.size(); I
!= N
; ++I
)
800 if (PartialSpecs
[I
]->isOutOfLine())
801 OutOfLinePartialSpecs
.push_back(std::make_pair(Inst
, PartialSpecs
[I
]));
808 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
809 ClassTemplatePartialSpecializationDecl
*D
) {
810 ClassTemplateDecl
*ClassTemplate
= D
->getSpecializedTemplate();
812 // Lookup the already-instantiated declaration in the instantiation
813 // of the class template and return that.
814 DeclContext::lookup_result Found
815 = Owner
->lookup(ClassTemplate
->getDeclName());
816 if (Found
.first
== Found
.second
)
819 ClassTemplateDecl
*InstClassTemplate
820 = dyn_cast
<ClassTemplateDecl
>(*Found
.first
);
821 if (!InstClassTemplate
)
824 if (ClassTemplatePartialSpecializationDecl
*Result
825 = InstClassTemplate
->findPartialSpecInstantiatedFromMember(D
))
828 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate
, D
);
832 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl
*D
) {
833 // Create a local instantiation scope for this function template, which
834 // will contain the instantiations of the template parameters and then get
835 // merged with the local instantiation scope for the function template
837 LocalInstantiationScope
Scope(SemaRef
);
839 TemplateParameterList
*TempParams
= D
->getTemplateParameters();
840 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
844 FunctionDecl
*Instantiated
= 0;
845 if (CXXMethodDecl
*DMethod
= dyn_cast
<CXXMethodDecl
>(D
->getTemplatedDecl()))
846 Instantiated
= cast_or_null
<FunctionDecl
>(VisitCXXMethodDecl(DMethod
,
849 Instantiated
= cast_or_null
<FunctionDecl
>(VisitFunctionDecl(
850 D
->getTemplatedDecl(),
856 Instantiated
->setAccess(D
->getAccess());
858 // Link the instantiated function template declaration to the function
859 // template from which it was instantiated.
860 FunctionTemplateDecl
*InstTemplate
861 = Instantiated
->getDescribedFunctionTemplate();
862 InstTemplate
->setAccess(D
->getAccess());
863 assert(InstTemplate
&&
864 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
866 bool isFriend
= (InstTemplate
->getFriendObjectKind() != Decl::FOK_None
);
868 // Link the instantiation back to the pattern *unless* this is a
869 // non-definition friend declaration.
870 if (!InstTemplate
->getInstantiatedFromMemberTemplate() &&
871 !(isFriend
&& !D
->getTemplatedDecl()->isThisDeclarationADefinition()))
872 InstTemplate
->setInstantiatedFromMemberTemplate(D
);
874 // Make declarations visible in the appropriate context.
876 Owner
->addDecl(InstTemplate
);
881 Decl
*TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl
*D
) {
882 CXXRecordDecl
*PrevDecl
= 0;
883 if (D
->isInjectedClassName())
884 PrevDecl
= cast
<CXXRecordDecl
>(Owner
);
885 else if (D
->getPreviousDeclaration()) {
886 NamedDecl
*Prev
= SemaRef
.FindInstantiatedDecl(D
->getLocation(),
887 D
->getPreviousDeclaration(),
890 PrevDecl
= cast
<CXXRecordDecl
>(Prev
);
893 CXXRecordDecl
*Record
894 = CXXRecordDecl::Create(SemaRef
.Context
, D
->getTagKind(), Owner
,
895 D
->getLocation(), D
->getIdentifier(),
896 D
->getTagKeywordLoc(), PrevDecl
);
898 // Substitute the nested name specifier, if any.
899 if (SubstQualifier(D
, Record
))
902 Record
->setImplicit(D
->isImplicit());
903 // FIXME: Check against AS_none is an ugly hack to work around the issue that
904 // the tag decls introduced by friend class declarations don't have an access
905 // specifier. Remove once this area of the code gets sorted out.
906 if (D
->getAccess() != AS_none
)
907 Record
->setAccess(D
->getAccess());
908 if (!D
->isInjectedClassName())
909 Record
->setInstantiationOfMemberClass(D
, TSK_ImplicitInstantiation
);
911 // If the original function was part of a friend declaration,
912 // inherit its namespace state.
913 if (Decl::FriendObjectKind FOK
= D
->getFriendObjectKind())
914 Record
->setObjectOfFriendDecl(FOK
== Decl::FOK_Declared
);
916 // Make sure that anonymous structs and unions are recorded.
917 if (D
->isAnonymousStructOrUnion()) {
918 Record
->setAnonymousStructOrUnion(true);
919 if (Record
->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
920 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Record
);
923 Owner
->addDecl(Record
);
927 /// Normal class members are of more specific types and therefore
928 /// don't make it here. This function serves two purposes:
929 /// 1) instantiating function templates
930 /// 2) substituting friend declarations
931 /// FIXME: preserve function definitions in case #2
932 Decl
*TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl
*D
,
933 TemplateParameterList
*TemplateParams
) {
934 // Check whether there is already a function template specialization for
936 FunctionTemplateDecl
*FunctionTemplate
= D
->getDescribedFunctionTemplate();
938 if (FunctionTemplate
&& !TemplateParams
) {
939 std::pair
<const TemplateArgument
*, unsigned> Innermost
940 = TemplateArgs
.getInnermost();
942 FunctionDecl
*SpecFunc
943 = FunctionTemplate
->findSpecialization(Innermost
.first
, Innermost
.second
,
946 // If we already have a function template specialization, return it.
952 if (FunctionTemplate
)
953 isFriend
= (FunctionTemplate
->getFriendObjectKind() != Decl::FOK_None
);
955 isFriend
= (D
->getFriendObjectKind() != Decl::FOK_None
);
957 bool MergeWithParentScope
= (TemplateParams
!= 0) ||
958 Owner
->isFunctionOrMethod() ||
959 !(isa
<Decl
>(Owner
) &&
960 cast
<Decl
>(Owner
)->isDefinedOutsideFunctionOrMethod());
961 LocalInstantiationScope
Scope(SemaRef
, MergeWithParentScope
);
963 llvm::SmallVector
<ParmVarDecl
*, 4> Params
;
964 TypeSourceInfo
*TInfo
= D
->getTypeSourceInfo();
965 TInfo
= SubstFunctionType(D
, Params
);
968 QualType T
= TInfo
->getType();
970 NestedNameSpecifier
*Qualifier
= D
->getQualifier();
972 Qualifier
= SemaRef
.SubstNestedNameSpecifier(Qualifier
,
973 D
->getQualifierRange(),
975 if (!Qualifier
) return 0;
978 // If we're instantiating a local function declaration, put the result
979 // in the owner; otherwise we need to find the instantiated context.
981 if (D
->getDeclContext()->isFunctionOrMethod())
983 else if (isFriend
&& Qualifier
) {
985 SS
.setScopeRep(Qualifier
);
986 SS
.setRange(D
->getQualifierRange());
987 DC
= SemaRef
.computeDeclContext(SS
);
990 DC
= SemaRef
.FindInstantiatedContext(D
->getLocation(), D
->getDeclContext(),
994 FunctionDecl
*Function
=
995 FunctionDecl::Create(SemaRef
.Context
, DC
, D
->getLocation(),
996 D
->getDeclName(), T
, TInfo
,
997 D
->getStorageClass(), D
->getStorageClassAsWritten(),
998 D
->isInlineSpecified(), D
->hasWrittenPrototype());
1001 Function
->setQualifierInfo(Qualifier
, D
->getQualifierRange());
1003 DeclContext
*LexicalDC
= Owner
;
1004 if (!isFriend
&& D
->isOutOfLine()) {
1005 assert(D
->getDeclContext()->isFileContext());
1006 LexicalDC
= D
->getDeclContext();
1009 Function
->setLexicalDeclContext(LexicalDC
);
1011 // Attach the parameters
1012 for (unsigned P
= 0; P
< Params
.size(); ++P
)
1014 Params
[P
]->setOwningFunction(Function
);
1015 Function
->setParams(Params
.data(), Params
.size());
1017 SourceLocation InstantiateAtPOI
;
1018 if (TemplateParams
) {
1019 // Our resulting instantiation is actually a function template, since we
1020 // are substituting only the outer template parameters. For example, given
1022 // template<typename T>
1024 // template<typename U> friend void f(T, U);
1029 // We are instantiating the friend function template "f" within X<int>,
1030 // which means substituting int for T, but leaving "f" as a friend function
1032 // Build the function template itself.
1033 FunctionTemplate
= FunctionTemplateDecl::Create(SemaRef
.Context
, DC
,
1034 Function
->getLocation(),
1035 Function
->getDeclName(),
1036 TemplateParams
, Function
);
1037 Function
->setDescribedFunctionTemplate(FunctionTemplate
);
1039 FunctionTemplate
->setLexicalDeclContext(LexicalDC
);
1041 if (isFriend
&& D
->isThisDeclarationADefinition()) {
1042 // TODO: should we remember this connection regardless of whether
1043 // the friend declaration provided a body?
1044 FunctionTemplate
->setInstantiatedFromMemberTemplate(
1045 D
->getDescribedFunctionTemplate());
1047 } else if (FunctionTemplate
) {
1048 // Record this function template specialization.
1049 std::pair
<const TemplateArgument
*, unsigned> Innermost
1050 = TemplateArgs
.getInnermost();
1051 Function
->setFunctionTemplateSpecialization(FunctionTemplate
,
1052 TemplateArgumentList::CreateCopy(SemaRef
.Context
,
1056 } else if (isFriend
&& D
->isThisDeclarationADefinition()) {
1057 // TODO: should we remember this connection regardless of whether
1058 // the friend declaration provided a body?
1059 Function
->setInstantiationOfMemberFunction(D
, TSK_ImplicitInstantiation
);
1062 if (InitFunctionInstantiation(Function
, D
))
1063 Function
->setInvalidDecl();
1065 bool Redeclaration
= false;
1066 bool isExplicitSpecialization
= false;
1068 LookupResult
Previous(SemaRef
, Function
->getDeclName(), SourceLocation(),
1069 Sema::LookupOrdinaryName
, Sema::ForRedeclaration
);
1071 if (DependentFunctionTemplateSpecializationInfo
*Info
1072 = D
->getDependentSpecializationInfo()) {
1073 assert(isFriend
&& "non-friend has dependent specialization info?");
1075 // This needs to be set now for future sanity.
1076 Function
->setObjectOfFriendDecl(/*HasPrevious*/ true);
1078 // Instantiate the explicit template arguments.
1079 TemplateArgumentListInfo
ExplicitArgs(Info
->getLAngleLoc(),
1080 Info
->getRAngleLoc());
1081 if (SemaRef
.Subst(Info
->getTemplateArgs(), Info
->getNumTemplateArgs(),
1082 ExplicitArgs
, TemplateArgs
))
1085 // Map the candidate templates to their instantiations.
1086 for (unsigned I
= 0, E
= Info
->getNumTemplates(); I
!= E
; ++I
) {
1087 Decl
*Temp
= SemaRef
.FindInstantiatedDecl(D
->getLocation(),
1088 Info
->getTemplate(I
),
1090 if (!Temp
) return 0;
1092 Previous
.addDecl(cast
<FunctionTemplateDecl
>(Temp
));
1095 if (SemaRef
.CheckFunctionTemplateSpecialization(Function
,
1098 Function
->setInvalidDecl();
1100 isExplicitSpecialization
= true;
1102 } else if (TemplateParams
|| !FunctionTemplate
) {
1103 // Look only into the namespace where the friend would be declared to
1104 // find a previous declaration. This is the innermost enclosing namespace,
1105 // as described in ActOnFriendFunctionDecl.
1106 SemaRef
.LookupQualifiedName(Previous
, DC
);
1108 // In C++, the previous declaration we find might be a tag type
1109 // (class or enum). In this case, the new declaration will hide the
1110 // tag type. Note that this does does not apply if we're declaring a
1111 // typedef (C++ [dcl.typedef]p4).
1112 if (Previous
.isSingleTagDecl())
1116 SemaRef
.CheckFunctionDeclaration(/*Scope*/ 0, Function
, Previous
,
1117 isExplicitSpecialization
, Redeclaration
);
1119 NamedDecl
*PrincipalDecl
= (TemplateParams
1120 ? cast
<NamedDecl
>(FunctionTemplate
)
1123 // If the original function was part of a friend declaration,
1124 // inherit its namespace state and add it to the owner.
1126 NamedDecl
*PrevDecl
;
1128 PrevDecl
= FunctionTemplate
->getPreviousDeclaration();
1130 PrevDecl
= Function
->getPreviousDeclaration();
1132 PrincipalDecl
->setObjectOfFriendDecl(PrevDecl
!= 0);
1133 DC
->makeDeclVisibleInContext(PrincipalDecl
, /*Recoverable=*/ false);
1135 bool queuedInstantiation
= false;
1137 if (!SemaRef
.getLangOptions().CPlusPlus0x
&&
1138 D
->isThisDeclarationADefinition()) {
1139 // Check for a function body.
1140 const FunctionDecl
*Definition
= 0;
1141 if (Function
->hasBody(Definition
) &&
1142 Definition
->getTemplateSpecializationKind() == TSK_Undeclared
) {
1143 SemaRef
.Diag(Function
->getLocation(), diag::err_redefinition
)
1144 << Function
->getDeclName();
1145 SemaRef
.Diag(Definition
->getLocation(), diag::note_previous_definition
);
1146 Function
->setInvalidDecl();
1148 // Check for redefinitions due to other instantiations of this or
1149 // a similar friend function.
1150 else for (FunctionDecl::redecl_iterator R
= Function
->redecls_begin(),
1151 REnd
= Function
->redecls_end();
1155 switch (R
->getFriendObjectKind()) {
1156 case Decl::FOK_None
:
1157 if (!queuedInstantiation
&& R
->isUsed(false)) {
1158 if (MemberSpecializationInfo
*MSInfo
1159 = Function
->getMemberSpecializationInfo()) {
1160 if (MSInfo
->getPointOfInstantiation().isInvalid()) {
1161 SourceLocation Loc
= R
->getLocation(); // FIXME
1162 MSInfo
->setPointOfInstantiation(Loc
);
1163 SemaRef
.PendingLocalImplicitInstantiations
.push_back(
1164 std::make_pair(Function
, Loc
));
1165 queuedInstantiation
= true;
1171 if (const FunctionDecl
*RPattern
1172 = R
->getTemplateInstantiationPattern())
1173 if (RPattern
->hasBody(RPattern
)) {
1174 SemaRef
.Diag(Function
->getLocation(), diag::err_redefinition
)
1175 << Function
->getDeclName();
1176 SemaRef
.Diag(R
->getLocation(), diag::note_previous_definition
);
1177 Function
->setInvalidDecl();
1185 if (Function
->isOverloadedOperator() && !DC
->isRecord() &&
1186 PrincipalDecl
->isInIdentifierNamespace(Decl::IDNS_Ordinary
))
1187 PrincipalDecl
->setNonMemberOperator();
1193 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl
*D
,
1194 TemplateParameterList
*TemplateParams
) {
1195 FunctionTemplateDecl
*FunctionTemplate
= D
->getDescribedFunctionTemplate();
1196 void *InsertPos
= 0;
1197 if (FunctionTemplate
&& !TemplateParams
) {
1198 // We are creating a function template specialization from a function
1199 // template. Check whether there is already a function template
1200 // specialization for this particular set of template arguments.
1201 std::pair
<const TemplateArgument
*, unsigned> Innermost
1202 = TemplateArgs
.getInnermost();
1204 FunctionDecl
*SpecFunc
1205 = FunctionTemplate
->findSpecialization(Innermost
.first
, Innermost
.second
,
1208 // If we already have a function template specialization, return it.
1214 if (FunctionTemplate
)
1215 isFriend
= (FunctionTemplate
->getFriendObjectKind() != Decl::FOK_None
);
1217 isFriend
= (D
->getFriendObjectKind() != Decl::FOK_None
);
1219 bool MergeWithParentScope
= (TemplateParams
!= 0) ||
1220 !(isa
<Decl
>(Owner
) &&
1221 cast
<Decl
>(Owner
)->isDefinedOutsideFunctionOrMethod());
1222 LocalInstantiationScope
Scope(SemaRef
, MergeWithParentScope
);
1224 // Instantiate enclosing template arguments for friends.
1225 llvm::SmallVector
<TemplateParameterList
*, 4> TempParamLists
;
1226 unsigned NumTempParamLists
= 0;
1227 if (isFriend
&& (NumTempParamLists
= D
->getNumTemplateParameterLists())) {
1228 TempParamLists
.set_size(NumTempParamLists
);
1229 for (unsigned I
= 0; I
!= NumTempParamLists
; ++I
) {
1230 TemplateParameterList
*TempParams
= D
->getTemplateParameterList(I
);
1231 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
1234 TempParamLists
[I
] = InstParams
;
1238 llvm::SmallVector
<ParmVarDecl
*, 4> Params
;
1239 TypeSourceInfo
*TInfo
= D
->getTypeSourceInfo();
1240 TInfo
= SubstFunctionType(D
, Params
);
1243 QualType T
= TInfo
->getType();
1245 // \brief If the type of this function, after ignoring parentheses,
1246 // is not *directly* a function type, then we're instantiating a function
1247 // that was declared via a typedef, e.g.,
1249 // typedef int functype(int, int);
1252 // In this case, we'll just go instantiate the ParmVarDecls that we
1253 // synthesized in the method declaration.
1254 if (!isa
<FunctionProtoType
>(T
.IgnoreParens())) {
1255 assert(!Params
.size() && "Instantiating type could not yield parameters");
1256 llvm::SmallVector
<QualType
, 4> ParamTypes
;
1257 if (SemaRef
.SubstParmTypes(D
->getLocation(), D
->param_begin(),
1258 D
->getNumParams(), TemplateArgs
, ParamTypes
,
1263 NestedNameSpecifier
*Qualifier
= D
->getQualifier();
1265 Qualifier
= SemaRef
.SubstNestedNameSpecifier(Qualifier
,
1266 D
->getQualifierRange(),
1268 if (!Qualifier
) return 0;
1271 DeclContext
*DC
= Owner
;
1275 SS
.setScopeRep(Qualifier
);
1276 SS
.setRange(D
->getQualifierRange());
1277 DC
= SemaRef
.computeDeclContext(SS
);
1279 if (DC
&& SemaRef
.RequireCompleteDeclContext(SS
, DC
))
1282 DC
= SemaRef
.FindInstantiatedContext(D
->getLocation(),
1283 D
->getDeclContext(),
1289 // Build the instantiated method declaration.
1290 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(DC
);
1291 CXXMethodDecl
*Method
= 0;
1293 DeclarationNameInfo NameInfo
1294 = SemaRef
.SubstDeclarationNameInfo(D
->getNameInfo(), TemplateArgs
);
1295 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(D
)) {
1296 Method
= CXXConstructorDecl::Create(SemaRef
.Context
, Record
,
1298 Constructor
->isExplicit(),
1299 Constructor
->isInlineSpecified(),
1301 } else if (CXXDestructorDecl
*Destructor
= dyn_cast
<CXXDestructorDecl
>(D
)) {
1302 Method
= CXXDestructorDecl::Create(SemaRef
.Context
, Record
,
1304 Destructor
->isInlineSpecified(),
1306 } else if (CXXConversionDecl
*Conversion
= dyn_cast
<CXXConversionDecl
>(D
)) {
1307 Method
= CXXConversionDecl::Create(SemaRef
.Context
, Record
,
1309 Conversion
->isInlineSpecified(),
1310 Conversion
->isExplicit());
1312 Method
= CXXMethodDecl::Create(SemaRef
.Context
, Record
,
1315 D
->getStorageClassAsWritten(),
1316 D
->isInlineSpecified());
1320 Method
->setQualifierInfo(Qualifier
, D
->getQualifierRange());
1322 if (TemplateParams
) {
1323 // Our resulting instantiation is actually a function template, since we
1324 // are substituting only the outer template parameters. For example, given
1326 // template<typename T>
1328 // template<typename U> void f(T, U);
1333 // We are instantiating the member template "f" within X<int>, which means
1334 // substituting int for T, but leaving "f" as a member function template.
1335 // Build the function template itself.
1336 FunctionTemplate
= FunctionTemplateDecl::Create(SemaRef
.Context
, Record
,
1337 Method
->getLocation(),
1338 Method
->getDeclName(),
1339 TemplateParams
, Method
);
1341 FunctionTemplate
->setLexicalDeclContext(Owner
);
1342 FunctionTemplate
->setObjectOfFriendDecl(true);
1343 } else if (D
->isOutOfLine())
1344 FunctionTemplate
->setLexicalDeclContext(D
->getLexicalDeclContext());
1345 Method
->setDescribedFunctionTemplate(FunctionTemplate
);
1346 } else if (FunctionTemplate
) {
1347 // Record this function template specialization.
1348 std::pair
<const TemplateArgument
*, unsigned> Innermost
1349 = TemplateArgs
.getInnermost();
1350 Method
->setFunctionTemplateSpecialization(FunctionTemplate
,
1351 TemplateArgumentList::CreateCopy(SemaRef
.Context
,
1355 } else if (!isFriend
) {
1356 // Record that this is an instantiation of a member function.
1357 Method
->setInstantiationOfMemberFunction(D
, TSK_ImplicitInstantiation
);
1360 // If we are instantiating a member function defined
1361 // out-of-line, the instantiation will have the same lexical
1362 // context (which will be a namespace scope) as the template.
1364 if (NumTempParamLists
)
1365 Method
->setTemplateParameterListsInfo(SemaRef
.Context
,
1367 TempParamLists
.data());
1369 Method
->setLexicalDeclContext(Owner
);
1370 Method
->setObjectOfFriendDecl(true);
1371 } else if (D
->isOutOfLine())
1372 Method
->setLexicalDeclContext(D
->getLexicalDeclContext());
1374 // Attach the parameters
1375 for (unsigned P
= 0; P
< Params
.size(); ++P
)
1376 Params
[P
]->setOwningFunction(Method
);
1377 Method
->setParams(Params
.data(), Params
.size());
1379 if (InitMethodInstantiation(Method
, D
))
1380 Method
->setInvalidDecl();
1382 LookupResult
Previous(SemaRef
, NameInfo
, Sema::LookupOrdinaryName
,
1383 Sema::ForRedeclaration
);
1385 if (!FunctionTemplate
|| TemplateParams
|| isFriend
) {
1386 SemaRef
.LookupQualifiedName(Previous
, Record
);
1388 // In C++, the previous declaration we find might be a tag type
1389 // (class or enum). In this case, the new declaration will hide the
1390 // tag type. Note that this does does not apply if we're declaring a
1391 // typedef (C++ [dcl.typedef]p4).
1392 if (Previous
.isSingleTagDecl())
1396 bool Redeclaration
= false;
1397 SemaRef
.CheckFunctionDeclaration(0, Method
, Previous
, false, Redeclaration
);
1400 SemaRef
.CheckPureMethod(Method
, SourceRange());
1402 Method
->setAccess(D
->getAccess());
1404 SemaRef
.CheckOverrideControl(Method
);
1406 if (FunctionTemplate
) {
1407 // If there's a function template, let our caller handle it.
1408 } else if (Method
->isInvalidDecl() && !Previous
.empty()) {
1409 // Don't hide a (potentially) valid declaration with an invalid one.
1411 NamedDecl
*DeclToAdd
= (TemplateParams
1412 ? cast
<NamedDecl
>(FunctionTemplate
)
1415 Record
->makeDeclVisibleInContext(DeclToAdd
);
1417 Owner
->addDecl(DeclToAdd
);
1423 Decl
*TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl
*D
) {
1424 return VisitCXXMethodDecl(D
);
1427 Decl
*TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl
*D
) {
1428 return VisitCXXMethodDecl(D
);
1431 Decl
*TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl
*D
) {
1432 return VisitCXXMethodDecl(D
);
1435 ParmVarDecl
*TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl
*D
) {
1436 return SemaRef
.SubstParmVarDecl(D
, TemplateArgs
, llvm::Optional
<unsigned>());
1439 Decl
*TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1440 TemplateTypeParmDecl
*D
) {
1441 // TODO: don't always clone when decls are refcounted.
1442 const Type
* T
= D
->getTypeForDecl();
1443 assert(T
->isTemplateTypeParmType());
1444 const TemplateTypeParmType
*TTPT
= T
->getAs
<TemplateTypeParmType
>();
1446 TemplateTypeParmDecl
*Inst
=
1447 TemplateTypeParmDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
1448 TTPT
->getDepth() - TemplateArgs
.getNumLevels(),
1449 TTPT
->getIndex(), D
->getIdentifier(),
1450 D
->wasDeclaredWithTypename(),
1451 D
->isParameterPack());
1453 if (D
->hasDefaultArgument())
1454 Inst
->setDefaultArgument(D
->getDefaultArgumentInfo(), false);
1456 // Introduce this template parameter's instantiation into the instantiation
1458 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Inst
);
1463 Decl
*TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1464 NonTypeTemplateParmDecl
*D
) {
1465 // Substitute into the type of the non-type template parameter.
1466 TypeLoc TL
= D
->getTypeSourceInfo()->getTypeLoc();
1467 llvm::SmallVector
<TypeSourceInfo
*, 4> ExpandedParameterPackTypesAsWritten
;
1468 llvm::SmallVector
<QualType
, 4> ExpandedParameterPackTypes
;
1469 bool IsExpandedParameterPack
= false;
1472 bool Invalid
= false;
1474 if (D
->isExpandedParameterPack()) {
1475 // The non-type template parameter pack is an already-expanded pack
1476 // expansion of types. Substitute into each of the expanded types.
1477 ExpandedParameterPackTypes
.reserve(D
->getNumExpansionTypes());
1478 ExpandedParameterPackTypesAsWritten
.reserve(D
->getNumExpansionTypes());
1479 for (unsigned I
= 0, N
= D
->getNumExpansionTypes(); I
!= N
; ++I
) {
1480 TypeSourceInfo
*NewDI
=SemaRef
.SubstType(D
->getExpansionTypeSourceInfo(I
),
1487 ExpandedParameterPackTypesAsWritten
.push_back(NewDI
);
1488 QualType NewT
=SemaRef
.CheckNonTypeTemplateParameterType(NewDI
->getType(),
1492 ExpandedParameterPackTypes
.push_back(NewT
);
1495 IsExpandedParameterPack
= true;
1496 DI
= D
->getTypeSourceInfo();
1498 } else if (isa
<PackExpansionTypeLoc
>(TL
)) {
1499 // The non-type template parameter pack's type is a pack expansion of types.
1500 // Determine whether we need to expand this parameter pack into separate
1502 PackExpansionTypeLoc Expansion
= cast
<PackExpansionTypeLoc
>(TL
);
1503 TypeLoc Pattern
= Expansion
.getPatternLoc();
1504 llvm::SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
1505 SemaRef
.collectUnexpandedParameterPacks(Pattern
, Unexpanded
);
1507 // Determine whether the set of unexpanded parameter packs can and should
1510 bool RetainExpansion
= false;
1511 llvm::Optional
<unsigned> OrigNumExpansions
1512 = Expansion
.getTypePtr()->getNumExpansions();
1513 llvm::Optional
<unsigned> NumExpansions
= OrigNumExpansions
;
1514 if (SemaRef
.CheckParameterPacksForExpansion(Expansion
.getEllipsisLoc(),
1515 Pattern
.getSourceRange(),
1519 Expand
, RetainExpansion
,
1524 for (unsigned I
= 0; I
!= *NumExpansions
; ++I
) {
1525 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, I
);
1526 TypeSourceInfo
*NewDI
= SemaRef
.SubstType(Pattern
, TemplateArgs
,
1532 ExpandedParameterPackTypesAsWritten
.push_back(NewDI
);
1533 QualType NewT
= SemaRef
.CheckNonTypeTemplateParameterType(
1538 ExpandedParameterPackTypes
.push_back(NewT
);
1541 // Note that we have an expanded parameter pack. The "type" of this
1542 // expanded parameter pack is the original expansion type, but callers
1543 // will end up using the expanded parameter pack types for type-checking.
1544 IsExpandedParameterPack
= true;
1545 DI
= D
->getTypeSourceInfo();
1548 // We cannot fully expand the pack expansion now, so substitute into the
1549 // pattern and create a new pack expansion type.
1550 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, -1);
1551 TypeSourceInfo
*NewPattern
= SemaRef
.SubstType(Pattern
, TemplateArgs
,
1557 DI
= SemaRef
.CheckPackExpansion(NewPattern
, Expansion
.getEllipsisLoc(),
1565 // Simple case: substitution into a parameter that is not a parameter pack.
1566 DI
= SemaRef
.SubstType(D
->getTypeSourceInfo(), TemplateArgs
,
1567 D
->getLocation(), D
->getDeclName());
1571 // Check that this type is acceptable for a non-type template parameter.
1572 bool Invalid
= false;
1573 T
= SemaRef
.CheckNonTypeTemplateParameterType(DI
->getType(),
1576 T
= SemaRef
.Context
.IntTy
;
1581 NonTypeTemplateParmDecl
*Param
;
1582 if (IsExpandedParameterPack
)
1583 Param
= NonTypeTemplateParmDecl::Create(SemaRef
.Context
, Owner
,
1585 D
->getDepth() - TemplateArgs
.getNumLevels(),
1587 D
->getIdentifier(), T
,
1589 ExpandedParameterPackTypes
.data(),
1590 ExpandedParameterPackTypes
.size(),
1591 ExpandedParameterPackTypesAsWritten
.data());
1593 Param
= NonTypeTemplateParmDecl::Create(SemaRef
.Context
, Owner
,
1595 D
->getDepth() - TemplateArgs
.getNumLevels(),
1597 D
->getIdentifier(), T
,
1598 D
->isParameterPack(), DI
);
1601 Param
->setInvalidDecl();
1603 Param
->setDefaultArgument(D
->getDefaultArgument(), false);
1605 // Introduce this template parameter's instantiation into the instantiation
1607 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Param
);
1612 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1613 TemplateTemplateParmDecl
*D
) {
1614 // Instantiate the template parameter list of the template template parameter.
1615 TemplateParameterList
*TempParams
= D
->getTemplateParameters();
1616 TemplateParameterList
*InstParams
;
1618 // Perform the actual substitution of template parameters within a new,
1619 // local instantiation scope.
1620 LocalInstantiationScope
Scope(SemaRef
);
1621 InstParams
= SubstTemplateParams(TempParams
);
1626 // Build the template template parameter.
1627 TemplateTemplateParmDecl
*Param
1628 = TemplateTemplateParmDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
1629 D
->getDepth() - TemplateArgs
.getNumLevels(),
1630 D
->getPosition(), D
->isParameterPack(),
1631 D
->getIdentifier(), InstParams
);
1632 Param
->setDefaultArgument(D
->getDefaultArgument(), false);
1634 // Introduce this template parameter's instantiation into the instantiation
1636 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Param
);
1641 Decl
*TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl
*D
) {
1642 // Using directives are never dependent, so they require no explicit
1644 UsingDirectiveDecl
*Inst
1645 = UsingDirectiveDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
1646 D
->getNamespaceKeyLocation(),
1647 D
->getQualifierRange(), D
->getQualifier(),
1648 D
->getIdentLocation(),
1649 D
->getNominatedNamespace(),
1650 D
->getCommonAncestor());
1651 Owner
->addDecl(Inst
);
1655 Decl
*TemplateDeclInstantiator::VisitUsingDecl(UsingDecl
*D
) {
1657 // The nested name specifier may be dependent, for example
1658 // template <typename T> struct t {
1659 // struct s1 { T f1(); };
1660 // struct s2 : s1 { using s1::f1; };
1662 // template struct t<int>;
1663 // Here, in using s1::f1, s1 refers to t<T>::s1;
1664 // we need to substitute for t<int>::s1.
1665 NestedNameSpecifier
*NNS
=
1666 SemaRef
.SubstNestedNameSpecifier(D
->getTargetNestedNameDecl(),
1667 D
->getNestedNameRange(),
1672 // The name info is non-dependent, so no transformation
1674 DeclarationNameInfo NameInfo
= D
->getNameInfo();
1676 // We only need to do redeclaration lookups if we're in a class
1677 // scope (in fact, it's not really even possible in non-class
1679 bool CheckRedeclaration
= Owner
->isRecord();
1681 LookupResult
Prev(SemaRef
, NameInfo
, Sema::LookupUsingDeclName
,
1682 Sema::ForRedeclaration
);
1684 UsingDecl
*NewUD
= UsingDecl::Create(SemaRef
.Context
, Owner
,
1685 D
->getNestedNameRange(),
1686 D
->getUsingLocation(),
1692 SS
.setScopeRep(NNS
);
1693 SS
.setRange(D
->getNestedNameRange());
1695 if (CheckRedeclaration
) {
1696 Prev
.setHideTags(false);
1697 SemaRef
.LookupQualifiedName(Prev
, Owner
);
1699 // Check for invalid redeclarations.
1700 if (SemaRef
.CheckUsingDeclRedeclaration(D
->getUsingLocation(),
1701 D
->isTypeName(), SS
,
1702 D
->getLocation(), Prev
))
1703 NewUD
->setInvalidDecl();
1707 if (!NewUD
->isInvalidDecl() &&
1708 SemaRef
.CheckUsingDeclQualifier(D
->getUsingLocation(), SS
,
1710 NewUD
->setInvalidDecl();
1712 SemaRef
.Context
.setInstantiatedFromUsingDecl(NewUD
, D
);
1713 NewUD
->setAccess(D
->getAccess());
1714 Owner
->addDecl(NewUD
);
1716 // Don't process the shadow decls for an invalid decl.
1717 if (NewUD
->isInvalidDecl())
1720 bool isFunctionScope
= Owner
->isFunctionOrMethod();
1722 // Process the shadow decls.
1723 for (UsingDecl::shadow_iterator I
= D
->shadow_begin(), E
= D
->shadow_end();
1725 UsingShadowDecl
*Shadow
= *I
;
1726 NamedDecl
*InstTarget
=
1727 cast
<NamedDecl
>(SemaRef
.FindInstantiatedDecl(Shadow
->getLocation(),
1728 Shadow
->getTargetDecl(),
1731 if (CheckRedeclaration
&&
1732 SemaRef
.CheckUsingShadowDecl(NewUD
, InstTarget
, Prev
))
1735 UsingShadowDecl
*InstShadow
1736 = SemaRef
.BuildUsingShadowDecl(/*Scope*/ 0, NewUD
, InstTarget
);
1737 SemaRef
.Context
.setInstantiatedFromUsingShadowDecl(InstShadow
, Shadow
);
1739 if (isFunctionScope
)
1740 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(Shadow
, InstShadow
);
1746 Decl
*TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl
*D
) {
1747 // Ignore these; we handle them in bulk when processing the UsingDecl.
1751 Decl
* TemplateDeclInstantiator
1752 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl
*D
) {
1753 NestedNameSpecifier
*NNS
=
1754 SemaRef
.SubstNestedNameSpecifier(D
->getTargetNestedNameSpecifier(),
1755 D
->getTargetNestedNameRange(),
1761 SS
.setRange(D
->getTargetNestedNameRange());
1762 SS
.setScopeRep(NNS
);
1764 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1765 // Hence, no tranformation is required for it.
1766 DeclarationNameInfo
NameInfo(D
->getDeclName(), D
->getLocation());
1768 SemaRef
.BuildUsingDeclaration(/*Scope*/ 0, D
->getAccess(),
1769 D
->getUsingLoc(), SS
, NameInfo
, 0,
1770 /*instantiation*/ true,
1771 /*typename*/ true, D
->getTypenameLoc());
1773 SemaRef
.Context
.setInstantiatedFromUsingDecl(cast
<UsingDecl
>(UD
), D
);
1778 Decl
* TemplateDeclInstantiator
1779 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl
*D
) {
1780 NestedNameSpecifier
*NNS
=
1781 SemaRef
.SubstNestedNameSpecifier(D
->getTargetNestedNameSpecifier(),
1782 D
->getTargetNestedNameRange(),
1788 SS
.setRange(D
->getTargetNestedNameRange());
1789 SS
.setScopeRep(NNS
);
1791 DeclarationNameInfo NameInfo
1792 = SemaRef
.SubstDeclarationNameInfo(D
->getNameInfo(), TemplateArgs
);
1795 SemaRef
.BuildUsingDeclaration(/*Scope*/ 0, D
->getAccess(),
1796 D
->getUsingLoc(), SS
, NameInfo
, 0,
1797 /*instantiation*/ true,
1798 /*typename*/ false, SourceLocation());
1800 SemaRef
.Context
.setInstantiatedFromUsingDecl(cast
<UsingDecl
>(UD
), D
);
1805 Decl
*Sema::SubstDecl(Decl
*D
, DeclContext
*Owner
,
1806 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
1807 TemplateDeclInstantiator
Instantiator(*this, Owner
, TemplateArgs
);
1808 if (D
->isInvalidDecl())
1811 return Instantiator
.Visit(D
);
1814 /// \brief Instantiates a nested template parameter list in the current
1815 /// instantiation context.
1817 /// \param L The parameter list to instantiate
1819 /// \returns NULL if there was an error
1820 TemplateParameterList
*
1821 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList
*L
) {
1822 // Get errors for all the parameters before bailing out.
1823 bool Invalid
= false;
1825 unsigned N
= L
->size();
1826 typedef llvm::SmallVector
<NamedDecl
*, 8> ParamVector
;
1829 for (TemplateParameterList::iterator PI
= L
->begin(), PE
= L
->end();
1831 NamedDecl
*D
= cast_or_null
<NamedDecl
>(Visit(*PI
));
1832 Params
.push_back(D
);
1833 Invalid
= Invalid
|| !D
|| D
->isInvalidDecl();
1836 // Clean up if we had an error.
1840 TemplateParameterList
*InstL
1841 = TemplateParameterList::Create(SemaRef
.Context
, L
->getTemplateLoc(),
1842 L
->getLAngleLoc(), &Params
.front(), N
,
1847 /// \brief Instantiate the declaration of a class template partial
1850 /// \param ClassTemplate the (instantiated) class template that is partially
1851 // specialized by the instantiation of \p PartialSpec.
1853 /// \param PartialSpec the (uninstantiated) class template partial
1854 /// specialization that we are instantiating.
1856 /// \returns The instantiated partial specialization, if successful; otherwise,
1857 /// NULL to indicate an error.
1858 ClassTemplatePartialSpecializationDecl
*
1859 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1860 ClassTemplateDecl
*ClassTemplate
,
1861 ClassTemplatePartialSpecializationDecl
*PartialSpec
) {
1862 // Create a local instantiation scope for this class template partial
1863 // specialization, which will contain the instantiations of the template
1865 LocalInstantiationScope
Scope(SemaRef
);
1867 // Substitute into the template parameters of the class template partial
1869 TemplateParameterList
*TempParams
= PartialSpec
->getTemplateParameters();
1870 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
1874 // Substitute into the template arguments of the class template partial
1876 TemplateArgumentListInfo InstTemplateArgs
; // no angle locations
1877 if (SemaRef
.Subst(PartialSpec
->getTemplateArgsAsWritten(),
1878 PartialSpec
->getNumTemplateArgsAsWritten(),
1879 InstTemplateArgs
, TemplateArgs
))
1882 // Check that the template argument list is well-formed for this
1884 llvm::SmallVector
<TemplateArgument
, 4> Converted
;
1885 if (SemaRef
.CheckTemplateArgumentList(ClassTemplate
,
1886 PartialSpec
->getLocation(),
1892 // Figure out where to insert this class template partial specialization
1893 // in the member template's set of class template partial specializations.
1894 void *InsertPos
= 0;
1895 ClassTemplateSpecializationDecl
*PrevDecl
1896 = ClassTemplate
->findPartialSpecialization(Converted
.data(),
1897 Converted
.size(), InsertPos
);
1899 // Build the canonical type that describes the converted template
1900 // arguments of the class template partial specialization.
1902 = SemaRef
.Context
.getTemplateSpecializationType(TemplateName(ClassTemplate
),
1906 // Build the fully-sugared type for this class template
1907 // specialization as the user wrote in the specialization
1908 // itself. This means that we'll pretty-print the type retrieved
1909 // from the specialization's declaration the way that the user
1910 // actually wrote the specialization, rather than formatting the
1911 // name based on the "canonical" representation used to store the
1912 // template arguments in the specialization.
1913 TypeSourceInfo
*WrittenTy
1914 = SemaRef
.Context
.getTemplateSpecializationTypeInfo(
1915 TemplateName(ClassTemplate
),
1916 PartialSpec
->getLocation(),
1921 // We've already seen a partial specialization with the same template
1922 // parameters and template arguments. This can happen, for example, when
1923 // substituting the outer template arguments ends up causing two
1924 // class template partial specializations of a member class template
1925 // to have identical forms, e.g.,
1927 // template<typename T, typename U>
1929 // template<typename X, typename Y> struct Inner;
1930 // template<typename Y> struct Inner<T, Y>;
1931 // template<typename Y> struct Inner<U, Y>;
1934 // Outer<int, int> outer; // error: the partial specializations of Inner
1935 // // have the same signature.
1936 SemaRef
.Diag(PartialSpec
->getLocation(), diag::err_partial_spec_redeclared
)
1937 << WrittenTy
->getType();
1938 SemaRef
.Diag(PrevDecl
->getLocation(), diag::note_prev_partial_spec_here
)
1939 << SemaRef
.Context
.getTypeDeclType(PrevDecl
);
1944 // Create the class template partial specialization declaration.
1945 ClassTemplatePartialSpecializationDecl
*InstPartialSpec
1946 = ClassTemplatePartialSpecializationDecl::Create(SemaRef
.Context
,
1947 PartialSpec
->getTagKind(),
1949 PartialSpec
->getLocation(),
1957 ClassTemplate
->getNextPartialSpecSequenceNumber());
1958 // Substitute the nested name specifier, if any.
1959 if (SubstQualifier(PartialSpec
, InstPartialSpec
))
1962 InstPartialSpec
->setInstantiatedFromMember(PartialSpec
);
1963 InstPartialSpec
->setTypeAsWritten(WrittenTy
);
1965 // Add this partial specialization to the set of class template partial
1967 ClassTemplate
->AddPartialSpecialization(InstPartialSpec
, InsertPos
);
1968 return InstPartialSpec
;
1972 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl
*D
,
1973 llvm::SmallVectorImpl
<ParmVarDecl
*> &Params
) {
1974 TypeSourceInfo
*OldTInfo
= D
->getTypeSourceInfo();
1975 assert(OldTInfo
&& "substituting function without type source info");
1976 assert(Params
.empty() && "parameter vector is non-empty at start");
1977 TypeSourceInfo
*NewTInfo
1978 = SemaRef
.SubstFunctionDeclType(OldTInfo
, TemplateArgs
,
1979 D
->getTypeSpecStartLoc(),
1984 if (NewTInfo
!= OldTInfo
) {
1985 // Get parameters from the new type info.
1986 TypeLoc OldTL
= OldTInfo
->getTypeLoc().IgnoreParens();
1987 if (FunctionProtoTypeLoc
*OldProtoLoc
1988 = dyn_cast
<FunctionProtoTypeLoc
>(&OldTL
)) {
1989 TypeLoc NewTL
= NewTInfo
->getTypeLoc().IgnoreParens();
1990 FunctionProtoTypeLoc
*NewProtoLoc
= cast
<FunctionProtoTypeLoc
>(&NewTL
);
1991 assert(NewProtoLoc
&& "Missing prototype?");
1992 unsigned NewIdx
= 0, NumNewParams
= NewProtoLoc
->getNumArgs();
1993 for (unsigned OldIdx
= 0, NumOldParams
= OldProtoLoc
->getNumArgs();
1994 OldIdx
!= NumOldParams
; ++OldIdx
) {
1995 ParmVarDecl
*OldParam
= OldProtoLoc
->getArg(OldIdx
);
1996 if (!OldParam
->isParameterPack() ||
1997 (NewIdx
< NumNewParams
&&
1998 NewProtoLoc
->getArg(NewIdx
)->isParameterPack())) {
1999 // Simple case: normal parameter, or a parameter pack that's
2000 // instantiated to a (still-dependent) parameter pack.
2001 ParmVarDecl
*NewParam
= NewProtoLoc
->getArg(NewIdx
++);
2002 Params
.push_back(NewParam
);
2003 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(OldParam
,
2008 // Parameter pack: make the instantiation an argument pack.
2009 SemaRef
.CurrentInstantiationScope
->MakeInstantiatedLocalArgPack(
2011 unsigned NumArgumentsInExpansion
2012 = SemaRef
.getNumArgumentsInExpansion(OldParam
->getType(),
2014 while (NumArgumentsInExpansion
--) {
2015 ParmVarDecl
*NewParam
= NewProtoLoc
->getArg(NewIdx
++);
2016 Params
.push_back(NewParam
);
2017 SemaRef
.CurrentInstantiationScope
->InstantiatedLocalPackArg(OldParam
,
2023 // The function type itself was not dependent and therefore no
2024 // substitution occurred. However, we still need to instantiate
2025 // the function parameters themselves.
2026 TypeLoc OldTL
= OldTInfo
->getTypeLoc().IgnoreParens();
2027 if (FunctionProtoTypeLoc
*OldProtoLoc
2028 = dyn_cast
<FunctionProtoTypeLoc
>(&OldTL
)) {
2029 for (unsigned i
= 0, i_end
= OldProtoLoc
->getNumArgs(); i
!= i_end
; ++i
) {
2030 ParmVarDecl
*Parm
= VisitParmVarDecl(OldProtoLoc
->getArg(i
));
2033 Params
.push_back(Parm
);
2040 /// \brief Initializes the common fields of an instantiation function
2041 /// declaration (New) from the corresponding fields of its template (Tmpl).
2043 /// \returns true if there was an error
2045 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl
*New
,
2046 FunctionDecl
*Tmpl
) {
2047 if (Tmpl
->isDeleted())
2050 // If we are performing substituting explicitly-specified template arguments
2051 // or deduced template arguments into a function template and we reach this
2052 // point, we are now past the point where SFINAE applies and have committed
2053 // to keeping the new function template specialization. We therefore
2054 // convert the active template instantiation for the function template
2055 // into a template instantiation for this specific function template
2056 // specialization, which is not a SFINAE context, so that we diagnose any
2057 // further errors in the declaration itself.
2058 typedef Sema::ActiveTemplateInstantiation ActiveInstType
;
2059 ActiveInstType
&ActiveInst
= SemaRef
.ActiveTemplateInstantiations
.back();
2060 if (ActiveInst
.Kind
== ActiveInstType::ExplicitTemplateArgumentSubstitution
||
2061 ActiveInst
.Kind
== ActiveInstType::DeducedTemplateArgumentSubstitution
) {
2062 if (FunctionTemplateDecl
*FunTmpl
2063 = dyn_cast
<FunctionTemplateDecl
>((Decl
*)ActiveInst
.Entity
)) {
2064 assert(FunTmpl
->getTemplatedDecl() == Tmpl
&&
2065 "Deduction from the wrong function template?");
2067 ActiveInst
.Kind
= ActiveInstType::TemplateInstantiation
;
2068 ActiveInst
.Entity
= reinterpret_cast<uintptr_t>(New
);
2069 --SemaRef
.NonInstantiationEntries
;
2073 const FunctionProtoType
*Proto
= Tmpl
->getType()->getAs
<FunctionProtoType
>();
2074 assert(Proto
&& "Function template without prototype?");
2076 if (Proto
->hasExceptionSpec() || Proto
->hasAnyExceptionSpec() ||
2077 Proto
->getNoReturnAttr()) {
2078 // The function has an exception specification or a "noreturn"
2079 // attribute. Substitute into each of the exception types.
2080 llvm::SmallVector
<QualType
, 4> Exceptions
;
2081 for (unsigned I
= 0, N
= Proto
->getNumExceptions(); I
!= N
; ++I
) {
2082 // FIXME: Poor location information!
2083 if (const PackExpansionType
*PackExpansion
2084 = Proto
->getExceptionType(I
)->getAs
<PackExpansionType
>()) {
2085 // We have a pack expansion. Instantiate it.
2086 llvm::SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
2087 SemaRef
.collectUnexpandedParameterPacks(PackExpansion
->getPattern(),
2089 assert(!Unexpanded
.empty() &&
2090 "Pack expansion without parameter packs?");
2092 bool Expand
= false;
2093 bool RetainExpansion
= false;
2094 llvm::Optional
<unsigned> NumExpansions
2095 = PackExpansion
->getNumExpansions();
2096 if (SemaRef
.CheckParameterPacksForExpansion(New
->getLocation(),
2107 // We can't expand this pack expansion into separate arguments yet;
2108 // just substitute into the pattern and create a new pack expansion
2110 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, -1);
2111 QualType T
= SemaRef
.SubstType(PackExpansion
->getPattern(),
2113 New
->getLocation(), New
->getDeclName());
2117 T
= SemaRef
.Context
.getPackExpansionType(T
, NumExpansions
);
2118 Exceptions
.push_back(T
);
2122 // Substitute into the pack expansion pattern for each template
2123 bool Invalid
= false;
2124 for (unsigned ArgIdx
= 0; ArgIdx
!= *NumExpansions
; ++ArgIdx
) {
2125 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, ArgIdx
);
2127 QualType T
= SemaRef
.SubstType(PackExpansion
->getPattern(),
2129 New
->getLocation(), New
->getDeclName());
2135 Exceptions
.push_back(T
);
2145 = SemaRef
.SubstType(Proto
->getExceptionType(I
), TemplateArgs
,
2146 New
->getLocation(), New
->getDeclName());
2148 SemaRef
.CheckSpecifiedExceptionType(T
, New
->getLocation()))
2151 Exceptions
.push_back(T
);
2154 // Rebuild the function type
2156 FunctionProtoType::ExtProtoInfo EPI
= Proto
->getExtProtoInfo();
2157 EPI
.HasExceptionSpec
= Proto
->hasExceptionSpec();
2158 EPI
.HasAnyExceptionSpec
= Proto
->hasAnyExceptionSpec();
2159 EPI
.NumExceptions
= Exceptions
.size();
2160 EPI
.Exceptions
= Exceptions
.data();
2161 EPI
.ExtInfo
= Proto
->getExtInfo();
2163 const FunctionProtoType
*NewProto
2164 = New
->getType()->getAs
<FunctionProtoType
>();
2165 assert(NewProto
&& "Template instantiation without function prototype?");
2166 New
->setType(SemaRef
.Context
.getFunctionType(NewProto
->getResultType(),
2167 NewProto
->arg_type_begin(),
2168 NewProto
->getNumArgs(),
2172 SemaRef
.InstantiateAttrs(TemplateArgs
, Tmpl
, New
);
2177 /// \brief Initializes common fields of an instantiated method
2178 /// declaration (New) from the corresponding fields of its template
2181 /// \returns true if there was an error
2183 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl
*New
,
2184 CXXMethodDecl
*Tmpl
) {
2185 if (InitFunctionInstantiation(New
, Tmpl
))
2188 New
->setAccess(Tmpl
->getAccess());
2189 if (Tmpl
->isVirtualAsWritten())
2190 New
->setVirtualAsWritten(true);
2192 // FIXME: attributes
2193 // FIXME: New needs a pointer to Tmpl
2197 /// \brief Instantiate the definition of the given function from its
2200 /// \param PointOfInstantiation the point at which the instantiation was
2201 /// required. Note that this is not precisely a "point of instantiation"
2202 /// for the function, but it's close.
2204 /// \param Function the already-instantiated declaration of a
2205 /// function template specialization or member function of a class template
2208 /// \param Recursive if true, recursively instantiates any functions that
2209 /// are required by this instantiation.
2211 /// \param DefinitionRequired if true, then we are performing an explicit
2212 /// instantiation where the body of the function is required. Complain if
2213 /// there is no such body.
2214 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation
,
2215 FunctionDecl
*Function
,
2217 bool DefinitionRequired
) {
2218 if (Function
->isInvalidDecl() || Function
->hasBody())
2221 // Never instantiate an explicit specialization.
2222 if (Function
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
)
2225 // Find the function body that we'll be substituting.
2226 const FunctionDecl
*PatternDecl
= Function
->getTemplateInstantiationPattern();
2229 Pattern
= PatternDecl
->getBody(PatternDecl
);
2232 if (DefinitionRequired
) {
2233 if (Function
->getPrimaryTemplate())
2234 Diag(PointOfInstantiation
,
2235 diag::err_explicit_instantiation_undefined_func_template
)
2236 << Function
->getPrimaryTemplate();
2238 Diag(PointOfInstantiation
,
2239 diag::err_explicit_instantiation_undefined_member
)
2240 << 1 << Function
->getDeclName() << Function
->getDeclContext();
2243 Diag(PatternDecl
->getLocation(),
2244 diag::note_explicit_instantiation_here
);
2245 Function
->setInvalidDecl();
2246 } else if (Function
->getTemplateSpecializationKind()
2247 == TSK_ExplicitInstantiationDefinition
) {
2248 PendingInstantiations
.push_back(
2249 std::make_pair(Function
, PointOfInstantiation
));
2255 // C++0x [temp.explicit]p9:
2256 // Except for inline functions, other explicit instantiation declarations
2257 // have the effect of suppressing the implicit instantiation of the entity
2258 // to which they refer.
2259 if (Function
->getTemplateSpecializationKind()
2260 == TSK_ExplicitInstantiationDeclaration
&&
2261 !PatternDecl
->isInlined())
2264 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, Function
);
2268 // If we're performing recursive template instantiation, create our own
2269 // queue of pending implicit instantiations that we will instantiate later,
2270 // while we're still within our own instantiation context.
2271 llvm::SmallVector
<VTableUse
, 16> SavedVTableUses
;
2272 std::deque
<PendingImplicitInstantiation
> SavedPendingInstantiations
;
2274 VTableUses
.swap(SavedVTableUses
);
2275 PendingInstantiations
.swap(SavedPendingInstantiations
);
2278 EnterExpressionEvaluationContext
EvalContext(*this,
2279 Sema::PotentiallyEvaluated
);
2280 ActOnStartOfFunctionDef(0, Function
);
2282 // Introduce a new scope where local variable instantiations will be
2283 // recorded, unless we're actually a member function within a local
2284 // class, in which case we need to merge our results with the parent
2285 // scope (of the enclosing function).
2286 bool MergeWithParentScope
= false;
2287 if (CXXRecordDecl
*Rec
= dyn_cast
<CXXRecordDecl
>(Function
->getDeclContext()))
2288 MergeWithParentScope
= Rec
->isLocalClass();
2290 LocalInstantiationScope
Scope(*this, MergeWithParentScope
);
2292 // Introduce the instantiated function parameters into the local
2293 // instantiation scope, and set the parameter names to those used
2295 unsigned FParamIdx
= 0;
2296 for (unsigned I
= 0, N
= PatternDecl
->getNumParams(); I
!= N
; ++I
) {
2297 const ParmVarDecl
*PatternParam
= PatternDecl
->getParamDecl(I
);
2298 if (!PatternParam
->isParameterPack()) {
2299 // Simple case: not a parameter pack.
2300 assert(FParamIdx
< Function
->getNumParams());
2301 ParmVarDecl
*FunctionParam
= Function
->getParamDecl(I
);
2302 FunctionParam
->setDeclName(PatternParam
->getDeclName());
2303 Scope
.InstantiatedLocal(PatternParam
, FunctionParam
);
2308 // Expand the parameter pack.
2309 Scope
.MakeInstantiatedLocalArgPack(PatternParam
);
2310 for (unsigned NumFParams
= Function
->getNumParams();
2311 FParamIdx
< NumFParams
;
2313 ParmVarDecl
*FunctionParam
= Function
->getParamDecl(FParamIdx
);
2314 FunctionParam
->setDeclName(PatternParam
->getDeclName());
2315 Scope
.InstantiatedLocalPackArg(PatternParam
, FunctionParam
);
2319 // Enter the scope of this instantiation. We don't use
2320 // PushDeclContext because we don't have a scope.
2321 Sema::ContextRAII
savedContext(*this, Function
);
2323 MultiLevelTemplateArgumentList TemplateArgs
=
2324 getTemplateInstantiationArgs(Function
, 0, false, PatternDecl
);
2326 // If this is a constructor, instantiate the member initializers.
2327 if (const CXXConstructorDecl
*Ctor
=
2328 dyn_cast
<CXXConstructorDecl
>(PatternDecl
)) {
2329 InstantiateMemInitializers(cast
<CXXConstructorDecl
>(Function
), Ctor
,
2333 // Instantiate the function body.
2334 StmtResult Body
= SubstStmt(Pattern
, TemplateArgs
);
2336 if (Body
.isInvalid())
2337 Function
->setInvalidDecl();
2339 ActOnFinishFunctionBody(Function
, Body
.get(),
2340 /*IsInstantiation=*/true);
2342 PerformDependentDiagnostics(PatternDecl
, TemplateArgs
);
2346 DeclGroupRef
DG(Function
);
2347 Consumer
.HandleTopLevelDecl(DG
);
2349 // This class may have local implicit instantiations that need to be
2350 // instantiation within this scope.
2351 PerformPendingInstantiations(/*LocalOnly=*/true);
2355 // Define any pending vtables.
2356 DefineUsedVTables();
2358 // Instantiate any pending implicit instantiations found during the
2359 // instantiation of this template.
2360 PerformPendingInstantiations();
2362 // Restore the set of pending vtables.
2363 VTableUses
.swap(SavedVTableUses
);
2365 // Restore the set of pending implicit instantiations.
2366 PendingInstantiations
.swap(SavedPendingInstantiations
);
2370 /// \brief Instantiate the definition of the given variable from its
2373 /// \param PointOfInstantiation the point at which the instantiation was
2374 /// required. Note that this is not precisely a "point of instantiation"
2375 /// for the function, but it's close.
2377 /// \param Var the already-instantiated declaration of a static member
2378 /// variable of a class template specialization.
2380 /// \param Recursive if true, recursively instantiates any functions that
2381 /// are required by this instantiation.
2383 /// \param DefinitionRequired if true, then we are performing an explicit
2384 /// instantiation where an out-of-line definition of the member variable
2385 /// is required. Complain if there is no such definition.
2386 void Sema::InstantiateStaticDataMemberDefinition(
2387 SourceLocation PointOfInstantiation
,
2390 bool DefinitionRequired
) {
2391 if (Var
->isInvalidDecl())
2394 // Find the out-of-line definition of this static data member.
2395 VarDecl
*Def
= Var
->getInstantiatedFromStaticDataMember();
2396 assert(Def
&& "This data member was not instantiated from a template?");
2397 assert(Def
->isStaticDataMember() && "Not a static data member?");
2398 Def
= Def
->getOutOfLineDefinition();
2401 // We did not find an out-of-line definition of this static data member,
2402 // so we won't perform any instantiation. Rather, we rely on the user to
2403 // instantiate this definition (or provide a specialization for it) in
2404 // another translation unit.
2405 if (DefinitionRequired
) {
2406 Def
= Var
->getInstantiatedFromStaticDataMember();
2407 Diag(PointOfInstantiation
,
2408 diag::err_explicit_instantiation_undefined_member
)
2409 << 2 << Var
->getDeclName() << Var
->getDeclContext();
2410 Diag(Def
->getLocation(), diag::note_explicit_instantiation_here
);
2411 } else if (Var
->getTemplateSpecializationKind()
2412 == TSK_ExplicitInstantiationDefinition
) {
2413 PendingInstantiations
.push_back(
2414 std::make_pair(Var
, PointOfInstantiation
));
2420 // Never instantiate an explicit specialization.
2421 if (Var
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
)
2424 // C++0x [temp.explicit]p9:
2425 // Except for inline functions, other explicit instantiation declarations
2426 // have the effect of suppressing the implicit instantiation of the entity
2427 // to which they refer.
2428 if (Var
->getTemplateSpecializationKind()
2429 == TSK_ExplicitInstantiationDeclaration
)
2432 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, Var
);
2436 // If we're performing recursive template instantiation, create our own
2437 // queue of pending implicit instantiations that we will instantiate later,
2438 // while we're still within our own instantiation context.
2439 std::deque
<PendingImplicitInstantiation
> SavedPendingInstantiations
;
2441 PendingInstantiations
.swap(SavedPendingInstantiations
);
2443 // Enter the scope of this instantiation. We don't use
2444 // PushDeclContext because we don't have a scope.
2445 ContextRAII
previousContext(*this, Var
->getDeclContext());
2447 VarDecl
*OldVar
= Var
;
2448 Var
= cast_or_null
<VarDecl
>(SubstDecl(Def
, Var
->getDeclContext(),
2449 getTemplateInstantiationArgs(Var
)));
2451 previousContext
.pop();
2454 MemberSpecializationInfo
*MSInfo
= OldVar
->getMemberSpecializationInfo();
2455 assert(MSInfo
&& "Missing member specialization information?");
2456 Var
->setTemplateSpecializationKind(MSInfo
->getTemplateSpecializationKind(),
2457 MSInfo
->getPointOfInstantiation());
2458 DeclGroupRef
DG(Var
);
2459 Consumer
.HandleTopLevelDecl(DG
);
2463 // Instantiate any pending implicit instantiations found during the
2464 // instantiation of this template.
2465 PerformPendingInstantiations();
2467 // Restore the set of pending implicit instantiations.
2468 PendingInstantiations
.swap(SavedPendingInstantiations
);
2473 Sema::InstantiateMemInitializers(CXXConstructorDecl
*New
,
2474 const CXXConstructorDecl
*Tmpl
,
2475 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
2477 llvm::SmallVector
<MemInitTy
*, 4> NewInits
;
2478 bool AnyErrors
= false;
2480 // Instantiate all the initializers.
2481 for (CXXConstructorDecl::init_const_iterator Inits
= Tmpl
->init_begin(),
2482 InitsEnd
= Tmpl
->init_end();
2483 Inits
!= InitsEnd
; ++Inits
) {
2484 CXXCtorInitializer
*Init
= *Inits
;
2486 // Only instantiate written initializers, let Sema re-construct implicit
2488 if (!Init
->isWritten())
2491 SourceLocation LParenLoc
, RParenLoc
;
2492 ASTOwningVector
<Expr
*> NewArgs(*this);
2494 SourceLocation EllipsisLoc
;
2496 if (Init
->isPackExpansion()) {
2497 // This is a pack expansion. We should expand it now.
2498 TypeLoc BaseTL
= Init
->getBaseClassInfo()->getTypeLoc();
2499 llvm::SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
2500 collectUnexpandedParameterPacks(BaseTL
, Unexpanded
);
2501 bool ShouldExpand
= false;
2502 bool RetainExpansion
= false;
2503 llvm::Optional
<unsigned> NumExpansions
;
2504 if (CheckParameterPacksForExpansion(Init
->getEllipsisLoc(),
2505 BaseTL
.getSourceRange(),
2508 TemplateArgs
, ShouldExpand
,
2512 New
->setInvalidDecl();
2515 assert(ShouldExpand
&& "Partial instantiation of base initializer?");
2517 // Loop over all of the arguments in the argument pack(s),
2518 for (unsigned I
= 0; I
!= *NumExpansions
; ++I
) {
2519 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(*this, I
);
2521 // Instantiate the initializer.
2522 if (InstantiateInitializer(*this, Init
->getInit(), TemplateArgs
,
2523 LParenLoc
, NewArgs
, RParenLoc
)) {
2528 // Instantiate the base type.
2529 TypeSourceInfo
*BaseTInfo
= SubstType(Init
->getBaseClassInfo(),
2531 Init
->getSourceLocation(),
2532 New
->getDeclName());
2538 // Build the initializer.
2539 MemInitResult NewInit
= BuildBaseInitializer(BaseTInfo
->getType(),
2541 (Expr
**)NewArgs
.data(),
2543 Init
->getLParenLoc(),
2544 Init
->getRParenLoc(),
2547 if (NewInit
.isInvalid()) {
2552 NewInits
.push_back(NewInit
.get());
2559 // Instantiate the initializer.
2560 if (InstantiateInitializer(*this, Init
->getInit(), TemplateArgs
,
2561 LParenLoc
, NewArgs
, RParenLoc
)) {
2566 MemInitResult NewInit
;
2567 if (Init
->isBaseInitializer()) {
2568 TypeSourceInfo
*BaseTInfo
= SubstType(Init
->getBaseClassInfo(),
2570 Init
->getSourceLocation(),
2571 New
->getDeclName());
2574 New
->setInvalidDecl();
2578 NewInit
= BuildBaseInitializer(BaseTInfo
->getType(), BaseTInfo
,
2579 (Expr
**)NewArgs
.data(),
2581 Init
->getLParenLoc(),
2582 Init
->getRParenLoc(),
2585 } else if (Init
->isMemberInitializer()) {
2586 FieldDecl
*Member
= cast
<FieldDecl
>(FindInstantiatedDecl(
2587 Init
->getMemberLocation(),
2591 NewInit
= BuildMemberInitializer(Member
, (Expr
**)NewArgs
.data(),
2593 Init
->getSourceLocation(),
2594 Init
->getLParenLoc(),
2595 Init
->getRParenLoc());
2596 } else if (Init
->isIndirectMemberInitializer()) {
2597 IndirectFieldDecl
*IndirectMember
=
2598 cast
<IndirectFieldDecl
>(FindInstantiatedDecl(
2599 Init
->getMemberLocation(),
2600 Init
->getIndirectMember(), TemplateArgs
));
2602 NewInit
= BuildMemberInitializer(IndirectMember
, (Expr
**)NewArgs
.data(),
2604 Init
->getSourceLocation(),
2605 Init
->getLParenLoc(),
2606 Init
->getRParenLoc());
2609 if (NewInit
.isInvalid()) {
2611 New
->setInvalidDecl();
2613 // FIXME: It would be nice if ASTOwningVector had a release function.
2616 NewInits
.push_back((MemInitTy
*)NewInit
.get());
2620 // Assign all the initializers to the new constructor.
2621 ActOnMemInitializers(New
,
2622 /*FIXME: ColonLoc */
2624 NewInits
.data(), NewInits
.size(),
2628 // TODO: this could be templated if the various decl types used the
2629 // same method name.
2630 static bool isInstantiationOf(ClassTemplateDecl
*Pattern
,
2631 ClassTemplateDecl
*Instance
) {
2632 Pattern
= Pattern
->getCanonicalDecl();
2635 Instance
= Instance
->getCanonicalDecl();
2636 if (Pattern
== Instance
) return true;
2637 Instance
= Instance
->getInstantiatedFromMemberTemplate();
2643 static bool isInstantiationOf(FunctionTemplateDecl
*Pattern
,
2644 FunctionTemplateDecl
*Instance
) {
2645 Pattern
= Pattern
->getCanonicalDecl();
2648 Instance
= Instance
->getCanonicalDecl();
2649 if (Pattern
== Instance
) return true;
2650 Instance
= Instance
->getInstantiatedFromMemberTemplate();
2657 isInstantiationOf(ClassTemplatePartialSpecializationDecl
*Pattern
,
2658 ClassTemplatePartialSpecializationDecl
*Instance
) {
2660 = cast
<ClassTemplatePartialSpecializationDecl
>(Pattern
->getCanonicalDecl());
2662 Instance
= cast
<ClassTemplatePartialSpecializationDecl
>(
2663 Instance
->getCanonicalDecl());
2664 if (Pattern
== Instance
)
2666 Instance
= Instance
->getInstantiatedFromMember();
2672 static bool isInstantiationOf(CXXRecordDecl
*Pattern
,
2673 CXXRecordDecl
*Instance
) {
2674 Pattern
= Pattern
->getCanonicalDecl();
2677 Instance
= Instance
->getCanonicalDecl();
2678 if (Pattern
== Instance
) return true;
2679 Instance
= Instance
->getInstantiatedFromMemberClass();
2685 static bool isInstantiationOf(FunctionDecl
*Pattern
,
2686 FunctionDecl
*Instance
) {
2687 Pattern
= Pattern
->getCanonicalDecl();
2690 Instance
= Instance
->getCanonicalDecl();
2691 if (Pattern
== Instance
) return true;
2692 Instance
= Instance
->getInstantiatedFromMemberFunction();
2698 static bool isInstantiationOf(EnumDecl
*Pattern
,
2699 EnumDecl
*Instance
) {
2700 Pattern
= Pattern
->getCanonicalDecl();
2703 Instance
= Instance
->getCanonicalDecl();
2704 if (Pattern
== Instance
) return true;
2705 Instance
= Instance
->getInstantiatedFromMemberEnum();
2711 static bool isInstantiationOf(UsingShadowDecl
*Pattern
,
2712 UsingShadowDecl
*Instance
,
2714 return C
.getInstantiatedFromUsingShadowDecl(Instance
) == Pattern
;
2717 static bool isInstantiationOf(UsingDecl
*Pattern
,
2718 UsingDecl
*Instance
,
2720 return C
.getInstantiatedFromUsingDecl(Instance
) == Pattern
;
2723 static bool isInstantiationOf(UnresolvedUsingValueDecl
*Pattern
,
2724 UsingDecl
*Instance
,
2726 return C
.getInstantiatedFromUsingDecl(Instance
) == Pattern
;
2729 static bool isInstantiationOf(UnresolvedUsingTypenameDecl
*Pattern
,
2730 UsingDecl
*Instance
,
2732 return C
.getInstantiatedFromUsingDecl(Instance
) == Pattern
;
2735 static bool isInstantiationOfStaticDataMember(VarDecl
*Pattern
,
2736 VarDecl
*Instance
) {
2737 assert(Instance
->isStaticDataMember());
2739 Pattern
= Pattern
->getCanonicalDecl();
2742 Instance
= Instance
->getCanonicalDecl();
2743 if (Pattern
== Instance
) return true;
2744 Instance
= Instance
->getInstantiatedFromStaticDataMember();
2750 // Other is the prospective instantiation
2751 // D is the prospective pattern
2752 static bool isInstantiationOf(ASTContext
&Ctx
, NamedDecl
*D
, Decl
*Other
) {
2753 if (D
->getKind() != Other
->getKind()) {
2754 if (UnresolvedUsingTypenameDecl
*UUD
2755 = dyn_cast
<UnresolvedUsingTypenameDecl
>(D
)) {
2756 if (UsingDecl
*UD
= dyn_cast
<UsingDecl
>(Other
)) {
2757 return isInstantiationOf(UUD
, UD
, Ctx
);
2761 if (UnresolvedUsingValueDecl
*UUD
2762 = dyn_cast
<UnresolvedUsingValueDecl
>(D
)) {
2763 if (UsingDecl
*UD
= dyn_cast
<UsingDecl
>(Other
)) {
2764 return isInstantiationOf(UUD
, UD
, Ctx
);
2771 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(Other
))
2772 return isInstantiationOf(cast
<CXXRecordDecl
>(D
), Record
);
2774 if (FunctionDecl
*Function
= dyn_cast
<FunctionDecl
>(Other
))
2775 return isInstantiationOf(cast
<FunctionDecl
>(D
), Function
);
2777 if (EnumDecl
*Enum
= dyn_cast
<EnumDecl
>(Other
))
2778 return isInstantiationOf(cast
<EnumDecl
>(D
), Enum
);
2780 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(Other
))
2781 if (Var
->isStaticDataMember())
2782 return isInstantiationOfStaticDataMember(cast
<VarDecl
>(D
), Var
);
2784 if (ClassTemplateDecl
*Temp
= dyn_cast
<ClassTemplateDecl
>(Other
))
2785 return isInstantiationOf(cast
<ClassTemplateDecl
>(D
), Temp
);
2787 if (FunctionTemplateDecl
*Temp
= dyn_cast
<FunctionTemplateDecl
>(Other
))
2788 return isInstantiationOf(cast
<FunctionTemplateDecl
>(D
), Temp
);
2790 if (ClassTemplatePartialSpecializationDecl
*PartialSpec
2791 = dyn_cast
<ClassTemplatePartialSpecializationDecl
>(Other
))
2792 return isInstantiationOf(cast
<ClassTemplatePartialSpecializationDecl
>(D
),
2795 if (FieldDecl
*Field
= dyn_cast
<FieldDecl
>(Other
)) {
2796 if (!Field
->getDeclName()) {
2797 // This is an unnamed field.
2798 return Ctx
.getInstantiatedFromUnnamedFieldDecl(Field
) ==
2803 if (UsingDecl
*Using
= dyn_cast
<UsingDecl
>(Other
))
2804 return isInstantiationOf(cast
<UsingDecl
>(D
), Using
, Ctx
);
2806 if (UsingShadowDecl
*Shadow
= dyn_cast
<UsingShadowDecl
>(Other
))
2807 return isInstantiationOf(cast
<UsingShadowDecl
>(D
), Shadow
, Ctx
);
2809 return D
->getDeclName() && isa
<NamedDecl
>(Other
) &&
2810 D
->getDeclName() == cast
<NamedDecl
>(Other
)->getDeclName();
2813 template<typename ForwardIterator
>
2814 static NamedDecl
*findInstantiationOf(ASTContext
&Ctx
,
2816 ForwardIterator first
,
2817 ForwardIterator last
) {
2818 for (; first
!= last
; ++first
)
2819 if (isInstantiationOf(Ctx
, D
, *first
))
2820 return cast
<NamedDecl
>(*first
);
2825 /// \brief Finds the instantiation of the given declaration context
2826 /// within the current instantiation.
2828 /// \returns NULL if there was an error
2829 DeclContext
*Sema::FindInstantiatedContext(SourceLocation Loc
, DeclContext
* DC
,
2830 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
2831 if (NamedDecl
*D
= dyn_cast
<NamedDecl
>(DC
)) {
2832 Decl
* ID
= FindInstantiatedDecl(Loc
, D
, TemplateArgs
);
2833 return cast_or_null
<DeclContext
>(ID
);
2837 /// \brief Find the instantiation of the given declaration within the
2838 /// current instantiation.
2840 /// This routine is intended to be used when \p D is a declaration
2841 /// referenced from within a template, that needs to mapped into the
2842 /// corresponding declaration within an instantiation. For example,
2846 /// template<typename T>
2849 /// KnownValue = sizeof(T)
2852 /// bool getKind() const { return KnownValue; }
2855 /// template struct X<int>;
2858 /// In the instantiation of X<int>::getKind(), we need to map the
2859 /// EnumConstantDecl for KnownValue (which refers to
2860 /// X<T>::<Kind>::KnownValue) to its instantiation
2861 /// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2862 /// this mapping from within the instantiation of X<int>.
2863 NamedDecl
*Sema::FindInstantiatedDecl(SourceLocation Loc
, NamedDecl
*D
,
2864 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
2865 DeclContext
*ParentDC
= D
->getDeclContext();
2866 if (isa
<ParmVarDecl
>(D
) || isa
<NonTypeTemplateParmDecl
>(D
) ||
2867 isa
<TemplateTypeParmDecl
>(D
) || isa
<TemplateTemplateParmDecl
>(D
) ||
2868 (ParentDC
->isFunctionOrMethod() && ParentDC
->isDependentContext())) {
2869 // D is a local of some kind. Look into the map of local
2870 // declarations to their instantiations.
2871 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack
;
2872 llvm::PointerUnion
<Decl
*, DeclArgumentPack
*> *Found
2873 = CurrentInstantiationScope
->findInstantiationOf(D
);
2876 if (Decl
*FD
= Found
->dyn_cast
<Decl
*>())
2877 return cast
<NamedDecl
>(FD
);
2879 unsigned PackIdx
= ArgumentPackSubstitutionIndex
;
2880 return cast
<NamedDecl
>((*Found
->get
<DeclArgumentPack
*>())[PackIdx
]);
2883 // If we didn't find the decl, then we must have a label decl that hasn't
2884 // been found yet. Lazily instantiate it and return it now.
2885 assert(isa
<LabelDecl
>(D
));
2887 Decl
*Inst
= SubstDecl(D
, CurContext
, TemplateArgs
);
2888 assert(Inst
&& "Failed to instantiate label??");
2890 CurrentInstantiationScope
->InstantiatedLocal(D
, Inst
);
2891 return cast
<LabelDecl
>(Inst
);
2894 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(D
)) {
2895 if (!Record
->isDependentContext())
2898 // If the RecordDecl is actually the injected-class-name or a
2899 // "templated" declaration for a class template, class template
2900 // partial specialization, or a member class of a class template,
2901 // substitute into the injected-class-name of the class template
2902 // or partial specialization to find the new DeclContext.
2904 ClassTemplateDecl
*ClassTemplate
= Record
->getDescribedClassTemplate();
2906 if (ClassTemplate
) {
2907 T
= ClassTemplate
->getInjectedClassNameSpecialization();
2908 } else if (ClassTemplatePartialSpecializationDecl
*PartialSpec
2909 = dyn_cast
<ClassTemplatePartialSpecializationDecl
>(Record
)) {
2910 ClassTemplate
= PartialSpec
->getSpecializedTemplate();
2912 // If we call SubstType with an InjectedClassNameType here we
2913 // can end up in an infinite loop.
2914 T
= Context
.getTypeDeclType(Record
);
2915 assert(isa
<InjectedClassNameType
>(T
) &&
2916 "type of partial specialization is not an InjectedClassNameType");
2917 T
= cast
<InjectedClassNameType
>(T
)->getInjectedSpecializationType();
2921 // Substitute into the injected-class-name to get the type
2922 // corresponding to the instantiation we want, which may also be
2923 // the current instantiation (if we're in a template
2924 // definition). This substitution should never fail, since we
2925 // know we can instantiate the injected-class-name or we
2926 // wouldn't have gotten to the injected-class-name!
2928 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2929 // extra instantiation in the common case?
2930 T
= SubstType(T
, TemplateArgs
, SourceLocation(), DeclarationName());
2931 assert(!T
.isNull() && "Instantiation of injected-class-name cannot fail.");
2933 if (!T
->isDependentType()) {
2934 assert(T
->isRecordType() && "Instantiation must produce a record type");
2935 return T
->getAs
<RecordType
>()->getDecl();
2938 // We are performing "partial" template instantiation to create
2939 // the member declarations for the members of a class template
2940 // specialization. Therefore, D is actually referring to something
2941 // in the current instantiation. Look through the current
2942 // context, which contains actual instantiations, to find the
2943 // instantiation of the "current instantiation" that D refers
2945 bool SawNonDependentContext
= false;
2946 for (DeclContext
*DC
= CurContext
; !DC
->isFileContext();
2947 DC
= DC
->getParent()) {
2948 if (ClassTemplateSpecializationDecl
*Spec
2949 = dyn_cast
<ClassTemplateSpecializationDecl
>(DC
))
2950 if (isInstantiationOf(ClassTemplate
,
2951 Spec
->getSpecializedTemplate()))
2954 if (!DC
->isDependentContext())
2955 SawNonDependentContext
= true;
2958 // We're performing "instantiation" of a member of the current
2959 // instantiation while we are type-checking the
2960 // definition. Compute the declaration context and return that.
2961 assert(!SawNonDependentContext
&&
2962 "No dependent context while instantiating record");
2963 DeclContext
*DC
= computeDeclContext(T
);
2965 "Unable to find declaration for the current instantiation");
2966 return cast
<CXXRecordDecl
>(DC
);
2969 // Fall through to deal with other dependent record types (e.g.,
2970 // anonymous unions in class templates).
2973 if (!ParentDC
->isDependentContext())
2976 ParentDC
= FindInstantiatedContext(Loc
, ParentDC
, TemplateArgs
);
2980 if (ParentDC
!= D
->getDeclContext()) {
2981 // We performed some kind of instantiation in the parent context,
2982 // so now we need to look into the instantiated parent context to
2983 // find the instantiation of the declaration D.
2985 // If our context used to be dependent, we may need to instantiate
2986 // it before performing lookup into that context.
2987 if (CXXRecordDecl
*Spec
= dyn_cast
<CXXRecordDecl
>(ParentDC
)) {
2988 if (!Spec
->isDependentContext()) {
2989 QualType T
= Context
.getTypeDeclType(Spec
);
2990 const RecordType
*Tag
= T
->getAs
<RecordType
>();
2991 assert(Tag
&& "type of non-dependent record is not a RecordType");
2992 if (!Tag
->isBeingDefined() &&
2993 RequireCompleteType(Loc
, T
, diag::err_incomplete_type
))
2996 ParentDC
= Tag
->getDecl();
3000 NamedDecl
*Result
= 0;
3001 if (D
->getDeclName()) {
3002 DeclContext::lookup_result Found
= ParentDC
->lookup(D
->getDeclName());
3003 Result
= findInstantiationOf(Context
, D
, Found
.first
, Found
.second
);
3005 // Since we don't have a name for the entity we're looking for,
3006 // our only option is to walk through all of the declarations to
3007 // find that name. This will occur in a few cases:
3009 // - anonymous struct/union within a template
3010 // - unnamed class/struct/union/enum within a template
3012 // FIXME: Find a better way to find these instantiations!
3013 Result
= findInstantiationOf(Context
, D
,
3014 ParentDC
->decls_begin(),
3015 ParentDC
->decls_end());
3018 // UsingShadowDecls can instantiate to nothing because of using hiding.
3019 assert((Result
|| isa
<UsingShadowDecl
>(D
) || D
->isInvalidDecl() ||
3020 cast
<Decl
>(ParentDC
)->isInvalidDecl())
3021 && "Unable to find instantiation of declaration!");
3029 /// \brief Performs template instantiation for all implicit template
3030 /// instantiations we have seen until this point.
3031 void Sema::PerformPendingInstantiations(bool LocalOnly
) {
3032 while (!PendingLocalImplicitInstantiations
.empty() ||
3033 (!LocalOnly
&& !PendingInstantiations
.empty())) {
3034 PendingImplicitInstantiation Inst
;
3036 if (PendingLocalImplicitInstantiations
.empty()) {
3037 Inst
= PendingInstantiations
.front();
3038 PendingInstantiations
.pop_front();
3040 Inst
= PendingLocalImplicitInstantiations
.front();
3041 PendingLocalImplicitInstantiations
.pop_front();
3044 // Instantiate function definitions
3045 if (FunctionDecl
*Function
= dyn_cast
<FunctionDecl
>(Inst
.first
)) {
3046 PrettyDeclStackTraceEntry
CrashInfo(*this, Function
, SourceLocation(),
3047 "instantiating function definition");
3048 bool DefinitionRequired
= Function
->getTemplateSpecializationKind() ==
3049 TSK_ExplicitInstantiationDefinition
;
3050 InstantiateFunctionDefinition(/*FIXME:*/Inst
.second
, Function
, true,
3051 DefinitionRequired
);
3055 // Instantiate static data member definitions.
3056 VarDecl
*Var
= cast
<VarDecl
>(Inst
.first
);
3057 assert(Var
->isStaticDataMember() && "Not a static data member?");
3059 // Don't try to instantiate declarations if the most recent redeclaration
3061 if (Var
->getMostRecentDeclaration()->isInvalidDecl())
3064 // Check if the most recent declaration has changed the specialization kind
3065 // and removed the need for implicit instantiation.
3066 switch (Var
->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
3067 case TSK_Undeclared
:
3068 assert(false && "Cannot instantitiate an undeclared specialization.");
3069 case TSK_ExplicitInstantiationDeclaration
:
3070 case TSK_ExplicitSpecialization
:
3071 continue; // No longer need to instantiate this type.
3072 case TSK_ExplicitInstantiationDefinition
:
3073 // We only need an instantiation if the pending instantiation *is* the
3074 // explicit instantiation.
3075 if (Var
!= Var
->getMostRecentDeclaration()) continue;
3076 case TSK_ImplicitInstantiation
:
3080 PrettyDeclStackTraceEntry
CrashInfo(*this, Var
, Var
->getLocation(),
3081 "instantiating static data member "
3084 bool DefinitionRequired
= Var
->getTemplateSpecializationKind() ==
3085 TSK_ExplicitInstantiationDefinition
;
3086 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst
.second
, Var
, true,
3087 DefinitionRequired
);
3091 void Sema::PerformDependentDiagnostics(const DeclContext
*Pattern
,
3092 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
3093 for (DeclContext::ddiag_iterator I
= Pattern
->ddiag_begin(),
3094 E
= Pattern
->ddiag_end(); I
!= E
; ++I
) {
3095 DependentDiagnostic
*DD
= *I
;
3097 switch (DD
->getKind()) {
3098 case DependentDiagnostic::Access
:
3099 HandleDependentAccessCheck(*DD
, TemplateArgs
);