1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
9 // This file implements C++ template instantiation for declarations.
11 //===----------------------------------------------------------------------===/
12 #include "clang/Sema/SemaInternal.h"
13 #include "clang/Sema/Lookup.h"
14 #include "clang/Sema/PrettyDeclStackTrace.h"
15 #include "clang/Sema/Template.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/DependentDiagnostic.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/Lex/Preprocessor.h"
26 using namespace clang;
28 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29 DeclaratorDecl *NewDecl) {
30 if (!OldDecl->getQualifierLoc())
33 NestedNameSpecifierLoc NewQualifierLoc
34 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
40 NewDecl->setQualifierInfo(NewQualifierLoc);
44 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
46 if (!OldDecl->getQualifierLoc())
49 NestedNameSpecifierLoc NewQualifierLoc
50 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
56 NewDecl->setQualifierInfo(NewQualifierLoc);
60 // Include attribute instantiation code.
61 #include "clang/Sema/AttrTemplateInstantiate.inc"
63 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
64 const Decl *Tmpl, Decl *New,
65 LateInstantiatedAttrVec *LateAttrs,
66 LocalInstantiationScope *OuterMostScope) {
67 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
69 const Attr *TmplAttr = *i;
71 // FIXME: This should be generalized to more than just the AlignedAttr.
72 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
73 if (Aligned->isAlignmentDependent()) {
74 if (Aligned->isAlignmentExpr()) {
75 // The alignment expression is a constant expression.
76 EnterExpressionEvaluationContext Unevaluated(*this,
77 Sema::ConstantEvaluated);
79 ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
81 if (!Result.isInvalid())
82 AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>());
84 TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
86 Aligned->getLocation(),
89 AddAlignedAttr(Aligned->getLocation(), New, Result);
95 if (TmplAttr->isLateParsed() && LateAttrs) {
96 // Late parsed attributes must be instantiated and attached after the
97 // enclosing class has been instantiated. See Sema::InstantiateClass.
98 LocalInstantiationScope *Saved = 0;
99 if (CurrentInstantiationScope)
100 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
101 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
103 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
104 *this, TemplateArgs);
105 New->addAttr(NewAttr);
111 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
112 llvm_unreachable("Translation units cannot be instantiated");
116 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
117 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
119 Owner->addDecl(Inst);
124 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
125 llvm_unreachable("Namespaces cannot be instantiated");
129 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
130 NamespaceAliasDecl *Inst
131 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
132 D->getNamespaceLoc(),
135 D->getQualifierLoc(),
136 D->getTargetNameLoc(),
138 Owner->addDecl(Inst);
142 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
144 bool Invalid = false;
145 TypeSourceInfo *DI = D->getTypeSourceInfo();
146 if (DI->getType()->isInstantiationDependentType() ||
147 DI->getType()->isVariablyModifiedType()) {
148 DI = SemaRef.SubstType(DI, TemplateArgs,
149 D->getLocation(), D->getDeclName());
152 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
155 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
158 // Create the new typedef
159 TypedefNameDecl *Typedef;
161 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
162 D->getLocation(), D->getIdentifier(), DI);
164 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
165 D->getLocation(), D->getIdentifier(), DI);
167 Typedef->setInvalidDecl();
169 // If the old typedef was the name for linkage purposes of an anonymous
170 // tag decl, re-establish that relationship for the new typedef.
171 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
172 TagDecl *oldTag = oldTagType->getDecl();
173 if (oldTag->getTypedefNameForAnonDecl() == D) {
174 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
175 assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
176 newTag->setTypedefNameForAnonDecl(Typedef);
180 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
181 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
186 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
188 // If the typedef types are not identical, reject them.
189 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
191 Typedef->setPreviousDeclaration(InstPrevTypedef);
194 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
196 Typedef->setAccess(D->getAccess());
201 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
202 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
203 Owner->addDecl(Typedef);
207 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
208 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
209 Owner->addDecl(Typedef);
214 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
215 // Create a local instantiation scope for this type alias template, which
216 // will contain the instantiations of the template parameters.
217 LocalInstantiationScope Scope(SemaRef);
219 TemplateParameterList *TempParams = D->getTemplateParameters();
220 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
224 TypeAliasDecl *Pattern = D->getTemplatedDecl();
226 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
227 if (Pattern->getPreviousDecl()) {
228 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
229 if (Found.first != Found.second) {
230 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first);
234 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
235 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
239 TypeAliasTemplateDecl *Inst
240 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
241 D->getDeclName(), InstParams, AliasInst);
242 if (PrevAliasTemplate)
243 Inst->setPreviousDeclaration(PrevAliasTemplate);
245 Inst->setAccess(D->getAccess());
247 if (!PrevAliasTemplate)
248 Inst->setInstantiatedFromMemberTemplate(D);
250 Owner->addDecl(Inst);
255 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
256 // If this is the variable for an anonymous struct or union,
257 // instantiate the anonymous struct/union type first.
258 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
259 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
260 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
263 // Do substitution on the type of the declaration
264 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
266 D->getTypeSpecStartLoc(),
271 if (DI->getType()->isFunctionType()) {
272 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
273 << D->isStaticDataMember() << DI->getType();
277 // Build the instantiated declaration
278 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
279 D->getInnerLocStart(),
280 D->getLocation(), D->getIdentifier(),
282 D->getStorageClass(),
283 D->getStorageClassAsWritten());
284 Var->setThreadSpecified(D->isThreadSpecified());
285 Var->setInitStyle(D->getInitStyle());
286 Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
287 Var->setConstexpr(D->isConstexpr());
289 // Substitute the nested name specifier, if any.
290 if (SubstQualifier(D, Var))
293 // If we are instantiating a static data member defined
294 // out-of-line, the instantiation will have the same lexical
295 // context (which will be a namespace scope) as the template.
296 if (D->isOutOfLine())
297 Var->setLexicalDeclContext(D->getLexicalDeclContext());
299 Var->setAccess(D->getAccess());
301 if (!D->isStaticDataMember()) {
302 Var->setUsed(D->isUsed(false));
303 Var->setReferenced(D->isReferenced());
306 // FIXME: In theory, we could have a previous declaration for variables that
307 // are not static data members.
308 // FIXME: having to fake up a LookupResult is dumb.
309 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
310 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
311 if (D->isStaticDataMember())
312 SemaRef.LookupQualifiedName(Previous, Owner, false);
314 // In ARC, infer 'retaining' for variables of retainable type.
315 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
316 SemaRef.inferObjCARCLifetime(Var))
317 Var->setInvalidDecl();
319 SemaRef.CheckVariableDeclaration(Var, Previous);
321 if (D->isOutOfLine()) {
322 D->getLexicalDeclContext()->addDecl(Var);
323 Owner->makeDeclVisibleInContext(Var);
326 if (Owner->isFunctionOrMethod())
327 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
329 SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
331 // Link instantiations of static data members back to the template from
332 // which they were instantiated.
333 if (Var->isStaticDataMember())
334 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
335 TSK_ImplicitInstantiation);
337 if (Var->getAnyInitializer()) {
338 // We already have an initializer in the class.
339 } else if (D->getInit()) {
340 if (Var->isStaticDataMember() && !D->isOutOfLine())
341 SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated);
343 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
345 // Instantiate the initializer.
346 ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
347 D->getInitStyle() == VarDecl::CallInit);
348 if (!Init.isInvalid()) {
349 bool TypeMayContainAuto = true;
351 bool DirectInit = D->isDirectInit();
352 SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
355 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
357 // FIXME: Not too happy about invalidating the declaration
358 // because of a bogus initializer.
359 Var->setInvalidDecl();
362 SemaRef.PopExpressionEvaluationContext();
363 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
364 !Var->isCXXForRangeDecl())
365 SemaRef.ActOnUninitializedDecl(Var, false);
367 // Diagnose unused local variables with dependent types, where the diagnostic
368 // will have been deferred.
369 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
370 D->getType()->isDependentType())
371 SemaRef.DiagnoseUnusedDecl(Var);
376 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
378 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
379 D->getAccessSpecifierLoc(), D->getColonLoc());
380 Owner->addHiddenDecl(AD);
384 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
385 bool Invalid = false;
386 TypeSourceInfo *DI = D->getTypeSourceInfo();
387 if (DI->getType()->isInstantiationDependentType() ||
388 DI->getType()->isVariablyModifiedType()) {
389 DI = SemaRef.SubstType(DI, TemplateArgs,
390 D->getLocation(), D->getDeclName());
392 DI = D->getTypeSourceInfo();
394 } else if (DI->getType()->isFunctionType()) {
395 // C++ [temp.arg.type]p3:
396 // If a declaration acquires a function type through a type
397 // dependent on a template-parameter and this causes a
398 // declaration that does not use the syntactic form of a
399 // function declarator to have function type, the program is
401 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
406 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
409 Expr *BitWidth = D->getBitWidth();
413 // The bit-width expression is a constant expression.
414 EnterExpressionEvaluationContext Unevaluated(SemaRef,
415 Sema::ConstantEvaluated);
417 ExprResult InstantiatedBitWidth
418 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
419 if (InstantiatedBitWidth.isInvalid()) {
423 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
426 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
428 cast<RecordDecl>(Owner),
432 D->hasInClassInitializer(),
433 D->getTypeSpecStartLoc(),
437 cast<Decl>(Owner)->setInvalidDecl();
441 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
444 Field->setInvalidDecl();
446 if (!Field->getDeclName()) {
447 // Keep track of where this decl came from.
448 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
450 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
451 if (Parent->isAnonymousStructOrUnion() &&
452 Parent->getRedeclContext()->isFunctionOrMethod())
453 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
456 Field->setImplicit(D->isImplicit());
457 Field->setAccess(D->getAccess());
458 Owner->addDecl(Field);
463 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
464 NamedDecl **NamedChain =
465 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
468 for (IndirectFieldDecl::chain_iterator PI =
469 D->chain_begin(), PE = D->chain_end();
471 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
476 NamedChain[i++] = Next;
479 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
480 IndirectFieldDecl* IndirectField
481 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
482 D->getIdentifier(), T,
483 NamedChain, D->getChainingSize());
486 IndirectField->setImplicit(D->isImplicit());
487 IndirectField->setAccess(D->getAccess());
488 Owner->addDecl(IndirectField);
489 return IndirectField;
492 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
493 // Handle friend type expressions by simply substituting template
494 // parameters into the pattern type and checking the result.
495 if (TypeSourceInfo *Ty = D->getFriendType()) {
496 TypeSourceInfo *InstTy;
497 // If this is an unsupported friend, don't bother substituting template
498 // arguments into it. The actual type referred to won't be used by any
499 // parts of Clang, and may not be valid for instantiating. Just use the
500 // same info for the instantiated friend.
501 if (D->isUnsupportedFriend()) {
504 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
505 D->getLocation(), DeclarationName());
510 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocation(),
511 D->getFriendLoc(), InstTy);
515 FD->setAccess(AS_public);
516 FD->setUnsupportedFriend(D->isUnsupportedFriend());
521 NamedDecl *ND = D->getFriendDecl();
522 assert(ND && "friend decl must be a decl or a type!");
524 // All of the Visit implementations for the various potential friend
525 // declarations have to be carefully written to work for friend
526 // objects, with the most important detail being that the target
527 // decl should almost certainly not be placed in Owner.
528 Decl *NewND = Visit(ND);
529 if (!NewND) return 0;
532 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
533 cast<NamedDecl>(NewND), D->getFriendLoc());
534 FD->setAccess(AS_public);
535 FD->setUnsupportedFriend(D->isUnsupportedFriend());
540 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
541 Expr *AssertExpr = D->getAssertExpr();
543 // The expression in a static assertion is a constant expression.
544 EnterExpressionEvaluationContext Unevaluated(SemaRef,
545 Sema::ConstantEvaluated);
547 ExprResult InstantiatedAssertExpr
548 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
549 if (InstantiatedAssertExpr.isInvalid())
552 ExprResult Message(D->getMessage());
554 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
555 InstantiatedAssertExpr.get(),
560 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
561 EnumDecl *PrevDecl = 0;
562 if (D->getPreviousDecl()) {
563 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
564 D->getPreviousDecl(),
567 PrevDecl = cast<EnumDecl>(Prev);
570 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
571 D->getLocation(), D->getIdentifier(),
572 PrevDecl, D->isScoped(),
573 D->isScopedUsingClassTag(), D->isFixed());
575 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
576 // If we have type source information for the underlying type, it means it
577 // has been explicitly set by the user. Perform substitution on it before
579 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
580 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
582 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
583 Enum->setIntegerType(SemaRef.Context.IntTy);
585 Enum->setIntegerTypeSourceInfo(NewTI);
587 assert(!D->getIntegerType()->isDependentType()
588 && "Dependent type without type source info");
589 Enum->setIntegerType(D->getIntegerType());
593 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
595 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
596 Enum->setAccess(D->getAccess());
597 if (SubstQualifier(D, Enum)) return 0;
598 Owner->addDecl(Enum);
600 EnumDecl *Def = D->getDefinition();
601 if (Def && Def != D) {
602 // If this is an out-of-line definition of an enum member template, check
603 // that the underlying types match in the instantiation of both
605 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
606 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
607 QualType DefnUnderlying =
608 SemaRef.SubstType(TI->getType(), TemplateArgs,
609 UnderlyingLoc, DeclarationName());
610 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
611 DefnUnderlying, Enum);
615 if (D->getDeclContext()->isFunctionOrMethod())
616 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
618 // C++11 [temp.inst]p1: The implicit instantiation of a class template
619 // specialization causes the implicit instantiation of the declarations, but
620 // not the definitions of scoped member enumerations.
621 // FIXME: There appears to be no wording for what happens for an enum defined
622 // within a block scope, but we treat that much like a member template. Only
623 // instantiate the definition when visiting the definition in that case, since
624 // we will visit all redeclarations.
625 if (!Enum->isScoped() && Def &&
626 (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
627 InstantiateEnumDefinition(Enum, Def);
632 void TemplateDeclInstantiator::InstantiateEnumDefinition(
633 EnumDecl *Enum, EnumDecl *Pattern) {
634 Enum->startDefinition();
636 // Update the location to refer to the definition.
637 Enum->setLocation(Pattern->getLocation());
639 SmallVector<Decl*, 4> Enumerators;
641 EnumConstantDecl *LastEnumConst = 0;
642 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
643 ECEnd = Pattern->enumerator_end();
645 // The specified value for the enumerator.
646 ExprResult Value = SemaRef.Owned((Expr *)0);
647 if (Expr *UninstValue = EC->getInitExpr()) {
648 // The enumerator's value expression is a constant expression.
649 EnterExpressionEvaluationContext Unevaluated(SemaRef,
650 Sema::ConstantEvaluated);
652 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
655 // Drop the initial value and continue.
656 bool isInvalid = false;
657 if (Value.isInvalid()) {
658 Value = SemaRef.Owned((Expr *)0);
662 EnumConstantDecl *EnumConst
663 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
664 EC->getLocation(), EC->getIdentifier(),
669 EnumConst->setInvalidDecl();
670 Enum->setInvalidDecl();
674 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
676 EnumConst->setAccess(Enum->getAccess());
677 Enum->addDecl(EnumConst);
678 Enumerators.push_back(EnumConst);
679 LastEnumConst = EnumConst;
681 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
683 // If the enumeration is within a function or method, record the enum
684 // constant as a local.
685 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
690 // FIXME: Fixup LBraceLoc
691 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
692 Enum->getRBraceLoc(), Enum,
693 Enumerators.data(), Enumerators.size(),
697 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
698 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
701 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
702 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
704 // Create a local instantiation scope for this class template, which
705 // will contain the instantiations of the template parameters.
706 LocalInstantiationScope Scope(SemaRef);
707 TemplateParameterList *TempParams = D->getTemplateParameters();
708 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
712 CXXRecordDecl *Pattern = D->getTemplatedDecl();
714 // Instantiate the qualifier. We have to do this first in case
715 // we're a friend declaration, because if we are then we need to put
716 // the new declaration in the appropriate context.
717 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
719 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
725 CXXRecordDecl *PrevDecl = 0;
726 ClassTemplateDecl *PrevClassTemplate = 0;
728 if (!isFriend && Pattern->getPreviousDecl()) {
729 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
730 if (Found.first != Found.second) {
731 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
732 if (PrevClassTemplate)
733 PrevDecl = PrevClassTemplate->getTemplatedDecl();
737 // If this isn't a friend, then it's a member template, in which
738 // case we just want to build the instantiation in the
739 // specialization. If it is a friend, we want to build it in
740 // the appropriate context.
741 DeclContext *DC = Owner;
745 SS.Adopt(QualifierLoc);
746 DC = SemaRef.computeDeclContext(SS);
749 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
750 Pattern->getDeclContext(),
754 // Look for a previous declaration of the template in the owning
756 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
757 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
758 SemaRef.LookupQualifiedName(R, DC);
760 if (R.isSingleResult()) {
761 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
762 if (PrevClassTemplate)
763 PrevDecl = PrevClassTemplate->getTemplatedDecl();
766 if (!PrevClassTemplate && QualifierLoc) {
767 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
768 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
769 << QualifierLoc.getSourceRange();
773 bool AdoptedPreviousTemplateParams = false;
774 if (PrevClassTemplate) {
775 bool Complain = true;
777 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
778 // template for struct std::tr1::__detail::_Map_base, where the
779 // template parameters of the friend declaration don't match the
780 // template parameters of the original declaration. In this one
781 // case, we don't complain about the ill-formed friend
783 if (isFriend && Pattern->getIdentifier() &&
784 Pattern->getIdentifier()->isStr("_Map_base") &&
786 cast<NamespaceDecl>(DC)->getIdentifier() &&
787 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
788 DeclContext *DCParent = DC->getParent();
789 if (DCParent->isNamespace() &&
790 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
791 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
792 DeclContext *DCParent2 = DCParent->getParent();
793 if (DCParent2->isNamespace() &&
794 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
795 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
796 DCParent2->getParent()->isTranslationUnit())
801 TemplateParameterList *PrevParams
802 = PrevClassTemplate->getTemplateParameters();
804 // Make sure the parameter lists match.
805 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
807 Sema::TPL_TemplateMatch)) {
811 AdoptedPreviousTemplateParams = true;
812 InstParams = PrevParams;
815 // Do some additional validation, then merge default arguments
816 // from the existing declarations.
817 if (!AdoptedPreviousTemplateParams &&
818 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
819 Sema::TPC_ClassTemplate))
824 CXXRecordDecl *RecordInst
825 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
826 Pattern->getLocStart(), Pattern->getLocation(),
827 Pattern->getIdentifier(), PrevDecl,
828 /*DelayTypeCreation=*/true);
831 RecordInst->setQualifierInfo(QualifierLoc);
833 ClassTemplateDecl *Inst
834 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
835 D->getIdentifier(), InstParams, RecordInst,
837 RecordInst->setDescribedClassTemplate(Inst);
840 if (PrevClassTemplate)
841 Inst->setAccess(PrevClassTemplate->getAccess());
843 Inst->setAccess(D->getAccess());
845 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
846 // TODO: do we want to track the instantiation progeny of this
847 // friend target decl?
849 Inst->setAccess(D->getAccess());
850 if (!PrevClassTemplate)
851 Inst->setInstantiatedFromMemberTemplate(D);
854 // Trigger creation of the type for the instantiation.
855 SemaRef.Context.getInjectedClassNameType(RecordInst,
856 Inst->getInjectedClassNameSpecialization());
858 // Finish handling of friends.
860 DC->makeDeclVisibleInContext(Inst);
861 Inst->setLexicalDeclContext(Owner);
862 RecordInst->setLexicalDeclContext(Owner);
866 if (D->isOutOfLine()) {
867 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
868 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
871 Owner->addDecl(Inst);
873 if (!PrevClassTemplate) {
874 // Queue up any out-of-line partial specializations of this member
875 // class template; the client will force their instantiation once
876 // the enclosing class has been instantiated.
877 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
878 D->getPartialSpecializations(PartialSpecs);
879 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
880 if (PartialSpecs[I]->isOutOfLine())
881 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
888 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
889 ClassTemplatePartialSpecializationDecl *D) {
890 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
892 // Lookup the already-instantiated declaration in the instantiation
893 // of the class template and return that.
894 DeclContext::lookup_result Found
895 = Owner->lookup(ClassTemplate->getDeclName());
896 if (Found.first == Found.second)
899 ClassTemplateDecl *InstClassTemplate
900 = dyn_cast<ClassTemplateDecl>(*Found.first);
901 if (!InstClassTemplate)
904 if (ClassTemplatePartialSpecializationDecl *Result
905 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
908 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
912 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
913 // Create a local instantiation scope for this function template, which
914 // will contain the instantiations of the template parameters and then get
915 // merged with the local instantiation scope for the function template
917 LocalInstantiationScope Scope(SemaRef);
919 TemplateParameterList *TempParams = D->getTemplateParameters();
920 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
924 FunctionDecl *Instantiated = 0;
925 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
926 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
929 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
930 D->getTemplatedDecl(),
936 Instantiated->setAccess(D->getAccess());
938 // Link the instantiated function template declaration to the function
939 // template from which it was instantiated.
940 FunctionTemplateDecl *InstTemplate
941 = Instantiated->getDescribedFunctionTemplate();
942 InstTemplate->setAccess(D->getAccess());
943 assert(InstTemplate &&
944 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
946 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
948 // Link the instantiation back to the pattern *unless* this is a
949 // non-definition friend declaration.
950 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
951 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
952 InstTemplate->setInstantiatedFromMemberTemplate(D);
954 // Make declarations visible in the appropriate context.
956 Owner->addDecl(InstTemplate);
961 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
962 CXXRecordDecl *PrevDecl = 0;
963 if (D->isInjectedClassName())
964 PrevDecl = cast<CXXRecordDecl>(Owner);
965 else if (D->getPreviousDecl()) {
966 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
967 D->getPreviousDecl(),
970 PrevDecl = cast<CXXRecordDecl>(Prev);
973 CXXRecordDecl *Record
974 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
975 D->getLocStart(), D->getLocation(),
976 D->getIdentifier(), PrevDecl);
978 // Substitute the nested name specifier, if any.
979 if (SubstQualifier(D, Record))
982 Record->setImplicit(D->isImplicit());
983 // FIXME: Check against AS_none is an ugly hack to work around the issue that
984 // the tag decls introduced by friend class declarations don't have an access
985 // specifier. Remove once this area of the code gets sorted out.
986 if (D->getAccess() != AS_none)
987 Record->setAccess(D->getAccess());
988 if (!D->isInjectedClassName())
989 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
991 // If the original function was part of a friend declaration,
992 // inherit its namespace state.
993 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
994 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
996 // Make sure that anonymous structs and unions are recorded.
997 if (D->isAnonymousStructOrUnion()) {
998 Record->setAnonymousStructOrUnion(true);
999 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
1000 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1003 Owner->addDecl(Record);
1007 /// Normal class members are of more specific types and therefore
1008 /// don't make it here. This function serves two purposes:
1009 /// 1) instantiating function templates
1010 /// 2) substituting friend declarations
1011 /// FIXME: preserve function definitions in case #2
1012 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1013 TemplateParameterList *TemplateParams) {
1014 // Check whether there is already a function template specialization for
1015 // this declaration.
1016 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1017 if (FunctionTemplate && !TemplateParams) {
1018 std::pair<const TemplateArgument *, unsigned> Innermost
1019 = TemplateArgs.getInnermost();
1021 void *InsertPos = 0;
1022 FunctionDecl *SpecFunc
1023 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1026 // If we already have a function template specialization, return it.
1032 if (FunctionTemplate)
1033 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1035 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1037 bool MergeWithParentScope = (TemplateParams != 0) ||
1038 Owner->isFunctionOrMethod() ||
1039 !(isa<Decl>(Owner) &&
1040 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1041 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1043 SmallVector<ParmVarDecl *, 4> Params;
1044 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1047 QualType T = TInfo->getType();
1049 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1051 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1057 // If we're instantiating a local function declaration, put the result
1058 // in the owner; otherwise we need to find the instantiated context.
1060 if (D->getDeclContext()->isFunctionOrMethod())
1062 else if (isFriend && QualifierLoc) {
1064 SS.Adopt(QualifierLoc);
1065 DC = SemaRef.computeDeclContext(SS);
1068 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1072 FunctionDecl *Function =
1073 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1074 D->getLocation(), D->getDeclName(), T, TInfo,
1075 D->getStorageClass(), D->getStorageClassAsWritten(),
1076 D->isInlineSpecified(), D->hasWrittenPrototype(),
1080 Function->setQualifierInfo(QualifierLoc);
1082 DeclContext *LexicalDC = Owner;
1083 if (!isFriend && D->isOutOfLine()) {
1084 assert(D->getDeclContext()->isFileContext());
1085 LexicalDC = D->getDeclContext();
1088 Function->setLexicalDeclContext(LexicalDC);
1090 // Attach the parameters
1091 if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
1092 // Adopt the already-instantiated parameters into our own context.
1093 for (unsigned P = 0; P < Params.size(); ++P)
1095 Params[P]->setOwningFunction(Function);
1097 // Since we were instantiated via a typedef of a function type, create
1099 const FunctionProtoType *Proto
1100 = Function->getType()->getAs<FunctionProtoType>();
1101 assert(Proto && "No function prototype in template instantiation?");
1102 for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
1103 AE = Proto->arg_type_end(); AI != AE; ++AI) {
1105 = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
1107 Param->setScopeInfo(0, Params.size());
1108 Params.push_back(Param);
1111 Function->setParams(Params);
1113 SourceLocation InstantiateAtPOI;
1114 if (TemplateParams) {
1115 // Our resulting instantiation is actually a function template, since we
1116 // are substituting only the outer template parameters. For example, given
1118 // template<typename T>
1120 // template<typename U> friend void f(T, U);
1125 // We are instantiating the friend function template "f" within X<int>,
1126 // which means substituting int for T, but leaving "f" as a friend function
1128 // Build the function template itself.
1129 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1130 Function->getLocation(),
1131 Function->getDeclName(),
1132 TemplateParams, Function);
1133 Function->setDescribedFunctionTemplate(FunctionTemplate);
1135 FunctionTemplate->setLexicalDeclContext(LexicalDC);
1137 if (isFriend && D->isThisDeclarationADefinition()) {
1138 // TODO: should we remember this connection regardless of whether
1139 // the friend declaration provided a body?
1140 FunctionTemplate->setInstantiatedFromMemberTemplate(
1141 D->getDescribedFunctionTemplate());
1143 } else if (FunctionTemplate) {
1144 // Record this function template specialization.
1145 std::pair<const TemplateArgument *, unsigned> Innermost
1146 = TemplateArgs.getInnermost();
1147 Function->setFunctionTemplateSpecialization(FunctionTemplate,
1148 TemplateArgumentList::CreateCopy(SemaRef.Context,
1152 } else if (isFriend) {
1153 // Note, we need this connection even if the friend doesn't have a body.
1154 // Its body may exist but not have been attached yet due to deferred
1156 // FIXME: It might be cleaner to set this when attaching the body to the
1157 // friend function declaration, however that would require finding all the
1158 // instantiations and modifying them.
1159 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1162 if (InitFunctionInstantiation(Function, D))
1163 Function->setInvalidDecl();
1165 bool isExplicitSpecialization = false;
1167 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1168 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1170 if (DependentFunctionTemplateSpecializationInfo *Info
1171 = D->getDependentSpecializationInfo()) {
1172 assert(isFriend && "non-friend has dependent specialization info?");
1174 // This needs to be set now for future sanity.
1175 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1177 // Instantiate the explicit template arguments.
1178 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1179 Info->getRAngleLoc());
1180 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1181 ExplicitArgs, TemplateArgs))
1184 // Map the candidate templates to their instantiations.
1185 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1186 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1187 Info->getTemplate(I),
1189 if (!Temp) return 0;
1191 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1194 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1197 Function->setInvalidDecl();
1199 isExplicitSpecialization = true;
1201 } else if (TemplateParams || !FunctionTemplate) {
1202 // Look only into the namespace where the friend would be declared to
1203 // find a previous declaration. This is the innermost enclosing namespace,
1204 // as described in ActOnFriendFunctionDecl.
1205 SemaRef.LookupQualifiedName(Previous, DC);
1207 // In C++, the previous declaration we find might be a tag type
1208 // (class or enum). In this case, the new declaration will hide the
1209 // tag type. Note that this does does not apply if we're declaring a
1210 // typedef (C++ [dcl.typedef]p4).
1211 if (Previous.isSingleTagDecl())
1215 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1216 isExplicitSpecialization);
1218 NamedDecl *PrincipalDecl = (TemplateParams
1219 ? cast<NamedDecl>(FunctionTemplate)
1222 // If the original function was part of a friend declaration,
1223 // inherit its namespace state and add it to the owner.
1225 NamedDecl *PrevDecl;
1227 PrevDecl = FunctionTemplate->getPreviousDecl();
1229 PrevDecl = Function->getPreviousDecl();
1231 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1232 DC->makeDeclVisibleInContext(PrincipalDecl);
1234 bool queuedInstantiation = false;
1236 // C++98 [temp.friend]p5: When a function is defined in a friend function
1237 // declaration in a class template, the function is defined at each
1238 // instantiation of the class template. The function is defined even if it
1240 // C++11 [temp.friend]p4: When a function is defined in a friend function
1241 // declaration in a class template, the function is instantiated when the
1242 // function is odr-used.
1244 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1245 // redefinition, but don't instantiate the function.
1246 if ((!SemaRef.getLangOpts().CPlusPlus0x ||
1247 SemaRef.Diags.getDiagnosticLevel(
1248 diag::warn_cxx98_compat_friend_redefinition,
1249 Function->getLocation())
1250 != DiagnosticsEngine::Ignored) &&
1251 D->isThisDeclarationADefinition()) {
1252 // Check for a function body.
1253 const FunctionDecl *Definition = 0;
1254 if (Function->isDefined(Definition) &&
1255 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1256 SemaRef.Diag(Function->getLocation(),
1257 SemaRef.getLangOpts().CPlusPlus0x ?
1258 diag::warn_cxx98_compat_friend_redefinition :
1259 diag::err_redefinition) << Function->getDeclName();
1260 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1261 if (!SemaRef.getLangOpts().CPlusPlus0x)
1262 Function->setInvalidDecl();
1264 // Check for redefinitions due to other instantiations of this or
1265 // a similar friend function.
1266 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1267 REnd = Function->redecls_end();
1271 switch (R->getFriendObjectKind()) {
1272 case Decl::FOK_None:
1273 if (!SemaRef.getLangOpts().CPlusPlus0x &&
1274 !queuedInstantiation && R->isUsed(false)) {
1275 if (MemberSpecializationInfo *MSInfo
1276 = Function->getMemberSpecializationInfo()) {
1277 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1278 SourceLocation Loc = R->getLocation(); // FIXME
1279 MSInfo->setPointOfInstantiation(Loc);
1280 SemaRef.PendingLocalImplicitInstantiations.push_back(
1281 std::make_pair(Function, Loc));
1282 queuedInstantiation = true;
1288 if (const FunctionDecl *RPattern
1289 = R->getTemplateInstantiationPattern())
1290 if (RPattern->isDefined(RPattern)) {
1291 SemaRef.Diag(Function->getLocation(),
1292 SemaRef.getLangOpts().CPlusPlus0x ?
1293 diag::warn_cxx98_compat_friend_redefinition :
1294 diag::err_redefinition)
1295 << Function->getDeclName();
1296 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1297 if (!SemaRef.getLangOpts().CPlusPlus0x)
1298 Function->setInvalidDecl();
1306 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1307 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1308 PrincipalDecl->setNonMemberOperator();
1310 assert(!D->isDefaulted() && "only methods should be defaulted");
1315 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1316 TemplateParameterList *TemplateParams,
1317 bool IsClassScopeSpecialization) {
1318 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1319 if (FunctionTemplate && !TemplateParams) {
1320 // We are creating a function template specialization from a function
1321 // template. Check whether there is already a function template
1322 // specialization for this particular set of template arguments.
1323 std::pair<const TemplateArgument *, unsigned> Innermost
1324 = TemplateArgs.getInnermost();
1326 void *InsertPos = 0;
1327 FunctionDecl *SpecFunc
1328 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1331 // If we already have a function template specialization, return it.
1337 if (FunctionTemplate)
1338 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1340 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1342 bool MergeWithParentScope = (TemplateParams != 0) ||
1343 !(isa<Decl>(Owner) &&
1344 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1345 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1347 // Instantiate enclosing template arguments for friends.
1348 SmallVector<TemplateParameterList *, 4> TempParamLists;
1349 unsigned NumTempParamLists = 0;
1350 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1351 TempParamLists.set_size(NumTempParamLists);
1352 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1353 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1354 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1357 TempParamLists[I] = InstParams;
1361 SmallVector<ParmVarDecl *, 4> Params;
1362 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1365 QualType T = TInfo->getType();
1367 // \brief If the type of this function, after ignoring parentheses,
1368 // is not *directly* a function type, then we're instantiating a function
1369 // that was declared via a typedef, e.g.,
1371 // typedef int functype(int, int);
1374 // In this case, we'll just go instantiate the ParmVarDecls that we
1375 // synthesized in the method declaration.
1376 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
1377 assert(!Params.size() && "Instantiating type could not yield parameters");
1378 SmallVector<QualType, 4> ParamTypes;
1379 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1380 D->getNumParams(), TemplateArgs, ParamTypes,
1385 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1387 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1393 DeclContext *DC = Owner;
1397 SS.Adopt(QualifierLoc);
1398 DC = SemaRef.computeDeclContext(SS);
1400 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1403 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1404 D->getDeclContext(),
1410 // Build the instantiated method declaration.
1411 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1412 CXXMethodDecl *Method = 0;
1414 SourceLocation StartLoc = D->getInnerLocStart();
1415 DeclarationNameInfo NameInfo
1416 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1417 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1418 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1419 StartLoc, NameInfo, T, TInfo,
1420 Constructor->isExplicit(),
1421 Constructor->isInlineSpecified(),
1422 false, Constructor->isConstexpr());
1423 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1424 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1425 StartLoc, NameInfo, T, TInfo,
1426 Destructor->isInlineSpecified(),
1428 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1429 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1430 StartLoc, NameInfo, T, TInfo,
1431 Conversion->isInlineSpecified(),
1432 Conversion->isExplicit(),
1433 Conversion->isConstexpr(),
1434 Conversion->getLocEnd());
1436 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1437 StartLoc, NameInfo, T, TInfo,
1439 D->getStorageClassAsWritten(),
1440 D->isInlineSpecified(),
1441 D->isConstexpr(), D->getLocEnd());
1445 Method->setQualifierInfo(QualifierLoc);
1447 if (TemplateParams) {
1448 // Our resulting instantiation is actually a function template, since we
1449 // are substituting only the outer template parameters. For example, given
1451 // template<typename T>
1453 // template<typename U> void f(T, U);
1458 // We are instantiating the member template "f" within X<int>, which means
1459 // substituting int for T, but leaving "f" as a member function template.
1460 // Build the function template itself.
1461 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1462 Method->getLocation(),
1463 Method->getDeclName(),
1464 TemplateParams, Method);
1466 FunctionTemplate->setLexicalDeclContext(Owner);
1467 FunctionTemplate->setObjectOfFriendDecl(true);
1468 } else if (D->isOutOfLine())
1469 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1470 Method->setDescribedFunctionTemplate(FunctionTemplate);
1471 } else if (FunctionTemplate) {
1472 // Record this function template specialization.
1473 std::pair<const TemplateArgument *, unsigned> Innermost
1474 = TemplateArgs.getInnermost();
1475 Method->setFunctionTemplateSpecialization(FunctionTemplate,
1476 TemplateArgumentList::CreateCopy(SemaRef.Context,
1480 } else if (!isFriend) {
1481 // Record that this is an instantiation of a member function.
1482 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1485 // If we are instantiating a member function defined
1486 // out-of-line, the instantiation will have the same lexical
1487 // context (which will be a namespace scope) as the template.
1489 if (NumTempParamLists)
1490 Method->setTemplateParameterListsInfo(SemaRef.Context,
1492 TempParamLists.data());
1494 Method->setLexicalDeclContext(Owner);
1495 Method->setObjectOfFriendDecl(true);
1496 } else if (D->isOutOfLine())
1497 Method->setLexicalDeclContext(D->getLexicalDeclContext());
1499 // Attach the parameters
1500 for (unsigned P = 0; P < Params.size(); ++P)
1501 Params[P]->setOwningFunction(Method);
1502 Method->setParams(Params);
1504 if (InitMethodInstantiation(Method, D))
1505 Method->setInvalidDecl();
1507 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1508 Sema::ForRedeclaration);
1510 if (!FunctionTemplate || TemplateParams || isFriend) {
1511 SemaRef.LookupQualifiedName(Previous, Record);
1513 // In C++, the previous declaration we find might be a tag type
1514 // (class or enum). In this case, the new declaration will hide the
1515 // tag type. Note that this does does not apply if we're declaring a
1516 // typedef (C++ [dcl.typedef]p4).
1517 if (Previous.isSingleTagDecl())
1521 if (!IsClassScopeSpecialization)
1522 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
1525 SemaRef.CheckPureMethod(Method, SourceRange());
1527 Method->setAccess(D->getAccess());
1529 SemaRef.CheckOverrideControl(Method);
1531 // If a function is defined as defaulted or deleted, mark it as such now.
1532 if (D->isDefaulted())
1533 Method->setDefaulted();
1534 if (D->isDeletedAsWritten())
1535 Method->setDeletedAsWritten();
1537 if (FunctionTemplate) {
1538 // If there's a function template, let our caller handle it.
1539 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1540 // Don't hide a (potentially) valid declaration with an invalid one.
1542 NamedDecl *DeclToAdd = (TemplateParams
1543 ? cast<NamedDecl>(FunctionTemplate)
1546 Record->makeDeclVisibleInContext(DeclToAdd);
1547 else if (!IsClassScopeSpecialization)
1548 Owner->addDecl(DeclToAdd);
1551 if (D->isExplicitlyDefaulted()) {
1552 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1554 assert(!D->isDefaulted() &&
1555 "should not implicitly default uninstantiated function");
1561 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1562 return VisitCXXMethodDecl(D);
1565 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1566 return VisitCXXMethodDecl(D);
1569 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1570 return VisitCXXMethodDecl(D);
1573 ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1574 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
1575 llvm::Optional<unsigned>(),
1576 /*ExpectParameterPack=*/false);
1579 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1580 TemplateTypeParmDecl *D) {
1581 // TODO: don't always clone when decls are refcounted.
1582 assert(D->getTypeForDecl()->isTemplateTypeParmType());
1584 TemplateTypeParmDecl *Inst =
1585 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1586 D->getLocStart(), D->getLocation(),
1587 D->getDepth() - TemplateArgs.getNumLevels(),
1588 D->getIndex(), D->getIdentifier(),
1589 D->wasDeclaredWithTypename(),
1590 D->isParameterPack());
1591 Inst->setAccess(AS_public);
1593 if (D->hasDefaultArgument())
1594 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1596 // Introduce this template parameter's instantiation into the instantiation
1598 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1603 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1604 NonTypeTemplateParmDecl *D) {
1605 // Substitute into the type of the non-type template parameter.
1606 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1607 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1608 SmallVector<QualType, 4> ExpandedParameterPackTypes;
1609 bool IsExpandedParameterPack = false;
1612 bool Invalid = false;
1614 if (D->isExpandedParameterPack()) {
1615 // The non-type template parameter pack is an already-expanded pack
1616 // expansion of types. Substitute into each of the expanded types.
1617 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1618 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1619 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1620 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1627 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1628 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1632 ExpandedParameterPackTypes.push_back(NewT);
1635 IsExpandedParameterPack = true;
1636 DI = D->getTypeSourceInfo();
1638 } else if (isa<PackExpansionTypeLoc>(TL)) {
1639 // The non-type template parameter pack's type is a pack expansion of types.
1640 // Determine whether we need to expand this parameter pack into separate
1642 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1643 TypeLoc Pattern = Expansion.getPatternLoc();
1644 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1645 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1647 // Determine whether the set of unexpanded parameter packs can and should
1650 bool RetainExpansion = false;
1651 llvm::Optional<unsigned> OrigNumExpansions
1652 = Expansion.getTypePtr()->getNumExpansions();
1653 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1654 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1655 Pattern.getSourceRange(),
1658 Expand, RetainExpansion,
1663 for (unsigned I = 0; I != *NumExpansions; ++I) {
1664 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1665 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1671 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1672 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1677 ExpandedParameterPackTypes.push_back(NewT);
1680 // Note that we have an expanded parameter pack. The "type" of this
1681 // expanded parameter pack is the original expansion type, but callers
1682 // will end up using the expanded parameter pack types for type-checking.
1683 IsExpandedParameterPack = true;
1684 DI = D->getTypeSourceInfo();
1687 // We cannot fully expand the pack expansion now, so substitute into the
1688 // pattern and create a new pack expansion type.
1689 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1690 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1696 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1704 // Simple case: substitution into a parameter that is not a parameter pack.
1705 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1706 D->getLocation(), D->getDeclName());
1710 // Check that this type is acceptable for a non-type template parameter.
1711 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1714 T = SemaRef.Context.IntTy;
1719 NonTypeTemplateParmDecl *Param;
1720 if (IsExpandedParameterPack)
1721 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1722 D->getInnerLocStart(),
1724 D->getDepth() - TemplateArgs.getNumLevels(),
1726 D->getIdentifier(), T,
1728 ExpandedParameterPackTypes.data(),
1729 ExpandedParameterPackTypes.size(),
1730 ExpandedParameterPackTypesAsWritten.data());
1732 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1733 D->getInnerLocStart(),
1735 D->getDepth() - TemplateArgs.getNumLevels(),
1737 D->getIdentifier(), T,
1738 D->isParameterPack(), DI);
1740 Param->setAccess(AS_public);
1742 Param->setInvalidDecl();
1744 Param->setDefaultArgument(D->getDefaultArgument(), false);
1746 // Introduce this template parameter's instantiation into the instantiation
1748 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1753 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1754 TemplateTemplateParmDecl *D) {
1755 // Instantiate the template parameter list of the template template parameter.
1756 TemplateParameterList *TempParams = D->getTemplateParameters();
1757 TemplateParameterList *InstParams;
1759 // Perform the actual substitution of template parameters within a new,
1760 // local instantiation scope.
1761 LocalInstantiationScope Scope(SemaRef);
1762 InstParams = SubstTemplateParams(TempParams);
1767 // Build the template template parameter.
1768 TemplateTemplateParmDecl *Param
1769 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1770 D->getDepth() - TemplateArgs.getNumLevels(),
1771 D->getPosition(), D->isParameterPack(),
1772 D->getIdentifier(), InstParams);
1773 Param->setDefaultArgument(D->getDefaultArgument(), false);
1774 Param->setAccess(AS_public);
1776 // Introduce this template parameter's instantiation into the instantiation
1778 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1783 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1784 // Using directives are never dependent (and never contain any types or
1785 // expressions), so they require no explicit instantiation work.
1787 UsingDirectiveDecl *Inst
1788 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1789 D->getNamespaceKeyLocation(),
1790 D->getQualifierLoc(),
1791 D->getIdentLocation(),
1792 D->getNominatedNamespace(),
1793 D->getCommonAncestor());
1794 Owner->addDecl(Inst);
1798 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1800 // The nested name specifier may be dependent, for example
1801 // template <typename T> struct t {
1802 // struct s1 { T f1(); };
1803 // struct s2 : s1 { using s1::f1; };
1805 // template struct t<int>;
1806 // Here, in using s1::f1, s1 refers to t<T>::s1;
1807 // we need to substitute for t<int>::s1.
1808 NestedNameSpecifierLoc QualifierLoc
1809 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1814 // The name info is non-dependent, so no transformation
1816 DeclarationNameInfo NameInfo = D->getNameInfo();
1818 // We only need to do redeclaration lookups if we're in a class
1819 // scope (in fact, it's not really even possible in non-class
1821 bool CheckRedeclaration = Owner->isRecord();
1823 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1824 Sema::ForRedeclaration);
1826 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1827 D->getUsingLocation(),
1833 SS.Adopt(QualifierLoc);
1834 if (CheckRedeclaration) {
1835 Prev.setHideTags(false);
1836 SemaRef.LookupQualifiedName(Prev, Owner);
1838 // Check for invalid redeclarations.
1839 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1840 D->isTypeName(), SS,
1841 D->getLocation(), Prev))
1842 NewUD->setInvalidDecl();
1846 if (!NewUD->isInvalidDecl() &&
1847 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
1849 NewUD->setInvalidDecl();
1851 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1852 NewUD->setAccess(D->getAccess());
1853 Owner->addDecl(NewUD);
1855 // Don't process the shadow decls for an invalid decl.
1856 if (NewUD->isInvalidDecl())
1859 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
1860 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
1861 NewUD->setInvalidDecl();
1865 bool isFunctionScope = Owner->isFunctionOrMethod();
1867 // Process the shadow decls.
1868 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1870 UsingShadowDecl *Shadow = *I;
1871 NamedDecl *InstTarget =
1872 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
1873 Shadow->getLocation(),
1874 Shadow->getTargetDecl(),
1879 if (CheckRedeclaration &&
1880 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1883 UsingShadowDecl *InstShadow
1884 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1885 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
1887 if (isFunctionScope)
1888 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
1894 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
1895 // Ignore these; we handle them in bulk when processing the UsingDecl.
1899 Decl * TemplateDeclInstantiator
1900 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1901 NestedNameSpecifierLoc QualifierLoc
1902 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1908 SS.Adopt(QualifierLoc);
1910 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1911 // Hence, no tranformation is required for it.
1912 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
1914 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1915 D->getUsingLoc(), SS, NameInfo, 0,
1916 /*instantiation*/ true,
1917 /*typename*/ true, D->getTypenameLoc());
1919 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1924 Decl * TemplateDeclInstantiator
1925 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1926 NestedNameSpecifierLoc QualifierLoc
1927 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
1932 SS.Adopt(QualifierLoc);
1934 DeclarationNameInfo NameInfo
1935 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1938 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1939 D->getUsingLoc(), SS, NameInfo, 0,
1940 /*instantiation*/ true,
1941 /*typename*/ false, SourceLocation());
1943 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1949 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
1950 ClassScopeFunctionSpecializationDecl *Decl) {
1951 CXXMethodDecl *OldFD = Decl->getSpecialization();
1952 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, 0, true));
1954 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
1955 Sema::ForRedeclaration);
1957 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
1958 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, 0, Previous)) {
1959 NewFD->setInvalidDecl();
1963 // Associate the specialization with the pattern.
1964 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
1965 assert(Specialization && "Class scope Specialization is null");
1966 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
1971 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
1972 const MultiLevelTemplateArgumentList &TemplateArgs) {
1973 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
1974 if (D->isInvalidDecl())
1977 return Instantiator.Visit(D);
1980 /// \brief Instantiates a nested template parameter list in the current
1981 /// instantiation context.
1983 /// \param L The parameter list to instantiate
1985 /// \returns NULL if there was an error
1986 TemplateParameterList *
1987 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
1988 // Get errors for all the parameters before bailing out.
1989 bool Invalid = false;
1991 unsigned N = L->size();
1992 typedef SmallVector<NamedDecl *, 8> ParamVector;
1995 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1997 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
1998 Params.push_back(D);
1999 Invalid = Invalid || !D || D->isInvalidDecl();
2002 // Clean up if we had an error.
2006 TemplateParameterList *InstL
2007 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2008 L->getLAngleLoc(), &Params.front(), N,
2013 /// \brief Instantiate the declaration of a class template partial
2016 /// \param ClassTemplate the (instantiated) class template that is partially
2017 // specialized by the instantiation of \p PartialSpec.
2019 /// \param PartialSpec the (uninstantiated) class template partial
2020 /// specialization that we are instantiating.
2022 /// \returns The instantiated partial specialization, if successful; otherwise,
2023 /// NULL to indicate an error.
2024 ClassTemplatePartialSpecializationDecl *
2025 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2026 ClassTemplateDecl *ClassTemplate,
2027 ClassTemplatePartialSpecializationDecl *PartialSpec) {
2028 // Create a local instantiation scope for this class template partial
2029 // specialization, which will contain the instantiations of the template
2031 LocalInstantiationScope Scope(SemaRef);
2033 // Substitute into the template parameters of the class template partial
2035 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2036 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2040 // Substitute into the template arguments of the class template partial
2042 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
2043 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
2044 PartialSpec->getNumTemplateArgsAsWritten(),
2045 InstTemplateArgs, TemplateArgs))
2048 // Check that the template argument list is well-formed for this
2050 SmallVector<TemplateArgument, 4> Converted;
2051 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2052 PartialSpec->getLocation(),
2058 // Figure out where to insert this class template partial specialization
2059 // in the member template's set of class template partial specializations.
2060 void *InsertPos = 0;
2061 ClassTemplateSpecializationDecl *PrevDecl
2062 = ClassTemplate->findPartialSpecialization(Converted.data(),
2063 Converted.size(), InsertPos);
2065 // Build the canonical type that describes the converted template
2066 // arguments of the class template partial specialization.
2068 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2072 // Build the fully-sugared type for this class template
2073 // specialization as the user wrote in the specialization
2074 // itself. This means that we'll pretty-print the type retrieved
2075 // from the specialization's declaration the way that the user
2076 // actually wrote the specialization, rather than formatting the
2077 // name based on the "canonical" representation used to store the
2078 // template arguments in the specialization.
2079 TypeSourceInfo *WrittenTy
2080 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2081 TemplateName(ClassTemplate),
2082 PartialSpec->getLocation(),
2087 // We've already seen a partial specialization with the same template
2088 // parameters and template arguments. This can happen, for example, when
2089 // substituting the outer template arguments ends up causing two
2090 // class template partial specializations of a member class template
2091 // to have identical forms, e.g.,
2093 // template<typename T, typename U>
2095 // template<typename X, typename Y> struct Inner;
2096 // template<typename Y> struct Inner<T, Y>;
2097 // template<typename Y> struct Inner<U, Y>;
2100 // Outer<int, int> outer; // error: the partial specializations of Inner
2101 // // have the same signature.
2102 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2103 << WrittenTy->getType();
2104 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2105 << SemaRef.Context.getTypeDeclType(PrevDecl);
2110 // Create the class template partial specialization declaration.
2111 ClassTemplatePartialSpecializationDecl *InstPartialSpec
2112 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2113 PartialSpec->getTagKind(),
2115 PartialSpec->getLocStart(),
2116 PartialSpec->getLocation(),
2124 ClassTemplate->getNextPartialSpecSequenceNumber());
2125 // Substitute the nested name specifier, if any.
2126 if (SubstQualifier(PartialSpec, InstPartialSpec))
2129 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2130 InstPartialSpec->setTypeAsWritten(WrittenTy);
2132 // Add this partial specialization to the set of class template partial
2134 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
2135 return InstPartialSpec;
2139 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
2140 SmallVectorImpl<ParmVarDecl *> &Params) {
2141 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2142 assert(OldTInfo && "substituting function without type source info");
2143 assert(Params.empty() && "parameter vector is non-empty at start");
2145 CXXRecordDecl *ThisContext = 0;
2146 unsigned ThisTypeQuals = 0;
2147 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2148 ThisContext = Method->getParent();
2149 ThisTypeQuals = Method->getTypeQualifiers();
2152 TypeSourceInfo *NewTInfo
2153 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2154 D->getTypeSpecStartLoc(),
2156 ThisContext, ThisTypeQuals);
2160 if (NewTInfo != OldTInfo) {
2161 // Get parameters from the new type info.
2162 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2163 if (FunctionProtoTypeLoc *OldProtoLoc
2164 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2165 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
2166 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2167 assert(NewProtoLoc && "Missing prototype?");
2168 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
2169 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2170 OldIdx != NumOldParams; ++OldIdx) {
2171 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2172 if (!OldParam->isParameterPack() ||
2173 // FIXME: Is this right? OldParam could expand to an empty parameter
2174 // pack and the next parameter could be an unexpanded parameter pack
2175 (NewIdx < NumNewParams &&
2176 NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
2177 // Simple case: normal parameter, or a parameter pack that's
2178 // instantiated to a (still-dependent) parameter pack.
2179 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2180 Params.push_back(NewParam);
2181 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2186 // Parameter pack: make the instantiation an argument pack.
2187 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2189 unsigned NumArgumentsInExpansion
2190 = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2192 while (NumArgumentsInExpansion--) {
2193 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2194 Params.push_back(NewParam);
2195 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2201 // The function type itself was not dependent and therefore no
2202 // substitution occurred. However, we still need to instantiate
2203 // the function parameters themselves.
2204 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2205 if (FunctionProtoTypeLoc *OldProtoLoc
2206 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2207 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2208 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2211 Params.push_back(Parm);
2218 /// Introduce the instantiated function parameters into the local
2219 /// instantiation scope, and set the parameter names to those used
2220 /// in the template.
2221 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2222 const FunctionDecl *PatternDecl,
2223 LocalInstantiationScope &Scope,
2224 const MultiLevelTemplateArgumentList &TemplateArgs) {
2225 unsigned FParamIdx = 0;
2226 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2227 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2228 if (!PatternParam->isParameterPack()) {
2229 // Simple case: not a parameter pack.
2230 assert(FParamIdx < Function->getNumParams());
2231 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2232 FunctionParam->setDeclName(PatternParam->getDeclName());
2233 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2238 // Expand the parameter pack.
2239 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2240 unsigned NumArgumentsInExpansion
2241 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
2242 for (unsigned Arg = 0; Arg < NumArgumentsInExpansion; ++Arg) {
2243 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2244 FunctionParam->setDeclName(PatternParam->getDeclName());
2245 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2251 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2252 const FunctionProtoType *Proto,
2253 const MultiLevelTemplateArgumentList &TemplateArgs) {
2254 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2256 // C++11 [expr.prim.general]p3:
2257 // If a declaration declares a member function or member function
2258 // template of a class X, the expression this is a prvalue of type
2259 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2260 // and the end of the function-definition, member-declarator, or
2262 CXXRecordDecl *ThisContext = 0;
2263 unsigned ThisTypeQuals = 0;
2264 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2265 ThisContext = Method->getParent();
2266 ThisTypeQuals = Method->getTypeQualifiers();
2268 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
2269 SemaRef.getLangOpts().CPlusPlus0x);
2271 // The function has an exception specification or a "noreturn"
2272 // attribute. Substitute into each of the exception types.
2273 SmallVector<QualType, 4> Exceptions;
2274 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2275 // FIXME: Poor location information!
2276 if (const PackExpansionType *PackExpansion
2277 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2278 // We have a pack expansion. Instantiate it.
2279 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2280 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2282 assert(!Unexpanded.empty() &&
2283 "Pack expansion without parameter packs?");
2285 bool Expand = false;
2286 bool RetainExpansion = false;
2287 llvm::Optional<unsigned> NumExpansions
2288 = PackExpansion->getNumExpansions();
2289 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2299 // We can't expand this pack expansion into separate arguments yet;
2300 // just substitute into the pattern and create a new pack expansion
2302 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2303 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2305 New->getLocation(), New->getDeclName());
2309 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2310 Exceptions.push_back(T);
2314 // Substitute into the pack expansion pattern for each template
2315 bool Invalid = false;
2316 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2317 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2319 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2321 New->getLocation(), New->getDeclName());
2327 Exceptions.push_back(T);
2337 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2338 New->getLocation(), New->getDeclName());
2340 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2343 Exceptions.push_back(T);
2345 Expr *NoexceptExpr = 0;
2346 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2347 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2348 Sema::ConstantEvaluated);
2349 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2351 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2354 NoexceptExpr = E.take();
2355 if (!NoexceptExpr->isTypeDependent() &&
2356 !NoexceptExpr->isValueDependent())
2357 NoexceptExpr = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2358 0, SemaRef.PDiag(diag::err_noexcept_needs_constant_expression),
2359 /*AllowFold*/ false).take();
2363 // Rebuild the function type
2364 const FunctionProtoType *NewProto
2365 = New->getType()->getAs<FunctionProtoType>();
2366 assert(NewProto && "Template instantiation without function prototype?");
2368 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2369 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2370 EPI.NumExceptions = Exceptions.size();
2371 EPI.Exceptions = Exceptions.data();
2372 EPI.NoexceptExpr = NoexceptExpr;
2374 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2375 NewProto->arg_type_begin(),
2376 NewProto->getNumArgs(),
2380 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2381 FunctionDecl *Decl) {
2382 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2383 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
2386 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2387 InstantiatingTemplate::ExceptionSpecification());
2391 // Enter the scope of this instantiation. We don't use
2392 // PushDeclContext because we don't have a scope.
2393 Sema::ContextRAII savedContext(*this, Decl);
2394 LocalInstantiationScope Scope(*this);
2396 MultiLevelTemplateArgumentList TemplateArgs =
2397 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2399 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2400 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
2402 ::InstantiateExceptionSpec(*this, Decl,
2403 Template->getType()->castAs<FunctionProtoType>(),
2407 /// \brief Initializes the common fields of an instantiation function
2408 /// declaration (New) from the corresponding fields of its template (Tmpl).
2410 /// \returns true if there was an error
2412 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
2413 FunctionDecl *Tmpl) {
2414 if (Tmpl->isDeletedAsWritten())
2415 New->setDeletedAsWritten();
2417 // If we are performing substituting explicitly-specified template arguments
2418 // or deduced template arguments into a function template and we reach this
2419 // point, we are now past the point where SFINAE applies and have committed
2420 // to keeping the new function template specialization. We therefore
2421 // convert the active template instantiation for the function template
2422 // into a template instantiation for this specific function template
2423 // specialization, which is not a SFINAE context, so that we diagnose any
2424 // further errors in the declaration itself.
2425 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2426 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2427 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2428 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
2429 if (FunctionTemplateDecl *FunTmpl
2430 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
2431 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
2432 "Deduction from the wrong function template?");
2434 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2435 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
2436 --SemaRef.NonInstantiationEntries;
2440 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2441 assert(Proto && "Function template without prototype?");
2443 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
2444 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2446 // DR1330: In C++11, defer instantiation of a non-trivial
2447 // exception specification.
2448 if (SemaRef.getLangOpts().CPlusPlus0x &&
2449 EPI.ExceptionSpecType != EST_None &&
2450 EPI.ExceptionSpecType != EST_DynamicNone &&
2451 EPI.ExceptionSpecType != EST_BasicNoexcept) {
2452 FunctionDecl *ExceptionSpecTemplate = Tmpl;
2453 if (EPI.ExceptionSpecType == EST_Uninstantiated)
2454 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
2456 // Mark the function has having an uninstantiated exception specification.
2457 const FunctionProtoType *NewProto
2458 = New->getType()->getAs<FunctionProtoType>();
2459 assert(NewProto && "Template instantiation without function prototype?");
2460 EPI = NewProto->getExtProtoInfo();
2461 EPI.ExceptionSpecType = EST_Uninstantiated;
2462 EPI.ExceptionSpecDecl = New;
2463 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
2464 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2465 NewProto->arg_type_begin(),
2466 NewProto->getNumArgs(),
2469 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
2473 // Get the definition. Leaves the variable unchanged if undefined.
2474 const FunctionDecl *Definition = Tmpl;
2475 Tmpl->isDefined(Definition);
2477 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
2478 LateAttrs, StartingScope);
2483 /// \brief Initializes common fields of an instantiated method
2484 /// declaration (New) from the corresponding fields of its template
2487 /// \returns true if there was an error
2489 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
2490 CXXMethodDecl *Tmpl) {
2491 if (InitFunctionInstantiation(New, Tmpl))
2494 New->setAccess(Tmpl->getAccess());
2495 if (Tmpl->isVirtualAsWritten())
2496 New->setVirtualAsWritten(true);
2498 // FIXME: attributes
2499 // FIXME: New needs a pointer to Tmpl
2503 /// \brief Instantiate the definition of the given function from its
2506 /// \param PointOfInstantiation the point at which the instantiation was
2507 /// required. Note that this is not precisely a "point of instantiation"
2508 /// for the function, but it's close.
2510 /// \param Function the already-instantiated declaration of a
2511 /// function template specialization or member function of a class template
2514 /// \param Recursive if true, recursively instantiates any functions that
2515 /// are required by this instantiation.
2517 /// \param DefinitionRequired if true, then we are performing an explicit
2518 /// instantiation where the body of the function is required. Complain if
2519 /// there is no such body.
2520 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
2521 FunctionDecl *Function,
2523 bool DefinitionRequired) {
2524 if (Function->isInvalidDecl() || Function->isDefined())
2527 // Never instantiate an explicit specialization except if it is a class scope
2528 // explicit specialization.
2529 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2530 !Function->getClassScopeSpecializationPattern())
2533 // Find the function body that we'll be substituting.
2534 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
2535 assert(PatternDecl && "instantiating a non-template");
2537 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2538 assert(PatternDecl && "template definition is not a template");
2540 // Try to find a defaulted definition
2541 PatternDecl->isDefined(PatternDecl);
2543 assert(PatternDecl && "template definition is not a template");
2545 // Postpone late parsed template instantiations.
2546 if (PatternDecl->isLateTemplateParsed() &&
2547 !LateTemplateParser) {
2548 PendingInstantiations.push_back(
2549 std::make_pair(Function, PointOfInstantiation));
2553 // Call the LateTemplateParser callback if there a need to late parse
2554 // a templated function definition.
2555 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
2556 LateTemplateParser) {
2557 LateTemplateParser(OpaqueParser, PatternDecl);
2558 Pattern = PatternDecl->getBody(PatternDecl);
2561 if (!Pattern && !PatternDecl->isDefaulted()) {
2562 if (DefinitionRequired) {
2563 if (Function->getPrimaryTemplate())
2564 Diag(PointOfInstantiation,
2565 diag::err_explicit_instantiation_undefined_func_template)
2566 << Function->getPrimaryTemplate();
2568 Diag(PointOfInstantiation,
2569 diag::err_explicit_instantiation_undefined_member)
2570 << 1 << Function->getDeclName() << Function->getDeclContext();
2573 Diag(PatternDecl->getLocation(),
2574 diag::note_explicit_instantiation_here);
2575 Function->setInvalidDecl();
2576 } else if (Function->getTemplateSpecializationKind()
2577 == TSK_ExplicitInstantiationDefinition) {
2578 PendingInstantiations.push_back(
2579 std::make_pair(Function, PointOfInstantiation));
2585 // C++0x [temp.explicit]p9:
2586 // Except for inline functions, other explicit instantiation declarations
2587 // have the effect of suppressing the implicit instantiation of the entity
2588 // to which they refer.
2589 if (Function->getTemplateSpecializationKind()
2590 == TSK_ExplicitInstantiationDeclaration &&
2591 !PatternDecl->isInlined())
2594 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2598 // Copy the inner loc start from the pattern.
2599 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2601 // If we're performing recursive template instantiation, create our own
2602 // queue of pending implicit instantiations that we will instantiate later,
2603 // while we're still within our own instantiation context.
2604 SmallVector<VTableUse, 16> SavedVTableUses;
2605 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2607 VTableUses.swap(SavedVTableUses);
2608 PendingInstantiations.swap(SavedPendingInstantiations);
2611 EnterExpressionEvaluationContext EvalContext(*this,
2612 Sema::PotentiallyEvaluated);
2613 ActOnStartOfFunctionDef(0, Function);
2615 // Introduce a new scope where local variable instantiations will be
2616 // recorded, unless we're actually a member function within a local
2617 // class, in which case we need to merge our results with the parent
2618 // scope (of the enclosing function).
2619 bool MergeWithParentScope = false;
2620 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2621 MergeWithParentScope = Rec->isLocalClass();
2623 LocalInstantiationScope Scope(*this, MergeWithParentScope);
2625 // Enter the scope of this instantiation. We don't use
2626 // PushDeclContext because we don't have a scope.
2627 Sema::ContextRAII savedContext(*this, Function);
2629 MultiLevelTemplateArgumentList TemplateArgs =
2630 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2632 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
2635 if (PatternDecl->isDefaulted()) {
2636 ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true);
2638 SetDeclDefaulted(Function, PatternDecl->getLocation());
2640 // If this is a constructor, instantiate the member initializers.
2641 if (const CXXConstructorDecl *Ctor =
2642 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2643 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2647 // Instantiate the function body.
2648 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2650 if (Body.isInvalid())
2651 Function->setInvalidDecl();
2653 ActOnFinishFunctionBody(Function, Body.get(),
2654 /*IsInstantiation=*/true);
2657 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2661 DeclGroupRef DG(Function);
2662 Consumer.HandleTopLevelDecl(DG);
2664 // This class may have local implicit instantiations that need to be
2665 // instantiation within this scope.
2666 PerformPendingInstantiations(/*LocalOnly=*/true);
2670 // Define any pending vtables.
2671 DefineUsedVTables();
2673 // Instantiate any pending implicit instantiations found during the
2674 // instantiation of this template.
2675 PerformPendingInstantiations();
2677 // Restore the set of pending vtables.
2678 assert(VTableUses.empty() &&
2679 "VTableUses should be empty before it is discarded.");
2680 VTableUses.swap(SavedVTableUses);
2682 // Restore the set of pending implicit instantiations.
2683 assert(PendingInstantiations.empty() &&
2684 "PendingInstantiations should be empty before it is discarded.");
2685 PendingInstantiations.swap(SavedPendingInstantiations);
2689 /// \brief Instantiate the definition of the given variable from its
2692 /// \param PointOfInstantiation the point at which the instantiation was
2693 /// required. Note that this is not precisely a "point of instantiation"
2694 /// for the function, but it's close.
2696 /// \param Var the already-instantiated declaration of a static member
2697 /// variable of a class template specialization.
2699 /// \param Recursive if true, recursively instantiates any functions that
2700 /// are required by this instantiation.
2702 /// \param DefinitionRequired if true, then we are performing an explicit
2703 /// instantiation where an out-of-line definition of the member variable
2704 /// is required. Complain if there is no such definition.
2705 void Sema::InstantiateStaticDataMemberDefinition(
2706 SourceLocation PointOfInstantiation,
2709 bool DefinitionRequired) {
2710 if (Var->isInvalidDecl())
2713 // Find the out-of-line definition of this static data member.
2714 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
2715 assert(Def && "This data member was not instantiated from a template?");
2716 assert(Def->isStaticDataMember() && "Not a static data member?");
2717 Def = Def->getOutOfLineDefinition();
2720 // We did not find an out-of-line definition of this static data member,
2721 // so we won't perform any instantiation. Rather, we rely on the user to
2722 // instantiate this definition (or provide a specialization for it) in
2723 // another translation unit.
2724 if (DefinitionRequired) {
2725 Def = Var->getInstantiatedFromStaticDataMember();
2726 Diag(PointOfInstantiation,
2727 diag::err_explicit_instantiation_undefined_member)
2728 << 2 << Var->getDeclName() << Var->getDeclContext();
2729 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2730 } else if (Var->getTemplateSpecializationKind()
2731 == TSK_ExplicitInstantiationDefinition) {
2732 PendingInstantiations.push_back(
2733 std::make_pair(Var, PointOfInstantiation));
2739 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
2741 // Never instantiate an explicit specialization.
2742 if (TSK == TSK_ExplicitSpecialization)
2745 // C++0x [temp.explicit]p9:
2746 // Except for inline functions, other explicit instantiation declarations
2747 // have the effect of suppressing the implicit instantiation of the entity
2748 // to which they refer.
2749 if (TSK == TSK_ExplicitInstantiationDeclaration)
2752 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
2754 // If we already have a definition, we're done.
2755 if (VarDecl *Def = Var->getDefinition()) {
2756 // We may be explicitly instantiating something we've already implicitly
2758 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
2759 PointOfInstantiation);
2763 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2767 // If we're performing recursive template instantiation, create our own
2768 // queue of pending implicit instantiations that we will instantiate later,
2769 // while we're still within our own instantiation context.
2770 SmallVector<VTableUse, 16> SavedVTableUses;
2771 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2773 VTableUses.swap(SavedVTableUses);
2774 PendingInstantiations.swap(SavedPendingInstantiations);
2777 // Enter the scope of this instantiation. We don't use
2778 // PushDeclContext because we don't have a scope.
2779 ContextRAII previousContext(*this, Var->getDeclContext());
2780 LocalInstantiationScope Local(*this);
2782 VarDecl *OldVar = Var;
2783 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
2784 getTemplateInstantiationArgs(Var)));
2786 previousContext.pop();
2789 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2790 assert(MSInfo && "Missing member specialization information?");
2791 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2792 MSInfo->getPointOfInstantiation());
2793 DeclGroupRef DG(Var);
2794 Consumer.HandleTopLevelDecl(DG);
2799 // Define any newly required vtables.
2800 DefineUsedVTables();
2802 // Instantiate any pending implicit instantiations found during the
2803 // instantiation of this template.
2804 PerformPendingInstantiations();
2806 // Restore the set of pending vtables.
2807 assert(VTableUses.empty() &&
2808 "VTableUses should be empty before it is discarded, "
2809 "while instantiating static data member.");
2810 VTableUses.swap(SavedVTableUses);
2812 // Restore the set of pending implicit instantiations.
2813 assert(PendingInstantiations.empty() &&
2814 "PendingInstantiations should be empty before it is discarded, "
2815 "while instantiating static data member.");
2816 PendingInstantiations.swap(SavedPendingInstantiations);
2821 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2822 const CXXConstructorDecl *Tmpl,
2823 const MultiLevelTemplateArgumentList &TemplateArgs) {
2825 SmallVector<CXXCtorInitializer*, 4> NewInits;
2826 bool AnyErrors = false;
2828 // Instantiate all the initializers.
2829 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
2830 InitsEnd = Tmpl->init_end();
2831 Inits != InitsEnd; ++Inits) {
2832 CXXCtorInitializer *Init = *Inits;
2834 // Only instantiate written initializers, let Sema re-construct implicit
2836 if (!Init->isWritten())
2839 SourceLocation EllipsisLoc;
2841 if (Init->isPackExpansion()) {
2842 // This is a pack expansion. We should expand it now.
2843 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
2844 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2845 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2846 bool ShouldExpand = false;
2847 bool RetainExpansion = false;
2848 llvm::Optional<unsigned> NumExpansions;
2849 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2850 BaseTL.getSourceRange(),
2852 TemplateArgs, ShouldExpand,
2856 New->setInvalidDecl();
2859 assert(ShouldExpand && "Partial instantiation of base initializer?");
2861 // Loop over all of the arguments in the argument pack(s),
2862 for (unsigned I = 0; I != *NumExpansions; ++I) {
2863 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2865 // Instantiate the initializer.
2866 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
2867 /*CXXDirectInit=*/true);
2868 if (TempInit.isInvalid()) {
2873 // Instantiate the base type.
2874 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
2876 Init->getSourceLocation(),
2877 New->getDeclName());
2883 // Build the initializer.
2884 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2885 BaseTInfo, TempInit.take(),
2888 if (NewInit.isInvalid()) {
2893 NewInits.push_back(NewInit.get());
2899 // Instantiate the initializer.
2900 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
2901 /*CXXDirectInit=*/true);
2902 if (TempInit.isInvalid()) {
2907 MemInitResult NewInit;
2908 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
2909 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
2911 Init->getSourceLocation(),
2912 New->getDeclName());
2915 New->setInvalidDecl();
2919 if (Init->isBaseInitializer())
2920 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
2921 New->getParent(), EllipsisLoc);
2923 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
2924 cast<CXXRecordDecl>(CurContext->getParent()));
2925 } else if (Init->isMemberInitializer()) {
2926 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
2927 Init->getMemberLocation(),
2932 New->setInvalidDecl();
2936 NewInit = BuildMemberInitializer(Member, TempInit.take(),
2937 Init->getSourceLocation());
2938 } else if (Init->isIndirectMemberInitializer()) {
2939 IndirectFieldDecl *IndirectMember =
2940 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
2941 Init->getMemberLocation(),
2942 Init->getIndirectMember(), TemplateArgs));
2944 if (!IndirectMember) {
2946 New->setInvalidDecl();
2950 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
2951 Init->getSourceLocation());
2954 if (NewInit.isInvalid()) {
2956 New->setInvalidDecl();
2958 NewInits.push_back(NewInit.get());
2962 // Assign all the initializers to the new constructor.
2963 ActOnMemInitializers(New,
2964 /*FIXME: ColonLoc */
2966 NewInits.data(), NewInits.size(),
2970 ExprResult Sema::SubstInitializer(Expr *Init,
2971 const MultiLevelTemplateArgumentList &TemplateArgs,
2972 bool CXXDirectInit) {
2973 // Initializers are instantiated like expressions, except that various outer
2974 // layers are stripped.
2978 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
2979 Init = ExprTemp->getSubExpr();
2981 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
2982 Init = Binder->getSubExpr();
2984 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
2985 Init = ICE->getSubExprAsWritten();
2987 // If this is a direct-initializer, we take apart CXXConstructExprs.
2988 // Everything else is passed through.
2989 CXXConstructExpr *Construct;
2990 if (!CXXDirectInit || !(Construct = dyn_cast<CXXConstructExpr>(Init)) ||
2991 isa<CXXTemporaryObjectExpr>(Construct))
2992 return SubstExpr(Init, TemplateArgs);
2994 ASTOwningVector<Expr*> NewArgs(*this);
2995 if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
2996 TemplateArgs, NewArgs))
2999 // Treat an empty initializer like none.
3000 if (NewArgs.empty())
3001 return Owned((Expr*)0);
3003 // Build a ParenListExpr to represent anything else.
3004 // FIXME: Fake locations!
3005 SourceLocation Loc = PP.getLocForEndOfToken(Init->getLocStart());
3006 return ActOnParenListExpr(Loc, Loc, move_arg(NewArgs));
3009 // TODO: this could be templated if the various decl types used the
3010 // same method name.
3011 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3012 ClassTemplateDecl *Instance) {
3013 Pattern = Pattern->getCanonicalDecl();
3016 Instance = Instance->getCanonicalDecl();
3017 if (Pattern == Instance) return true;
3018 Instance = Instance->getInstantiatedFromMemberTemplate();
3024 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3025 FunctionTemplateDecl *Instance) {
3026 Pattern = Pattern->getCanonicalDecl();
3029 Instance = Instance->getCanonicalDecl();
3030 if (Pattern == Instance) return true;
3031 Instance = Instance->getInstantiatedFromMemberTemplate();
3038 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3039 ClassTemplatePartialSpecializationDecl *Instance) {
3041 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3043 Instance = cast<ClassTemplatePartialSpecializationDecl>(
3044 Instance->getCanonicalDecl());
3045 if (Pattern == Instance)
3047 Instance = Instance->getInstantiatedFromMember();
3053 static bool isInstantiationOf(CXXRecordDecl *Pattern,
3054 CXXRecordDecl *Instance) {
3055 Pattern = Pattern->getCanonicalDecl();
3058 Instance = Instance->getCanonicalDecl();
3059 if (Pattern == Instance) return true;
3060 Instance = Instance->getInstantiatedFromMemberClass();
3066 static bool isInstantiationOf(FunctionDecl *Pattern,
3067 FunctionDecl *Instance) {
3068 Pattern = Pattern->getCanonicalDecl();
3071 Instance = Instance->getCanonicalDecl();
3072 if (Pattern == Instance) return true;
3073 Instance = Instance->getInstantiatedFromMemberFunction();
3079 static bool isInstantiationOf(EnumDecl *Pattern,
3080 EnumDecl *Instance) {
3081 Pattern = Pattern->getCanonicalDecl();
3084 Instance = Instance->getCanonicalDecl();
3085 if (Pattern == Instance) return true;
3086 Instance = Instance->getInstantiatedFromMemberEnum();
3092 static bool isInstantiationOf(UsingShadowDecl *Pattern,
3093 UsingShadowDecl *Instance,
3095 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3098 static bool isInstantiationOf(UsingDecl *Pattern,
3099 UsingDecl *Instance,
3101 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3104 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3105 UsingDecl *Instance,
3107 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3110 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
3111 UsingDecl *Instance,
3113 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3116 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3117 VarDecl *Instance) {
3118 assert(Instance->isStaticDataMember());
3120 Pattern = Pattern->getCanonicalDecl();
3123 Instance = Instance->getCanonicalDecl();
3124 if (Pattern == Instance) return true;
3125 Instance = Instance->getInstantiatedFromStaticDataMember();
3131 // Other is the prospective instantiation
3132 // D is the prospective pattern
3133 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
3134 if (D->getKind() != Other->getKind()) {
3135 if (UnresolvedUsingTypenameDecl *UUD
3136 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3137 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3138 return isInstantiationOf(UUD, UD, Ctx);
3142 if (UnresolvedUsingValueDecl *UUD
3143 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3144 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3145 return isInstantiationOf(UUD, UD, Ctx);
3152 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3153 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
3155 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3156 return isInstantiationOf(cast<FunctionDecl>(D), Function);
3158 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3159 return isInstantiationOf(cast<EnumDecl>(D), Enum);
3161 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
3162 if (Var->isStaticDataMember())
3163 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3165 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3166 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
3168 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3169 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3171 if (ClassTemplatePartialSpecializationDecl *PartialSpec
3172 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3173 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3176 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3177 if (!Field->getDeclName()) {
3178 // This is an unnamed field.
3179 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
3184 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3185 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3187 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3188 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3190 return D->getDeclName() && isa<NamedDecl>(Other) &&
3191 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3194 template<typename ForwardIterator>
3195 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
3197 ForwardIterator first,
3198 ForwardIterator last) {
3199 for (; first != last; ++first)
3200 if (isInstantiationOf(Ctx, D, *first))
3201 return cast<NamedDecl>(*first);
3206 /// \brief Finds the instantiation of the given declaration context
3207 /// within the current instantiation.
3209 /// \returns NULL if there was an error
3210 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
3211 const MultiLevelTemplateArgumentList &TemplateArgs) {
3212 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
3213 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
3214 return cast_or_null<DeclContext>(ID);
3218 /// \brief Find the instantiation of the given declaration within the
3219 /// current instantiation.
3221 /// This routine is intended to be used when \p D is a declaration
3222 /// referenced from within a template, that needs to mapped into the
3223 /// corresponding declaration within an instantiation. For example,
3227 /// template<typename T>
3230 /// KnownValue = sizeof(T)
3233 /// bool getKind() const { return KnownValue; }
3236 /// template struct X<int>;
3239 /// In the instantiation of X<int>::getKind(), we need to map the
3240 /// EnumConstantDecl for KnownValue (which refers to
3241 /// X<T>::<Kind>::KnownValue) to its instantiation
3242 /// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
3243 /// this mapping from within the instantiation of X<int>.
3244 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
3245 const MultiLevelTemplateArgumentList &TemplateArgs) {
3246 DeclContext *ParentDC = D->getDeclContext();
3247 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
3248 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
3249 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
3250 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
3251 // D is a local of some kind. Look into the map of local
3252 // declarations to their instantiations.
3253 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3254 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3255 = CurrentInstantiationScope->findInstantiationOf(D);
3258 if (Decl *FD = Found->dyn_cast<Decl *>())
3259 return cast<NamedDecl>(FD);
3261 unsigned PackIdx = ArgumentPackSubstitutionIndex;
3262 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3265 // If we didn't find the decl, then we must have a label decl that hasn't
3266 // been found yet. Lazily instantiate it and return it now.
3267 assert(isa<LabelDecl>(D));
3269 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3270 assert(Inst && "Failed to instantiate label??");
3272 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3273 return cast<LabelDecl>(Inst);
3276 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3277 if (!Record->isDependentContext())
3280 // Determine whether this record is the "templated" declaration describing
3281 // a class template or class template partial specialization.
3282 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
3284 ClassTemplate = ClassTemplate->getCanonicalDecl();
3285 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3286 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3287 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3289 // Walk the current context to find either the record or an instantiation of
3291 DeclContext *DC = CurContext;
3292 while (!DC->isFileContext()) {
3293 // If we're performing substitution while we're inside the template
3294 // definition, we'll find our own context. We're done.
3295 if (DC->Equals(Record))
3298 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3299 // Check whether we're in the process of instantiating a class template
3300 // specialization of the template we're mapping.
3301 if (ClassTemplateSpecializationDecl *InstSpec
3302 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3303 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3304 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3308 // Check whether we're in the process of instantiating a member class.
3309 if (isInstantiationOf(Record, InstRecord))
3314 // Move to the outer template scope.
3315 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3316 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3317 DC = FD->getLexicalDeclContext();
3322 DC = DC->getParent();
3325 // Fall through to deal with other dependent record types (e.g.,
3326 // anonymous unions in class templates).
3329 if (!ParentDC->isDependentContext())
3332 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
3336 if (ParentDC != D->getDeclContext()) {
3337 // We performed some kind of instantiation in the parent context,
3338 // so now we need to look into the instantiated parent context to
3339 // find the instantiation of the declaration D.
3341 // If our context used to be dependent, we may need to instantiate
3342 // it before performing lookup into that context.
3343 bool IsBeingInstantiated = false;
3344 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
3345 if (!Spec->isDependentContext()) {
3346 QualType T = Context.getTypeDeclType(Spec);
3347 const RecordType *Tag = T->getAs<RecordType>();
3348 assert(Tag && "type of non-dependent record is not a RecordType");
3349 if (Tag->isBeingDefined())
3350 IsBeingInstantiated = true;
3351 if (!Tag->isBeingDefined() &&
3352 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3355 ParentDC = Tag->getDecl();
3359 NamedDecl *Result = 0;
3360 if (D->getDeclName()) {
3361 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
3362 Result = findInstantiationOf(Context, D, Found.first, Found.second);
3364 // Since we don't have a name for the entity we're looking for,
3365 // our only option is to walk through all of the declarations to
3366 // find that name. This will occur in a few cases:
3368 // - anonymous struct/union within a template
3369 // - unnamed class/struct/union/enum within a template
3371 // FIXME: Find a better way to find these instantiations!
3372 Result = findInstantiationOf(Context, D,
3373 ParentDC->decls_begin(),
3374 ParentDC->decls_end());
3378 if (isa<UsingShadowDecl>(D)) {
3379 // UsingShadowDecls can instantiate to nothing because of using hiding.
3380 } else if (Diags.hasErrorOccurred()) {
3381 // We've already complained about something, so most likely this
3382 // declaration failed to instantiate. There's no point in complaining
3383 // further, since this is normal in invalid code.
3384 } else if (IsBeingInstantiated) {
3385 // The class in which this member exists is currently being
3386 // instantiated, and we haven't gotten around to instantiating this
3387 // member yet. This can happen when the code uses forward declarations
3388 // of member classes, and introduces ordering dependencies via
3389 // template instantiation.
3390 Diag(Loc, diag::err_member_not_yet_instantiated)
3392 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3393 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3394 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
3395 // This enumeration constant was found when the template was defined,
3396 // but can't be found in the instantiation. This can happen if an
3397 // unscoped enumeration member is explicitly specialized.
3398 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
3399 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
3401 assert(Spec->getTemplateSpecializationKind() ==
3402 TSK_ExplicitSpecialization);
3403 Diag(Loc, diag::err_enumerator_does_not_exist)
3405 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
3406 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
3407 << Context.getTypeDeclType(Spec);
3409 // We should have found something, but didn't.
3410 llvm_unreachable("Unable to find instantiation of declaration!");
3420 /// \brief Performs template instantiation for all implicit template
3421 /// instantiations we have seen until this point.
3422 void Sema::PerformPendingInstantiations(bool LocalOnly) {
3423 // Load pending instantiations from the external source.
3424 if (!LocalOnly && ExternalSource) {
3425 SmallVector<std::pair<ValueDecl *, SourceLocation>, 4> Pending;
3426 ExternalSource->ReadPendingInstantiations(Pending);
3427 PendingInstantiations.insert(PendingInstantiations.begin(),
3428 Pending.begin(), Pending.end());
3431 while (!PendingLocalImplicitInstantiations.empty() ||
3432 (!LocalOnly && !PendingInstantiations.empty())) {
3433 PendingImplicitInstantiation Inst;
3435 if (PendingLocalImplicitInstantiations.empty()) {
3436 Inst = PendingInstantiations.front();
3437 PendingInstantiations.pop_front();
3439 Inst = PendingLocalImplicitInstantiations.front();
3440 PendingLocalImplicitInstantiations.pop_front();
3443 // Instantiate function definitions
3444 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
3445 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3446 "instantiating function definition");
3447 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3448 TSK_ExplicitInstantiationDefinition;
3449 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3450 DefinitionRequired);
3454 // Instantiate static data member definitions.
3455 VarDecl *Var = cast<VarDecl>(Inst.first);
3456 assert(Var->isStaticDataMember() && "Not a static data member?");
3458 // Don't try to instantiate declarations if the most recent redeclaration
3460 if (Var->getMostRecentDecl()->isInvalidDecl())
3463 // Check if the most recent declaration has changed the specialization kind
3464 // and removed the need for implicit instantiation.
3465 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
3466 case TSK_Undeclared:
3467 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
3468 case TSK_ExplicitInstantiationDeclaration:
3469 case TSK_ExplicitSpecialization:
3470 continue; // No longer need to instantiate this type.
3471 case TSK_ExplicitInstantiationDefinition:
3472 // We only need an instantiation if the pending instantiation *is* the
3473 // explicit instantiation.
3474 if (Var != Var->getMostRecentDecl()) continue;
3475 case TSK_ImplicitInstantiation:
3479 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3480 "instantiating static data member "
3483 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3484 TSK_ExplicitInstantiationDefinition;
3485 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3486 DefinitionRequired);
3490 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3491 const MultiLevelTemplateArgumentList &TemplateArgs) {
3492 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3493 E = Pattern->ddiag_end(); I != E; ++I) {
3494 DependentDiagnostic *DD = *I;
3496 switch (DD->getKind()) {
3497 case DependentDiagnostic::Access:
3498 HandleDependentAccessCheck(*DD, TemplateArgs);