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/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/DeclVisitor.h"
17 #include "clang/AST/DependentDiagnostic.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/TypeLoc.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/Sema/Lookup.h"
23 #include "clang/Sema/PrettyDeclStackTrace.h"
24 #include "clang/Sema/Template.h"
26 using namespace clang;
28 static bool isDeclWithinFunction(const Decl *D) {
29 const DeclContext *DC = D->getDeclContext();
30 if (DC->isFunctionOrMethod())
34 return cast<CXXRecordDecl>(DC)->isLocalClass();
39 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
40 DeclaratorDecl *NewDecl) {
41 if (!OldDecl->getQualifierLoc())
44 NestedNameSpecifierLoc NewQualifierLoc
45 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
51 NewDecl->setQualifierInfo(NewQualifierLoc);
55 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
57 if (!OldDecl->getQualifierLoc())
60 NestedNameSpecifierLoc NewQualifierLoc
61 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
67 NewDecl->setQualifierInfo(NewQualifierLoc);
71 // Include attribute instantiation code.
72 #include "clang/Sema/AttrTemplateInstantiate.inc"
74 static void instantiateDependentAlignedAttr(
75 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
76 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
77 if (Aligned->isAlignmentExpr()) {
78 // The alignment expression is a constant expression.
79 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
80 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
81 if (!Result.isInvalid())
82 S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
83 Aligned->getSpellingListIndex(), IsPackExpansion);
85 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
86 TemplateArgs, Aligned->getLocation(),
89 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
90 Aligned->getSpellingListIndex(), IsPackExpansion);
94 static void instantiateDependentAlignedAttr(
95 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
96 const AlignedAttr *Aligned, Decl *New) {
97 if (!Aligned->isPackExpansion()) {
98 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
102 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
103 if (Aligned->isAlignmentExpr())
104 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
107 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
109 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
111 // Determine whether we can expand this attribute pack yet.
112 bool Expand = true, RetainExpansion = false;
113 Optional<unsigned> NumExpansions;
114 // FIXME: Use the actual location of the ellipsis.
115 SourceLocation EllipsisLoc = Aligned->getLocation();
116 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
117 Unexpanded, TemplateArgs, Expand,
118 RetainExpansion, NumExpansions))
122 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
123 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
125 for (unsigned I = 0; I != *NumExpansions; ++I) {
126 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
127 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
132 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
133 const Decl *Tmpl, Decl *New,
134 LateInstantiatedAttrVec *LateAttrs,
135 LocalInstantiationScope *OuterMostScope) {
136 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
138 const Attr *TmplAttr = *i;
140 // FIXME: This should be generalized to more than just the AlignedAttr.
141 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
142 if (Aligned && Aligned->isAlignmentDependent()) {
143 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
147 assert(!TmplAttr->isPackExpansion());
148 if (TmplAttr->isLateParsed() && LateAttrs) {
149 // Late parsed attributes must be instantiated and attached after the
150 // enclosing class has been instantiated. See Sema::InstantiateClass.
151 LocalInstantiationScope *Saved = 0;
152 if (CurrentInstantiationScope)
153 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
154 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
156 // Allow 'this' within late-parsed attributes.
157 NamedDecl *ND = dyn_cast<NamedDecl>(New);
158 CXXRecordDecl *ThisContext =
159 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
160 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
161 ND && ND->isCXXInstanceMember());
163 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
164 *this, TemplateArgs);
166 New->addAttr(NewAttr);
172 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
173 llvm_unreachable("Translation units cannot be instantiated");
177 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
178 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
180 Owner->addDecl(Inst);
185 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
186 llvm_unreachable("Namespaces cannot be instantiated");
190 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
191 NamespaceAliasDecl *Inst
192 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
193 D->getNamespaceLoc(),
196 D->getQualifierLoc(),
197 D->getTargetNameLoc(),
199 Owner->addDecl(Inst);
203 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
205 bool Invalid = false;
206 TypeSourceInfo *DI = D->getTypeSourceInfo();
207 if (DI->getType()->isInstantiationDependentType() ||
208 DI->getType()->isVariablyModifiedType()) {
209 DI = SemaRef.SubstType(DI, TemplateArgs,
210 D->getLocation(), D->getDeclName());
213 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
216 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
219 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
220 // libstdc++ relies upon this bug in its implementation of common_type.
221 // If we happen to be processing that implementation, fake up the g++ ?:
222 // semantics. See LWG issue 2141 for more information on the bug.
223 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
224 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
225 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
226 DT->isReferenceType() &&
227 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
228 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
229 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
230 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
231 // Fold it to the (non-reference) type which g++ would have produced.
232 DI = SemaRef.Context.getTrivialTypeSourceInfo(
233 DI->getType().getNonReferenceType());
235 // Create the new typedef
236 TypedefNameDecl *Typedef;
238 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
239 D->getLocation(), D->getIdentifier(), DI);
241 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
242 D->getLocation(), D->getIdentifier(), DI);
244 Typedef->setInvalidDecl();
246 // If the old typedef was the name for linkage purposes of an anonymous
247 // tag decl, re-establish that relationship for the new typedef.
248 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
249 TagDecl *oldTag = oldTagType->getDecl();
250 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
251 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
252 assert(!newTag->hasNameForLinkage());
253 newTag->setTypedefNameForAnonDecl(Typedef);
257 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
258 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
263 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
265 // If the typedef types are not identical, reject them.
266 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
268 Typedef->setPreviousDecl(InstPrevTypedef);
271 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
273 Typedef->setAccess(D->getAccess());
278 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
279 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
280 Owner->addDecl(Typedef);
284 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
285 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
286 Owner->addDecl(Typedef);
291 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
292 // Create a local instantiation scope for this type alias template, which
293 // will contain the instantiations of the template parameters.
294 LocalInstantiationScope Scope(SemaRef);
296 TemplateParameterList *TempParams = D->getTemplateParameters();
297 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
301 TypeAliasDecl *Pattern = D->getTemplatedDecl();
303 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
304 if (Pattern->getPreviousDecl()) {
305 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
306 if (!Found.empty()) {
307 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
311 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
312 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
316 TypeAliasTemplateDecl *Inst
317 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
318 D->getDeclName(), InstParams, AliasInst);
319 if (PrevAliasTemplate)
320 Inst->setPreviousDecl(PrevAliasTemplate);
322 Inst->setAccess(D->getAccess());
324 if (!PrevAliasTemplate)
325 Inst->setInstantiatedFromMemberTemplate(D);
327 Owner->addDecl(Inst);
332 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
333 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
336 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
337 bool InstantiatingVarTemplate) {
339 // If this is the variable for an anonymous struct or union,
340 // instantiate the anonymous struct/union type first.
341 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
342 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
343 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
346 // Do substitution on the type of the declaration
347 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
349 D->getTypeSpecStartLoc(),
354 if (DI->getType()->isFunctionType()) {
355 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
356 << D->isStaticDataMember() << DI->getType();
360 DeclContext *DC = Owner;
361 if (D->isLocalExternDecl())
362 SemaRef.adjustContextForLocalExternDecl(DC);
364 // Build the instantiated declaration.
365 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
366 D->getLocation(), D->getIdentifier(),
367 DI->getType(), DI, D->getStorageClass());
369 // In ARC, infer 'retaining' for variables of retainable type.
370 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
371 SemaRef.inferObjCARCLifetime(Var))
372 Var->setInvalidDecl();
374 // Substitute the nested name specifier, if any.
375 if (SubstQualifier(D, Var))
378 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
379 StartingScope, InstantiatingVarTemplate);
383 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
385 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
386 D->getAccessSpecifierLoc(), D->getColonLoc());
387 Owner->addHiddenDecl(AD);
391 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
392 bool Invalid = false;
393 TypeSourceInfo *DI = D->getTypeSourceInfo();
394 if (DI->getType()->isInstantiationDependentType() ||
395 DI->getType()->isVariablyModifiedType()) {
396 DI = SemaRef.SubstType(DI, TemplateArgs,
397 D->getLocation(), D->getDeclName());
399 DI = D->getTypeSourceInfo();
401 } else if (DI->getType()->isFunctionType()) {
402 // C++ [temp.arg.type]p3:
403 // If a declaration acquires a function type through a type
404 // dependent on a template-parameter and this causes a
405 // declaration that does not use the syntactic form of a
406 // function declarator to have function type, the program is
408 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
413 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
416 Expr *BitWidth = D->getBitWidth();
420 // The bit-width expression is a constant expression.
421 EnterExpressionEvaluationContext Unevaluated(SemaRef,
422 Sema::ConstantEvaluated);
424 ExprResult InstantiatedBitWidth
425 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
426 if (InstantiatedBitWidth.isInvalid()) {
430 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
433 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
435 cast<RecordDecl>(Owner),
439 D->getInClassInitStyle(),
440 D->getInnerLocStart(),
444 cast<Decl>(Owner)->setInvalidDecl();
448 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
450 if (Field->hasAttrs())
451 SemaRef.CheckAlignasUnderalignment(Field);
454 Field->setInvalidDecl();
456 if (!Field->getDeclName()) {
457 // Keep track of where this decl came from.
458 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
460 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
461 if (Parent->isAnonymousStructOrUnion() &&
462 Parent->getRedeclContext()->isFunctionOrMethod())
463 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
466 Field->setImplicit(D->isImplicit());
467 Field->setAccess(D->getAccess());
468 Owner->addDecl(Field);
473 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
474 bool Invalid = false;
475 TypeSourceInfo *DI = D->getTypeSourceInfo();
477 if (DI->getType()->isVariablyModifiedType()) {
478 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
481 } else if (DI->getType()->isInstantiationDependentType()) {
482 DI = SemaRef.SubstType(DI, TemplateArgs,
483 D->getLocation(), D->getDeclName());
485 DI = D->getTypeSourceInfo();
487 } else if (DI->getType()->isFunctionType()) {
488 // C++ [temp.arg.type]p3:
489 // If a declaration acquires a function type through a type
490 // dependent on a template-parameter and this causes a
491 // declaration that does not use the syntactic form of a
492 // function declarator to have function type, the program is
494 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
499 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
502 MSPropertyDecl *Property = new (SemaRef.Context)
503 MSPropertyDecl(Owner, D->getLocation(),
504 D->getDeclName(), DI->getType(), DI,
506 D->getGetterId(), D->getSetterId());
508 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
512 Property->setInvalidDecl();
514 Property->setAccess(D->getAccess());
515 Owner->addDecl(Property);
520 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
521 NamedDecl **NamedChain =
522 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
525 for (IndirectFieldDecl::chain_iterator PI =
526 D->chain_begin(), PE = D->chain_end();
528 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
533 NamedChain[i++] = Next;
536 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
537 IndirectFieldDecl* IndirectField
538 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
539 D->getIdentifier(), T,
540 NamedChain, D->getChainingSize());
543 IndirectField->setImplicit(D->isImplicit());
544 IndirectField->setAccess(D->getAccess());
545 Owner->addDecl(IndirectField);
546 return IndirectField;
549 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
550 // Handle friend type expressions by simply substituting template
551 // parameters into the pattern type and checking the result.
552 if (TypeSourceInfo *Ty = D->getFriendType()) {
553 TypeSourceInfo *InstTy;
554 // If this is an unsupported friend, don't bother substituting template
555 // arguments into it. The actual type referred to won't be used by any
556 // parts of Clang, and may not be valid for instantiating. Just use the
557 // same info for the instantiated friend.
558 if (D->isUnsupportedFriend()) {
561 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
562 D->getLocation(), DeclarationName());
567 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
568 D->getFriendLoc(), InstTy);
572 FD->setAccess(AS_public);
573 FD->setUnsupportedFriend(D->isUnsupportedFriend());
578 NamedDecl *ND = D->getFriendDecl();
579 assert(ND && "friend decl must be a decl or a type!");
581 // All of the Visit implementations for the various potential friend
582 // declarations have to be carefully written to work for friend
583 // objects, with the most important detail being that the target
584 // decl should almost certainly not be placed in Owner.
585 Decl *NewND = Visit(ND);
586 if (!NewND) return 0;
589 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
590 cast<NamedDecl>(NewND), D->getFriendLoc());
591 FD->setAccess(AS_public);
592 FD->setUnsupportedFriend(D->isUnsupportedFriend());
597 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
598 Expr *AssertExpr = D->getAssertExpr();
600 // The expression in a static assertion is a constant expression.
601 EnterExpressionEvaluationContext Unevaluated(SemaRef,
602 Sema::ConstantEvaluated);
604 ExprResult InstantiatedAssertExpr
605 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
606 if (InstantiatedAssertExpr.isInvalid())
609 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
610 InstantiatedAssertExpr.get(),
616 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
617 EnumDecl *PrevDecl = 0;
618 if (D->getPreviousDecl()) {
619 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
620 D->getPreviousDecl(),
623 PrevDecl = cast<EnumDecl>(Prev);
626 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
627 D->getLocation(), D->getIdentifier(),
628 PrevDecl, D->isScoped(),
629 D->isScopedUsingClassTag(), D->isFixed());
631 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
632 // If we have type source information for the underlying type, it means it
633 // has been explicitly set by the user. Perform substitution on it before
635 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
636 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
638 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
639 Enum->setIntegerType(SemaRef.Context.IntTy);
641 Enum->setIntegerTypeSourceInfo(NewTI);
643 assert(!D->getIntegerType()->isDependentType()
644 && "Dependent type without type source info");
645 Enum->setIntegerType(D->getIntegerType());
649 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
651 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
652 Enum->setAccess(D->getAccess());
653 if (SubstQualifier(D, Enum)) return 0;
654 Owner->addDecl(Enum);
656 EnumDecl *Def = D->getDefinition();
657 if (Def && Def != D) {
658 // If this is an out-of-line definition of an enum member template, check
659 // that the underlying types match in the instantiation of both
661 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
662 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
663 QualType DefnUnderlying =
664 SemaRef.SubstType(TI->getType(), TemplateArgs,
665 UnderlyingLoc, DeclarationName());
666 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
667 DefnUnderlying, Enum);
671 // C++11 [temp.inst]p1: The implicit instantiation of a class template
672 // specialization causes the implicit instantiation of the declarations, but
673 // not the definitions of scoped member enumerations.
675 // DR1484 clarifies that enumeration definitions inside of a template
676 // declaration aren't considered entities that can be separately instantiated
677 // from the rest of the entity they are declared inside of.
678 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
679 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
680 InstantiateEnumDefinition(Enum, Def);
686 void TemplateDeclInstantiator::InstantiateEnumDefinition(
687 EnumDecl *Enum, EnumDecl *Pattern) {
688 Enum->startDefinition();
690 // Update the location to refer to the definition.
691 Enum->setLocation(Pattern->getLocation());
693 SmallVector<Decl*, 4> Enumerators;
695 EnumConstantDecl *LastEnumConst = 0;
696 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
697 ECEnd = Pattern->enumerator_end();
699 // The specified value for the enumerator.
700 ExprResult Value = SemaRef.Owned((Expr *)0);
701 if (Expr *UninstValue = EC->getInitExpr()) {
702 // The enumerator's value expression is a constant expression.
703 EnterExpressionEvaluationContext Unevaluated(SemaRef,
704 Sema::ConstantEvaluated);
706 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
709 // Drop the initial value and continue.
710 bool isInvalid = false;
711 if (Value.isInvalid()) {
712 Value = SemaRef.Owned((Expr *)0);
716 EnumConstantDecl *EnumConst
717 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
718 EC->getLocation(), EC->getIdentifier(),
723 EnumConst->setInvalidDecl();
724 Enum->setInvalidDecl();
728 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
730 EnumConst->setAccess(Enum->getAccess());
731 Enum->addDecl(EnumConst);
732 Enumerators.push_back(EnumConst);
733 LastEnumConst = EnumConst;
735 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
737 // If the enumeration is within a function or method, record the enum
738 // constant as a local.
739 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
744 // FIXME: Fixup LBraceLoc
745 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
746 Enum->getRBraceLoc(), Enum,
751 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
752 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
755 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
756 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
758 // Create a local instantiation scope for this class template, which
759 // will contain the instantiations of the template parameters.
760 LocalInstantiationScope Scope(SemaRef);
761 TemplateParameterList *TempParams = D->getTemplateParameters();
762 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
766 CXXRecordDecl *Pattern = D->getTemplatedDecl();
768 // Instantiate the qualifier. We have to do this first in case
769 // we're a friend declaration, because if we are then we need to put
770 // the new declaration in the appropriate context.
771 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
773 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
779 CXXRecordDecl *PrevDecl = 0;
780 ClassTemplateDecl *PrevClassTemplate = 0;
782 if (!isFriend && Pattern->getPreviousDecl()) {
783 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
784 if (!Found.empty()) {
785 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
786 if (PrevClassTemplate)
787 PrevDecl = PrevClassTemplate->getTemplatedDecl();
791 // If this isn't a friend, then it's a member template, in which
792 // case we just want to build the instantiation in the
793 // specialization. If it is a friend, we want to build it in
794 // the appropriate context.
795 DeclContext *DC = Owner;
799 SS.Adopt(QualifierLoc);
800 DC = SemaRef.computeDeclContext(SS);
803 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
804 Pattern->getDeclContext(),
808 // Look for a previous declaration of the template in the owning
810 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
811 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
812 SemaRef.LookupQualifiedName(R, DC);
814 if (R.isSingleResult()) {
815 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
816 if (PrevClassTemplate)
817 PrevDecl = PrevClassTemplate->getTemplatedDecl();
820 if (!PrevClassTemplate && QualifierLoc) {
821 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
822 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
823 << QualifierLoc.getSourceRange();
827 bool AdoptedPreviousTemplateParams = false;
828 if (PrevClassTemplate) {
829 bool Complain = true;
831 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
832 // template for struct std::tr1::__detail::_Map_base, where the
833 // template parameters of the friend declaration don't match the
834 // template parameters of the original declaration. In this one
835 // case, we don't complain about the ill-formed friend
837 if (isFriend && Pattern->getIdentifier() &&
838 Pattern->getIdentifier()->isStr("_Map_base") &&
840 cast<NamespaceDecl>(DC)->getIdentifier() &&
841 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
842 DeclContext *DCParent = DC->getParent();
843 if (DCParent->isNamespace() &&
844 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
845 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
846 DeclContext *DCParent2 = DCParent->getParent();
847 if (DCParent2->isNamespace() &&
848 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
849 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
850 DCParent2->getParent()->isTranslationUnit())
855 TemplateParameterList *PrevParams
856 = PrevClassTemplate->getTemplateParameters();
858 // Make sure the parameter lists match.
859 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
861 Sema::TPL_TemplateMatch)) {
865 AdoptedPreviousTemplateParams = true;
866 InstParams = PrevParams;
869 // Do some additional validation, then merge default arguments
870 // from the existing declarations.
871 if (!AdoptedPreviousTemplateParams &&
872 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
873 Sema::TPC_ClassTemplate))
878 CXXRecordDecl *RecordInst
879 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
880 Pattern->getLocStart(), Pattern->getLocation(),
881 Pattern->getIdentifier(), PrevDecl,
882 /*DelayTypeCreation=*/true);
885 RecordInst->setQualifierInfo(QualifierLoc);
887 ClassTemplateDecl *Inst
888 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
889 D->getIdentifier(), InstParams, RecordInst,
891 RecordInst->setDescribedClassTemplate(Inst);
894 if (PrevClassTemplate)
895 Inst->setAccess(PrevClassTemplate->getAccess());
897 Inst->setAccess(D->getAccess());
899 Inst->setObjectOfFriendDecl();
900 // TODO: do we want to track the instantiation progeny of this
901 // friend target decl?
903 Inst->setAccess(D->getAccess());
904 if (!PrevClassTemplate)
905 Inst->setInstantiatedFromMemberTemplate(D);
908 // Trigger creation of the type for the instantiation.
909 SemaRef.Context.getInjectedClassNameType(RecordInst,
910 Inst->getInjectedClassNameSpecialization());
912 // Finish handling of friends.
914 DC->makeDeclVisibleInContext(Inst);
915 Inst->setLexicalDeclContext(Owner);
916 RecordInst->setLexicalDeclContext(Owner);
920 if (D->isOutOfLine()) {
921 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
922 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
925 Owner->addDecl(Inst);
927 if (!PrevClassTemplate) {
928 // Queue up any out-of-line partial specializations of this member
929 // class template; the client will force their instantiation once
930 // the enclosing class has been instantiated.
931 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
932 D->getPartialSpecializations(PartialSpecs);
933 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
934 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
935 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
942 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
943 ClassTemplatePartialSpecializationDecl *D) {
944 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
946 // Lookup the already-instantiated declaration in the instantiation
947 // of the class template and return that.
948 DeclContext::lookup_result Found
949 = Owner->lookup(ClassTemplate->getDeclName());
953 ClassTemplateDecl *InstClassTemplate
954 = dyn_cast<ClassTemplateDecl>(Found.front());
955 if (!InstClassTemplate)
958 if (ClassTemplatePartialSpecializationDecl *Result
959 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
962 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
965 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
966 assert(D->getTemplatedDecl()->isStaticDataMember() &&
967 "Only static data member templates are allowed.");
969 // Create a local instantiation scope for this variable template, which
970 // will contain the instantiations of the template parameters.
971 LocalInstantiationScope Scope(SemaRef);
972 TemplateParameterList *TempParams = D->getTemplateParameters();
973 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
977 VarDecl *Pattern = D->getTemplatedDecl();
978 VarTemplateDecl *PrevVarTemplate = 0;
980 if (Pattern->getPreviousDecl()) {
981 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
983 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
987 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
988 /*InstantiatingVarTemplate=*/true));
990 DeclContext *DC = Owner;
992 VarTemplateDecl *Inst = VarTemplateDecl::Create(
993 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
994 VarInst, PrevVarTemplate);
995 VarInst->setDescribedVarTemplate(Inst);
997 Inst->setAccess(D->getAccess());
998 if (!PrevVarTemplate)
999 Inst->setInstantiatedFromMemberTemplate(D);
1001 if (D->isOutOfLine()) {
1002 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1003 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1006 Owner->addDecl(Inst);
1008 if (!PrevVarTemplate) {
1009 // Queue up any out-of-line partial specializations of this member
1010 // variable template; the client will force their instantiation once
1011 // the enclosing class has been instantiated.
1012 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1013 D->getPartialSpecializations(PartialSpecs);
1014 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1015 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1016 OutOfLineVarPartialSpecs.push_back(
1017 std::make_pair(Inst, PartialSpecs[I]));
1023 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1024 VarTemplatePartialSpecializationDecl *D) {
1025 assert(D->isStaticDataMember() &&
1026 "Only static data member templates are allowed.");
1028 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1030 // Lookup the already-instantiated declaration and return that.
1031 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1032 assert(!Found.empty() && "Instantiation found nothing?");
1034 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1035 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1037 if (VarTemplatePartialSpecializationDecl *Result =
1038 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1041 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1045 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1046 // Create a local instantiation scope for this function template, which
1047 // will contain the instantiations of the template parameters and then get
1048 // merged with the local instantiation scope for the function template
1050 LocalInstantiationScope Scope(SemaRef);
1052 TemplateParameterList *TempParams = D->getTemplateParameters();
1053 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1057 FunctionDecl *Instantiated = 0;
1058 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1059 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1062 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1063 D->getTemplatedDecl(),
1069 // Link the instantiated function template declaration to the function
1070 // template from which it was instantiated.
1071 FunctionTemplateDecl *InstTemplate
1072 = Instantiated->getDescribedFunctionTemplate();
1073 InstTemplate->setAccess(D->getAccess());
1074 assert(InstTemplate &&
1075 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1077 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1079 // Link the instantiation back to the pattern *unless* this is a
1080 // non-definition friend declaration.
1081 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1082 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1083 InstTemplate->setInstantiatedFromMemberTemplate(D);
1085 // Make declarations visible in the appropriate context.
1087 Owner->addDecl(InstTemplate);
1088 } else if (InstTemplate->getDeclContext()->isRecord() &&
1089 !D->getPreviousDecl()) {
1090 SemaRef.CheckFriendAccess(InstTemplate);
1093 return InstTemplate;
1096 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1097 CXXRecordDecl *PrevDecl = 0;
1098 if (D->isInjectedClassName())
1099 PrevDecl = cast<CXXRecordDecl>(Owner);
1100 else if (D->getPreviousDecl()) {
1101 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1102 D->getPreviousDecl(),
1104 if (!Prev) return 0;
1105 PrevDecl = cast<CXXRecordDecl>(Prev);
1108 CXXRecordDecl *Record
1109 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1110 D->getLocStart(), D->getLocation(),
1111 D->getIdentifier(), PrevDecl);
1113 // Substitute the nested name specifier, if any.
1114 if (SubstQualifier(D, Record))
1117 Record->setImplicit(D->isImplicit());
1118 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1119 // the tag decls introduced by friend class declarations don't have an access
1120 // specifier. Remove once this area of the code gets sorted out.
1121 if (D->getAccess() != AS_none)
1122 Record->setAccess(D->getAccess());
1123 if (!D->isInjectedClassName())
1124 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1126 // If the original function was part of a friend declaration,
1127 // inherit its namespace state.
1128 if (D->getFriendObjectKind())
1129 Record->setObjectOfFriendDecl();
1131 // Make sure that anonymous structs and unions are recorded.
1132 if (D->isAnonymousStructOrUnion())
1133 Record->setAnonymousStructOrUnion(true);
1135 if (D->isLocalClass())
1136 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1138 Owner->addDecl(Record);
1140 // DR1484 clarifies that the members of a local class are instantiated as part
1141 // of the instantiation of their enclosing entity.
1142 if (D->isCompleteDefinition() && D->isLocalClass()) {
1143 if (SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1144 TSK_ImplicitInstantiation,
1145 /*Complain=*/true)) {
1146 llvm_unreachable("InstantiateClass shouldn't fail here!");
1148 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1149 TSK_ImplicitInstantiation);
1155 /// \brief Adjust the given function type for an instantiation of the
1156 /// given declaration, to cope with modifications to the function's type that
1157 /// aren't reflected in the type-source information.
1159 /// \param D The declaration we're instantiating.
1160 /// \param TInfo The already-instantiated type.
1161 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1163 TypeSourceInfo *TInfo) {
1164 const FunctionProtoType *OrigFunc
1165 = D->getType()->castAs<FunctionProtoType>();
1166 const FunctionProtoType *NewFunc
1167 = TInfo->getType()->castAs<FunctionProtoType>();
1168 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1169 return TInfo->getType();
1171 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1172 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1173 return Context.getFunctionType(NewFunc->getResultType(),
1174 NewFunc->getArgTypes(), NewEPI);
1177 /// Normal class members are of more specific types and therefore
1178 /// don't make it here. This function serves two purposes:
1179 /// 1) instantiating function templates
1180 /// 2) substituting friend declarations
1181 /// FIXME: preserve function definitions in case #2
1182 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1183 TemplateParameterList *TemplateParams) {
1184 // Check whether there is already a function template specialization for
1185 // this declaration.
1186 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1187 if (FunctionTemplate && !TemplateParams) {
1188 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1190 void *InsertPos = 0;
1191 FunctionDecl *SpecFunc
1192 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
1195 // If we already have a function template specialization, return it.
1201 if (FunctionTemplate)
1202 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1204 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1206 bool MergeWithParentScope = (TemplateParams != 0) ||
1207 Owner->isFunctionOrMethod() ||
1208 !(isa<Decl>(Owner) &&
1209 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1210 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1212 SmallVector<ParmVarDecl *, 4> Params;
1213 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1216 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1218 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1220 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1226 // If we're instantiating a local function declaration, put the result
1227 // in the enclosing namespace; otherwise we need to find the instantiated
1230 if (D->isLocalExternDecl()) {
1232 SemaRef.adjustContextForLocalExternDecl(DC);
1233 } else if (isFriend && QualifierLoc) {
1235 SS.Adopt(QualifierLoc);
1236 DC = SemaRef.computeDeclContext(SS);
1239 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1243 FunctionDecl *Function =
1244 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1245 D->getNameInfo(), T, TInfo,
1246 D->getCanonicalDecl()->getStorageClass(),
1247 D->isInlineSpecified(), D->hasWrittenPrototype(),
1249 Function->setRangeEnd(D->getSourceRange().getEnd());
1252 Function->setImplicitlyInline();
1255 Function->setQualifierInfo(QualifierLoc);
1257 if (D->isLocalExternDecl())
1258 Function->setLocalExternDecl();
1260 DeclContext *LexicalDC = Owner;
1261 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1262 assert(D->getDeclContext()->isFileContext());
1263 LexicalDC = D->getDeclContext();
1266 Function->setLexicalDeclContext(LexicalDC);
1268 // Attach the parameters
1269 for (unsigned P = 0; P < Params.size(); ++P)
1271 Params[P]->setOwningFunction(Function);
1272 Function->setParams(Params);
1274 SourceLocation InstantiateAtPOI;
1275 if (TemplateParams) {
1276 // Our resulting instantiation is actually a function template, since we
1277 // are substituting only the outer template parameters. For example, given
1279 // template<typename T>
1281 // template<typename U> friend void f(T, U);
1286 // We are instantiating the friend function template "f" within X<int>,
1287 // which means substituting int for T, but leaving "f" as a friend function
1289 // Build the function template itself.
1290 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1291 Function->getLocation(),
1292 Function->getDeclName(),
1293 TemplateParams, Function);
1294 Function->setDescribedFunctionTemplate(FunctionTemplate);
1296 FunctionTemplate->setLexicalDeclContext(LexicalDC);
1298 if (isFriend && D->isThisDeclarationADefinition()) {
1299 // TODO: should we remember this connection regardless of whether
1300 // the friend declaration provided a body?
1301 FunctionTemplate->setInstantiatedFromMemberTemplate(
1302 D->getDescribedFunctionTemplate());
1304 } else if (FunctionTemplate) {
1305 // Record this function template specialization.
1306 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1307 Function->setFunctionTemplateSpecialization(FunctionTemplate,
1308 TemplateArgumentList::CreateCopy(SemaRef.Context,
1312 } else if (isFriend) {
1313 // Note, we need this connection even if the friend doesn't have a body.
1314 // Its body may exist but not have been attached yet due to deferred
1316 // FIXME: It might be cleaner to set this when attaching the body to the
1317 // friend function declaration, however that would require finding all the
1318 // instantiations and modifying them.
1319 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1322 if (InitFunctionInstantiation(Function, D))
1323 Function->setInvalidDecl();
1325 bool isExplicitSpecialization = false;
1327 LookupResult Previous(
1328 SemaRef, Function->getDeclName(), SourceLocation(),
1329 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1330 : Sema::LookupOrdinaryName,
1331 Sema::ForRedeclaration);
1333 if (DependentFunctionTemplateSpecializationInfo *Info
1334 = D->getDependentSpecializationInfo()) {
1335 assert(isFriend && "non-friend has dependent specialization info?");
1337 // This needs to be set now for future sanity.
1338 Function->setObjectOfFriendDecl();
1340 // Instantiate the explicit template arguments.
1341 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1342 Info->getRAngleLoc());
1343 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1344 ExplicitArgs, TemplateArgs))
1347 // Map the candidate templates to their instantiations.
1348 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1349 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1350 Info->getTemplate(I),
1352 if (!Temp) return 0;
1354 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1357 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1360 Function->setInvalidDecl();
1362 isExplicitSpecialization = true;
1364 } else if (TemplateParams || !FunctionTemplate) {
1365 // Look only into the namespace where the friend would be declared to
1366 // find a previous declaration. This is the innermost enclosing namespace,
1367 // as described in ActOnFriendFunctionDecl.
1368 SemaRef.LookupQualifiedName(Previous, DC);
1370 // In C++, the previous declaration we find might be a tag type
1371 // (class or enum). In this case, the new declaration will hide the
1372 // tag type. Note that this does does not apply if we're declaring a
1373 // typedef (C++ [dcl.typedef]p4).
1374 if (Previous.isSingleTagDecl())
1378 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1379 isExplicitSpecialization);
1381 NamedDecl *PrincipalDecl = (TemplateParams
1382 ? cast<NamedDecl>(FunctionTemplate)
1385 // If the original function was part of a friend declaration,
1386 // inherit its namespace state and add it to the owner.
1388 PrincipalDecl->setObjectOfFriendDecl();
1389 DC->makeDeclVisibleInContext(PrincipalDecl);
1391 bool queuedInstantiation = false;
1393 // C++98 [temp.friend]p5: When a function is defined in a friend function
1394 // declaration in a class template, the function is defined at each
1395 // instantiation of the class template. The function is defined even if it
1397 // C++11 [temp.friend]p4: When a function is defined in a friend function
1398 // declaration in a class template, the function is instantiated when the
1399 // function is odr-used.
1401 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1402 // redefinition, but don't instantiate the function.
1403 if ((!SemaRef.getLangOpts().CPlusPlus11 ||
1404 SemaRef.Diags.getDiagnosticLevel(
1405 diag::warn_cxx98_compat_friend_redefinition,
1406 Function->getLocation())
1407 != DiagnosticsEngine::Ignored) &&
1408 D->isThisDeclarationADefinition()) {
1409 // Check for a function body.
1410 const FunctionDecl *Definition = 0;
1411 if (Function->isDefined(Definition) &&
1412 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1413 SemaRef.Diag(Function->getLocation(),
1414 SemaRef.getLangOpts().CPlusPlus11 ?
1415 diag::warn_cxx98_compat_friend_redefinition :
1416 diag::err_redefinition) << Function->getDeclName();
1417 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1418 if (!SemaRef.getLangOpts().CPlusPlus11)
1419 Function->setInvalidDecl();
1421 // Check for redefinitions due to other instantiations of this or
1422 // a similar friend function.
1423 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1424 REnd = Function->redecls_end();
1428 switch (R->getFriendObjectKind()) {
1429 case Decl::FOK_None:
1430 if (!SemaRef.getLangOpts().CPlusPlus11 &&
1431 !queuedInstantiation && R->isUsed(false)) {
1432 if (MemberSpecializationInfo *MSInfo
1433 = Function->getMemberSpecializationInfo()) {
1434 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1435 SourceLocation Loc = R->getLocation(); // FIXME
1436 MSInfo->setPointOfInstantiation(Loc);
1437 SemaRef.PendingLocalImplicitInstantiations.push_back(
1438 std::make_pair(Function, Loc));
1439 queuedInstantiation = true;
1445 if (const FunctionDecl *RPattern
1446 = R->getTemplateInstantiationPattern())
1447 if (RPattern->isDefined(RPattern)) {
1448 SemaRef.Diag(Function->getLocation(),
1449 SemaRef.getLangOpts().CPlusPlus11 ?
1450 diag::warn_cxx98_compat_friend_redefinition :
1451 diag::err_redefinition)
1452 << Function->getDeclName();
1453 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1454 if (!SemaRef.getLangOpts().CPlusPlus11)
1455 Function->setInvalidDecl();
1463 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1464 DC->makeDeclVisibleInContext(PrincipalDecl);
1466 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1467 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1468 PrincipalDecl->setNonMemberOperator();
1470 assert(!D->isDefaulted() && "only methods should be defaulted");
1475 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1476 TemplateParameterList *TemplateParams,
1477 bool IsClassScopeSpecialization) {
1478 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1479 if (FunctionTemplate && !TemplateParams) {
1480 // We are creating a function template specialization from a function
1481 // template. Check whether there is already a function template
1482 // specialization for this particular set of template arguments.
1483 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1485 void *InsertPos = 0;
1486 FunctionDecl *SpecFunc
1487 = FunctionTemplate->findSpecialization(Innermost.begin(),
1491 // If we already have a function template specialization, return it.
1497 if (FunctionTemplate)
1498 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1500 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1502 bool MergeWithParentScope = (TemplateParams != 0) ||
1503 !(isa<Decl>(Owner) &&
1504 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1505 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1507 // Instantiate enclosing template arguments for friends.
1508 SmallVector<TemplateParameterList *, 4> TempParamLists;
1509 unsigned NumTempParamLists = 0;
1510 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1511 TempParamLists.set_size(NumTempParamLists);
1512 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1513 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1514 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1517 TempParamLists[I] = InstParams;
1521 SmallVector<ParmVarDecl *, 4> Params;
1522 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1525 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1527 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1529 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1535 DeclContext *DC = Owner;
1539 SS.Adopt(QualifierLoc);
1540 DC = SemaRef.computeDeclContext(SS);
1542 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1545 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1546 D->getDeclContext(),
1552 // Build the instantiated method declaration.
1553 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1554 CXXMethodDecl *Method = 0;
1556 SourceLocation StartLoc = D->getInnerLocStart();
1557 DeclarationNameInfo NameInfo
1558 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1559 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1560 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1561 StartLoc, NameInfo, T, TInfo,
1562 Constructor->isExplicit(),
1563 Constructor->isInlineSpecified(),
1564 false, Constructor->isConstexpr());
1566 // Claim that the instantiation of a constructor or constructor template
1567 // inherits the same constructor that the template does.
1568 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1569 Constructor->getInheritedConstructor())) {
1570 // If we're instantiating a specialization of a function template, our
1571 // "inherited constructor" will actually itself be a function template.
1572 // Instantiate a declaration of it, too.
1573 if (FunctionTemplate) {
1574 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1575 !Inh->getParent()->isDependentContext() &&
1576 "inheriting constructor template in dependent context?");
1577 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1579 if (Inst.isInvalid())
1581 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1582 LocalInstantiationScope LocalScope(SemaRef);
1584 // Use the same template arguments that we deduced for the inheriting
1585 // constructor. There's no way they could be deduced differently.
1586 MultiLevelTemplateArgumentList InheritedArgs;
1587 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1588 Inh = cast_or_null<CXXConstructorDecl>(
1589 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1593 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
1595 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1596 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1597 StartLoc, NameInfo, T, TInfo,
1598 Destructor->isInlineSpecified(),
1600 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1601 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1602 StartLoc, NameInfo, T, TInfo,
1603 Conversion->isInlineSpecified(),
1604 Conversion->isExplicit(),
1605 Conversion->isConstexpr(),
1606 Conversion->getLocEnd());
1608 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
1609 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1610 StartLoc, NameInfo, T, TInfo,
1611 SC, D->isInlineSpecified(),
1612 D->isConstexpr(), D->getLocEnd());
1616 Method->setImplicitlyInline();
1619 Method->setQualifierInfo(QualifierLoc);
1621 if (TemplateParams) {
1622 // Our resulting instantiation is actually a function template, since we
1623 // are substituting only the outer template parameters. For example, given
1625 // template<typename T>
1627 // template<typename U> void f(T, U);
1632 // We are instantiating the member template "f" within X<int>, which means
1633 // substituting int for T, but leaving "f" as a member function template.
1634 // Build the function template itself.
1635 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1636 Method->getLocation(),
1637 Method->getDeclName(),
1638 TemplateParams, Method);
1640 FunctionTemplate->setLexicalDeclContext(Owner);
1641 FunctionTemplate->setObjectOfFriendDecl();
1642 } else if (D->isOutOfLine())
1643 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1644 Method->setDescribedFunctionTemplate(FunctionTemplate);
1645 } else if (FunctionTemplate) {
1646 // Record this function template specialization.
1647 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1648 Method->setFunctionTemplateSpecialization(FunctionTemplate,
1649 TemplateArgumentList::CreateCopy(SemaRef.Context,
1653 } else if (!isFriend) {
1654 // Record that this is an instantiation of a member function.
1655 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1658 // If we are instantiating a member function defined
1659 // out-of-line, the instantiation will have the same lexical
1660 // context (which will be a namespace scope) as the template.
1662 if (NumTempParamLists)
1663 Method->setTemplateParameterListsInfo(SemaRef.Context,
1665 TempParamLists.data());
1667 Method->setLexicalDeclContext(Owner);
1668 Method->setObjectOfFriendDecl();
1669 } else if (D->isOutOfLine())
1670 Method->setLexicalDeclContext(D->getLexicalDeclContext());
1672 // Attach the parameters
1673 for (unsigned P = 0; P < Params.size(); ++P)
1674 Params[P]->setOwningFunction(Method);
1675 Method->setParams(Params);
1677 if (InitMethodInstantiation(Method, D))
1678 Method->setInvalidDecl();
1680 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1681 Sema::ForRedeclaration);
1683 if (!FunctionTemplate || TemplateParams || isFriend) {
1684 SemaRef.LookupQualifiedName(Previous, Record);
1686 // In C++, the previous declaration we find might be a tag type
1687 // (class or enum). In this case, the new declaration will hide the
1688 // tag type. Note that this does does not apply if we're declaring a
1689 // typedef (C++ [dcl.typedef]p4).
1690 if (Previous.isSingleTagDecl())
1694 if (!IsClassScopeSpecialization)
1695 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
1698 SemaRef.CheckPureMethod(Method, SourceRange());
1700 // Propagate access. For a non-friend declaration, the access is
1701 // whatever we're propagating from. For a friend, it should be the
1702 // previous declaration we just found.
1703 if (isFriend && Method->getPreviousDecl())
1704 Method->setAccess(Method->getPreviousDecl()->getAccess());
1706 Method->setAccess(D->getAccess());
1707 if (FunctionTemplate)
1708 FunctionTemplate->setAccess(Method->getAccess());
1710 SemaRef.CheckOverrideControl(Method);
1712 // If a function is defined as defaulted or deleted, mark it as such now.
1713 if (D->isExplicitlyDefaulted())
1714 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1715 if (D->isDeletedAsWritten())
1716 SemaRef.SetDeclDeleted(Method, Method->getLocation());
1718 // If there's a function template, let our caller handle it.
1719 if (FunctionTemplate) {
1722 // Don't hide a (potentially) valid declaration with an invalid one.
1723 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1726 // Otherwise, check access to friends and make them visible.
1727 } else if (isFriend) {
1728 // We only need to re-check access for methods which we didn't
1729 // manage to match during parsing.
1730 if (!D->getPreviousDecl())
1731 SemaRef.CheckFriendAccess(Method);
1733 Record->makeDeclVisibleInContext(Method);
1735 // Otherwise, add the declaration. We don't need to do this for
1736 // class-scope specializations because we'll have matched them with
1737 // the appropriate template.
1738 } else if (!IsClassScopeSpecialization) {
1739 Owner->addDecl(Method);
1745 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1746 return VisitCXXMethodDecl(D);
1749 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1750 return VisitCXXMethodDecl(D);
1753 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1754 return VisitCXXMethodDecl(D);
1757 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1758 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1759 /*ExpectParameterPack=*/ false);
1762 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1763 TemplateTypeParmDecl *D) {
1764 // TODO: don't always clone when decls are refcounted.
1765 assert(D->getTypeForDecl()->isTemplateTypeParmType());
1767 TemplateTypeParmDecl *Inst =
1768 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1769 D->getLocStart(), D->getLocation(),
1770 D->getDepth() - TemplateArgs.getNumLevels(),
1771 D->getIndex(), D->getIdentifier(),
1772 D->wasDeclaredWithTypename(),
1773 D->isParameterPack());
1774 Inst->setAccess(AS_public);
1776 if (D->hasDefaultArgument()) {
1777 TypeSourceInfo *InstantiatedDefaultArg =
1778 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1779 D->getDefaultArgumentLoc(), D->getDeclName());
1780 if (InstantiatedDefaultArg)
1781 Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1784 // Introduce this template parameter's instantiation into the instantiation
1786 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1791 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1792 NonTypeTemplateParmDecl *D) {
1793 // Substitute into the type of the non-type template parameter.
1794 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1795 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1796 SmallVector<QualType, 4> ExpandedParameterPackTypes;
1797 bool IsExpandedParameterPack = false;
1800 bool Invalid = false;
1802 if (D->isExpandedParameterPack()) {
1803 // The non-type template parameter pack is an already-expanded pack
1804 // expansion of types. Substitute into each of the expanded types.
1805 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1806 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1807 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1808 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1815 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1816 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1820 ExpandedParameterPackTypes.push_back(NewT);
1823 IsExpandedParameterPack = true;
1824 DI = D->getTypeSourceInfo();
1826 } else if (D->isPackExpansion()) {
1827 // The non-type template parameter pack's type is a pack expansion of types.
1828 // Determine whether we need to expand this parameter pack into separate
1830 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
1831 TypeLoc Pattern = Expansion.getPatternLoc();
1832 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1833 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1835 // Determine whether the set of unexpanded parameter packs can and should
1838 bool RetainExpansion = false;
1839 Optional<unsigned> OrigNumExpansions
1840 = Expansion.getTypePtr()->getNumExpansions();
1841 Optional<unsigned> NumExpansions = OrigNumExpansions;
1842 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1843 Pattern.getSourceRange(),
1846 Expand, RetainExpansion,
1851 for (unsigned I = 0; I != *NumExpansions; ++I) {
1852 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1853 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1859 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1860 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1865 ExpandedParameterPackTypes.push_back(NewT);
1868 // Note that we have an expanded parameter pack. The "type" of this
1869 // expanded parameter pack is the original expansion type, but callers
1870 // will end up using the expanded parameter pack types for type-checking.
1871 IsExpandedParameterPack = true;
1872 DI = D->getTypeSourceInfo();
1875 // We cannot fully expand the pack expansion now, so substitute into the
1876 // pattern and create a new pack expansion type.
1877 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1878 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1884 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1892 // Simple case: substitution into a parameter that is not a parameter pack.
1893 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1894 D->getLocation(), D->getDeclName());
1898 // Check that this type is acceptable for a non-type template parameter.
1899 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1902 T = SemaRef.Context.IntTy;
1907 NonTypeTemplateParmDecl *Param;
1908 if (IsExpandedParameterPack)
1909 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1910 D->getInnerLocStart(),
1912 D->getDepth() - TemplateArgs.getNumLevels(),
1914 D->getIdentifier(), T,
1916 ExpandedParameterPackTypes.data(),
1917 ExpandedParameterPackTypes.size(),
1918 ExpandedParameterPackTypesAsWritten.data());
1920 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1921 D->getInnerLocStart(),
1923 D->getDepth() - TemplateArgs.getNumLevels(),
1925 D->getIdentifier(), T,
1926 D->isParameterPack(), DI);
1928 Param->setAccess(AS_public);
1930 Param->setInvalidDecl();
1932 if (D->hasDefaultArgument()) {
1933 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
1934 if (!Value.isInvalid())
1935 Param->setDefaultArgument(Value.get(), false);
1938 // Introduce this template parameter's instantiation into the instantiation
1940 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1944 static void collectUnexpandedParameterPacks(
1946 TemplateParameterList *Params,
1947 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1948 for (TemplateParameterList::const_iterator I = Params->begin(),
1949 E = Params->end(); I != E; ++I) {
1950 if ((*I)->isTemplateParameterPack())
1952 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1953 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1955 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1956 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1962 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1963 TemplateTemplateParmDecl *D) {
1964 // Instantiate the template parameter list of the template template parameter.
1965 TemplateParameterList *TempParams = D->getTemplateParameters();
1966 TemplateParameterList *InstParams;
1967 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1969 bool IsExpandedParameterPack = false;
1971 if (D->isExpandedParameterPack()) {
1972 // The template template parameter pack is an already-expanded pack
1973 // expansion of template parameters. Substitute into each of the expanded
1975 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1976 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1978 LocalInstantiationScope Scope(SemaRef);
1979 TemplateParameterList *Expansion =
1980 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1983 ExpandedParams.push_back(Expansion);
1986 IsExpandedParameterPack = true;
1987 InstParams = TempParams;
1988 } else if (D->isPackExpansion()) {
1989 // The template template parameter pack expands to a pack of template
1990 // template parameters. Determine whether we need to expand this parameter
1991 // pack into separate parameters.
1992 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1993 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1996 // Determine whether the set of unexpanded parameter packs can and should
1999 bool RetainExpansion = false;
2000 Optional<unsigned> NumExpansions;
2001 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2002 TempParams->getSourceRange(),
2005 Expand, RetainExpansion,
2010 for (unsigned I = 0; I != *NumExpansions; ++I) {
2011 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2012 LocalInstantiationScope Scope(SemaRef);
2013 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2016 ExpandedParams.push_back(Expansion);
2019 // Note that we have an expanded parameter pack. The "type" of this
2020 // expanded parameter pack is the original expansion type, but callers
2021 // will end up using the expanded parameter pack types for type-checking.
2022 IsExpandedParameterPack = true;
2023 InstParams = TempParams;
2025 // We cannot fully expand the pack expansion now, so just substitute
2026 // into the pattern.
2027 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2029 LocalInstantiationScope Scope(SemaRef);
2030 InstParams = SubstTemplateParams(TempParams);
2035 // Perform the actual substitution of template parameters within a new,
2036 // local instantiation scope.
2037 LocalInstantiationScope Scope(SemaRef);
2038 InstParams = SubstTemplateParams(TempParams);
2043 // Build the template template parameter.
2044 TemplateTemplateParmDecl *Param;
2045 if (IsExpandedParameterPack)
2046 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2048 D->getDepth() - TemplateArgs.getNumLevels(),
2050 D->getIdentifier(), InstParams,
2053 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2055 D->getDepth() - TemplateArgs.getNumLevels(),
2057 D->isParameterPack(),
2058 D->getIdentifier(), InstParams);
2059 if (D->hasDefaultArgument()) {
2060 NestedNameSpecifierLoc QualifierLoc =
2061 D->getDefaultArgument().getTemplateQualifierLoc();
2063 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2064 TemplateName TName = SemaRef.SubstTemplateName(
2065 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2066 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2067 if (!TName.isNull())
2068 Param->setDefaultArgument(
2069 TemplateArgumentLoc(TemplateArgument(TName),
2070 D->getDefaultArgument().getTemplateQualifierLoc(),
2071 D->getDefaultArgument().getTemplateNameLoc()),
2074 Param->setAccess(AS_public);
2076 // Introduce this template parameter's instantiation into the instantiation
2078 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2083 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2084 // Using directives are never dependent (and never contain any types or
2085 // expressions), so they require no explicit instantiation work.
2087 UsingDirectiveDecl *Inst
2088 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2089 D->getNamespaceKeyLocation(),
2090 D->getQualifierLoc(),
2091 D->getIdentLocation(),
2092 D->getNominatedNamespace(),
2093 D->getCommonAncestor());
2095 // Add the using directive to its declaration context
2096 // only if this is not a function or method.
2097 if (!Owner->isFunctionOrMethod())
2098 Owner->addDecl(Inst);
2103 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2105 // The nested name specifier may be dependent, for example
2106 // template <typename T> struct t {
2107 // struct s1 { T f1(); };
2108 // struct s2 : s1 { using s1::f1; };
2110 // template struct t<int>;
2111 // Here, in using s1::f1, s1 refers to t<T>::s1;
2112 // we need to substitute for t<int>::s1.
2113 NestedNameSpecifierLoc QualifierLoc
2114 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2119 // The name info is non-dependent, so no transformation
2121 DeclarationNameInfo NameInfo = D->getNameInfo();
2123 // We only need to do redeclaration lookups if we're in a class
2124 // scope (in fact, it's not really even possible in non-class
2126 bool CheckRedeclaration = Owner->isRecord();
2128 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2129 Sema::ForRedeclaration);
2131 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2138 SS.Adopt(QualifierLoc);
2139 if (CheckRedeclaration) {
2140 Prev.setHideTags(false);
2141 SemaRef.LookupQualifiedName(Prev, Owner);
2143 // Check for invalid redeclarations.
2144 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2145 D->hasTypename(), SS,
2146 D->getLocation(), Prev))
2147 NewUD->setInvalidDecl();
2151 if (!NewUD->isInvalidDecl() &&
2152 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS,
2154 NewUD->setInvalidDecl();
2156 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2157 NewUD->setAccess(D->getAccess());
2158 Owner->addDecl(NewUD);
2160 // Don't process the shadow decls for an invalid decl.
2161 if (NewUD->isInvalidDecl())
2164 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2165 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2166 NewUD->setInvalidDecl();
2170 bool isFunctionScope = Owner->isFunctionOrMethod();
2172 // Process the shadow decls.
2173 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2175 UsingShadowDecl *Shadow = *I;
2176 NamedDecl *InstTarget =
2177 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2178 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
2182 UsingShadowDecl *PrevDecl = 0;
2183 if (CheckRedeclaration) {
2184 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2186 } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) {
2187 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2188 Shadow->getLocation(), OldPrev, TemplateArgs));
2191 UsingShadowDecl *InstShadow =
2192 SemaRef.BuildUsingShadowDecl(/*Scope*/0, NewUD, InstTarget, PrevDecl);
2193 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2195 if (isFunctionScope)
2196 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2202 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2203 // Ignore these; we handle them in bulk when processing the UsingDecl.
2207 Decl * TemplateDeclInstantiator
2208 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
2209 NestedNameSpecifierLoc QualifierLoc
2210 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2216 SS.Adopt(QualifierLoc);
2218 // Since NameInfo refers to a typename, it cannot be a C++ special name.
2219 // Hence, no transformation is required for it.
2220 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
2222 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
2223 D->getUsingLoc(), SS, NameInfo, 0,
2224 /*instantiation*/ true,
2225 /*typename*/ true, D->getTypenameLoc());
2227 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2232 Decl * TemplateDeclInstantiator
2233 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
2234 NestedNameSpecifierLoc QualifierLoc
2235 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2240 SS.Adopt(QualifierLoc);
2242 DeclarationNameInfo NameInfo
2243 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2246 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
2247 D->getUsingLoc(), SS, NameInfo, 0,
2248 /*instantiation*/ true,
2249 /*typename*/ false, SourceLocation());
2251 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2257 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2258 ClassScopeFunctionSpecializationDecl *Decl) {
2259 CXXMethodDecl *OldFD = Decl->getSpecialization();
2260 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2263 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2264 Sema::ForRedeclaration);
2266 TemplateArgumentListInfo TemplateArgs;
2267 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2268 if (Decl->hasExplicitTemplateArgs()) {
2269 TemplateArgs = Decl->templateArgs();
2270 TemplateArgsPtr = &TemplateArgs;
2273 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
2274 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2276 NewFD->setInvalidDecl();
2280 // Associate the specialization with the pattern.
2281 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2282 assert(Specialization && "Class scope Specialization is null");
2283 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2288 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2289 OMPThreadPrivateDecl *D) {
2290 SmallVector<Expr *, 5> Vars;
2291 for (ArrayRef<Expr *>::iterator I = D->varlist_begin(),
2292 E = D->varlist_end();
2294 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2295 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2296 Vars.push_back(Var);
2299 OMPThreadPrivateDecl *TD =
2300 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2305 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2306 return VisitFunctionDecl(D, 0);
2309 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2310 return VisitCXXMethodDecl(D, 0);
2313 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2314 llvm_unreachable("There are only CXXRecordDecls in C++");
2318 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2319 ClassTemplateSpecializationDecl *D) {
2320 // As a MS extension, we permit class-scope explicit specialization
2321 // of member class templates.
2322 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2323 assert(ClassTemplate->getDeclContext()->isRecord() &&
2324 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2325 "can only instantiate an explicit specialization "
2326 "for a member class template");
2328 // Lookup the already-instantiated declaration in the instantiation
2329 // of the class template. FIXME: Diagnose or assert if this fails?
2330 DeclContext::lookup_result Found
2331 = Owner->lookup(ClassTemplate->getDeclName());
2334 ClassTemplateDecl *InstClassTemplate
2335 = dyn_cast<ClassTemplateDecl>(Found.front());
2336 if (!InstClassTemplate)
2339 // Substitute into the template arguments of the class template explicit
2341 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2342 castAs<TemplateSpecializationTypeLoc>();
2343 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2344 Loc.getRAngleLoc());
2345 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2346 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2347 ArgLocs.push_back(Loc.getArgLoc(I));
2348 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2349 InstTemplateArgs, TemplateArgs))
2352 // Check that the template argument list is well-formed for this
2354 SmallVector<TemplateArgument, 4> Converted;
2355 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2362 // Figure out where to insert this class template explicit specialization
2363 // in the member template's set of class template explicit specializations.
2364 void *InsertPos = 0;
2365 ClassTemplateSpecializationDecl *PrevDecl =
2366 InstClassTemplate->findSpecialization(Converted.data(), Converted.size(),
2369 // Check whether we've already seen a conflicting instantiation of this
2370 // declaration (for instance, if there was a prior implicit instantiation).
2373 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2374 D->getSpecializationKind(),
2376 PrevDecl->getSpecializationKind(),
2377 PrevDecl->getPointOfInstantiation(),
2381 // If PrevDecl was a definition and D is also a definition, diagnose.
2382 // This happens in cases like:
2384 // template<typename T, typename U>
2386 // template<typename X> struct Inner;
2387 // template<> struct Inner<T> {};
2388 // template<> struct Inner<U> {};
2391 // Outer<int, int> outer; // error: the explicit specializations of Inner
2392 // // have the same signature.
2393 if (PrevDecl && PrevDecl->getDefinition() &&
2394 D->isThisDeclarationADefinition()) {
2395 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2396 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2397 diag::note_previous_definition);
2401 // Create the class template partial specialization declaration.
2402 ClassTemplateSpecializationDecl *InstD
2403 = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2413 // Add this partial specialization to the set of class template partial
2416 InstClassTemplate->AddSpecialization(InstD, InsertPos);
2418 // Substitute the nested name specifier, if any.
2419 if (SubstQualifier(D, InstD))
2422 // Build the canonical type that describes the converted template
2423 // arguments of the class template explicit specialization.
2424 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2425 TemplateName(InstClassTemplate), Converted.data(), Converted.size(),
2426 SemaRef.Context.getRecordType(InstD));
2428 // Build the fully-sugared type for this class template
2429 // specialization as the user wrote in the specialization
2430 // itself. This means that we'll pretty-print the type retrieved
2431 // from the specialization's declaration the way that the user
2432 // actually wrote the specialization, rather than formatting the
2433 // name based on the "canonical" representation used to store the
2434 // template arguments in the specialization.
2435 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2436 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2439 InstD->setAccess(D->getAccess());
2440 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2441 InstD->setSpecializationKind(D->getSpecializationKind());
2442 InstD->setTypeAsWritten(WrittenTy);
2443 InstD->setExternLoc(D->getExternLoc());
2444 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2446 Owner->addDecl(InstD);
2448 // Instantiate the members of the class-scope explicit specialization eagerly.
2449 // We don't have support for lazy instantiation of an explicit specialization
2450 // yet, and MSVC eagerly instantiates in this case.
2451 if (D->isThisDeclarationADefinition() &&
2452 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2453 TSK_ImplicitInstantiation,
2460 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2461 VarTemplateSpecializationDecl *D) {
2463 TemplateArgumentListInfo VarTemplateArgsInfo;
2464 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2465 assert(VarTemplate &&
2466 "A template specialization without specialized template?");
2468 // Substitute the current template arguments.
2469 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2470 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2471 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2473 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2474 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2477 // Check that the template argument list is well-formed for this template.
2478 SmallVector<TemplateArgument, 4> Converted;
2479 bool ExpansionIntoFixedList = false;
2480 if (SemaRef.CheckTemplateArgumentList(
2481 VarTemplate, VarTemplate->getLocStart(),
2482 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2483 Converted, &ExpansionIntoFixedList))
2486 // Find the variable template specialization declaration that
2487 // corresponds to these arguments.
2488 void *InsertPos = 0;
2489 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2490 Converted.data(), Converted.size(), InsertPos))
2491 // If we already have a variable template specialization, return it.
2494 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2495 VarTemplateArgsInfo, Converted);
2498 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2499 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2500 const TemplateArgumentListInfo &TemplateArgsInfo,
2501 llvm::ArrayRef<TemplateArgument> Converted) {
2503 // If this is the variable for an anonymous struct or union,
2504 // instantiate the anonymous struct/union type first.
2505 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2506 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2507 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2510 // Do substitution on the type of the declaration
2511 TypeSourceInfo *DI =
2512 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2513 D->getTypeSpecStartLoc(), D->getDeclName());
2517 if (DI->getType()->isFunctionType()) {
2518 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2519 << D->isStaticDataMember() << DI->getType();
2523 // Build the instantiated declaration
2524 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2525 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2526 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2528 Var->setTemplateArgsInfo(TemplateArgsInfo);
2530 VarTemplate->AddSpecialization(Var, InsertPos);
2532 // Substitute the nested name specifier, if any.
2533 if (SubstQualifier(D, Var))
2536 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
2537 Owner, StartingScope);
2542 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2543 llvm_unreachable("@defs is not supported in Objective-C++");
2546 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2547 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2548 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2549 DiagnosticsEngine::Error,
2550 "cannot instantiate %0 yet");
2551 SemaRef.Diag(D->getLocation(), DiagID)
2552 << D->getDeclKindName();
2557 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2558 llvm_unreachable("Unexpected decl");
2561 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
2562 const MultiLevelTemplateArgumentList &TemplateArgs) {
2563 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
2564 if (D->isInvalidDecl())
2567 return Instantiator.Visit(D);
2570 /// \brief Instantiates a nested template parameter list in the current
2571 /// instantiation context.
2573 /// \param L The parameter list to instantiate
2575 /// \returns NULL if there was an error
2576 TemplateParameterList *
2577 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
2578 // Get errors for all the parameters before bailing out.
2579 bool Invalid = false;
2581 unsigned N = L->size();
2582 typedef SmallVector<NamedDecl *, 8> ParamVector;
2585 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2587 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
2588 Params.push_back(D);
2589 Invalid = Invalid || !D || D->isInvalidDecl();
2592 // Clean up if we had an error.
2596 TemplateParameterList *InstL
2597 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2598 L->getLAngleLoc(), &Params.front(), N,
2603 /// \brief Instantiate the declaration of a class template partial
2606 /// \param ClassTemplate the (instantiated) class template that is partially
2607 // specialized by the instantiation of \p PartialSpec.
2609 /// \param PartialSpec the (uninstantiated) class template partial
2610 /// specialization that we are instantiating.
2612 /// \returns The instantiated partial specialization, if successful; otherwise,
2613 /// NULL to indicate an error.
2614 ClassTemplatePartialSpecializationDecl *
2615 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2616 ClassTemplateDecl *ClassTemplate,
2617 ClassTemplatePartialSpecializationDecl *PartialSpec) {
2618 // Create a local instantiation scope for this class template partial
2619 // specialization, which will contain the instantiations of the template
2621 LocalInstantiationScope Scope(SemaRef);
2623 // Substitute into the template parameters of the class template partial
2625 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2626 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2630 // Substitute into the template arguments of the class template partial
2632 const ASTTemplateArgumentListInfo *TemplArgInfo
2633 = PartialSpec->getTemplateArgsAsWritten();
2634 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2635 TemplArgInfo->RAngleLoc);
2636 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2637 TemplArgInfo->NumTemplateArgs,
2638 InstTemplateArgs, TemplateArgs))
2641 // Check that the template argument list is well-formed for this
2643 SmallVector<TemplateArgument, 4> Converted;
2644 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2645 PartialSpec->getLocation(),
2651 // Figure out where to insert this class template partial specialization
2652 // in the member template's set of class template partial specializations.
2653 void *InsertPos = 0;
2654 ClassTemplateSpecializationDecl *PrevDecl
2655 = ClassTemplate->findPartialSpecialization(Converted.data(),
2656 Converted.size(), InsertPos);
2658 // Build the canonical type that describes the converted template
2659 // arguments of the class template partial specialization.
2661 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2665 // Build the fully-sugared type for this class template
2666 // specialization as the user wrote in the specialization
2667 // itself. This means that we'll pretty-print the type retrieved
2668 // from the specialization's declaration the way that the user
2669 // actually wrote the specialization, rather than formatting the
2670 // name based on the "canonical" representation used to store the
2671 // template arguments in the specialization.
2672 TypeSourceInfo *WrittenTy
2673 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2674 TemplateName(ClassTemplate),
2675 PartialSpec->getLocation(),
2680 // We've already seen a partial specialization with the same template
2681 // parameters and template arguments. This can happen, for example, when
2682 // substituting the outer template arguments ends up causing two
2683 // class template partial specializations of a member class template
2684 // to have identical forms, e.g.,
2686 // template<typename T, typename U>
2688 // template<typename X, typename Y> struct Inner;
2689 // template<typename Y> struct Inner<T, Y>;
2690 // template<typename Y> struct Inner<U, Y>;
2693 // Outer<int, int> outer; // error: the partial specializations of Inner
2694 // // have the same signature.
2695 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2696 << WrittenTy->getType();
2697 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2698 << SemaRef.Context.getTypeDeclType(PrevDecl);
2703 // Create the class template partial specialization declaration.
2704 ClassTemplatePartialSpecializationDecl *InstPartialSpec
2705 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2706 PartialSpec->getTagKind(),
2708 PartialSpec->getLocStart(),
2709 PartialSpec->getLocation(),
2717 // Substitute the nested name specifier, if any.
2718 if (SubstQualifier(PartialSpec, InstPartialSpec))
2721 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2722 InstPartialSpec->setTypeAsWritten(WrittenTy);
2724 // Add this partial specialization to the set of class template partial
2726 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
2727 return InstPartialSpec;
2730 /// \brief Instantiate the declaration of a variable template partial
2733 /// \param VarTemplate the (instantiated) variable template that is partially
2734 /// specialized by the instantiation of \p PartialSpec.
2736 /// \param PartialSpec the (uninstantiated) variable template partial
2737 /// specialization that we are instantiating.
2739 /// \returns The instantiated partial specialization, if successful; otherwise,
2740 /// NULL to indicate an error.
2741 VarTemplatePartialSpecializationDecl *
2742 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2743 VarTemplateDecl *VarTemplate,
2744 VarTemplatePartialSpecializationDecl *PartialSpec) {
2745 // Create a local instantiation scope for this variable template partial
2746 // specialization, which will contain the instantiations of the template
2748 LocalInstantiationScope Scope(SemaRef);
2750 // Substitute into the template parameters of the variable template partial
2752 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2753 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2757 // Substitute into the template arguments of the variable template partial
2759 const ASTTemplateArgumentListInfo *TemplArgInfo
2760 = PartialSpec->getTemplateArgsAsWritten();
2761 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2762 TemplArgInfo->RAngleLoc);
2763 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2764 TemplArgInfo->NumTemplateArgs,
2765 InstTemplateArgs, TemplateArgs))
2768 // Check that the template argument list is well-formed for this
2770 SmallVector<TemplateArgument, 4> Converted;
2771 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2772 InstTemplateArgs, false, Converted))
2775 // Figure out where to insert this variable template partial specialization
2776 // in the member template's set of variable template partial specializations.
2777 void *InsertPos = 0;
2778 VarTemplateSpecializationDecl *PrevDecl =
2779 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
2782 // Build the canonical type that describes the converted template
2783 // arguments of the variable template partial specialization.
2784 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2785 TemplateName(VarTemplate), Converted.data(), Converted.size());
2787 // Build the fully-sugared type for this variable template
2788 // specialization as the user wrote in the specialization
2789 // itself. This means that we'll pretty-print the type retrieved
2790 // from the specialization's declaration the way that the user
2791 // actually wrote the specialization, rather than formatting the
2792 // name based on the "canonical" representation used to store the
2793 // template arguments in the specialization.
2794 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2795 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2799 // We've already seen a partial specialization with the same template
2800 // parameters and template arguments. This can happen, for example, when
2801 // substituting the outer template arguments ends up causing two
2802 // variable template partial specializations of a member variable template
2803 // to have identical forms, e.g.,
2805 // template<typename T, typename U>
2807 // template<typename X, typename Y> pair<X,Y> p;
2808 // template<typename Y> pair<T, Y> p;
2809 // template<typename Y> pair<U, Y> p;
2812 // Outer<int, int> outer; // error: the partial specializations of Inner
2813 // // have the same signature.
2814 SemaRef.Diag(PartialSpec->getLocation(),
2815 diag::err_var_partial_spec_redeclared)
2816 << WrittenTy->getType();
2817 SemaRef.Diag(PrevDecl->getLocation(),
2818 diag::note_var_prev_partial_spec_here);
2822 // Do substitution on the type of the declaration
2823 TypeSourceInfo *DI = SemaRef.SubstType(
2824 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2825 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2829 if (DI->getType()->isFunctionType()) {
2830 SemaRef.Diag(PartialSpec->getLocation(),
2831 diag::err_variable_instantiates_to_function)
2832 << PartialSpec->isStaticDataMember() << DI->getType();
2836 // Create the variable template partial specialization declaration.
2837 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2838 VarTemplatePartialSpecializationDecl::Create(
2839 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2840 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2841 DI, PartialSpec->getStorageClass(), Converted.data(),
2842 Converted.size(), InstTemplateArgs);
2844 // Substitute the nested name specifier, if any.
2845 if (SubstQualifier(PartialSpec, InstPartialSpec))
2848 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2849 InstPartialSpec->setTypeAsWritten(WrittenTy);
2851 // Add this partial specialization to the set of variable template partial
2852 // specializations. The instantiation of the initializer is not necessary.
2853 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
2855 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
2856 LateAttrs, Owner, StartingScope);
2858 return InstPartialSpec;
2862 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
2863 SmallVectorImpl<ParmVarDecl *> &Params) {
2864 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2865 assert(OldTInfo && "substituting function without type source info");
2866 assert(Params.empty() && "parameter vector is non-empty at start");
2868 CXXRecordDecl *ThisContext = 0;
2869 unsigned ThisTypeQuals = 0;
2870 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2871 ThisContext = cast<CXXRecordDecl>(Owner);
2872 ThisTypeQuals = Method->getTypeQualifiers();
2875 TypeSourceInfo *NewTInfo
2876 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2877 D->getTypeSpecStartLoc(),
2879 ThisContext, ThisTypeQuals);
2883 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2884 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2885 if (NewTInfo != OldTInfo) {
2886 // Get parameters from the new type info.
2887 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
2888 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
2889 unsigned NewIdx = 0;
2890 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
2891 OldIdx != NumOldParams; ++OldIdx) {
2892 ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
2893 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2895 Optional<unsigned> NumArgumentsInExpansion;
2896 if (OldParam->isParameterPack())
2897 NumArgumentsInExpansion =
2898 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2900 if (!NumArgumentsInExpansion) {
2901 // Simple case: normal parameter, or a parameter pack that's
2902 // instantiated to a (still-dependent) parameter pack.
2903 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
2904 Params.push_back(NewParam);
2905 Scope->InstantiatedLocal(OldParam, NewParam);
2907 // Parameter pack expansion: make the instantiation an argument pack.
2908 Scope->MakeInstantiatedLocalArgPack(OldParam);
2909 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
2910 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
2911 Params.push_back(NewParam);
2912 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2917 // The function type itself was not dependent and therefore no
2918 // substitution occurred. However, we still need to instantiate
2919 // the function parameters themselves.
2920 const FunctionProtoType *OldProto =
2921 cast<FunctionProtoType>(OldProtoLoc.getType());
2922 for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
2923 ParmVarDecl *OldParam = OldProtoLoc.getArg(i);
2925 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
2926 D, D->getLocation(), OldProto->getArgType(i)));
2931 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
2934 Params.push_back(Parm);
2938 // If the type of this function, after ignoring parentheses, is not
2939 // *directly* a function type, then we're instantiating a function that
2940 // was declared via a typedef or with attributes, e.g.,
2942 // typedef int functype(int, int);
2944 // int __cdecl meth(int, int);
2946 // In this case, we'll just go instantiate the ParmVarDecls that we
2947 // synthesized in the method declaration.
2948 SmallVector<QualType, 4> ParamTypes;
2949 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2950 D->getNumParams(), TemplateArgs, ParamTypes,
2958 /// Introduce the instantiated function parameters into the local
2959 /// instantiation scope, and set the parameter names to those used
2960 /// in the template.
2961 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2962 const FunctionDecl *PatternDecl,
2963 LocalInstantiationScope &Scope,
2964 const MultiLevelTemplateArgumentList &TemplateArgs) {
2965 unsigned FParamIdx = 0;
2966 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2967 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2968 if (!PatternParam->isParameterPack()) {
2969 // Simple case: not a parameter pack.
2970 assert(FParamIdx < Function->getNumParams());
2971 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2972 FunctionParam->setDeclName(PatternParam->getDeclName());
2973 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2978 // Expand the parameter pack.
2979 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2980 Optional<unsigned> NumArgumentsInExpansion
2981 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
2982 assert(NumArgumentsInExpansion &&
2983 "should only be called when all template arguments are known");
2984 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
2985 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2986 FunctionParam->setDeclName(PatternParam->getDeclName());
2987 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2993 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2994 const FunctionProtoType *Proto,
2995 const MultiLevelTemplateArgumentList &TemplateArgs) {
2996 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2998 // C++11 [expr.prim.general]p3:
2999 // If a declaration declares a member function or member function
3000 // template of a class X, the expression this is a prvalue of type
3001 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3002 // and the end of the function-definition, member-declarator, or
3004 CXXRecordDecl *ThisContext = 0;
3005 unsigned ThisTypeQuals = 0;
3006 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
3007 ThisContext = Method->getParent();
3008 ThisTypeQuals = Method->getTypeQualifiers();
3010 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
3011 SemaRef.getLangOpts().CPlusPlus11);
3013 // The function has an exception specification or a "noreturn"
3014 // attribute. Substitute into each of the exception types.
3015 SmallVector<QualType, 4> Exceptions;
3016 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
3017 // FIXME: Poor location information!
3018 if (const PackExpansionType *PackExpansion
3019 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
3020 // We have a pack expansion. Instantiate it.
3021 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3022 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
3024 assert(!Unexpanded.empty() &&
3025 "Pack expansion without parameter packs?");
3027 bool Expand = false;
3028 bool RetainExpansion = false;
3029 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
3030 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
3040 // We can't expand this pack expansion into separate arguments yet;
3041 // just substitute into the pattern and create a new pack expansion
3043 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3044 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3046 New->getLocation(), New->getDeclName());
3050 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
3051 Exceptions.push_back(T);
3055 // Substitute into the pack expansion pattern for each template
3056 bool Invalid = false;
3057 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
3058 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
3060 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3062 New->getLocation(), New->getDeclName());
3068 Exceptions.push_back(T);
3078 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
3079 New->getLocation(), New->getDeclName());
3081 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
3084 Exceptions.push_back(T);
3086 Expr *NoexceptExpr = 0;
3087 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
3088 EnterExpressionEvaluationContext Unevaluated(SemaRef,
3089 Sema::ConstantEvaluated);
3090 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
3092 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
3095 NoexceptExpr = E.take();
3096 if (!NoexceptExpr->isTypeDependent() &&
3097 !NoexceptExpr->isValueDependent())
3099 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
3100 0, diag::err_noexcept_needs_constant_expression,
3101 /*AllowFold*/ false).take();
3105 // Rebuild the function type
3106 const FunctionProtoType *NewProto
3107 = New->getType()->getAs<FunctionProtoType>();
3108 assert(NewProto && "Template instantiation without function prototype?");
3110 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
3111 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
3112 EPI.NumExceptions = Exceptions.size();
3113 EPI.Exceptions = Exceptions.data();
3114 EPI.NoexceptExpr = NoexceptExpr;
3116 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
3117 NewProto->getArgTypes(), EPI));
3120 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3121 FunctionDecl *Decl) {
3122 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3123 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3126 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3127 InstantiatingTemplate::ExceptionSpecification());
3128 if (Inst.isInvalid()) {
3129 // We hit the instantiation depth limit. Clear the exception specification
3130 // so that our callers don't have to cope with EST_Uninstantiated.
3131 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3132 EPI.ExceptionSpecType = EST_None;
3133 Decl->setType(Context.getFunctionType(Proto->getResultType(),
3134 Proto->getArgTypes(), EPI));
3138 // Enter the scope of this instantiation. We don't use
3139 // PushDeclContext because we don't have a scope.
3140 Sema::ContextRAII savedContext(*this, Decl);
3141 LocalInstantiationScope Scope(*this);
3143 MultiLevelTemplateArgumentList TemplateArgs =
3144 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
3146 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3147 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
3149 ::InstantiateExceptionSpec(*this, Decl,
3150 Template->getType()->castAs<FunctionProtoType>(),
3154 /// \brief Initializes the common fields of an instantiation function
3155 /// declaration (New) from the corresponding fields of its template (Tmpl).
3157 /// \returns true if there was an error
3159 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3160 FunctionDecl *Tmpl) {
3161 if (Tmpl->isDeleted())
3162 New->setDeletedAsWritten();
3164 // If we are performing substituting explicitly-specified template arguments
3165 // or deduced template arguments into a function template and we reach this
3166 // point, we are now past the point where SFINAE applies and have committed
3167 // to keeping the new function template specialization. We therefore
3168 // convert the active template instantiation for the function template
3169 // into a template instantiation for this specific function template
3170 // specialization, which is not a SFINAE context, so that we diagnose any
3171 // further errors in the declaration itself.
3172 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3173 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3174 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3175 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
3176 if (FunctionTemplateDecl *FunTmpl
3177 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3178 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
3179 "Deduction from the wrong function template?");
3181 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3182 ActiveInst.Entity = New;
3186 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3187 assert(Proto && "Function template without prototype?");
3189 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3190 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3192 // DR1330: In C++11, defer instantiation of a non-trivial
3193 // exception specification.
3194 if (SemaRef.getLangOpts().CPlusPlus11 &&
3195 EPI.ExceptionSpecType != EST_None &&
3196 EPI.ExceptionSpecType != EST_DynamicNone &&
3197 EPI.ExceptionSpecType != EST_BasicNoexcept) {
3198 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3199 if (EPI.ExceptionSpecType == EST_Uninstantiated)
3200 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
3201 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3202 if (EPI.ExceptionSpecType == EST_Unevaluated)
3203 NewEST = EST_Unevaluated;
3205 // Mark the function has having an uninstantiated exception specification.
3206 const FunctionProtoType *NewProto
3207 = New->getType()->getAs<FunctionProtoType>();
3208 assert(NewProto && "Template instantiation without function prototype?");
3209 EPI = NewProto->getExtProtoInfo();
3210 EPI.ExceptionSpecType = NewEST;
3211 EPI.ExceptionSpecDecl = New;
3212 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
3213 New->setType(SemaRef.Context.getFunctionType(
3214 NewProto->getResultType(), NewProto->getArgTypes(), EPI));
3216 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3220 // Get the definition. Leaves the variable unchanged if undefined.
3221 const FunctionDecl *Definition = Tmpl;
3222 Tmpl->isDefined(Definition);
3224 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3225 LateAttrs, StartingScope);
3230 /// \brief Initializes common fields of an instantiated method
3231 /// declaration (New) from the corresponding fields of its template
3234 /// \returns true if there was an error
3236 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
3237 CXXMethodDecl *Tmpl) {
3238 if (InitFunctionInstantiation(New, Tmpl))
3241 New->setAccess(Tmpl->getAccess());
3242 if (Tmpl->isVirtualAsWritten())
3243 New->setVirtualAsWritten(true);
3245 // FIXME: New needs a pointer to Tmpl
3249 /// \brief Instantiate the definition of the given function from its
3252 /// \param PointOfInstantiation the point at which the instantiation was
3253 /// required. Note that this is not precisely a "point of instantiation"
3254 /// for the function, but it's close.
3256 /// \param Function the already-instantiated declaration of a
3257 /// function template specialization or member function of a class template
3260 /// \param Recursive if true, recursively instantiates any functions that
3261 /// are required by this instantiation.
3263 /// \param DefinitionRequired if true, then we are performing an explicit
3264 /// instantiation where the body of the function is required. Complain if
3265 /// there is no such body.
3266 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
3267 FunctionDecl *Function,
3269 bool DefinitionRequired) {
3270 if (Function->isInvalidDecl() || Function->isDefined())
3273 // Never instantiate an explicit specialization except if it is a class scope
3274 // explicit specialization.
3275 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3276 !Function->getClassScopeSpecializationPattern())
3279 // Find the function body that we'll be substituting.
3280 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
3281 assert(PatternDecl && "instantiating a non-template");
3283 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3284 assert(PatternDecl && "template definition is not a template");
3286 // Try to find a defaulted definition
3287 PatternDecl->isDefined(PatternDecl);
3289 assert(PatternDecl && "template definition is not a template");
3291 // Postpone late parsed template instantiations.
3292 if (PatternDecl->isLateTemplateParsed() &&
3293 !LateTemplateParser) {
3294 PendingInstantiations.push_back(
3295 std::make_pair(Function, PointOfInstantiation));
3299 // Call the LateTemplateParser callback if there is a need to late parse
3300 // a templated function definition.
3301 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
3302 LateTemplateParser) {
3303 // FIXME: Optimize to allow individual templates to be deserialized.
3304 if (PatternDecl->isFromASTFile())
3305 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3307 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3308 assert(LPT && "missing LateParsedTemplate");
3309 LateTemplateParser(OpaqueParser, *LPT);
3310 Pattern = PatternDecl->getBody(PatternDecl);
3313 if (!Pattern && !PatternDecl->isDefaulted()) {
3314 if (DefinitionRequired) {
3315 if (Function->getPrimaryTemplate())
3316 Diag(PointOfInstantiation,
3317 diag::err_explicit_instantiation_undefined_func_template)
3318 << Function->getPrimaryTemplate();
3320 Diag(PointOfInstantiation,
3321 diag::err_explicit_instantiation_undefined_member)
3322 << 1 << Function->getDeclName() << Function->getDeclContext();
3325 Diag(PatternDecl->getLocation(),
3326 diag::note_explicit_instantiation_here);
3327 Function->setInvalidDecl();
3328 } else if (Function->getTemplateSpecializationKind()
3329 == TSK_ExplicitInstantiationDefinition) {
3330 PendingInstantiations.push_back(
3331 std::make_pair(Function, PointOfInstantiation));
3337 // C++1y [temp.explicit]p10:
3338 // Except for inline functions, declarations with types deduced from their
3339 // initializer or return value, and class template specializations, other
3340 // explicit instantiation declarations have the effect of suppressing the
3341 // implicit instantiation of the entity to which they refer.
3342 if (Function->getTemplateSpecializationKind()
3343 == TSK_ExplicitInstantiationDeclaration &&
3344 !PatternDecl->isInlined() &&
3345 !PatternDecl->getResultType()->getContainedAutoType())
3348 if (PatternDecl->isInlined())
3349 Function->setImplicitlyInline();
3351 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3352 if (Inst.isInvalid())
3355 // Copy the inner loc start from the pattern.
3356 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3358 // If we're performing recursive template instantiation, create our own
3359 // queue of pending implicit instantiations that we will instantiate later,
3360 // while we're still within our own instantiation context.
3361 SmallVector<VTableUse, 16> SavedVTableUses;
3362 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3363 SavePendingLocalImplicitInstantiationsRAII
3364 SavedPendingLocalImplicitInstantiations(*this);
3366 VTableUses.swap(SavedVTableUses);
3367 PendingInstantiations.swap(SavedPendingInstantiations);
3370 EnterExpressionEvaluationContext EvalContext(*this,
3371 Sema::PotentiallyEvaluated);
3373 // Introduce a new scope where local variable instantiations will be
3374 // recorded, unless we're actually a member function within a local
3375 // class, in which case we need to merge our results with the parent
3376 // scope (of the enclosing function).
3377 bool MergeWithParentScope = false;
3378 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3379 MergeWithParentScope = Rec->isLocalClass();
3381 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3383 if (PatternDecl->isDefaulted())
3384 SetDeclDefaulted(Function, PatternDecl->getLocation());
3386 ActOnStartOfFunctionDef(0, Function);
3388 // Enter the scope of this instantiation. We don't use
3389 // PushDeclContext because we don't have a scope.
3390 Sema::ContextRAII savedContext(*this, Function);
3392 MultiLevelTemplateArgumentList TemplateArgs =
3393 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
3395 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3398 // If this is a constructor, instantiate the member initializers.
3399 if (const CXXConstructorDecl *Ctor =
3400 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3401 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3405 // Instantiate the function body.
3406 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3408 if (Body.isInvalid())
3409 Function->setInvalidDecl();
3411 ActOnFinishFunctionBody(Function, Body.get(),
3412 /*IsInstantiation=*/true);
3414 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3419 DeclGroupRef DG(Function);
3420 Consumer.HandleTopLevelDecl(DG);
3422 // This class may have local implicit instantiations that need to be
3423 // instantiation within this scope.
3424 PerformPendingInstantiations(/*LocalOnly=*/true);
3428 // Define any pending vtables.
3429 DefineUsedVTables();
3431 // Instantiate any pending implicit instantiations found during the
3432 // instantiation of this template.
3433 PerformPendingInstantiations();
3435 // Restore the set of pending vtables.
3436 assert(VTableUses.empty() &&
3437 "VTableUses should be empty before it is discarded.");
3438 VTableUses.swap(SavedVTableUses);
3440 // Restore the set of pending implicit instantiations.
3441 assert(PendingInstantiations.empty() &&
3442 "PendingInstantiations should be empty before it is discarded.");
3443 PendingInstantiations.swap(SavedPendingInstantiations);
3447 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3448 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3449 const TemplateArgumentList &TemplateArgList,
3450 const TemplateArgumentListInfo &TemplateArgsInfo,
3451 SmallVectorImpl<TemplateArgument> &Converted,
3452 SourceLocation PointOfInstantiation, void *InsertPos,
3453 LateInstantiatedAttrVec *LateAttrs,
3454 LocalInstantiationScope *StartingScope) {
3455 if (FromVar->isInvalidDecl())
3458 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3459 if (Inst.isInvalid())
3462 MultiLevelTemplateArgumentList TemplateArgLists;
3463 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3465 // Instantiate the first declaration of the variable template: for a partial
3466 // specialization of a static data member template, the first declaration may
3467 // or may not be the declaration in the class; if it's in the class, we want
3468 // to instantiate a member in the class (a declaration), and if it's outside,
3469 // we want to instantiate a definition.
3470 FromVar = FromVar->getFirstDecl();
3472 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3473 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3476 // TODO: Set LateAttrs and StartingScope ...
3478 return cast_or_null<VarTemplateSpecializationDecl>(
3479 Instantiator.VisitVarTemplateSpecializationDecl(
3480 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3483 /// \brief Instantiates a variable template specialization by completing it
3484 /// with appropriate type information and initializer.
3485 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3486 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3487 const MultiLevelTemplateArgumentList &TemplateArgs) {
3489 // Do substitution on the type of the declaration
3490 TypeSourceInfo *DI =
3491 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
3492 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3496 // Update the type of this variable template specialization.
3497 VarSpec->setType(DI->getType());
3499 // Instantiate the initializer.
3500 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3505 /// BuildVariableInstantiation - Used after a new variable has been created.
3506 /// Sets basic variable data and decides whether to postpone the
3507 /// variable instantiation.
3508 void Sema::BuildVariableInstantiation(
3509 VarDecl *NewVar, VarDecl *OldVar,
3510 const MultiLevelTemplateArgumentList &TemplateArgs,
3511 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3512 LocalInstantiationScope *StartingScope,
3513 bool InstantiatingVarTemplate) {
3515 // If we are instantiating a local extern declaration, the
3516 // instantiation belongs lexically to the containing function.
3517 // If we are instantiating a static data member defined
3518 // out-of-line, the instantiation will have the same lexical
3519 // context (which will be a namespace scope) as the template.
3520 if (OldVar->isLocalExternDecl()) {
3521 NewVar->setLocalExternDecl();
3522 NewVar->setLexicalDeclContext(Owner);
3523 } else if (OldVar->isOutOfLine())
3524 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3525 NewVar->setTSCSpec(OldVar->getTSCSpec());
3526 NewVar->setInitStyle(OldVar->getInitStyle());
3527 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3528 NewVar->setConstexpr(OldVar->isConstexpr());
3529 NewVar->setInitCapture(OldVar->isInitCapture());
3530 NewVar->setPreviousDeclInSameBlockScope(
3531 OldVar->isPreviousDeclInSameBlockScope());
3532 NewVar->setAccess(OldVar->getAccess());
3534 if (!OldVar->isStaticDataMember()) {
3535 if (OldVar->isUsed(false))
3536 NewVar->setIsUsed();
3537 NewVar->setReferenced(OldVar->isReferenced());
3540 // See if the old variable had a type-specifier that defined an anonymous tag.
3541 // If it did, mark the new variable as being the declarator for the new
3543 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3544 TagDecl *OldTag = OldTagType->getDecl();
3545 if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3546 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3547 assert(!NewTag->hasNameForLinkage() &&
3548 !NewTag->hasDeclaratorForAnonDecl());
3549 NewTag->setDeclaratorForAnonDecl(NewVar);
3553 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3555 if (NewVar->hasAttrs())
3556 CheckAlignasUnderalignment(NewVar);
3558 LookupResult Previous(
3559 *this, NewVar->getDeclName(), NewVar->getLocation(),
3560 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3561 : Sema::LookupOrdinaryName,
3562 Sema::ForRedeclaration);
3564 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl()) {
3565 // We have a previous declaration. Use that one, so we merge with the
3567 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3568 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3569 Previous.addDecl(NewPrev);
3570 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3571 OldVar->hasLinkage())
3572 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
3573 CheckVariableDeclaration(NewVar, Previous);
3575 if (!InstantiatingVarTemplate) {
3576 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3577 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
3578 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3581 if (!OldVar->isOutOfLine()) {
3582 if (NewVar->getDeclContext()->isFunctionOrMethod())
3583 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3586 // Link instantiations of static data members back to the template from
3587 // which they were instantiated.
3588 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
3589 NewVar->setInstantiationOfStaticDataMember(OldVar,
3590 TSK_ImplicitInstantiation);
3592 // Delay instantiation of the initializer for variable templates until a
3593 // definition of the variable is needed.
3594 if (!isa<VarTemplateSpecializationDecl>(NewVar) && !InstantiatingVarTemplate)
3595 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3597 // Diagnose unused local variables with dependent types, where the diagnostic
3598 // will have been deferred.
3599 if (!NewVar->isInvalidDecl() &&
3600 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3601 OldVar->getType()->isDependentType())
3602 DiagnoseUnusedDecl(NewVar);
3605 /// \brief Instantiate the initializer of a variable.
3606 void Sema::InstantiateVariableInitializer(
3607 VarDecl *Var, VarDecl *OldVar,
3608 const MultiLevelTemplateArgumentList &TemplateArgs) {
3610 if (Var->getAnyInitializer())
3611 // We already have an initializer in the class.
3614 if (OldVar->getInit()) {
3615 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3616 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3618 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3620 // Instantiate the initializer.
3622 SubstInitializer(OldVar->getInit(), TemplateArgs,
3623 OldVar->getInitStyle() == VarDecl::CallInit);
3624 if (!Init.isInvalid()) {
3625 bool TypeMayContainAuto = true;
3627 bool DirectInit = OldVar->isDirectInit();
3628 AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
3630 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3632 // FIXME: Not too happy about invalidating the declaration
3633 // because of a bogus initializer.
3634 Var->setInvalidDecl();
3637 PopExpressionEvaluationContext();
3638 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3639 !Var->isCXXForRangeDecl())
3640 ActOnUninitializedDecl(Var, false);
3643 /// \brief Instantiate the definition of the given variable from its
3646 /// \param PointOfInstantiation the point at which the instantiation was
3647 /// required. Note that this is not precisely a "point of instantiation"
3648 /// for the function, but it's close.
3650 /// \param Var the already-instantiated declaration of a static member
3651 /// variable of a class template specialization.
3653 /// \param Recursive if true, recursively instantiates any functions that
3654 /// are required by this instantiation.
3656 /// \param DefinitionRequired if true, then we are performing an explicit
3657 /// instantiation where an out-of-line definition of the member variable
3658 /// is required. Complain if there is no such definition.
3659 void Sema::InstantiateStaticDataMemberDefinition(
3660 SourceLocation PointOfInstantiation,
3663 bool DefinitionRequired) {
3664 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3665 DefinitionRequired);
3668 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3669 VarDecl *Var, bool Recursive,
3670 bool DefinitionRequired) {
3671 if (Var->isInvalidDecl())
3674 VarTemplateSpecializationDecl *VarSpec =
3675 dyn_cast<VarTemplateSpecializationDecl>(Var);
3676 VarDecl *PatternDecl = 0, *Def = 0;
3677 MultiLevelTemplateArgumentList TemplateArgs =
3678 getTemplateInstantiationArgs(Var);
3681 // If this is a variable template specialization, make sure that it is
3682 // non-dependent, then find its instantiation pattern.
3683 bool InstantiationDependent = false;
3684 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3685 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3686 "Only instantiate variable template specializations that are "
3687 "not type-dependent");
3688 (void)InstantiationDependent;
3690 // Find the variable initialization that we'll be substituting. If the
3691 // pattern was instantiated from a member template, look back further to
3692 // find the real pattern.
3693 assert(VarSpec->getSpecializedTemplate() &&
3694 "Specialization without specialized template?");
3695 llvm::PointerUnion<VarTemplateDecl *,
3696 VarTemplatePartialSpecializationDecl *> PatternPtr =
3697 VarSpec->getSpecializedTemplateOrPartial();
3698 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
3699 VarTemplatePartialSpecializationDecl *Tmpl =
3700 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3701 while (VarTemplatePartialSpecializationDecl *From =
3702 Tmpl->getInstantiatedFromMember()) {
3703 if (Tmpl->isMemberSpecialization())
3710 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3711 while (VarTemplateDecl *From =
3712 Tmpl->getInstantiatedFromMemberTemplate()) {
3713 if (Tmpl->isMemberSpecialization())
3718 PatternDecl = Tmpl->getTemplatedDecl();
3721 // If this is a static data member template, there might be an
3722 // uninstantiated initializer on the declaration. If so, instantiate
3724 if (PatternDecl->isStaticDataMember() &&
3725 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
3727 // FIXME: Factor out the duplicated instantiation context setup/tear down
3729 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3730 if (Inst.isInvalid())
3733 // If we're performing recursive template instantiation, create our own
3734 // queue of pending implicit instantiations that we will instantiate
3735 // later, while we're still within our own instantiation context.
3736 SmallVector<VTableUse, 16> SavedVTableUses;
3737 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3739 VTableUses.swap(SavedVTableUses);
3740 PendingInstantiations.swap(SavedPendingInstantiations);
3743 LocalInstantiationScope Local(*this);
3745 // Enter the scope of this instantiation. We don't use
3746 // PushDeclContext because we don't have a scope.
3747 ContextRAII PreviousContext(*this, Var->getDeclContext());
3748 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3749 PreviousContext.pop();
3751 // FIXME: Need to inform the ASTConsumer that we instantiated the
3754 // This variable may have local implicit instantiations that need to be
3755 // instantiated within this scope.
3756 PerformPendingInstantiations(/*LocalOnly=*/true);
3761 // Define any newly required vtables.
3762 DefineUsedVTables();
3764 // Instantiate any pending implicit instantiations found during the
3765 // instantiation of this template.
3766 PerformPendingInstantiations();
3768 // Restore the set of pending vtables.
3769 assert(VTableUses.empty() &&
3770 "VTableUses should be empty before it is discarded.");
3771 VTableUses.swap(SavedVTableUses);
3773 // Restore the set of pending implicit instantiations.
3774 assert(PendingInstantiations.empty() &&
3775 "PendingInstantiations should be empty before it is discarded.");
3776 PendingInstantiations.swap(SavedPendingInstantiations);
3780 // Find actual definition
3781 Def = PatternDecl->getDefinition(getASTContext());
3783 // If this is a static data member, find its out-of-line definition.
3784 assert(Var->isStaticDataMember() && "not a static data member?");
3785 PatternDecl = Var->getInstantiatedFromStaticDataMember();
3787 assert(PatternDecl && "data member was not instantiated from a template?");
3788 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3789 Def = PatternDecl->getOutOfLineDefinition();
3792 // If we don't have a definition of the variable template, we won't perform
3793 // any instantiation. Rather, we rely on the user to instantiate this
3794 // definition (or provide a specialization for it) in another translation
3797 if (DefinitionRequired) {
3799 Diag(PointOfInstantiation,
3800 diag::err_explicit_instantiation_undefined_var_template) << Var;
3802 Diag(PointOfInstantiation,
3803 diag::err_explicit_instantiation_undefined_member)
3804 << 2 << Var->getDeclName() << Var->getDeclContext();
3805 Diag(PatternDecl->getLocation(),
3806 diag::note_explicit_instantiation_here);
3808 Var->setInvalidDecl();
3809 } else if (Var->getTemplateSpecializationKind()
3810 == TSK_ExplicitInstantiationDefinition) {
3811 PendingInstantiations.push_back(
3812 std::make_pair(Var, PointOfInstantiation));
3818 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3820 // Never instantiate an explicit specialization.
3821 if (TSK == TSK_ExplicitSpecialization)
3824 // C++11 [temp.explicit]p10:
3825 // Except for inline functions, [...] explicit instantiation declarations
3826 // have the effect of suppressing the implicit instantiation of the entity
3827 // to which they refer.
3828 if (TSK == TSK_ExplicitInstantiationDeclaration)
3831 // Make sure to pass the instantiated variable to the consumer at the end.
3832 struct PassToConsumerRAII {
3833 ASTConsumer &Consumer;
3836 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3837 : Consumer(Consumer), Var(Var) { }
3839 ~PassToConsumerRAII() {
3840 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3842 } PassToConsumerRAII(Consumer, Var);
3844 // If we already have a definition, we're done.
3845 if (VarDecl *Def = Var->getDefinition()) {
3846 // We may be explicitly instantiating something we've already implicitly
3848 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3849 PointOfInstantiation);
3853 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3854 if (Inst.isInvalid())
3857 // If we're performing recursive template instantiation, create our own
3858 // queue of pending implicit instantiations that we will instantiate later,
3859 // while we're still within our own instantiation context.
3860 SmallVector<VTableUse, 16> SavedVTableUses;
3861 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3862 SavePendingLocalImplicitInstantiationsRAII
3863 SavedPendingLocalImplicitInstantiations(*this);
3865 VTableUses.swap(SavedVTableUses);
3866 PendingInstantiations.swap(SavedPendingInstantiations);
3869 // Enter the scope of this instantiation. We don't use
3870 // PushDeclContext because we don't have a scope.
3871 ContextRAII PreviousContext(*this, Var->getDeclContext());
3872 LocalInstantiationScope Local(*this);
3874 VarDecl *OldVar = Var;
3876 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
3878 else if (Var->isStaticDataMember() &&
3879 Var->getLexicalDeclContext()->isRecord()) {
3880 // We need to instantiate the definition of a static data member template,
3881 // and all we have is the in-class declaration of it. Instantiate a separate
3882 // declaration of the definition.
3883 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3885 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
3886 VarSpec->getSpecializedTemplate(), Def, 0,
3887 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3889 llvm::PointerUnion<VarTemplateDecl *,
3890 VarTemplatePartialSpecializationDecl *> PatternPtr =
3891 VarSpec->getSpecializedTemplateOrPartial();
3892 if (VarTemplatePartialSpecializationDecl *Partial =
3893 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3894 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3895 Partial, &VarSpec->getTemplateInstantiationArgs());
3897 // Merge the definition with the declaration.
3898 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3899 LookupOrdinaryName, ForRedeclaration);
3901 MergeVarDecl(Var, R);
3903 // Attach the initializer.
3904 InstantiateVariableInitializer(Var, Def, TemplateArgs);
3907 // Complete the existing variable's definition with an appropriately
3908 // substituted type and initializer.
3909 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
3911 PreviousContext.pop();
3914 PassToConsumerRAII.Var = Var;
3915 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3916 OldVar->getPointOfInstantiation());
3919 // This variable may have local implicit instantiations that need to be
3920 // instantiated within this scope.
3921 PerformPendingInstantiations(/*LocalOnly=*/true);
3926 // Define any newly required vtables.
3927 DefineUsedVTables();
3929 // Instantiate any pending implicit instantiations found during the
3930 // instantiation of this template.
3931 PerformPendingInstantiations();
3933 // Restore the set of pending vtables.
3934 assert(VTableUses.empty() &&
3935 "VTableUses should be empty before it is discarded.");
3936 VTableUses.swap(SavedVTableUses);
3938 // Restore the set of pending implicit instantiations.
3939 assert(PendingInstantiations.empty() &&
3940 "PendingInstantiations should be empty before it is discarded.");
3941 PendingInstantiations.swap(SavedPendingInstantiations);
3946 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3947 const CXXConstructorDecl *Tmpl,
3948 const MultiLevelTemplateArgumentList &TemplateArgs) {
3950 SmallVector<CXXCtorInitializer*, 4> NewInits;
3951 bool AnyErrors = Tmpl->isInvalidDecl();
3953 // Instantiate all the initializers.
3954 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
3955 InitsEnd = Tmpl->init_end();
3956 Inits != InitsEnd; ++Inits) {
3957 CXXCtorInitializer *Init = *Inits;
3959 // Only instantiate written initializers, let Sema re-construct implicit
3961 if (!Init->isWritten())
3964 SourceLocation EllipsisLoc;
3966 if (Init->isPackExpansion()) {
3967 // This is a pack expansion. We should expand it now.
3968 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
3969 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
3970 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
3971 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
3972 bool ShouldExpand = false;
3973 bool RetainExpansion = false;
3974 Optional<unsigned> NumExpansions;
3975 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
3976 BaseTL.getSourceRange(),
3978 TemplateArgs, ShouldExpand,
3982 New->setInvalidDecl();
3985 assert(ShouldExpand && "Partial instantiation of base initializer?");
3987 // Loop over all of the arguments in the argument pack(s),
3988 for (unsigned I = 0; I != *NumExpansions; ++I) {
3989 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3991 // Instantiate the initializer.
3992 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3993 /*CXXDirectInit=*/true);
3994 if (TempInit.isInvalid()) {
3999 // Instantiate the base type.
4000 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4002 Init->getSourceLocation(),
4003 New->getDeclName());
4009 // Build the initializer.
4010 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4011 BaseTInfo, TempInit.take(),
4014 if (NewInit.isInvalid()) {
4019 NewInits.push_back(NewInit.get());
4025 // Instantiate the initializer.
4026 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4027 /*CXXDirectInit=*/true);
4028 if (TempInit.isInvalid()) {
4033 MemInitResult NewInit;
4034 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4035 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4037 Init->getSourceLocation(),
4038 New->getDeclName());
4041 New->setInvalidDecl();
4045 if (Init->isBaseInitializer())
4046 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
4047 New->getParent(), EllipsisLoc);
4049 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
4050 cast<CXXRecordDecl>(CurContext->getParent()));
4051 } else if (Init->isMemberInitializer()) {
4052 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
4053 Init->getMemberLocation(),
4058 New->setInvalidDecl();
4062 NewInit = BuildMemberInitializer(Member, TempInit.take(),
4063 Init->getSourceLocation());
4064 } else if (Init->isIndirectMemberInitializer()) {
4065 IndirectFieldDecl *IndirectMember =
4066 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
4067 Init->getMemberLocation(),
4068 Init->getIndirectMember(), TemplateArgs));
4070 if (!IndirectMember) {
4072 New->setInvalidDecl();
4076 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
4077 Init->getSourceLocation());
4080 if (NewInit.isInvalid()) {
4082 New->setInvalidDecl();
4084 NewInits.push_back(NewInit.get());
4088 // Assign all the initializers to the new constructor.
4089 ActOnMemInitializers(New,
4090 /*FIXME: ColonLoc */
4096 // TODO: this could be templated if the various decl types used the
4097 // same method name.
4098 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4099 ClassTemplateDecl *Instance) {
4100 Pattern = Pattern->getCanonicalDecl();
4103 Instance = Instance->getCanonicalDecl();
4104 if (Pattern == Instance) return true;
4105 Instance = Instance->getInstantiatedFromMemberTemplate();
4111 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4112 FunctionTemplateDecl *Instance) {
4113 Pattern = Pattern->getCanonicalDecl();
4116 Instance = Instance->getCanonicalDecl();
4117 if (Pattern == Instance) return true;
4118 Instance = Instance->getInstantiatedFromMemberTemplate();
4125 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4126 ClassTemplatePartialSpecializationDecl *Instance) {
4128 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4130 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4131 Instance->getCanonicalDecl());
4132 if (Pattern == Instance)
4134 Instance = Instance->getInstantiatedFromMember();
4140 static bool isInstantiationOf(CXXRecordDecl *Pattern,
4141 CXXRecordDecl *Instance) {
4142 Pattern = Pattern->getCanonicalDecl();
4145 Instance = Instance->getCanonicalDecl();
4146 if (Pattern == Instance) return true;
4147 Instance = Instance->getInstantiatedFromMemberClass();
4153 static bool isInstantiationOf(FunctionDecl *Pattern,
4154 FunctionDecl *Instance) {
4155 Pattern = Pattern->getCanonicalDecl();
4158 Instance = Instance->getCanonicalDecl();
4159 if (Pattern == Instance) return true;
4160 Instance = Instance->getInstantiatedFromMemberFunction();
4166 static bool isInstantiationOf(EnumDecl *Pattern,
4167 EnumDecl *Instance) {
4168 Pattern = Pattern->getCanonicalDecl();
4171 Instance = Instance->getCanonicalDecl();
4172 if (Pattern == Instance) return true;
4173 Instance = Instance->getInstantiatedFromMemberEnum();
4179 static bool isInstantiationOf(UsingShadowDecl *Pattern,
4180 UsingShadowDecl *Instance,
4182 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
4185 static bool isInstantiationOf(UsingDecl *Pattern,
4186 UsingDecl *Instance,
4188 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4191 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4192 UsingDecl *Instance,
4194 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4197 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
4198 UsingDecl *Instance,
4200 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4203 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4204 VarDecl *Instance) {
4205 assert(Instance->isStaticDataMember());
4207 Pattern = Pattern->getCanonicalDecl();
4210 Instance = Instance->getCanonicalDecl();
4211 if (Pattern == Instance) return true;
4212 Instance = Instance->getInstantiatedFromStaticDataMember();
4218 // Other is the prospective instantiation
4219 // D is the prospective pattern
4220 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
4221 if (D->getKind() != Other->getKind()) {
4222 if (UnresolvedUsingTypenameDecl *UUD
4223 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4224 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4225 return isInstantiationOf(UUD, UD, Ctx);
4229 if (UnresolvedUsingValueDecl *UUD
4230 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4231 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4232 return isInstantiationOf(UUD, UD, Ctx);
4239 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4240 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
4242 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4243 return isInstantiationOf(cast<FunctionDecl>(D), Function);
4245 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4246 return isInstantiationOf(cast<EnumDecl>(D), Enum);
4248 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
4249 if (Var->isStaticDataMember())
4250 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4252 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4253 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
4255 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4256 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4258 if (ClassTemplatePartialSpecializationDecl *PartialSpec
4259 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4260 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4263 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4264 if (!Field->getDeclName()) {
4265 // This is an unnamed field.
4266 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
4271 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4272 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4274 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4275 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4277 return D->getDeclName() && isa<NamedDecl>(Other) &&
4278 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4281 template<typename ForwardIterator>
4282 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
4284 ForwardIterator first,
4285 ForwardIterator last) {
4286 for (; first != last; ++first)
4287 if (isInstantiationOf(Ctx, D, *first))
4288 return cast<NamedDecl>(*first);
4293 /// \brief Finds the instantiation of the given declaration context
4294 /// within the current instantiation.
4296 /// \returns NULL if there was an error
4297 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
4298 const MultiLevelTemplateArgumentList &TemplateArgs) {
4299 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
4300 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
4301 return cast_or_null<DeclContext>(ID);
4305 /// \brief Find the instantiation of the given declaration within the
4306 /// current instantiation.
4308 /// This routine is intended to be used when \p D is a declaration
4309 /// referenced from within a template, that needs to mapped into the
4310 /// corresponding declaration within an instantiation. For example,
4314 /// template<typename T>
4317 /// KnownValue = sizeof(T)
4320 /// bool getKind() const { return KnownValue; }
4323 /// template struct X<int>;
4326 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4327 /// \p EnumConstantDecl for \p KnownValue (which refers to
4328 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4329 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4330 /// this mapping from within the instantiation of <tt>X<int></tt>.
4331 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4332 const MultiLevelTemplateArgumentList &TemplateArgs) {
4333 DeclContext *ParentDC = D->getDeclContext();
4334 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4335 // parameters (p below) can have their ParentDC set to the translation-unit
4336 // - thus we can not consistently check if the ParentDC of such a parameter
4337 // is Dependent or/and a FunctionOrMethod.
4338 // For e.g. this code, during Template argument deduction tries to
4339 // find an instantiated decl for (T y) when the ParentDC for y is
4340 // the translation unit.
4341 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
4342 // float baz(float(*)()) { return 0.0; }
\r
4344 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4345 // it gets here, always has a FunctionOrMethod as its ParentDC??
4347 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4348 // whose type is not instantiation dependent, do nothing to the decl
4349 // - otherwise find its instantiated decl.
4350 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4351 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4353 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
4354 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
4355 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4356 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
4357 // D is a local of some kind. Look into the map of local
4358 // declarations to their instantiations.
4359 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4360 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4361 = CurrentInstantiationScope->findInstantiationOf(D);
4364 if (Decl *FD = Found->dyn_cast<Decl *>())
4365 return cast<NamedDecl>(FD);
4367 int PackIdx = ArgumentPackSubstitutionIndex;
4368 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
4369 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4372 // If we're performing a partial substitution during template argument
4373 // deduction, we may not have values for template parameters yet. They
4374 // just map to themselves.
4375 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4376 isa<TemplateTemplateParmDecl>(D))
4379 if (D->isInvalidDecl())
4382 // If we didn't find the decl, then we must have a label decl that hasn't
4383 // been found yet. Lazily instantiate it and return it now.
4384 assert(isa<LabelDecl>(D));
4386 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4387 assert(Inst && "Failed to instantiate label??");
4389 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4390 return cast<LabelDecl>(Inst);
4393 // For variable template specializations, update those that are still
4395 if (VarTemplateSpecializationDecl *VarSpec =
4396 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4397 bool InstantiationDependent = false;
4398 const TemplateArgumentListInfo &VarTemplateArgs =
4399 VarSpec->getTemplateArgsInfo();
4400 if (TemplateSpecializationType::anyDependentTemplateArguments(
4401 VarTemplateArgs, InstantiationDependent))
4402 D = cast<NamedDecl>(
4403 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4407 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4408 if (!Record->isDependentContext())
4411 // Determine whether this record is the "templated" declaration describing
4412 // a class template or class template partial specialization.
4413 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
4415 ClassTemplate = ClassTemplate->getCanonicalDecl();
4416 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4417 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4418 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
4420 // Walk the current context to find either the record or an instantiation of
4422 DeclContext *DC = CurContext;
4423 while (!DC->isFileContext()) {
4424 // If we're performing substitution while we're inside the template
4425 // definition, we'll find our own context. We're done.
4426 if (DC->Equals(Record))
4429 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4430 // Check whether we're in the process of instantiating a class template
4431 // specialization of the template we're mapping.
4432 if (ClassTemplateSpecializationDecl *InstSpec
4433 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4434 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4435 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4439 // Check whether we're in the process of instantiating a member class.
4440 if (isInstantiationOf(Record, InstRecord))
4444 // Move to the outer template scope.
4445 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4446 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4447 DC = FD->getLexicalDeclContext();
4452 DC = DC->getParent();
4455 // Fall through to deal with other dependent record types (e.g.,
4456 // anonymous unions in class templates).
4459 if (!ParentDC->isDependentContext())
4462 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
4466 if (ParentDC != D->getDeclContext()) {
4467 // We performed some kind of instantiation in the parent context,
4468 // so now we need to look into the instantiated parent context to
4469 // find the instantiation of the declaration D.
4471 // If our context used to be dependent, we may need to instantiate
4472 // it before performing lookup into that context.
4473 bool IsBeingInstantiated = false;
4474 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
4475 if (!Spec->isDependentContext()) {
4476 QualType T = Context.getTypeDeclType(Spec);
4477 const RecordType *Tag = T->getAs<RecordType>();
4478 assert(Tag && "type of non-dependent record is not a RecordType");
4479 if (Tag->isBeingDefined())
4480 IsBeingInstantiated = true;
4481 if (!Tag->isBeingDefined() &&
4482 RequireCompleteType(Loc, T, diag::err_incomplete_type))
4485 ParentDC = Tag->getDecl();
4489 NamedDecl *Result = 0;
4490 if (D->getDeclName()) {
4491 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
4492 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
4494 // Since we don't have a name for the entity we're looking for,
4495 // our only option is to walk through all of the declarations to
4496 // find that name. This will occur in a few cases:
4498 // - anonymous struct/union within a template
4499 // - unnamed class/struct/union/enum within a template
4501 // FIXME: Find a better way to find these instantiations!
4502 Result = findInstantiationOf(Context, D,
4503 ParentDC->decls_begin(),
4504 ParentDC->decls_end());
4508 if (isa<UsingShadowDecl>(D)) {
4509 // UsingShadowDecls can instantiate to nothing because of using hiding.
4510 } else if (Diags.hasErrorOccurred()) {
4511 // We've already complained about something, so most likely this
4512 // declaration failed to instantiate. There's no point in complaining
4513 // further, since this is normal in invalid code.
4514 } else if (IsBeingInstantiated) {
4515 // The class in which this member exists is currently being
4516 // instantiated, and we haven't gotten around to instantiating this
4517 // member yet. This can happen when the code uses forward declarations
4518 // of member classes, and introduces ordering dependencies via
4519 // template instantiation.
4520 Diag(Loc, diag::err_member_not_yet_instantiated)
4522 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4523 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
4524 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4525 // This enumeration constant was found when the template was defined,
4526 // but can't be found in the instantiation. This can happen if an
4527 // unscoped enumeration member is explicitly specialized.
4528 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4529 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4531 assert(Spec->getTemplateSpecializationKind() ==
4532 TSK_ExplicitSpecialization);
4533 Diag(Loc, diag::err_enumerator_does_not_exist)
4535 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4536 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4537 << Context.getTypeDeclType(Spec);
4539 // We should have found something, but didn't.
4540 llvm_unreachable("Unable to find instantiation of declaration!");
4550 /// \brief Performs template instantiation for all implicit template
4551 /// instantiations we have seen until this point.
4552 void Sema::PerformPendingInstantiations(bool LocalOnly) {
4553 // Load pending instantiations from the external source.
4554 if (!LocalOnly && ExternalSource) {
4555 SmallVector<PendingImplicitInstantiation, 4> Pending;
4556 ExternalSource->ReadPendingInstantiations(Pending);
4557 PendingInstantiations.insert(PendingInstantiations.begin(),
4558 Pending.begin(), Pending.end());
4561 while (!PendingLocalImplicitInstantiations.empty() ||
4562 (!LocalOnly && !PendingInstantiations.empty())) {
4563 PendingImplicitInstantiation Inst;
4565 if (PendingLocalImplicitInstantiations.empty()) {
4566 Inst = PendingInstantiations.front();
4567 PendingInstantiations.pop_front();
4569 Inst = PendingLocalImplicitInstantiations.front();
4570 PendingLocalImplicitInstantiations.pop_front();
4573 // Instantiate function definitions
4574 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
4575 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4576 "instantiating function definition");
4577 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4578 TSK_ExplicitInstantiationDefinition;
4579 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4580 DefinitionRequired);
4584 // Instantiate variable definitions
4585 VarDecl *Var = cast<VarDecl>(Inst.first);
4587 assert((Var->isStaticDataMember() ||
4588 isa<VarTemplateSpecializationDecl>(Var)) &&
4589 "Not a static data member, nor a variable template"
4590 " specialization?");
4592 // Don't try to instantiate declarations if the most recent redeclaration
4594 if (Var->getMostRecentDecl()->isInvalidDecl())
4597 // Check if the most recent declaration has changed the specialization kind
4598 // and removed the need for implicit instantiation.
4599 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
4600 case TSK_Undeclared:
4601 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
4602 case TSK_ExplicitInstantiationDeclaration:
4603 case TSK_ExplicitSpecialization:
4604 continue; // No longer need to instantiate this type.
4605 case TSK_ExplicitInstantiationDefinition:
4606 // We only need an instantiation if the pending instantiation *is* the
4607 // explicit instantiation.
4608 if (Var != Var->getMostRecentDecl()) continue;
4609 case TSK_ImplicitInstantiation:
4613 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4614 "instantiating variable definition");
4615 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4616 TSK_ExplicitInstantiationDefinition;
4618 // Instantiate static data member definitions or variable template
4620 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4621 DefinitionRequired);
4625 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4626 const MultiLevelTemplateArgumentList &TemplateArgs) {
4627 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
4628 E = Pattern->ddiag_end(); I != E; ++I) {
4629 DependentDiagnostic *DD = *I;
4631 switch (DD->getKind()) {
4632 case DependentDiagnostic::Access:
4633 HandleDependentAccessCheck(*DD, TemplateArgs);