1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
9 // This file implements C++ template instantiation for declarations.
11 //===----------------------------------------------------------------------===/
12 #include "clang/Sema/SemaInternal.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTMutationListener.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/DependentDiagnostic.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/Sema/Lookup.h"
23 #include "clang/Sema/PrettyDeclStackTrace.h"
24 #include "clang/Sema/Template.h"
26 using namespace clang;
28 static bool isDeclWithinFunction(const Decl *D) {
29 const DeclContext *DC = D->getDeclContext();
30 if (DC->isFunctionOrMethod())
34 return cast<CXXRecordDecl>(DC)->isLocalClass();
39 template<typename DeclT>
40 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
41 const MultiLevelTemplateArgumentList &TemplateArgs) {
42 if (!OldDecl->getQualifierLoc())
45 assert((NewDecl->getFriendObjectKind() ||
46 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
47 "non-friend with qualified name defined in dependent context");
48 Sema::ContextRAII SavedContext(
50 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
51 ? NewDecl->getLexicalDeclContext()
52 : OldDecl->getLexicalDeclContext()));
54 NestedNameSpecifierLoc NewQualifierLoc
55 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
61 NewDecl->setQualifierInfo(NewQualifierLoc);
65 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
66 DeclaratorDecl *NewDecl) {
67 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
70 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
72 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
75 // Include attribute instantiation code.
76 #include "clang/Sema/AttrTemplateInstantiate.inc"
78 static void instantiateDependentAlignedAttr(
79 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
80 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
81 if (Aligned->isAlignmentExpr()) {
82 // The alignment expression is a constant expression.
83 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
84 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
85 if (!Result.isInvalid())
86 S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
87 Aligned->getSpellingListIndex(), IsPackExpansion);
89 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
90 TemplateArgs, Aligned->getLocation(),
93 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
94 Aligned->getSpellingListIndex(), IsPackExpansion);
98 static void instantiateDependentAlignedAttr(
99 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
100 const AlignedAttr *Aligned, Decl *New) {
101 if (!Aligned->isPackExpansion()) {
102 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
106 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
107 if (Aligned->isAlignmentExpr())
108 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
111 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
113 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
115 // Determine whether we can expand this attribute pack yet.
116 bool Expand = true, RetainExpansion = false;
117 Optional<unsigned> NumExpansions;
118 // FIXME: Use the actual location of the ellipsis.
119 SourceLocation EllipsisLoc = Aligned->getLocation();
120 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
121 Unexpanded, TemplateArgs, Expand,
122 RetainExpansion, NumExpansions))
126 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
127 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
129 for (unsigned I = 0; I != *NumExpansions; ++I) {
130 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
131 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
136 static void instantiateDependentAssumeAlignedAttr(
137 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
138 const AssumeAlignedAttr *Aligned, Decl *New) {
139 // The alignment expression is a constant expression.
140 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
142 Expr *E, *OE = nullptr;
143 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
144 if (Result.isInvalid())
146 E = Result.getAs<Expr>();
148 if (Aligned->getOffset()) {
149 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
150 if (Result.isInvalid())
152 OE = Result.getAs<Expr>();
155 S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
156 Aligned->getSpellingListIndex());
159 static void instantiateDependentAlignValueAttr(
160 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
161 const AlignValueAttr *Aligned, Decl *New) {
162 // The alignment expression is a constant expression.
163 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
164 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
165 if (!Result.isInvalid())
166 S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
167 Aligned->getSpellingListIndex());
170 static void instantiateDependentEnableIfAttr(
171 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
172 const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
173 Expr *Cond = nullptr;
175 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
176 ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
177 if (Result.isInvalid())
179 Cond = Result.getAs<Expr>();
181 if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
182 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
183 if (Converted.isInvalid())
185 Cond = Converted.get();
188 SmallVector<PartialDiagnosticAt, 8> Diags;
189 if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
190 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl),
192 S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
193 for (int I = 0, N = Diags.size(); I != N; ++I)
194 S.Diag(Diags[I].first, Diags[I].second);
198 EnableIfAttr *EIA = new (S.getASTContext())
199 EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
201 A->getSpellingListIndex());
205 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
206 // template A as the base and arguments from TemplateArgs.
207 static void instantiateDependentCUDALaunchBoundsAttr(
208 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
209 const CUDALaunchBoundsAttr &Attr, Decl *New) {
210 // The alignment expression is a constant expression.
211 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
213 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
214 if (Result.isInvalid())
216 Expr *MaxThreads = Result.getAs<Expr>();
218 Expr *MinBlocks = nullptr;
219 if (Attr.getMinBlocks()) {
220 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
221 if (Result.isInvalid())
223 MinBlocks = Result.getAs<Expr>();
226 S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks,
227 Attr.getSpellingListIndex());
231 instantiateDependentModeAttr(Sema &S,
232 const MultiLevelTemplateArgumentList &TemplateArgs,
233 const ModeAttr &Attr, Decl *New) {
234 S.AddModeAttr(Attr.getRange(), New, Attr.getMode(),
235 Attr.getSpellingListIndex(), /*InInstantiation=*/true);
238 /// Instantiation of 'declare simd' attribute and its arguments.
239 static void instantiateOMPDeclareSimdDeclAttr(
240 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
241 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
242 // Allow 'this' in clauses with varlists.
243 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
244 New = FTD->getTemplatedDecl();
245 auto *FD = cast<FunctionDecl>(New);
246 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
247 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
248 SmallVector<unsigned, 4> LinModifiers;
250 auto &&Subst = [&](Expr *E) -> ExprResult {
251 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
252 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
253 Sema::ContextRAII SavedContext(S, FD);
254 LocalInstantiationScope Local(S);
255 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
256 Local.InstantiatedLocal(
257 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
258 return S.SubstExpr(E, TemplateArgs);
260 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, /*TypeQuals=*/0,
261 FD->isCXXInstanceMember());
262 return S.SubstExpr(E, TemplateArgs);
266 if (auto *E = Attr.getSimdlen())
269 if (Attr.uniforms_size() > 0) {
270 for(auto *E : Attr.uniforms()) {
271 ExprResult Inst = Subst(E);
272 if (Inst.isInvalid())
274 Uniforms.push_back(Inst.get());
278 auto AI = Attr.alignments_begin();
279 for (auto *E : Attr.aligneds()) {
280 ExprResult Inst = Subst(E);
281 if (Inst.isInvalid())
283 Aligneds.push_back(Inst.get());
286 Inst = S.SubstExpr(*AI, TemplateArgs);
287 Alignments.push_back(Inst.get());
291 auto SI = Attr.steps_begin();
292 for (auto *E : Attr.linears()) {
293 ExprResult Inst = Subst(E);
294 if (Inst.isInvalid())
296 Linears.push_back(Inst.get());
299 Inst = S.SubstExpr(*SI, TemplateArgs);
300 Steps.push_back(Inst.get());
303 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
304 (void)S.ActOnOpenMPDeclareSimdDirective(
305 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
306 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
310 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
311 const Decl *Tmpl, Decl *New,
312 LateInstantiatedAttrVec *LateAttrs,
313 LocalInstantiationScope *OuterMostScope) {
314 for (const auto *TmplAttr : Tmpl->attrs()) {
315 // FIXME: This should be generalized to more than just the AlignedAttr.
316 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
317 if (Aligned && Aligned->isAlignmentDependent()) {
318 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
322 const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
324 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
328 const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
330 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
334 const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
335 if (EnableIf && EnableIf->getCond()->isValueDependent()) {
336 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
341 if (const CUDALaunchBoundsAttr *CUDALaunchBounds =
342 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
343 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
344 *CUDALaunchBounds, New);
348 if (const ModeAttr *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
349 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
353 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
354 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
358 // Existing DLL attribute on the instantiation takes precedence.
359 if (TmplAttr->getKind() == attr::DLLExport ||
360 TmplAttr->getKind() == attr::DLLImport) {
361 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
366 if (auto ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
367 AddParameterABIAttr(ABIAttr->getRange(), New, ABIAttr->getABI(),
368 ABIAttr->getSpellingListIndex());
372 if (isa<NSConsumedAttr>(TmplAttr) || isa<CFConsumedAttr>(TmplAttr)) {
373 AddNSConsumedAttr(TmplAttr->getRange(), New,
374 TmplAttr->getSpellingListIndex(),
375 isa<NSConsumedAttr>(TmplAttr),
376 /*template instantiation*/ true);
380 assert(!TmplAttr->isPackExpansion());
381 if (TmplAttr->isLateParsed() && LateAttrs) {
382 // Late parsed attributes must be instantiated and attached after the
383 // enclosing class has been instantiated. See Sema::InstantiateClass.
384 LocalInstantiationScope *Saved = nullptr;
385 if (CurrentInstantiationScope)
386 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
387 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
389 // Allow 'this' within late-parsed attributes.
390 NamedDecl *ND = dyn_cast<NamedDecl>(New);
391 CXXRecordDecl *ThisContext =
392 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
393 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
394 ND && ND->isCXXInstanceMember());
396 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
397 *this, TemplateArgs);
399 New->addAttr(NewAttr);
404 /// Get the previous declaration of a declaration for the purposes of template
405 /// instantiation. If this finds a previous declaration, then the previous
406 /// declaration of the instantiation of D should be an instantiation of the
407 /// result of this function.
408 template<typename DeclT>
409 static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
410 DeclT *Result = D->getPreviousDecl();
412 // If the declaration is within a class, and the previous declaration was
413 // merged from a different definition of that class, then we don't have a
414 // previous declaration for the purpose of template instantiation.
415 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
416 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
423 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
424 llvm_unreachable("Translation units cannot be instantiated");
428 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
429 llvm_unreachable("pragma comment cannot be instantiated");
432 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
433 PragmaDetectMismatchDecl *D) {
434 llvm_unreachable("pragma comment cannot be instantiated");
438 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
439 llvm_unreachable("extern \"C\" context cannot be instantiated");
443 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
444 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
446 Owner->addDecl(Inst);
451 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
452 llvm_unreachable("Namespaces cannot be instantiated");
456 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
457 NamespaceAliasDecl *Inst
458 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
459 D->getNamespaceLoc(),
462 D->getQualifierLoc(),
463 D->getTargetNameLoc(),
465 Owner->addDecl(Inst);
469 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
471 bool Invalid = false;
472 TypeSourceInfo *DI = D->getTypeSourceInfo();
473 if (DI->getType()->isInstantiationDependentType() ||
474 DI->getType()->isVariablyModifiedType()) {
475 DI = SemaRef.SubstType(DI, TemplateArgs,
476 D->getLocation(), D->getDeclName());
479 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
482 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
485 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
486 // libstdc++ relies upon this bug in its implementation of common_type.
487 // If we happen to be processing that implementation, fake up the g++ ?:
488 // semantics. See LWG issue 2141 for more information on the bug.
489 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
490 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
491 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
492 DT->isReferenceType() &&
493 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
494 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
495 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
496 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
497 // Fold it to the (non-reference) type which g++ would have produced.
498 DI = SemaRef.Context.getTrivialTypeSourceInfo(
499 DI->getType().getNonReferenceType());
501 // Create the new typedef
502 TypedefNameDecl *Typedef;
504 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
505 D->getLocation(), D->getIdentifier(), DI);
507 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
508 D->getLocation(), D->getIdentifier(), DI);
510 Typedef->setInvalidDecl();
512 // If the old typedef was the name for linkage purposes of an anonymous
513 // tag decl, re-establish that relationship for the new typedef.
514 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
515 TagDecl *oldTag = oldTagType->getDecl();
516 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
517 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
518 assert(!newTag->hasNameForLinkage());
519 newTag->setTypedefNameForAnonDecl(Typedef);
523 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
524 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
529 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
531 // If the typedef types are not identical, reject them.
532 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
534 Typedef->setPreviousDecl(InstPrevTypedef);
537 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
539 Typedef->setAccess(D->getAccess());
544 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
545 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
547 Owner->addDecl(Typedef);
551 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
552 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
554 Owner->addDecl(Typedef);
559 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
560 // Create a local instantiation scope for this type alias template, which
561 // will contain the instantiations of the template parameters.
562 LocalInstantiationScope Scope(SemaRef);
564 TemplateParameterList *TempParams = D->getTemplateParameters();
565 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
569 TypeAliasDecl *Pattern = D->getTemplatedDecl();
571 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
572 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
573 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
574 if (!Found.empty()) {
575 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
579 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
580 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
584 TypeAliasTemplateDecl *Inst
585 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
586 D->getDeclName(), InstParams, AliasInst);
587 AliasInst->setDescribedAliasTemplate(Inst);
588 if (PrevAliasTemplate)
589 Inst->setPreviousDecl(PrevAliasTemplate);
591 Inst->setAccess(D->getAccess());
593 if (!PrevAliasTemplate)
594 Inst->setInstantiatedFromMemberTemplate(D);
596 Owner->addDecl(Inst);
601 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
602 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
605 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
606 bool InstantiatingVarTemplate) {
608 // Do substitution on the type of the declaration
609 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
611 D->getTypeSpecStartLoc(),
616 if (DI->getType()->isFunctionType()) {
617 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
618 << D->isStaticDataMember() << DI->getType();
622 DeclContext *DC = Owner;
623 if (D->isLocalExternDecl())
624 SemaRef.adjustContextForLocalExternDecl(DC);
626 // Build the instantiated declaration.
627 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
628 D->getLocation(), D->getIdentifier(),
629 DI->getType(), DI, D->getStorageClass());
631 // In ARC, infer 'retaining' for variables of retainable type.
632 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
633 SemaRef.inferObjCARCLifetime(Var))
634 Var->setInvalidDecl();
636 // Substitute the nested name specifier, if any.
637 if (SubstQualifier(D, Var))
640 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
641 StartingScope, InstantiatingVarTemplate);
643 if (D->isNRVOVariable()) {
644 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
645 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
646 Var->setNRVOVariable(true);
649 Var->setImplicit(D->isImplicit());
654 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
656 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
657 D->getAccessSpecifierLoc(), D->getColonLoc());
658 Owner->addHiddenDecl(AD);
662 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
663 bool Invalid = false;
664 TypeSourceInfo *DI = D->getTypeSourceInfo();
665 if (DI->getType()->isInstantiationDependentType() ||
666 DI->getType()->isVariablyModifiedType()) {
667 DI = SemaRef.SubstType(DI, TemplateArgs,
668 D->getLocation(), D->getDeclName());
670 DI = D->getTypeSourceInfo();
672 } else if (DI->getType()->isFunctionType()) {
673 // C++ [temp.arg.type]p3:
674 // If a declaration acquires a function type through a type
675 // dependent on a template-parameter and this causes a
676 // declaration that does not use the syntactic form of a
677 // function declarator to have function type, the program is
679 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
684 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
687 Expr *BitWidth = D->getBitWidth();
691 // The bit-width expression is a constant expression.
692 EnterExpressionEvaluationContext Unevaluated(SemaRef,
693 Sema::ConstantEvaluated);
695 ExprResult InstantiatedBitWidth
696 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
697 if (InstantiatedBitWidth.isInvalid()) {
701 BitWidth = InstantiatedBitWidth.getAs<Expr>();
704 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
706 cast<RecordDecl>(Owner),
710 D->getInClassInitStyle(),
711 D->getInnerLocStart(),
715 cast<Decl>(Owner)->setInvalidDecl();
719 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
721 if (Field->hasAttrs())
722 SemaRef.CheckAlignasUnderalignment(Field);
725 Field->setInvalidDecl();
727 if (!Field->getDeclName()) {
728 // Keep track of where this decl came from.
729 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
731 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
732 if (Parent->isAnonymousStructOrUnion() &&
733 Parent->getRedeclContext()->isFunctionOrMethod())
734 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
737 Field->setImplicit(D->isImplicit());
738 Field->setAccess(D->getAccess());
739 Owner->addDecl(Field);
744 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
745 bool Invalid = false;
746 TypeSourceInfo *DI = D->getTypeSourceInfo();
748 if (DI->getType()->isVariablyModifiedType()) {
749 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
752 } else if (DI->getType()->isInstantiationDependentType()) {
753 DI = SemaRef.SubstType(DI, TemplateArgs,
754 D->getLocation(), D->getDeclName());
756 DI = D->getTypeSourceInfo();
758 } else if (DI->getType()->isFunctionType()) {
759 // C++ [temp.arg.type]p3:
760 // If a declaration acquires a function type through a type
761 // dependent on a template-parameter and this causes a
762 // declaration that does not use the syntactic form of a
763 // function declarator to have function type, the program is
765 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
770 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
773 MSPropertyDecl *Property = MSPropertyDecl::Create(
774 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
775 DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
777 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
781 Property->setInvalidDecl();
783 Property->setAccess(D->getAccess());
784 Owner->addDecl(Property);
789 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
790 NamedDecl **NamedChain =
791 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
794 for (auto *PI : D->chain()) {
795 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
800 NamedChain[i++] = Next;
803 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
804 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
805 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
806 {NamedChain, D->getChainingSize()});
808 for (const auto *Attr : D->attrs())
809 IndirectField->addAttr(Attr->clone(SemaRef.Context));
811 IndirectField->setImplicit(D->isImplicit());
812 IndirectField->setAccess(D->getAccess());
813 Owner->addDecl(IndirectField);
814 return IndirectField;
817 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
818 // Handle friend type expressions by simply substituting template
819 // parameters into the pattern type and checking the result.
820 if (TypeSourceInfo *Ty = D->getFriendType()) {
821 TypeSourceInfo *InstTy;
822 // If this is an unsupported friend, don't bother substituting template
823 // arguments into it. The actual type referred to won't be used by any
824 // parts of Clang, and may not be valid for instantiating. Just use the
825 // same info for the instantiated friend.
826 if (D->isUnsupportedFriend()) {
829 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
830 D->getLocation(), DeclarationName());
835 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
836 D->getFriendLoc(), InstTy);
840 FD->setAccess(AS_public);
841 FD->setUnsupportedFriend(D->isUnsupportedFriend());
846 NamedDecl *ND = D->getFriendDecl();
847 assert(ND && "friend decl must be a decl or a type!");
849 // All of the Visit implementations for the various potential friend
850 // declarations have to be carefully written to work for friend
851 // objects, with the most important detail being that the target
852 // decl should almost certainly not be placed in Owner.
853 Decl *NewND = Visit(ND);
854 if (!NewND) return nullptr;
857 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
858 cast<NamedDecl>(NewND), D->getFriendLoc());
859 FD->setAccess(AS_public);
860 FD->setUnsupportedFriend(D->isUnsupportedFriend());
865 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
866 Expr *AssertExpr = D->getAssertExpr();
868 // The expression in a static assertion is a constant expression.
869 EnterExpressionEvaluationContext Unevaluated(SemaRef,
870 Sema::ConstantEvaluated);
872 ExprResult InstantiatedAssertExpr
873 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
874 if (InstantiatedAssertExpr.isInvalid())
877 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
878 InstantiatedAssertExpr.get(),
884 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
885 EnumDecl *PrevDecl = nullptr;
886 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
887 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
890 if (!Prev) return nullptr;
891 PrevDecl = cast<EnumDecl>(Prev);
894 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
895 D->getLocation(), D->getIdentifier(),
896 PrevDecl, D->isScoped(),
897 D->isScopedUsingClassTag(), D->isFixed());
899 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
900 // If we have type source information for the underlying type, it means it
901 // has been explicitly set by the user. Perform substitution on it before
903 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
904 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
906 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
907 Enum->setIntegerType(SemaRef.Context.IntTy);
909 Enum->setIntegerTypeSourceInfo(NewTI);
911 assert(!D->getIntegerType()->isDependentType()
912 && "Dependent type without type source info");
913 Enum->setIntegerType(D->getIntegerType());
917 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
919 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
920 Enum->setAccess(D->getAccess());
921 // Forward the mangling number from the template to the instantiated decl.
922 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
923 // See if the old tag was defined along with a declarator.
924 // If it did, mark the new tag as being associated with that declarator.
925 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
926 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
927 // See if the old tag was defined along with a typedef.
928 // If it did, mark the new tag as being associated with that typedef.
929 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
930 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
931 if (SubstQualifier(D, Enum)) return nullptr;
932 Owner->addDecl(Enum);
934 EnumDecl *Def = D->getDefinition();
935 if (Def && Def != D) {
936 // If this is an out-of-line definition of an enum member template, check
937 // that the underlying types match in the instantiation of both
939 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
940 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
941 QualType DefnUnderlying =
942 SemaRef.SubstType(TI->getType(), TemplateArgs,
943 UnderlyingLoc, DeclarationName());
944 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
946 /*EnumUnderlyingIsImplicit=*/false, Enum);
950 // C++11 [temp.inst]p1: The implicit instantiation of a class template
951 // specialization causes the implicit instantiation of the declarations, but
952 // not the definitions of scoped member enumerations.
954 // DR1484 clarifies that enumeration definitions inside of a template
955 // declaration aren't considered entities that can be separately instantiated
956 // from the rest of the entity they are declared inside of.
957 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
958 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
959 InstantiateEnumDefinition(Enum, Def);
965 void TemplateDeclInstantiator::InstantiateEnumDefinition(
966 EnumDecl *Enum, EnumDecl *Pattern) {
967 Enum->startDefinition();
969 // Update the location to refer to the definition.
970 Enum->setLocation(Pattern->getLocation());
972 SmallVector<Decl*, 4> Enumerators;
974 EnumConstantDecl *LastEnumConst = nullptr;
975 for (auto *EC : Pattern->enumerators()) {
976 // The specified value for the enumerator.
977 ExprResult Value((Expr *)nullptr);
978 if (Expr *UninstValue = EC->getInitExpr()) {
979 // The enumerator's value expression is a constant expression.
980 EnterExpressionEvaluationContext Unevaluated(SemaRef,
981 Sema::ConstantEvaluated);
983 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
986 // Drop the initial value and continue.
987 bool isInvalid = false;
988 if (Value.isInvalid()) {
993 EnumConstantDecl *EnumConst
994 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
995 EC->getLocation(), EC->getIdentifier(),
1000 EnumConst->setInvalidDecl();
1001 Enum->setInvalidDecl();
1005 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1007 EnumConst->setAccess(Enum->getAccess());
1008 Enum->addDecl(EnumConst);
1009 Enumerators.push_back(EnumConst);
1010 LastEnumConst = EnumConst;
1012 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1013 !Enum->isScoped()) {
1014 // If the enumeration is within a function or method, record the enum
1015 // constant as a local.
1016 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1021 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1026 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1027 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1031 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1032 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1035 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1036 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1038 // Create a local instantiation scope for this class template, which
1039 // will contain the instantiations of the template parameters.
1040 LocalInstantiationScope Scope(SemaRef);
1041 TemplateParameterList *TempParams = D->getTemplateParameters();
1042 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1046 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1048 // Instantiate the qualifier. We have to do this first in case
1049 // we're a friend declaration, because if we are then we need to put
1050 // the new declaration in the appropriate context.
1051 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1053 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1059 CXXRecordDecl *PrevDecl = nullptr;
1060 ClassTemplateDecl *PrevClassTemplate = nullptr;
1062 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1063 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1064 if (!Found.empty()) {
1065 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1066 if (PrevClassTemplate)
1067 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1071 // If this isn't a friend, then it's a member template, in which
1072 // case we just want to build the instantiation in the
1073 // specialization. If it is a friend, we want to build it in
1074 // the appropriate context.
1075 DeclContext *DC = Owner;
1079 SS.Adopt(QualifierLoc);
1080 DC = SemaRef.computeDeclContext(SS);
1081 if (!DC) return nullptr;
1083 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1084 Pattern->getDeclContext(),
1088 // Look for a previous declaration of the template in the owning
1090 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1091 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1092 SemaRef.LookupQualifiedName(R, DC);
1094 if (R.isSingleResult()) {
1095 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1096 if (PrevClassTemplate)
1097 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1100 if (!PrevClassTemplate && QualifierLoc) {
1101 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1102 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1103 << QualifierLoc.getSourceRange();
1107 bool AdoptedPreviousTemplateParams = false;
1108 if (PrevClassTemplate) {
1109 bool Complain = true;
1111 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1112 // template for struct std::tr1::__detail::_Map_base, where the
1113 // template parameters of the friend declaration don't match the
1114 // template parameters of the original declaration. In this one
1115 // case, we don't complain about the ill-formed friend
1117 if (isFriend && Pattern->getIdentifier() &&
1118 Pattern->getIdentifier()->isStr("_Map_base") &&
1119 DC->isNamespace() &&
1120 cast<NamespaceDecl>(DC)->getIdentifier() &&
1121 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
1122 DeclContext *DCParent = DC->getParent();
1123 if (DCParent->isNamespace() &&
1124 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1125 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
1126 if (cast<Decl>(DCParent)->isInStdNamespace())
1131 TemplateParameterList *PrevParams
1132 = PrevClassTemplate->getTemplateParameters();
1134 // Make sure the parameter lists match.
1135 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
1137 Sema::TPL_TemplateMatch)) {
1141 AdoptedPreviousTemplateParams = true;
1142 InstParams = PrevParams;
1145 // Do some additional validation, then merge default arguments
1146 // from the existing declarations.
1147 if (!AdoptedPreviousTemplateParams &&
1148 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1149 Sema::TPC_ClassTemplate))
1154 CXXRecordDecl *RecordInst
1155 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
1156 Pattern->getLocStart(), Pattern->getLocation(),
1157 Pattern->getIdentifier(), PrevDecl,
1158 /*DelayTypeCreation=*/true);
1161 RecordInst->setQualifierInfo(QualifierLoc);
1163 ClassTemplateDecl *Inst
1164 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1165 D->getIdentifier(), InstParams, RecordInst,
1167 RecordInst->setDescribedClassTemplate(Inst);
1170 if (PrevClassTemplate)
1171 Inst->setAccess(PrevClassTemplate->getAccess());
1173 Inst->setAccess(D->getAccess());
1175 Inst->setObjectOfFriendDecl();
1176 // TODO: do we want to track the instantiation progeny of this
1177 // friend target decl?
1179 Inst->setAccess(D->getAccess());
1180 if (!PrevClassTemplate)
1181 Inst->setInstantiatedFromMemberTemplate(D);
1184 // Trigger creation of the type for the instantiation.
1185 SemaRef.Context.getInjectedClassNameType(RecordInst,
1186 Inst->getInjectedClassNameSpecialization());
1188 // Finish handling of friends.
1190 DC->makeDeclVisibleInContext(Inst);
1191 Inst->setLexicalDeclContext(Owner);
1192 RecordInst->setLexicalDeclContext(Owner);
1196 if (D->isOutOfLine()) {
1197 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1198 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1201 Owner->addDecl(Inst);
1203 if (!PrevClassTemplate) {
1204 // Queue up any out-of-line partial specializations of this member
1205 // class template; the client will force their instantiation once
1206 // the enclosing class has been instantiated.
1207 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1208 D->getPartialSpecializations(PartialSpecs);
1209 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1210 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1211 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1218 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1219 ClassTemplatePartialSpecializationDecl *D) {
1220 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1222 // Lookup the already-instantiated declaration in the instantiation
1223 // of the class template and return that.
1224 DeclContext::lookup_result Found
1225 = Owner->lookup(ClassTemplate->getDeclName());
1229 ClassTemplateDecl *InstClassTemplate
1230 = dyn_cast<ClassTemplateDecl>(Found.front());
1231 if (!InstClassTemplate)
1234 if (ClassTemplatePartialSpecializationDecl *Result
1235 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1238 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1241 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1242 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1243 "Only static data member templates are allowed.");
1245 // Create a local instantiation scope for this variable template, which
1246 // will contain the instantiations of the template parameters.
1247 LocalInstantiationScope Scope(SemaRef);
1248 TemplateParameterList *TempParams = D->getTemplateParameters();
1249 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1253 VarDecl *Pattern = D->getTemplatedDecl();
1254 VarTemplateDecl *PrevVarTemplate = nullptr;
1256 if (getPreviousDeclForInstantiation(Pattern)) {
1257 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1259 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1263 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1264 /*InstantiatingVarTemplate=*/true));
1265 if (!VarInst) return nullptr;
1267 DeclContext *DC = Owner;
1269 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1270 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1272 VarInst->setDescribedVarTemplate(Inst);
1273 Inst->setPreviousDecl(PrevVarTemplate);
1275 Inst->setAccess(D->getAccess());
1276 if (!PrevVarTemplate)
1277 Inst->setInstantiatedFromMemberTemplate(D);
1279 if (D->isOutOfLine()) {
1280 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1281 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1284 Owner->addDecl(Inst);
1286 if (!PrevVarTemplate) {
1287 // Queue up any out-of-line partial specializations of this member
1288 // variable template; the client will force their instantiation once
1289 // the enclosing class has been instantiated.
1290 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1291 D->getPartialSpecializations(PartialSpecs);
1292 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1293 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1294 OutOfLineVarPartialSpecs.push_back(
1295 std::make_pair(Inst, PartialSpecs[I]));
1301 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1302 VarTemplatePartialSpecializationDecl *D) {
1303 assert(D->isStaticDataMember() &&
1304 "Only static data member templates are allowed.");
1306 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1308 // Lookup the already-instantiated declaration and return that.
1309 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1310 assert(!Found.empty() && "Instantiation found nothing?");
1312 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1313 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1315 if (VarTemplatePartialSpecializationDecl *Result =
1316 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1319 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1323 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1324 // Create a local instantiation scope for this function template, which
1325 // will contain the instantiations of the template parameters and then get
1326 // merged with the local instantiation scope for the function template
1328 LocalInstantiationScope Scope(SemaRef);
1330 TemplateParameterList *TempParams = D->getTemplateParameters();
1331 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1335 FunctionDecl *Instantiated = nullptr;
1336 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1337 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1340 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1341 D->getTemplatedDecl(),
1347 // Link the instantiated function template declaration to the function
1348 // template from which it was instantiated.
1349 FunctionTemplateDecl *InstTemplate
1350 = Instantiated->getDescribedFunctionTemplate();
1351 InstTemplate->setAccess(D->getAccess());
1352 assert(InstTemplate &&
1353 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1355 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1357 // Link the instantiation back to the pattern *unless* this is a
1358 // non-definition friend declaration.
1359 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1360 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1361 InstTemplate->setInstantiatedFromMemberTemplate(D);
1363 // Make declarations visible in the appropriate context.
1365 Owner->addDecl(InstTemplate);
1366 } else if (InstTemplate->getDeclContext()->isRecord() &&
1367 !getPreviousDeclForInstantiation(D)) {
1368 SemaRef.CheckFriendAccess(InstTemplate);
1371 return InstTemplate;
1374 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1375 CXXRecordDecl *PrevDecl = nullptr;
1376 if (D->isInjectedClassName())
1377 PrevDecl = cast<CXXRecordDecl>(Owner);
1378 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1379 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1382 if (!Prev) return nullptr;
1383 PrevDecl = cast<CXXRecordDecl>(Prev);
1386 CXXRecordDecl *Record
1387 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1388 D->getLocStart(), D->getLocation(),
1389 D->getIdentifier(), PrevDecl);
1391 // Substitute the nested name specifier, if any.
1392 if (SubstQualifier(D, Record))
1395 Record->setImplicit(D->isImplicit());
1396 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1397 // the tag decls introduced by friend class declarations don't have an access
1398 // specifier. Remove once this area of the code gets sorted out.
1399 if (D->getAccess() != AS_none)
1400 Record->setAccess(D->getAccess());
1401 if (!D->isInjectedClassName())
1402 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1404 // If the original function was part of a friend declaration,
1405 // inherit its namespace state.
1406 if (D->getFriendObjectKind())
1407 Record->setObjectOfFriendDecl();
1409 // Make sure that anonymous structs and unions are recorded.
1410 if (D->isAnonymousStructOrUnion())
1411 Record->setAnonymousStructOrUnion(true);
1413 if (D->isLocalClass())
1414 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1416 // Forward the mangling number from the template to the instantiated decl.
1417 SemaRef.Context.setManglingNumber(Record,
1418 SemaRef.Context.getManglingNumber(D));
1420 // See if the old tag was defined along with a declarator.
1421 // If it did, mark the new tag as being associated with that declarator.
1422 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1423 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1425 // See if the old tag was defined along with a typedef.
1426 // If it did, mark the new tag as being associated with that typedef.
1427 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1428 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1430 Owner->addDecl(Record);
1432 // DR1484 clarifies that the members of a local class are instantiated as part
1433 // of the instantiation of their enclosing entity.
1434 if (D->isCompleteDefinition() && D->isLocalClass()) {
1435 Sema::SavePendingLocalImplicitInstantiationsRAII
1436 SavedPendingLocalImplicitInstantiations(SemaRef);
1438 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1439 TSK_ImplicitInstantiation,
1442 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1443 TSK_ImplicitInstantiation);
1445 // This class may have local implicit instantiations that need to be
1446 // performed within this scope.
1447 SemaRef.PerformPendingInstantiations(/*LocalOnly=*/true);
1450 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1455 /// \brief Adjust the given function type for an instantiation of the
1456 /// given declaration, to cope with modifications to the function's type that
1457 /// aren't reflected in the type-source information.
1459 /// \param D The declaration we're instantiating.
1460 /// \param TInfo The already-instantiated type.
1461 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1463 TypeSourceInfo *TInfo) {
1464 const FunctionProtoType *OrigFunc
1465 = D->getType()->castAs<FunctionProtoType>();
1466 const FunctionProtoType *NewFunc
1467 = TInfo->getType()->castAs<FunctionProtoType>();
1468 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1469 return TInfo->getType();
1471 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1472 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1473 return Context.getFunctionType(NewFunc->getReturnType(),
1474 NewFunc->getParamTypes(), NewEPI);
1477 /// Normal class members are of more specific types and therefore
1478 /// don't make it here. This function serves two purposes:
1479 /// 1) instantiating function templates
1480 /// 2) substituting friend declarations
1481 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1482 TemplateParameterList *TemplateParams) {
1483 // Check whether there is already a function template specialization for
1484 // this declaration.
1485 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1486 if (FunctionTemplate && !TemplateParams) {
1487 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1489 void *InsertPos = nullptr;
1490 FunctionDecl *SpecFunc
1491 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1493 // If we already have a function template specialization, return it.
1499 if (FunctionTemplate)
1500 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1502 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1504 bool MergeWithParentScope = (TemplateParams != nullptr) ||
1505 Owner->isFunctionOrMethod() ||
1506 !(isa<Decl>(Owner) &&
1507 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1508 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1510 SmallVector<ParmVarDecl *, 4> Params;
1511 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1514 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1516 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1518 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1524 // If we're instantiating a local function declaration, put the result
1525 // in the enclosing namespace; otherwise we need to find the instantiated
1528 if (D->isLocalExternDecl()) {
1530 SemaRef.adjustContextForLocalExternDecl(DC);
1531 } else if (isFriend && QualifierLoc) {
1533 SS.Adopt(QualifierLoc);
1534 DC = SemaRef.computeDeclContext(SS);
1535 if (!DC) return nullptr;
1537 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1541 FunctionDecl *Function =
1542 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1543 D->getNameInfo(), T, TInfo,
1544 D->getCanonicalDecl()->getStorageClass(),
1545 D->isInlineSpecified(), D->hasWrittenPrototype(),
1547 Function->setRangeEnd(D->getSourceRange().getEnd());
1550 Function->setImplicitlyInline();
1553 Function->setQualifierInfo(QualifierLoc);
1555 if (D->isLocalExternDecl())
1556 Function->setLocalExternDecl();
1558 DeclContext *LexicalDC = Owner;
1559 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1560 assert(D->getDeclContext()->isFileContext());
1561 LexicalDC = D->getDeclContext();
1564 Function->setLexicalDeclContext(LexicalDC);
1566 // Attach the parameters
1567 for (unsigned P = 0; P < Params.size(); ++P)
1569 Params[P]->setOwningFunction(Function);
1570 Function->setParams(Params);
1572 SourceLocation InstantiateAtPOI;
1573 if (TemplateParams) {
1574 // Our resulting instantiation is actually a function template, since we
1575 // are substituting only the outer template parameters. For example, given
1577 // template<typename T>
1579 // template<typename U> friend void f(T, U);
1584 // We are instantiating the friend function template "f" within X<int>,
1585 // which means substituting int for T, but leaving "f" as a friend function
1587 // Build the function template itself.
1588 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1589 Function->getLocation(),
1590 Function->getDeclName(),
1591 TemplateParams, Function);
1592 Function->setDescribedFunctionTemplate(FunctionTemplate);
1594 FunctionTemplate->setLexicalDeclContext(LexicalDC);
1596 if (isFriend && D->isThisDeclarationADefinition()) {
1597 // TODO: should we remember this connection regardless of whether
1598 // the friend declaration provided a body?
1599 FunctionTemplate->setInstantiatedFromMemberTemplate(
1600 D->getDescribedFunctionTemplate());
1602 } else if (FunctionTemplate) {
1603 // Record this function template specialization.
1604 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1605 Function->setFunctionTemplateSpecialization(FunctionTemplate,
1606 TemplateArgumentList::CreateCopy(SemaRef.Context,
1608 /*InsertPos=*/nullptr);
1609 } else if (isFriend) {
1610 // Note, we need this connection even if the friend doesn't have a body.
1611 // Its body may exist but not have been attached yet due to deferred
1613 // FIXME: It might be cleaner to set this when attaching the body to the
1614 // friend function declaration, however that would require finding all the
1615 // instantiations and modifying them.
1616 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1619 if (InitFunctionInstantiation(Function, D))
1620 Function->setInvalidDecl();
1622 bool isExplicitSpecialization = false;
1624 LookupResult Previous(
1625 SemaRef, Function->getDeclName(), SourceLocation(),
1626 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1627 : Sema::LookupOrdinaryName,
1628 Sema::ForRedeclaration);
1630 if (DependentFunctionTemplateSpecializationInfo *Info
1631 = D->getDependentSpecializationInfo()) {
1632 assert(isFriend && "non-friend has dependent specialization info?");
1634 // This needs to be set now for future sanity.
1635 Function->setObjectOfFriendDecl();
1637 // Instantiate the explicit template arguments.
1638 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1639 Info->getRAngleLoc());
1640 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1641 ExplicitArgs, TemplateArgs))
1644 // Map the candidate templates to their instantiations.
1645 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1646 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1647 Info->getTemplate(I),
1649 if (!Temp) return nullptr;
1651 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1654 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1657 Function->setInvalidDecl();
1659 isExplicitSpecialization = true;
1661 } else if (TemplateParams || !FunctionTemplate) {
1662 // Look only into the namespace where the friend would be declared to
1663 // find a previous declaration. This is the innermost enclosing namespace,
1664 // as described in ActOnFriendFunctionDecl.
1665 SemaRef.LookupQualifiedName(Previous, DC);
1667 // In C++, the previous declaration we find might be a tag type
1668 // (class or enum). In this case, the new declaration will hide the
1669 // tag type. Note that this does does not apply if we're declaring a
1670 // typedef (C++ [dcl.typedef]p4).
1671 if (Previous.isSingleTagDecl())
1675 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
1676 isExplicitSpecialization);
1678 NamedDecl *PrincipalDecl = (TemplateParams
1679 ? cast<NamedDecl>(FunctionTemplate)
1682 // If the original function was part of a friend declaration,
1683 // inherit its namespace state and add it to the owner.
1685 PrincipalDecl->setObjectOfFriendDecl();
1686 DC->makeDeclVisibleInContext(PrincipalDecl);
1688 bool QueuedInstantiation = false;
1690 // C++11 [temp.friend]p4 (DR329):
1691 // When a function is defined in a friend function declaration in a class
1692 // template, the function is instantiated when the function is odr-used.
1693 // The same restrictions on multiple declarations and definitions that
1694 // apply to non-template function declarations and definitions also apply
1695 // to these implicit definitions.
1696 if (D->isThisDeclarationADefinition()) {
1697 // Check for a function body.
1698 const FunctionDecl *Definition = nullptr;
1699 if (Function->isDefined(Definition) &&
1700 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1701 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1702 << Function->getDeclName();
1703 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1705 // Check for redefinitions due to other instantiations of this or
1706 // a similar friend function.
1707 else for (auto R : Function->redecls()) {
1711 // If some prior declaration of this function has been used, we need
1712 // to instantiate its definition.
1713 if (!QueuedInstantiation && R->isUsed(false)) {
1714 if (MemberSpecializationInfo *MSInfo =
1715 Function->getMemberSpecializationInfo()) {
1716 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1717 SourceLocation Loc = R->getLocation(); // FIXME
1718 MSInfo->setPointOfInstantiation(Loc);
1719 SemaRef.PendingLocalImplicitInstantiations.push_back(
1720 std::make_pair(Function, Loc));
1721 QueuedInstantiation = true;
1726 // If some prior declaration of this function was a friend with an
1727 // uninstantiated definition, reject it.
1728 if (R->getFriendObjectKind()) {
1729 if (const FunctionDecl *RPattern =
1730 R->getTemplateInstantiationPattern()) {
1731 if (RPattern->isDefined(RPattern)) {
1732 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1733 << Function->getDeclName();
1734 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1743 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1744 DC->makeDeclVisibleInContext(PrincipalDecl);
1746 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1747 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1748 PrincipalDecl->setNonMemberOperator();
1750 assert(!D->isDefaulted() && "only methods should be defaulted");
1755 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1756 TemplateParameterList *TemplateParams,
1757 bool IsClassScopeSpecialization) {
1758 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1759 if (FunctionTemplate && !TemplateParams) {
1760 // We are creating a function template specialization from a function
1761 // template. Check whether there is already a function template
1762 // specialization for this particular set of template arguments.
1763 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1765 void *InsertPos = nullptr;
1766 FunctionDecl *SpecFunc
1767 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1769 // If we already have a function template specialization, return it.
1775 if (FunctionTemplate)
1776 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1778 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1780 bool MergeWithParentScope = (TemplateParams != nullptr) ||
1781 !(isa<Decl>(Owner) &&
1782 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1783 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1785 // Instantiate enclosing template arguments for friends.
1786 SmallVector<TemplateParameterList *, 4> TempParamLists;
1787 unsigned NumTempParamLists = 0;
1788 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1789 TempParamLists.resize(NumTempParamLists);
1790 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1791 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1792 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1795 TempParamLists[I] = InstParams;
1799 SmallVector<ParmVarDecl *, 4> Params;
1800 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1803 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1805 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1807 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1813 DeclContext *DC = Owner;
1817 SS.Adopt(QualifierLoc);
1818 DC = SemaRef.computeDeclContext(SS);
1820 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1823 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1824 D->getDeclContext(),
1827 if (!DC) return nullptr;
1830 // Build the instantiated method declaration.
1831 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1832 CXXMethodDecl *Method = nullptr;
1834 SourceLocation StartLoc = D->getInnerLocStart();
1835 DeclarationNameInfo NameInfo
1836 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1837 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1838 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1839 StartLoc, NameInfo, T, TInfo,
1840 Constructor->isExplicit(),
1841 Constructor->isInlineSpecified(),
1842 false, Constructor->isConstexpr());
1843 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1844 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1845 StartLoc, NameInfo, T, TInfo,
1846 Destructor->isInlineSpecified(),
1848 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1849 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1850 StartLoc, NameInfo, T, TInfo,
1851 Conversion->isInlineSpecified(),
1852 Conversion->isExplicit(),
1853 Conversion->isConstexpr(),
1854 Conversion->getLocEnd());
1856 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
1857 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1858 StartLoc, NameInfo, T, TInfo,
1859 SC, D->isInlineSpecified(),
1860 D->isConstexpr(), D->getLocEnd());
1864 Method->setImplicitlyInline();
1867 Method->setQualifierInfo(QualifierLoc);
1869 if (TemplateParams) {
1870 // Our resulting instantiation is actually a function template, since we
1871 // are substituting only the outer template parameters. For example, given
1873 // template<typename T>
1875 // template<typename U> void f(T, U);
1880 // We are instantiating the member template "f" within X<int>, which means
1881 // substituting int for T, but leaving "f" as a member function template.
1882 // Build the function template itself.
1883 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1884 Method->getLocation(),
1885 Method->getDeclName(),
1886 TemplateParams, Method);
1888 FunctionTemplate->setLexicalDeclContext(Owner);
1889 FunctionTemplate->setObjectOfFriendDecl();
1890 } else if (D->isOutOfLine())
1891 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1892 Method->setDescribedFunctionTemplate(FunctionTemplate);
1893 } else if (FunctionTemplate) {
1894 // Record this function template specialization.
1895 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1896 Method->setFunctionTemplateSpecialization(FunctionTemplate,
1897 TemplateArgumentList::CreateCopy(SemaRef.Context,
1899 /*InsertPos=*/nullptr);
1900 } else if (!isFriend) {
1901 // Record that this is an instantiation of a member function.
1902 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1905 // If we are instantiating a member function defined
1906 // out-of-line, the instantiation will have the same lexical
1907 // context (which will be a namespace scope) as the template.
1909 if (NumTempParamLists)
1910 Method->setTemplateParameterListsInfo(
1912 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
1914 Method->setLexicalDeclContext(Owner);
1915 Method->setObjectOfFriendDecl();
1916 } else if (D->isOutOfLine())
1917 Method->setLexicalDeclContext(D->getLexicalDeclContext());
1919 // Attach the parameters
1920 for (unsigned P = 0; P < Params.size(); ++P)
1921 Params[P]->setOwningFunction(Method);
1922 Method->setParams(Params);
1924 if (InitMethodInstantiation(Method, D))
1925 Method->setInvalidDecl();
1927 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1928 Sema::ForRedeclaration);
1930 if (!FunctionTemplate || TemplateParams || isFriend) {
1931 SemaRef.LookupQualifiedName(Previous, Record);
1933 // In C++, the previous declaration we find might be a tag type
1934 // (class or enum). In this case, the new declaration will hide the
1935 // tag type. Note that this does does not apply if we're declaring a
1936 // typedef (C++ [dcl.typedef]p4).
1937 if (Previous.isSingleTagDecl())
1941 if (!IsClassScopeSpecialization)
1942 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
1945 SemaRef.CheckPureMethod(Method, SourceRange());
1947 // Propagate access. For a non-friend declaration, the access is
1948 // whatever we're propagating from. For a friend, it should be the
1949 // previous declaration we just found.
1950 if (isFriend && Method->getPreviousDecl())
1951 Method->setAccess(Method->getPreviousDecl()->getAccess());
1953 Method->setAccess(D->getAccess());
1954 if (FunctionTemplate)
1955 FunctionTemplate->setAccess(Method->getAccess());
1957 SemaRef.CheckOverrideControl(Method);
1959 // If a function is defined as defaulted or deleted, mark it as such now.
1960 if (D->isExplicitlyDefaulted())
1961 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1962 if (D->isDeletedAsWritten())
1963 SemaRef.SetDeclDeleted(Method, Method->getLocation());
1965 // If there's a function template, let our caller handle it.
1966 if (FunctionTemplate) {
1969 // Don't hide a (potentially) valid declaration with an invalid one.
1970 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1973 // Otherwise, check access to friends and make them visible.
1974 } else if (isFriend) {
1975 // We only need to re-check access for methods which we didn't
1976 // manage to match during parsing.
1977 if (!D->getPreviousDecl())
1978 SemaRef.CheckFriendAccess(Method);
1980 Record->makeDeclVisibleInContext(Method);
1982 // Otherwise, add the declaration. We don't need to do this for
1983 // class-scope specializations because we'll have matched them with
1984 // the appropriate template.
1985 } else if (!IsClassScopeSpecialization) {
1986 Owner->addDecl(Method);
1992 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1993 return VisitCXXMethodDecl(D);
1996 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1997 return VisitCXXMethodDecl(D);
2000 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2001 return VisitCXXMethodDecl(D);
2004 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2005 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2006 /*ExpectParameterPack=*/ false);
2009 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2010 TemplateTypeParmDecl *D) {
2011 // TODO: don't always clone when decls are refcounted.
2012 assert(D->getTypeForDecl()->isTemplateTypeParmType());
2014 TemplateTypeParmDecl *Inst =
2015 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
2016 D->getLocStart(), D->getLocation(),
2017 D->getDepth() - TemplateArgs.getNumLevels(),
2018 D->getIndex(), D->getIdentifier(),
2019 D->wasDeclaredWithTypename(),
2020 D->isParameterPack());
2021 Inst->setAccess(AS_public);
2023 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2024 TypeSourceInfo *InstantiatedDefaultArg =
2025 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2026 D->getDefaultArgumentLoc(), D->getDeclName());
2027 if (InstantiatedDefaultArg)
2028 Inst->setDefaultArgument(InstantiatedDefaultArg);
2031 // Introduce this template parameter's instantiation into the instantiation
2033 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2038 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2039 NonTypeTemplateParmDecl *D) {
2040 // Substitute into the type of the non-type template parameter.
2041 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2042 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2043 SmallVector<QualType, 4> ExpandedParameterPackTypes;
2044 bool IsExpandedParameterPack = false;
2047 bool Invalid = false;
2049 if (D->isExpandedParameterPack()) {
2050 // The non-type template parameter pack is an already-expanded pack
2051 // expansion of types. Substitute into each of the expanded types.
2052 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2053 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2054 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2055 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
2062 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2063 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
2067 ExpandedParameterPackTypes.push_back(NewT);
2070 IsExpandedParameterPack = true;
2071 DI = D->getTypeSourceInfo();
2073 } else if (D->isPackExpansion()) {
2074 // The non-type template parameter pack's type is a pack expansion of types.
2075 // Determine whether we need to expand this parameter pack into separate
2077 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2078 TypeLoc Pattern = Expansion.getPatternLoc();
2079 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2080 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2082 // Determine whether the set of unexpanded parameter packs can and should
2085 bool RetainExpansion = false;
2086 Optional<unsigned> OrigNumExpansions
2087 = Expansion.getTypePtr()->getNumExpansions();
2088 Optional<unsigned> NumExpansions = OrigNumExpansions;
2089 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2090 Pattern.getSourceRange(),
2093 Expand, RetainExpansion,
2098 for (unsigned I = 0; I != *NumExpansions; ++I) {
2099 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2100 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2106 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2107 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
2112 ExpandedParameterPackTypes.push_back(NewT);
2115 // Note that we have an expanded parameter pack. The "type" of this
2116 // expanded parameter pack is the original expansion type, but callers
2117 // will end up using the expanded parameter pack types for type-checking.
2118 IsExpandedParameterPack = true;
2119 DI = D->getTypeSourceInfo();
2122 // We cannot fully expand the pack expansion now, so substitute into the
2123 // pattern and create a new pack expansion type.
2124 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2125 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2131 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2139 // Simple case: substitution into a parameter that is not a parameter pack.
2140 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2141 D->getLocation(), D->getDeclName());
2145 // Check that this type is acceptable for a non-type template parameter.
2146 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
2149 T = SemaRef.Context.IntTy;
2154 NonTypeTemplateParmDecl *Param;
2155 if (IsExpandedParameterPack)
2156 Param = NonTypeTemplateParmDecl::Create(
2157 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2158 D->getDepth() - TemplateArgs.getNumLevels(), D->getPosition(),
2159 D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
2160 ExpandedParameterPackTypesAsWritten);
2162 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
2163 D->getInnerLocStart(),
2165 D->getDepth() - TemplateArgs.getNumLevels(),
2167 D->getIdentifier(), T,
2168 D->isParameterPack(), DI);
2170 Param->setAccess(AS_public);
2172 Param->setInvalidDecl();
2174 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2175 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
2176 Sema::ConstantEvaluated);
2177 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2178 if (!Value.isInvalid())
2179 Param->setDefaultArgument(Value.get());
2182 // Introduce this template parameter's instantiation into the instantiation
2184 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2188 static void collectUnexpandedParameterPacks(
2190 TemplateParameterList *Params,
2191 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2192 for (const auto &P : *Params) {
2193 if (P->isTemplateParameterPack())
2195 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
2196 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2198 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
2199 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2205 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2206 TemplateTemplateParmDecl *D) {
2207 // Instantiate the template parameter list of the template template parameter.
2208 TemplateParameterList *TempParams = D->getTemplateParameters();
2209 TemplateParameterList *InstParams;
2210 SmallVector<TemplateParameterList*, 8> ExpandedParams;
2212 bool IsExpandedParameterPack = false;
2214 if (D->isExpandedParameterPack()) {
2215 // The template template parameter pack is an already-expanded pack
2216 // expansion of template parameters. Substitute into each of the expanded
2218 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2219 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2221 LocalInstantiationScope Scope(SemaRef);
2222 TemplateParameterList *Expansion =
2223 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2226 ExpandedParams.push_back(Expansion);
2229 IsExpandedParameterPack = true;
2230 InstParams = TempParams;
2231 } else if (D->isPackExpansion()) {
2232 // The template template parameter pack expands to a pack of template
2233 // template parameters. Determine whether we need to expand this parameter
2234 // pack into separate parameters.
2235 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2236 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2239 // Determine whether the set of unexpanded parameter packs can and should
2242 bool RetainExpansion = false;
2243 Optional<unsigned> NumExpansions;
2244 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2245 TempParams->getSourceRange(),
2248 Expand, RetainExpansion,
2253 for (unsigned I = 0; I != *NumExpansions; ++I) {
2254 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2255 LocalInstantiationScope Scope(SemaRef);
2256 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2259 ExpandedParams.push_back(Expansion);
2262 // Note that we have an expanded parameter pack. The "type" of this
2263 // expanded parameter pack is the original expansion type, but callers
2264 // will end up using the expanded parameter pack types for type-checking.
2265 IsExpandedParameterPack = true;
2266 InstParams = TempParams;
2268 // We cannot fully expand the pack expansion now, so just substitute
2269 // into the pattern.
2270 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2272 LocalInstantiationScope Scope(SemaRef);
2273 InstParams = SubstTemplateParams(TempParams);
2278 // Perform the actual substitution of template parameters within a new,
2279 // local instantiation scope.
2280 LocalInstantiationScope Scope(SemaRef);
2281 InstParams = SubstTemplateParams(TempParams);
2286 // Build the template template parameter.
2287 TemplateTemplateParmDecl *Param;
2288 if (IsExpandedParameterPack)
2289 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2291 D->getDepth() - TemplateArgs.getNumLevels(),
2293 D->getIdentifier(), InstParams,
2296 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2298 D->getDepth() - TemplateArgs.getNumLevels(),
2300 D->isParameterPack(),
2301 D->getIdentifier(), InstParams);
2302 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2303 NestedNameSpecifierLoc QualifierLoc =
2304 D->getDefaultArgument().getTemplateQualifierLoc();
2306 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2307 TemplateName TName = SemaRef.SubstTemplateName(
2308 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2309 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2310 if (!TName.isNull())
2311 Param->setDefaultArgument(
2313 TemplateArgumentLoc(TemplateArgument(TName),
2314 D->getDefaultArgument().getTemplateQualifierLoc(),
2315 D->getDefaultArgument().getTemplateNameLoc()));
2317 Param->setAccess(AS_public);
2319 // Introduce this template parameter's instantiation into the instantiation
2321 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2326 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2327 // Using directives are never dependent (and never contain any types or
2328 // expressions), so they require no explicit instantiation work.
2330 UsingDirectiveDecl *Inst
2331 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2332 D->getNamespaceKeyLocation(),
2333 D->getQualifierLoc(),
2334 D->getIdentLocation(),
2335 D->getNominatedNamespace(),
2336 D->getCommonAncestor());
2338 // Add the using directive to its declaration context
2339 // only if this is not a function or method.
2340 if (!Owner->isFunctionOrMethod())
2341 Owner->addDecl(Inst);
2346 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2348 // The nested name specifier may be dependent, for example
2349 // template <typename T> struct t {
2350 // struct s1 { T f1(); };
2351 // struct s2 : s1 { using s1::f1; };
2353 // template struct t<int>;
2354 // Here, in using s1::f1, s1 refers to t<T>::s1;
2355 // we need to substitute for t<int>::s1.
2356 NestedNameSpecifierLoc QualifierLoc
2357 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2362 // For an inheriting constructor declaration, the name of the using
2363 // declaration is the name of a constructor in this class, not in the
2365 DeclarationNameInfo NameInfo = D->getNameInfo();
2366 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2367 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
2368 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
2369 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
2371 // We only need to do redeclaration lookups if we're in a class
2372 // scope (in fact, it's not really even possible in non-class
2374 bool CheckRedeclaration = Owner->isRecord();
2376 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2377 Sema::ForRedeclaration);
2379 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2386 SS.Adopt(QualifierLoc);
2387 if (CheckRedeclaration) {
2388 Prev.setHideTags(false);
2389 SemaRef.LookupQualifiedName(Prev, Owner);
2391 // Check for invalid redeclarations.
2392 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2393 D->hasTypename(), SS,
2394 D->getLocation(), Prev))
2395 NewUD->setInvalidDecl();
2399 if (!NewUD->isInvalidDecl() &&
2400 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo,
2402 NewUD->setInvalidDecl();
2404 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2405 NewUD->setAccess(D->getAccess());
2406 Owner->addDecl(NewUD);
2408 // Don't process the shadow decls for an invalid decl.
2409 if (NewUD->isInvalidDecl())
2412 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2413 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
2415 bool isFunctionScope = Owner->isFunctionOrMethod();
2417 // Process the shadow decls.
2418 for (auto *Shadow : D->shadows()) {
2419 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
2420 // reconstruct it in the case where it matters.
2421 NamedDecl *OldTarget = Shadow->getTargetDecl();
2422 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
2423 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
2424 OldTarget = BaseShadow;
2426 NamedDecl *InstTarget =
2427 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2428 Shadow->getLocation(), OldTarget, TemplateArgs));
2432 UsingShadowDecl *PrevDecl = nullptr;
2433 if (CheckRedeclaration) {
2434 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2436 } else if (UsingShadowDecl *OldPrev =
2437 getPreviousDeclForInstantiation(Shadow)) {
2438 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2439 Shadow->getLocation(), OldPrev, TemplateArgs));
2442 UsingShadowDecl *InstShadow =
2443 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2445 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2447 if (isFunctionScope)
2448 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2454 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2455 // Ignore these; we handle them in bulk when processing the UsingDecl.
2459 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
2460 ConstructorUsingShadowDecl *D) {
2461 // Ignore these; we handle them in bulk when processing the UsingDecl.
2465 Decl * TemplateDeclInstantiator
2466 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
2467 NestedNameSpecifierLoc QualifierLoc
2468 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2474 SS.Adopt(QualifierLoc);
2476 // Since NameInfo refers to a typename, it cannot be a C++ special name.
2477 // Hence, no transformation is required for it.
2478 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
2480 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2481 D->getUsingLoc(), SS, NameInfo, nullptr,
2482 /*instantiation*/ true,
2483 /*typename*/ true, D->getTypenameLoc());
2485 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2490 Decl * TemplateDeclInstantiator
2491 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
2492 NestedNameSpecifierLoc QualifierLoc
2493 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2498 SS.Adopt(QualifierLoc);
2500 DeclarationNameInfo NameInfo
2501 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2504 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2505 D->getUsingLoc(), SS, NameInfo, nullptr,
2506 /*instantiation*/ true,
2507 /*typename*/ false, SourceLocation());
2509 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2515 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2516 ClassScopeFunctionSpecializationDecl *Decl) {
2517 CXXMethodDecl *OldFD = Decl->getSpecialization();
2518 CXXMethodDecl *NewFD =
2519 cast_or_null<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, nullptr, true));
2523 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2524 Sema::ForRedeclaration);
2526 TemplateArgumentListInfo TemplateArgs;
2527 TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
2528 if (Decl->hasExplicitTemplateArgs()) {
2529 TemplateArgs = Decl->templateArgs();
2530 TemplateArgsPtr = &TemplateArgs;
2533 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
2534 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2536 NewFD->setInvalidDecl();
2540 // Associate the specialization with the pattern.
2541 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2542 assert(Specialization && "Class scope Specialization is null");
2543 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2548 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2549 OMPThreadPrivateDecl *D) {
2550 SmallVector<Expr *, 5> Vars;
2551 for (auto *I : D->varlists()) {
2552 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2553 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2554 Vars.push_back(Var);
2557 OMPThreadPrivateDecl *TD =
2558 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2560 TD->setAccess(AS_public);
2566 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
2567 OMPDeclareReductionDecl *D) {
2568 // Instantiate type and check if it is allowed.
2569 QualType SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
2571 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
2572 D->getLocation(), DeclarationName())));
2573 if (SubstReductionType.isNull())
2575 bool IsCorrect = !SubstReductionType.isNull();
2576 // Create instantiated copy.
2577 std::pair<QualType, SourceLocation> ReductionTypes[] = {
2578 std::make_pair(SubstReductionType, D->getLocation())};
2579 auto *PrevDeclInScope = D->getPrevDeclInScope();
2580 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
2581 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
2582 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
2585 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
2586 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
2588 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
2589 if (isDeclWithinFunction(NewDRD))
2590 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
2591 Expr *SubstCombiner = nullptr;
2592 Expr *SubstInitializer = nullptr;
2593 // Combiners instantiation sequence.
2594 if (D->getCombiner()) {
2595 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
2596 /*S=*/nullptr, NewDRD);
2597 const char *Names[] = {"omp_in", "omp_out"};
2598 for (auto &Name : Names) {
2599 DeclarationName DN(&SemaRef.Context.Idents.get(Name));
2600 auto OldLookup = D->lookup(DN);
2601 auto Lookup = NewDRD->lookup(DN);
2602 if (!OldLookup.empty() && !Lookup.empty()) {
2603 assert(Lookup.size() == 1 && OldLookup.size() == 1);
2604 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldLookup.front(),
2608 SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
2609 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
2610 // Initializers instantiation sequence.
2611 if (D->getInitializer()) {
2612 SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
2613 /*S=*/nullptr, NewDRD);
2614 const char *Names[] = {"omp_orig", "omp_priv"};
2615 for (auto &Name : Names) {
2616 DeclarationName DN(&SemaRef.Context.Idents.get(Name));
2617 auto OldLookup = D->lookup(DN);
2618 auto Lookup = NewDRD->lookup(DN);
2619 if (!OldLookup.empty() && !Lookup.empty()) {
2620 assert(Lookup.size() == 1 && OldLookup.size() == 1);
2621 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
2622 OldLookup.front(), Lookup.front());
2626 SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
2627 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD,
2630 IsCorrect = IsCorrect && SubstCombiner &&
2631 (!D->getInitializer() || SubstInitializer);
2635 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
2641 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
2642 OMPCapturedExprDecl * /*D*/) {
2643 llvm_unreachable("Should not be met in templates");
2646 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2647 return VisitFunctionDecl(D, nullptr);
2650 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2651 return VisitCXXMethodDecl(D, nullptr);
2654 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2655 llvm_unreachable("There are only CXXRecordDecls in C++");
2659 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2660 ClassTemplateSpecializationDecl *D) {
2661 // As a MS extension, we permit class-scope explicit specialization
2662 // of member class templates.
2663 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2664 assert(ClassTemplate->getDeclContext()->isRecord() &&
2665 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2666 "can only instantiate an explicit specialization "
2667 "for a member class template");
2669 // Lookup the already-instantiated declaration in the instantiation
2670 // of the class template. FIXME: Diagnose or assert if this fails?
2671 DeclContext::lookup_result Found
2672 = Owner->lookup(ClassTemplate->getDeclName());
2675 ClassTemplateDecl *InstClassTemplate
2676 = dyn_cast<ClassTemplateDecl>(Found.front());
2677 if (!InstClassTemplate)
2680 // Substitute into the template arguments of the class template explicit
2682 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2683 castAs<TemplateSpecializationTypeLoc>();
2684 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2685 Loc.getRAngleLoc());
2686 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2687 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2688 ArgLocs.push_back(Loc.getArgLoc(I));
2689 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2690 InstTemplateArgs, TemplateArgs))
2693 // Check that the template argument list is well-formed for this
2695 SmallVector<TemplateArgument, 4> Converted;
2696 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2703 // Figure out where to insert this class template explicit specialization
2704 // in the member template's set of class template explicit specializations.
2705 void *InsertPos = nullptr;
2706 ClassTemplateSpecializationDecl *PrevDecl =
2707 InstClassTemplate->findSpecialization(Converted, InsertPos);
2709 // Check whether we've already seen a conflicting instantiation of this
2710 // declaration (for instance, if there was a prior implicit instantiation).
2713 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2714 D->getSpecializationKind(),
2716 PrevDecl->getSpecializationKind(),
2717 PrevDecl->getPointOfInstantiation(),
2721 // If PrevDecl was a definition and D is also a definition, diagnose.
2722 // This happens in cases like:
2724 // template<typename T, typename U>
2726 // template<typename X> struct Inner;
2727 // template<> struct Inner<T> {};
2728 // template<> struct Inner<U> {};
2731 // Outer<int, int> outer; // error: the explicit specializations of Inner
2732 // // have the same signature.
2733 if (PrevDecl && PrevDecl->getDefinition() &&
2734 D->isThisDeclarationADefinition()) {
2735 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2736 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2737 diag::note_previous_definition);
2741 // Create the class template partial specialization declaration.
2742 ClassTemplateSpecializationDecl *InstD
2743 = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2752 // Add this partial specialization to the set of class template partial
2755 InstClassTemplate->AddSpecialization(InstD, InsertPos);
2757 // Substitute the nested name specifier, if any.
2758 if (SubstQualifier(D, InstD))
2761 // Build the canonical type that describes the converted template
2762 // arguments of the class template explicit specialization.
2763 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2764 TemplateName(InstClassTemplate), Converted,
2765 SemaRef.Context.getRecordType(InstD));
2767 // Build the fully-sugared type for this class template
2768 // specialization as the user wrote in the specialization
2769 // itself. This means that we'll pretty-print the type retrieved
2770 // from the specialization's declaration the way that the user
2771 // actually wrote the specialization, rather than formatting the
2772 // name based on the "canonical" representation used to store the
2773 // template arguments in the specialization.
2774 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2775 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2778 InstD->setAccess(D->getAccess());
2779 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2780 InstD->setSpecializationKind(D->getSpecializationKind());
2781 InstD->setTypeAsWritten(WrittenTy);
2782 InstD->setExternLoc(D->getExternLoc());
2783 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2785 Owner->addDecl(InstD);
2787 // Instantiate the members of the class-scope explicit specialization eagerly.
2788 // We don't have support for lazy instantiation of an explicit specialization
2789 // yet, and MSVC eagerly instantiates in this case.
2790 if (D->isThisDeclarationADefinition() &&
2791 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2792 TSK_ImplicitInstantiation,
2799 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2800 VarTemplateSpecializationDecl *D) {
2802 TemplateArgumentListInfo VarTemplateArgsInfo;
2803 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2804 assert(VarTemplate &&
2805 "A template specialization without specialized template?");
2807 // Substitute the current template arguments.
2808 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2809 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2810 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2812 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2813 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2816 // Check that the template argument list is well-formed for this template.
2817 SmallVector<TemplateArgument, 4> Converted;
2818 if (SemaRef.CheckTemplateArgumentList(
2819 VarTemplate, VarTemplate->getLocStart(),
2820 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2824 // Find the variable template specialization declaration that
2825 // corresponds to these arguments.
2826 void *InsertPos = nullptr;
2827 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2828 Converted, InsertPos))
2829 // If we already have a variable template specialization, return it.
2832 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2833 VarTemplateArgsInfo, Converted);
2836 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2837 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2838 const TemplateArgumentListInfo &TemplateArgsInfo,
2839 ArrayRef<TemplateArgument> Converted) {
2841 // Do substitution on the type of the declaration
2842 TypeSourceInfo *DI =
2843 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2844 D->getTypeSpecStartLoc(), D->getDeclName());
2848 if (DI->getType()->isFunctionType()) {
2849 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2850 << D->isStaticDataMember() << DI->getType();
2854 // Build the instantiated declaration
2855 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2856 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2857 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
2858 Var->setTemplateArgsInfo(TemplateArgsInfo);
2860 VarTemplate->AddSpecialization(Var, InsertPos);
2862 // Substitute the nested name specifier, if any.
2863 if (SubstQualifier(D, Var))
2866 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
2867 Owner, StartingScope);
2872 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2873 llvm_unreachable("@defs is not supported in Objective-C++");
2876 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2877 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2878 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2879 DiagnosticsEngine::Error,
2880 "cannot instantiate %0 yet");
2881 SemaRef.Diag(D->getLocation(), DiagID)
2882 << D->getDeclKindName();
2887 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2888 llvm_unreachable("Unexpected decl");
2891 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
2892 const MultiLevelTemplateArgumentList &TemplateArgs) {
2893 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
2894 if (D->isInvalidDecl())
2897 return Instantiator.Visit(D);
2900 /// \brief Instantiates a nested template parameter list in the current
2901 /// instantiation context.
2903 /// \param L The parameter list to instantiate
2905 /// \returns NULL if there was an error
2906 TemplateParameterList *
2907 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
2908 // Get errors for all the parameters before bailing out.
2909 bool Invalid = false;
2911 unsigned N = L->size();
2912 typedef SmallVector<NamedDecl *, 8> ParamVector;
2915 for (auto &P : *L) {
2916 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
2917 Params.push_back(D);
2918 Invalid = Invalid || !D || D->isInvalidDecl();
2921 // Clean up if we had an error.
2925 TemplateParameterList *InstL
2926 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2927 L->getLAngleLoc(), Params,
2932 /// \brief Instantiate the declaration of a class template partial
2935 /// \param ClassTemplate the (instantiated) class template that is partially
2936 // specialized by the instantiation of \p PartialSpec.
2938 /// \param PartialSpec the (uninstantiated) class template partial
2939 /// specialization that we are instantiating.
2941 /// \returns The instantiated partial specialization, if successful; otherwise,
2942 /// NULL to indicate an error.
2943 ClassTemplatePartialSpecializationDecl *
2944 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2945 ClassTemplateDecl *ClassTemplate,
2946 ClassTemplatePartialSpecializationDecl *PartialSpec) {
2947 // Create a local instantiation scope for this class template partial
2948 // specialization, which will contain the instantiations of the template
2950 LocalInstantiationScope Scope(SemaRef);
2952 // Substitute into the template parameters of the class template partial
2954 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2955 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2959 // Substitute into the template arguments of the class template partial
2961 const ASTTemplateArgumentListInfo *TemplArgInfo
2962 = PartialSpec->getTemplateArgsAsWritten();
2963 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2964 TemplArgInfo->RAngleLoc);
2965 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2966 TemplArgInfo->NumTemplateArgs,
2967 InstTemplateArgs, TemplateArgs))
2970 // Check that the template argument list is well-formed for this
2972 SmallVector<TemplateArgument, 4> Converted;
2973 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2974 PartialSpec->getLocation(),
2980 // Figure out where to insert this class template partial specialization
2981 // in the member template's set of class template partial specializations.
2982 void *InsertPos = nullptr;
2983 ClassTemplateSpecializationDecl *PrevDecl
2984 = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
2986 // Build the canonical type that describes the converted template
2987 // arguments of the class template partial specialization.
2989 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2992 // Build the fully-sugared type for this class template
2993 // specialization as the user wrote in the specialization
2994 // itself. This means that we'll pretty-print the type retrieved
2995 // from the specialization's declaration the way that the user
2996 // actually wrote the specialization, rather than formatting the
2997 // name based on the "canonical" representation used to store the
2998 // template arguments in the specialization.
2999 TypeSourceInfo *WrittenTy
3000 = SemaRef.Context.getTemplateSpecializationTypeInfo(
3001 TemplateName(ClassTemplate),
3002 PartialSpec->getLocation(),
3007 // We've already seen a partial specialization with the same template
3008 // parameters and template arguments. This can happen, for example, when
3009 // substituting the outer template arguments ends up causing two
3010 // class template partial specializations of a member class template
3011 // to have identical forms, e.g.,
3013 // template<typename T, typename U>
3015 // template<typename X, typename Y> struct Inner;
3016 // template<typename Y> struct Inner<T, Y>;
3017 // template<typename Y> struct Inner<U, Y>;
3020 // Outer<int, int> outer; // error: the partial specializations of Inner
3021 // // have the same signature.
3022 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
3023 << WrittenTy->getType();
3024 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3025 << SemaRef.Context.getTypeDeclType(PrevDecl);
3030 // Create the class template partial specialization declaration.
3031 ClassTemplatePartialSpecializationDecl *InstPartialSpec
3032 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
3033 PartialSpec->getTagKind(),
3035 PartialSpec->getLocStart(),
3036 PartialSpec->getLocation(),
3043 // Substitute the nested name specifier, if any.
3044 if (SubstQualifier(PartialSpec, InstPartialSpec))
3047 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3048 InstPartialSpec->setTypeAsWritten(WrittenTy);
3050 // Add this partial specialization to the set of class template partial
3052 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3053 /*InsertPos=*/nullptr);
3054 return InstPartialSpec;
3057 /// \brief Instantiate the declaration of a variable template partial
3060 /// \param VarTemplate the (instantiated) variable template that is partially
3061 /// specialized by the instantiation of \p PartialSpec.
3063 /// \param PartialSpec the (uninstantiated) variable template partial
3064 /// specialization that we are instantiating.
3066 /// \returns The instantiated partial specialization, if successful; otherwise,
3067 /// NULL to indicate an error.
3068 VarTemplatePartialSpecializationDecl *
3069 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3070 VarTemplateDecl *VarTemplate,
3071 VarTemplatePartialSpecializationDecl *PartialSpec) {
3072 // Create a local instantiation scope for this variable template partial
3073 // specialization, which will contain the instantiations of the template
3075 LocalInstantiationScope Scope(SemaRef);
3077 // Substitute into the template parameters of the variable template partial
3079 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3080 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3084 // Substitute into the template arguments of the variable template partial
3086 const ASTTemplateArgumentListInfo *TemplArgInfo
3087 = PartialSpec->getTemplateArgsAsWritten();
3088 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3089 TemplArgInfo->RAngleLoc);
3090 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3091 TemplArgInfo->NumTemplateArgs,
3092 InstTemplateArgs, TemplateArgs))
3095 // Check that the template argument list is well-formed for this
3097 SmallVector<TemplateArgument, 4> Converted;
3098 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3099 InstTemplateArgs, false, Converted))
3102 // Figure out where to insert this variable template partial specialization
3103 // in the member template's set of variable template partial specializations.
3104 void *InsertPos = nullptr;
3105 VarTemplateSpecializationDecl *PrevDecl =
3106 VarTemplate->findPartialSpecialization(Converted, InsertPos);
3108 // Build the canonical type that describes the converted template
3109 // arguments of the variable template partial specialization.
3110 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3111 TemplateName(VarTemplate), Converted);
3113 // Build the fully-sugared type for this variable template
3114 // specialization as the user wrote in the specialization
3115 // itself. This means that we'll pretty-print the type retrieved
3116 // from the specialization's declaration the way that the user
3117 // actually wrote the specialization, rather than formatting the
3118 // name based on the "canonical" representation used to store the
3119 // template arguments in the specialization.
3120 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3121 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3125 // We've already seen a partial specialization with the same template
3126 // parameters and template arguments. This can happen, for example, when
3127 // substituting the outer template arguments ends up causing two
3128 // variable template partial specializations of a member variable template
3129 // to have identical forms, e.g.,
3131 // template<typename T, typename U>
3133 // template<typename X, typename Y> pair<X,Y> p;
3134 // template<typename Y> pair<T, Y> p;
3135 // template<typename Y> pair<U, Y> p;
3138 // Outer<int, int> outer; // error: the partial specializations of Inner
3139 // // have the same signature.
3140 SemaRef.Diag(PartialSpec->getLocation(),
3141 diag::err_var_partial_spec_redeclared)
3142 << WrittenTy->getType();
3143 SemaRef.Diag(PrevDecl->getLocation(),
3144 diag::note_var_prev_partial_spec_here);
3148 // Do substitution on the type of the declaration
3149 TypeSourceInfo *DI = SemaRef.SubstType(
3150 PartialSpec->getTypeSourceInfo(), TemplateArgs,
3151 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3155 if (DI->getType()->isFunctionType()) {
3156 SemaRef.Diag(PartialSpec->getLocation(),
3157 diag::err_variable_instantiates_to_function)
3158 << PartialSpec->isStaticDataMember() << DI->getType();
3162 // Create the variable template partial specialization declaration.
3163 VarTemplatePartialSpecializationDecl *InstPartialSpec =
3164 VarTemplatePartialSpecializationDecl::Create(
3165 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3166 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
3167 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
3169 // Substitute the nested name specifier, if any.
3170 if (SubstQualifier(PartialSpec, InstPartialSpec))
3173 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3174 InstPartialSpec->setTypeAsWritten(WrittenTy);
3176 // Add this partial specialization to the set of variable template partial
3177 // specializations. The instantiation of the initializer is not necessary.
3178 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
3180 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
3181 LateAttrs, Owner, StartingScope);
3183 return InstPartialSpec;
3187 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
3188 SmallVectorImpl<ParmVarDecl *> &Params) {
3189 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3190 assert(OldTInfo && "substituting function without type source info");
3191 assert(Params.empty() && "parameter vector is non-empty at start");
3193 CXXRecordDecl *ThisContext = nullptr;
3194 unsigned ThisTypeQuals = 0;
3195 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3196 ThisContext = cast<CXXRecordDecl>(Owner);
3197 ThisTypeQuals = Method->getTypeQualifiers();
3200 TypeSourceInfo *NewTInfo
3201 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3202 D->getTypeSpecStartLoc(),
3204 ThisContext, ThisTypeQuals);
3208 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3209 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3210 if (NewTInfo != OldTInfo) {
3211 // Get parameters from the new type info.
3212 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
3213 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
3214 unsigned NewIdx = 0;
3215 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
3216 OldIdx != NumOldParams; ++OldIdx) {
3217 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
3218 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3220 Optional<unsigned> NumArgumentsInExpansion;
3221 if (OldParam->isParameterPack())
3222 NumArgumentsInExpansion =
3223 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3225 if (!NumArgumentsInExpansion) {
3226 // Simple case: normal parameter, or a parameter pack that's
3227 // instantiated to a (still-dependent) parameter pack.
3228 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3229 Params.push_back(NewParam);
3230 Scope->InstantiatedLocal(OldParam, NewParam);
3232 // Parameter pack expansion: make the instantiation an argument pack.
3233 Scope->MakeInstantiatedLocalArgPack(OldParam);
3234 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
3235 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3236 Params.push_back(NewParam);
3237 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3242 // The function type itself was not dependent and therefore no
3243 // substitution occurred. However, we still need to instantiate
3244 // the function parameters themselves.
3245 const FunctionProtoType *OldProto =
3246 cast<FunctionProtoType>(OldProtoLoc.getType());
3247 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3249 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
3251 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
3252 D, D->getLocation(), OldProto->getParamType(i)));
3257 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
3260 Params.push_back(Parm);
3264 // If the type of this function, after ignoring parentheses, is not
3265 // *directly* a function type, then we're instantiating a function that
3266 // was declared via a typedef or with attributes, e.g.,
3268 // typedef int functype(int, int);
3270 // int __cdecl meth(int, int);
3272 // In this case, we'll just go instantiate the ParmVarDecls that we
3273 // synthesized in the method declaration.
3274 SmallVector<QualType, 4> ParamTypes;
3275 Sema::ExtParameterInfoBuilder ExtParamInfos;
3276 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
3277 TemplateArgs, ParamTypes, &Params,
3285 /// Introduce the instantiated function parameters into the local
3286 /// instantiation scope, and set the parameter names to those used
3287 /// in the template.
3288 static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
3289 const FunctionDecl *PatternDecl,
3290 LocalInstantiationScope &Scope,
3291 const MultiLevelTemplateArgumentList &TemplateArgs) {
3292 unsigned FParamIdx = 0;
3293 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3294 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3295 if (!PatternParam->isParameterPack()) {
3296 // Simple case: not a parameter pack.
3297 assert(FParamIdx < Function->getNumParams());
3298 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3299 FunctionParam->setDeclName(PatternParam->getDeclName());
3300 // If the parameter's type is not dependent, update it to match the type
3301 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3302 // the pattern's type here. If the type is dependent, they can't differ,
3303 // per core issue 1668. Substitute into the type from the pattern, in case
3304 // it's instantiation-dependent.
3305 // FIXME: Updating the type to work around this is at best fragile.
3306 if (!PatternDecl->getType()->isDependentType()) {
3307 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3308 FunctionParam->getLocation(),
3309 FunctionParam->getDeclName());
3312 FunctionParam->setType(T);
3315 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3320 // Expand the parameter pack.
3321 Scope.MakeInstantiatedLocalArgPack(PatternParam);
3322 Optional<unsigned> NumArgumentsInExpansion
3323 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
3324 assert(NumArgumentsInExpansion &&
3325 "should only be called when all template arguments are known");
3326 QualType PatternType =
3327 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
3328 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3329 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3330 FunctionParam->setDeclName(PatternParam->getDeclName());
3331 if (!PatternDecl->getType()->isDependentType()) {
3332 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3333 QualType T = S.SubstType(PatternType, TemplateArgs,
3334 FunctionParam->getLocation(),
3335 FunctionParam->getDeclName());
3338 FunctionParam->setType(T);
3341 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3349 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3350 FunctionDecl *Decl) {
3351 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3352 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3355 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3356 InstantiatingTemplate::ExceptionSpecification());
3357 if (Inst.isInvalid()) {
3358 // We hit the instantiation depth limit. Clear the exception specification
3359 // so that our callers don't have to cope with EST_Uninstantiated.
3360 UpdateExceptionSpec(Decl, EST_None);
3363 if (Inst.isAlreadyInstantiating()) {
3364 // This exception specification indirectly depends on itself. Reject.
3365 // FIXME: Corresponding rule in the standard?
3366 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
3367 UpdateExceptionSpec(Decl, EST_None);
3371 // Enter the scope of this instantiation. We don't use
3372 // PushDeclContext because we don't have a scope.
3373 Sema::ContextRAII savedContext(*this, Decl);
3374 LocalInstantiationScope Scope(*this);
3376 MultiLevelTemplateArgumentList TemplateArgs =
3377 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
3379 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3380 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3382 UpdateExceptionSpec(Decl, EST_None);
3386 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3390 /// \brief Initializes the common fields of an instantiation function
3391 /// declaration (New) from the corresponding fields of its template (Tmpl).
3393 /// \returns true if there was an error
3395 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3396 FunctionDecl *Tmpl) {
3397 if (Tmpl->isDeleted())
3398 New->setDeletedAsWritten();
3400 // Forward the mangling number from the template to the instantiated decl.
3401 SemaRef.Context.setManglingNumber(New,
3402 SemaRef.Context.getManglingNumber(Tmpl));
3404 // If we are performing substituting explicitly-specified template arguments
3405 // or deduced template arguments into a function template and we reach this
3406 // point, we are now past the point where SFINAE applies and have committed
3407 // to keeping the new function template specialization. We therefore
3408 // convert the active template instantiation for the function template
3409 // into a template instantiation for this specific function template
3410 // specialization, which is not a SFINAE context, so that we diagnose any
3411 // further errors in the declaration itself.
3412 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3413 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3414 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3415 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
3416 if (FunctionTemplateDecl *FunTmpl
3417 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3418 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
3419 "Deduction from the wrong function template?");
3421 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3422 ActiveInst.Entity = New;
3426 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3427 assert(Proto && "Function template without prototype?");
3429 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3430 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3432 // DR1330: In C++11, defer instantiation of a non-trivial
3433 // exception specification.
3434 // DR1484: Local classes and their members are instantiated along with the
3435 // containing function.
3436 if (SemaRef.getLangOpts().CPlusPlus11 &&
3437 EPI.ExceptionSpec.Type != EST_None &&
3438 EPI.ExceptionSpec.Type != EST_DynamicNone &&
3439 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
3440 !Tmpl->isLexicallyWithinFunctionOrMethod()) {
3441 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3442 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3443 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
3444 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3445 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
3446 NewEST = EST_Unevaluated;
3448 // Mark the function has having an uninstantiated exception specification.
3449 const FunctionProtoType *NewProto
3450 = New->getType()->getAs<FunctionProtoType>();
3451 assert(NewProto && "Template instantiation without function prototype?");
3452 EPI = NewProto->getExtProtoInfo();
3453 EPI.ExceptionSpec.Type = NewEST;
3454 EPI.ExceptionSpec.SourceDecl = New;
3455 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
3456 New->setType(SemaRef.Context.getFunctionType(
3457 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
3459 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
3463 // Get the definition. Leaves the variable unchanged if undefined.
3464 const FunctionDecl *Definition = Tmpl;
3465 Tmpl->isDefined(Definition);
3467 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3468 LateAttrs, StartingScope);
3473 /// \brief Initializes common fields of an instantiated method
3474 /// declaration (New) from the corresponding fields of its template
3477 /// \returns true if there was an error
3479 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
3480 CXXMethodDecl *Tmpl) {
3481 if (InitFunctionInstantiation(New, Tmpl))
3484 New->setAccess(Tmpl->getAccess());
3485 if (Tmpl->isVirtualAsWritten())
3486 New->setVirtualAsWritten(true);
3488 // FIXME: New needs a pointer to Tmpl
3492 /// \brief Instantiate the definition of the given function from its
3495 /// \param PointOfInstantiation the point at which the instantiation was
3496 /// required. Note that this is not precisely a "point of instantiation"
3497 /// for the function, but it's close.
3499 /// \param Function the already-instantiated declaration of a
3500 /// function template specialization or member function of a class template
3503 /// \param Recursive if true, recursively instantiates any functions that
3504 /// are required by this instantiation.
3506 /// \param DefinitionRequired if true, then we are performing an explicit
3507 /// instantiation where the body of the function is required. Complain if
3508 /// there is no such body.
3509 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
3510 FunctionDecl *Function,
3512 bool DefinitionRequired,
3514 if (Function->isInvalidDecl() || Function->isDefined())
3517 // Never instantiate an explicit specialization except if it is a class scope
3518 // explicit specialization.
3519 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3520 !Function->getClassScopeSpecializationPattern())
3523 // Find the function body that we'll be substituting.
3524 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
3525 assert(PatternDecl && "instantiating a non-template");
3527 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3528 assert(PatternDecl && "template definition is not a template");
3530 // Try to find a defaulted definition
3531 PatternDecl->isDefined(PatternDecl);
3533 assert(PatternDecl && "template definition is not a template");
3535 // Postpone late parsed template instantiations.
3536 if (PatternDecl->isLateTemplateParsed() &&
3537 !LateTemplateParser) {
3538 PendingInstantiations.push_back(
3539 std::make_pair(Function, PointOfInstantiation));
3543 // If we're performing recursive template instantiation, create our own
3544 // queue of pending implicit instantiations that we will instantiate later,
3545 // while we're still within our own instantiation context.
3546 // This has to happen before LateTemplateParser below is called, so that
3547 // it marks vtables used in late parsed templates as used.
3548 SavePendingLocalImplicitInstantiationsRAII
3549 SavedPendingLocalImplicitInstantiations(*this);
3550 SavePendingInstantiationsAndVTableUsesRAII
3551 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
3553 // Call the LateTemplateParser callback if there is a need to late parse
3554 // a templated function definition.
3555 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
3556 LateTemplateParser) {
3557 // FIXME: Optimize to allow individual templates to be deserialized.
3558 if (PatternDecl->isFromASTFile())
3559 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3561 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3562 assert(LPT && "missing LateParsedTemplate");
3563 LateTemplateParser(OpaqueParser, *LPT);
3564 Pattern = PatternDecl->getBody(PatternDecl);
3567 // FIXME: Check that the definition is visible before trying to instantiate
3568 // it. This requires us to track the instantiation stack in order to know
3569 // which definitions should be visible.
3571 if (!Pattern && !PatternDecl->isDefaulted()) {
3572 if (DefinitionRequired) {
3573 if (Function->getPrimaryTemplate())
3574 Diag(PointOfInstantiation,
3575 diag::err_explicit_instantiation_undefined_func_template)
3576 << Function->getPrimaryTemplate();
3578 Diag(PointOfInstantiation,
3579 diag::err_explicit_instantiation_undefined_member)
3580 << 1 << Function->getDeclName() << Function->getDeclContext();
3583 Diag(PatternDecl->getLocation(),
3584 diag::note_explicit_instantiation_here);
3585 Function->setInvalidDecl();
3586 } else if (Function->getTemplateSpecializationKind()
3587 == TSK_ExplicitInstantiationDefinition) {
3589 PendingInstantiations.push_back(
3590 std::make_pair(Function, PointOfInstantiation));
3591 } else if (Function->getTemplateSpecializationKind()
3592 == TSK_ImplicitInstantiation) {
3593 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred()) {
3594 Diag(PointOfInstantiation, diag::warn_func_template_missing)
3596 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
3597 if (getLangOpts().CPlusPlus11)
3598 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
3606 // C++1y [temp.explicit]p10:
3607 // Except for inline functions, declarations with types deduced from their
3608 // initializer or return value, and class template specializations, other
3609 // explicit instantiation declarations have the effect of suppressing the
3610 // implicit instantiation of the entity to which they refer.
3611 if (Function->getTemplateSpecializationKind() ==
3612 TSK_ExplicitInstantiationDeclaration &&
3613 !PatternDecl->isInlined() &&
3614 !PatternDecl->getReturnType()->getContainedAutoType())
3617 if (PatternDecl->isInlined()) {
3618 // Function, and all later redeclarations of it (from imported modules,
3619 // for instance), are now implicitly inline.
3620 for (auto *D = Function->getMostRecentDecl(); /**/;
3621 D = D->getPreviousDecl()) {
3622 D->setImplicitlyInline();
3628 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3629 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
3631 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3632 "instantiating function definition");
3634 // Copy the inner loc start from the pattern.
3635 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3637 EnterExpressionEvaluationContext EvalContext(*this,
3638 Sema::PotentiallyEvaluated);
3640 // Introduce a new scope where local variable instantiations will be
3641 // recorded, unless we're actually a member function within a local
3642 // class, in which case we need to merge our results with the parent
3643 // scope (of the enclosing function).
3644 bool MergeWithParentScope = false;
3645 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3646 MergeWithParentScope = Rec->isLocalClass();
3648 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3650 if (PatternDecl->isDefaulted())
3651 SetDeclDefaulted(Function, PatternDecl->getLocation());
3653 MultiLevelTemplateArgumentList TemplateArgs =
3654 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
3656 // Substitute into the qualifier; we can get a substitution failure here
3657 // through evil use of alias templates.
3658 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
3659 // of the) lexical context of the pattern?
3660 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
3662 ActOnStartOfFunctionDef(nullptr, Function);
3664 // Enter the scope of this instantiation. We don't use
3665 // PushDeclContext because we don't have a scope.
3666 Sema::ContextRAII savedContext(*this, Function);
3668 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3672 // If this is a constructor, instantiate the member initializers.
3673 if (const CXXConstructorDecl *Ctor =
3674 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3675 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3679 // Instantiate the function body.
3680 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3682 if (Body.isInvalid())
3683 Function->setInvalidDecl();
3685 ActOnFinishFunctionBody(Function, Body.get(),
3686 /*IsInstantiation=*/true);
3688 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3690 if (auto *Listener = getASTMutationListener())
3691 Listener->FunctionDefinitionInstantiated(Function);
3696 DeclGroupRef DG(Function);
3697 Consumer.HandleTopLevelDecl(DG);
3699 // This class may have local implicit instantiations that need to be
3700 // instantiation within this scope.
3701 PerformPendingInstantiations(/*LocalOnly=*/true);
3705 // Define any pending vtables.
3706 DefineUsedVTables();
3708 // Instantiate any pending implicit instantiations found during the
3709 // instantiation of this template.
3710 PerformPendingInstantiations();
3712 // PendingInstantiations and VTableUses are restored through
3713 // SavePendingInstantiationsAndVTableUses's destructor.
3717 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3718 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3719 const TemplateArgumentList &TemplateArgList,
3720 const TemplateArgumentListInfo &TemplateArgsInfo,
3721 SmallVectorImpl<TemplateArgument> &Converted,
3722 SourceLocation PointOfInstantiation, void *InsertPos,
3723 LateInstantiatedAttrVec *LateAttrs,
3724 LocalInstantiationScope *StartingScope) {
3725 if (FromVar->isInvalidDecl())
3728 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3729 if (Inst.isInvalid())
3732 MultiLevelTemplateArgumentList TemplateArgLists;
3733 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3735 // Instantiate the first declaration of the variable template: for a partial
3736 // specialization of a static data member template, the first declaration may
3737 // or may not be the declaration in the class; if it's in the class, we want
3738 // to instantiate a member in the class (a declaration), and if it's outside,
3739 // we want to instantiate a definition.
3741 // If we're instantiating an explicitly-specialized member template or member
3742 // partial specialization, don't do this. The member specialization completely
3743 // replaces the original declaration in this case.
3744 bool IsMemberSpec = false;
3745 if (VarTemplatePartialSpecializationDecl *PartialSpec =
3746 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3747 IsMemberSpec = PartialSpec->isMemberSpecialization();
3748 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3749 IsMemberSpec = FromTemplate->isMemberSpecialization();
3751 FromVar = FromVar->getFirstDecl();
3753 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3754 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3757 // TODO: Set LateAttrs and StartingScope ...
3759 return cast_or_null<VarTemplateSpecializationDecl>(
3760 Instantiator.VisitVarTemplateSpecializationDecl(
3761 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3764 /// \brief Instantiates a variable template specialization by completing it
3765 /// with appropriate type information and initializer.
3766 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3767 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3768 const MultiLevelTemplateArgumentList &TemplateArgs) {
3770 // Do substitution on the type of the declaration
3771 TypeSourceInfo *DI =
3772 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
3773 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3777 // Update the type of this variable template specialization.
3778 VarSpec->setType(DI->getType());
3780 // Instantiate the initializer.
3781 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3786 /// BuildVariableInstantiation - Used after a new variable has been created.
3787 /// Sets basic variable data and decides whether to postpone the
3788 /// variable instantiation.
3789 void Sema::BuildVariableInstantiation(
3790 VarDecl *NewVar, VarDecl *OldVar,
3791 const MultiLevelTemplateArgumentList &TemplateArgs,
3792 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3793 LocalInstantiationScope *StartingScope,
3794 bool InstantiatingVarTemplate) {
3796 // If we are instantiating a local extern declaration, the
3797 // instantiation belongs lexically to the containing function.
3798 // If we are instantiating a static data member defined
3799 // out-of-line, the instantiation will have the same lexical
3800 // context (which will be a namespace scope) as the template.
3801 if (OldVar->isLocalExternDecl()) {
3802 NewVar->setLocalExternDecl();
3803 NewVar->setLexicalDeclContext(Owner);
3804 } else if (OldVar->isOutOfLine())
3805 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3806 NewVar->setTSCSpec(OldVar->getTSCSpec());
3807 NewVar->setInitStyle(OldVar->getInitStyle());
3808 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3809 NewVar->setConstexpr(OldVar->isConstexpr());
3810 NewVar->setInitCapture(OldVar->isInitCapture());
3811 NewVar->setPreviousDeclInSameBlockScope(
3812 OldVar->isPreviousDeclInSameBlockScope());
3813 NewVar->setAccess(OldVar->getAccess());
3815 if (!OldVar->isStaticDataMember()) {
3816 if (OldVar->isUsed(false))
3817 NewVar->setIsUsed();
3818 NewVar->setReferenced(OldVar->isReferenced());
3821 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3823 LookupResult Previous(
3824 *this, NewVar->getDeclName(), NewVar->getLocation(),
3825 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3826 : Sema::LookupOrdinaryName,
3827 Sema::ForRedeclaration);
3829 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3830 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3831 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
3832 // We have a previous declaration. Use that one, so we merge with the
3834 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3835 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3836 Previous.addDecl(NewPrev);
3837 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3838 OldVar->hasLinkage())
3839 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
3840 CheckVariableDeclaration(NewVar, Previous);
3842 if (!InstantiatingVarTemplate) {
3843 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3844 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
3845 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3848 if (!OldVar->isOutOfLine()) {
3849 if (NewVar->getDeclContext()->isFunctionOrMethod())
3850 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3853 // Link instantiations of static data members back to the template from
3854 // which they were instantiated.
3855 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
3856 NewVar->setInstantiationOfStaticDataMember(OldVar,
3857 TSK_ImplicitInstantiation);
3859 // Forward the mangling number from the template to the instantiated decl.
3860 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
3861 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
3863 // Delay instantiation of the initializer for variable templates or inline
3864 // static data members until a definition of the variable is needed. We need
3865 // it right away if the type contains 'auto'.
3866 if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
3867 !InstantiatingVarTemplate &&
3868 !(OldVar->isInline() && OldVar->isThisDeclarationADefinition())) ||
3869 NewVar->getType()->isUndeducedType())
3870 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3872 // Diagnose unused local variables with dependent types, where the diagnostic
3873 // will have been deferred.
3874 if (!NewVar->isInvalidDecl() &&
3875 NewVar->getDeclContext()->isFunctionOrMethod() &&
3876 OldVar->getType()->isDependentType())
3877 DiagnoseUnusedDecl(NewVar);
3880 /// \brief Instantiate the initializer of a variable.
3881 void Sema::InstantiateVariableInitializer(
3882 VarDecl *Var, VarDecl *OldVar,
3883 const MultiLevelTemplateArgumentList &TemplateArgs) {
3884 // We propagate the 'inline' flag with the initializer, because it
3885 // would otherwise imply that the variable is a definition for a
3886 // non-static data member.
3887 if (OldVar->isInlineSpecified())
3888 Var->setInlineSpecified();
3889 else if (OldVar->isInline())
3890 Var->setImplicitlyInline();
3892 if (OldVar->getInit()) {
3893 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3894 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3896 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3898 // Instantiate the initializer.
3902 ContextRAII SwitchContext(*this, Var->getDeclContext());
3903 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
3904 OldVar->getInitStyle() == VarDecl::CallInit);
3907 if (!Init.isInvalid()) {
3908 bool TypeMayContainAuto = true;
3909 Expr *InitExpr = Init.get();
3911 if (Var->hasAttr<DLLImportAttr>() &&
3913 !InitExpr->isConstantInitializer(getASTContext(), false))) {
3914 // Do not dynamically initialize dllimport variables.
3915 } else if (InitExpr) {
3916 bool DirectInit = OldVar->isDirectInit();
3917 AddInitializerToDecl(Var, InitExpr, DirectInit, TypeMayContainAuto);
3919 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3921 // FIXME: Not too happy about invalidating the declaration
3922 // because of a bogus initializer.
3923 Var->setInvalidDecl();
3926 PopExpressionEvaluationContext();
3928 if (Var->isStaticDataMember()) {
3929 if (!Var->isOutOfLine())
3932 // If the declaration inside the class had an initializer, don't add
3933 // another one to the out-of-line definition.
3934 if (OldVar->getFirstDecl()->hasInit())
3938 // We'll add an initializer to a for-range declaration later.
3939 if (Var->isCXXForRangeDecl())
3942 ActOnUninitializedDecl(Var, false);
3946 /// \brief Instantiate the definition of the given variable from its
3949 /// \param PointOfInstantiation the point at which the instantiation was
3950 /// required. Note that this is not precisely a "point of instantiation"
3951 /// for the function, but it's close.
3953 /// \param Var the already-instantiated declaration of a static member
3954 /// variable of a class template specialization.
3956 /// \param Recursive if true, recursively instantiates any functions that
3957 /// are required by this instantiation.
3959 /// \param DefinitionRequired if true, then we are performing an explicit
3960 /// instantiation where an out-of-line definition of the member variable
3961 /// is required. Complain if there is no such definition.
3962 void Sema::InstantiateStaticDataMemberDefinition(
3963 SourceLocation PointOfInstantiation,
3966 bool DefinitionRequired) {
3967 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3968 DefinitionRequired);
3971 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3972 VarDecl *Var, bool Recursive,
3973 bool DefinitionRequired, bool AtEndOfTU) {
3974 if (Var->isInvalidDecl())
3977 VarTemplateSpecializationDecl *VarSpec =
3978 dyn_cast<VarTemplateSpecializationDecl>(Var);
3979 VarDecl *PatternDecl = nullptr, *Def = nullptr;
3980 MultiLevelTemplateArgumentList TemplateArgs =
3981 getTemplateInstantiationArgs(Var);
3984 // If this is a variable template specialization, make sure that it is
3985 // non-dependent, then find its instantiation pattern.
3986 bool InstantiationDependent = false;
3987 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3988 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3989 "Only instantiate variable template specializations that are "
3990 "not type-dependent");
3991 (void)InstantiationDependent;
3993 // Find the variable initialization that we'll be substituting. If the
3994 // pattern was instantiated from a member template, look back further to
3995 // find the real pattern.
3996 assert(VarSpec->getSpecializedTemplate() &&
3997 "Specialization without specialized template?");
3998 llvm::PointerUnion<VarTemplateDecl *,
3999 VarTemplatePartialSpecializationDecl *> PatternPtr =
4000 VarSpec->getSpecializedTemplateOrPartial();
4001 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
4002 VarTemplatePartialSpecializationDecl *Tmpl =
4003 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
4004 while (VarTemplatePartialSpecializationDecl *From =
4005 Tmpl->getInstantiatedFromMember()) {
4006 if (Tmpl->isMemberSpecialization())
4013 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
4014 while (VarTemplateDecl *From =
4015 Tmpl->getInstantiatedFromMemberTemplate()) {
4016 if (Tmpl->isMemberSpecialization())
4021 PatternDecl = Tmpl->getTemplatedDecl();
4024 // If this is a static data member template, there might be an
4025 // uninstantiated initializer on the declaration. If so, instantiate
4027 if (PatternDecl->isStaticDataMember() &&
4028 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
4030 // FIXME: Factor out the duplicated instantiation context setup/tear down
4032 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4033 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4035 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4036 "instantiating variable initializer");
4038 // If we're performing recursive template instantiation, create our own
4039 // queue of pending implicit instantiations that we will instantiate
4040 // later, while we're still within our own instantiation context.
4041 SavePendingInstantiationsAndVTableUsesRAII
4042 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
4044 LocalInstantiationScope Local(*this);
4046 // Enter the scope of this instantiation. We don't use
4047 // PushDeclContext because we don't have a scope.
4048 ContextRAII PreviousContext(*this, Var->getDeclContext());
4049 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4050 PreviousContext.pop();
4052 // FIXME: Need to inform the ASTConsumer that we instantiated the
4055 // This variable may have local implicit instantiations that need to be
4056 // instantiated within this scope.
4057 PerformPendingInstantiations(/*LocalOnly=*/true);
4062 // Define any newly required vtables.
4063 DefineUsedVTables();
4065 // Instantiate any pending implicit instantiations found during the
4066 // instantiation of this template.
4067 PerformPendingInstantiations();
4069 // PendingInstantiations and VTableUses are restored through
4070 // SavePendingInstantiationsAndVTableUses's destructor.
4074 // Find actual definition
4075 Def = PatternDecl->getDefinition(getASTContext());
4077 // If this is a static data member, find its out-of-line definition.
4078 assert(Var->isStaticDataMember() && "not a static data member?");
4079 PatternDecl = Var->getInstantiatedFromStaticDataMember();
4081 assert(PatternDecl && "data member was not instantiated from a template?");
4082 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
4083 Def = PatternDecl->getDefinition();
4086 // FIXME: Check that the definition is visible before trying to instantiate
4087 // it. This requires us to track the instantiation stack in order to know
4088 // which definitions should be visible.
4090 // If we don't have a definition of the variable template, we won't perform
4091 // any instantiation. Rather, we rely on the user to instantiate this
4092 // definition (or provide a specialization for it) in another translation
4095 if (DefinitionRequired) {
4097 Diag(PointOfInstantiation,
4098 diag::err_explicit_instantiation_undefined_var_template) << Var;
4100 Diag(PointOfInstantiation,
4101 diag::err_explicit_instantiation_undefined_member)
4102 << 2 << Var->getDeclName() << Var->getDeclContext();
4103 Diag(PatternDecl->getLocation(),
4104 diag::note_explicit_instantiation_here);
4106 Var->setInvalidDecl();
4107 } else if (Var->getTemplateSpecializationKind()
4108 == TSK_ExplicitInstantiationDefinition) {
4109 PendingInstantiations.push_back(
4110 std::make_pair(Var, PointOfInstantiation));
4111 } else if (Var->getTemplateSpecializationKind()
4112 == TSK_ImplicitInstantiation) {
4113 // Warn about missing definition at the end of translation unit.
4114 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred()) {
4115 Diag(PointOfInstantiation, diag::warn_var_template_missing)
4117 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4118 if (getLangOpts().CPlusPlus11)
4119 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
4126 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
4128 // Never instantiate an explicit specialization.
4129 if (TSK == TSK_ExplicitSpecialization)
4132 // C++11 [temp.explicit]p10:
4133 // Except for inline functions, [...] explicit instantiation declarations
4134 // have the effect of suppressing the implicit instantiation of the entity
4135 // to which they refer.
4136 if (TSK == TSK_ExplicitInstantiationDeclaration)
4139 // Make sure to pass the instantiated variable to the consumer at the end.
4140 struct PassToConsumerRAII {
4141 ASTConsumer &Consumer;
4144 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4145 : Consumer(Consumer), Var(Var) { }
4147 ~PassToConsumerRAII() {
4148 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
4150 } PassToConsumerRAII(Consumer, Var);
4152 // If we already have a definition, we're done.
4153 if (VarDecl *Def = Var->getDefinition()) {
4154 // We may be explicitly instantiating something we've already implicitly
4156 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
4157 PointOfInstantiation);
4161 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4162 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4164 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4165 "instantiating variable definition");
4167 // If we're performing recursive template instantiation, create our own
4168 // queue of pending implicit instantiations that we will instantiate later,
4169 // while we're still within our own instantiation context.
4170 SavePendingLocalImplicitInstantiationsRAII
4171 SavedPendingLocalImplicitInstantiations(*this);
4172 SavePendingInstantiationsAndVTableUsesRAII
4173 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
4175 // Enter the scope of this instantiation. We don't use
4176 // PushDeclContext because we don't have a scope.
4177 ContextRAII PreviousContext(*this, Var->getDeclContext());
4178 LocalInstantiationScope Local(*this);
4180 VarDecl *OldVar = Var;
4181 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
4182 // We're instantiating an inline static data member whose definition was
4183 // provided inside the class.
4184 // FIXME: Update record?
4185 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4186 } else if (!VarSpec) {
4187 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
4189 } else if (Var->isStaticDataMember() &&
4190 Var->getLexicalDeclContext()->isRecord()) {
4191 // We need to instantiate the definition of a static data member template,
4192 // and all we have is the in-class declaration of it. Instantiate a separate
4193 // declaration of the definition.
4194 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
4196 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
4197 VarSpec->getSpecializedTemplate(), Def, nullptr,
4198 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
4200 llvm::PointerUnion<VarTemplateDecl *,
4201 VarTemplatePartialSpecializationDecl *> PatternPtr =
4202 VarSpec->getSpecializedTemplateOrPartial();
4203 if (VarTemplatePartialSpecializationDecl *Partial =
4204 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4205 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4206 Partial, &VarSpec->getTemplateInstantiationArgs());
4208 // Merge the definition with the declaration.
4209 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
4210 LookupOrdinaryName, ForRedeclaration);
4212 MergeVarDecl(Var, R);
4214 // Attach the initializer.
4215 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4218 // Complete the existing variable's definition with an appropriately
4219 // substituted type and initializer.
4220 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
4222 PreviousContext.pop();
4225 PassToConsumerRAII.Var = Var;
4226 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
4227 OldVar->getPointOfInstantiation());
4230 // This variable may have local implicit instantiations that need to be
4231 // instantiated within this scope.
4232 PerformPendingInstantiations(/*LocalOnly=*/true);
4237 // Define any newly required vtables.
4238 DefineUsedVTables();
4240 // Instantiate any pending implicit instantiations found during the
4241 // instantiation of this template.
4242 PerformPendingInstantiations();
4244 // PendingInstantiations and VTableUses are restored through
4245 // SavePendingInstantiationsAndVTableUses's destructor.
4250 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4251 const CXXConstructorDecl *Tmpl,
4252 const MultiLevelTemplateArgumentList &TemplateArgs) {
4254 SmallVector<CXXCtorInitializer*, 4> NewInits;
4255 bool AnyErrors = Tmpl->isInvalidDecl();
4257 // Instantiate all the initializers.
4258 for (const auto *Init : Tmpl->inits()) {
4259 // Only instantiate written initializers, let Sema re-construct implicit
4261 if (!Init->isWritten())
4264 SourceLocation EllipsisLoc;
4266 if (Init->isPackExpansion()) {
4267 // This is a pack expansion. We should expand it now.
4268 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
4269 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4270 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
4271 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
4272 bool ShouldExpand = false;
4273 bool RetainExpansion = false;
4274 Optional<unsigned> NumExpansions;
4275 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
4276 BaseTL.getSourceRange(),
4278 TemplateArgs, ShouldExpand,
4282 New->setInvalidDecl();
4285 assert(ShouldExpand && "Partial instantiation of base initializer?");
4287 // Loop over all of the arguments in the argument pack(s),
4288 for (unsigned I = 0; I != *NumExpansions; ++I) {
4289 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4291 // Instantiate the initializer.
4292 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4293 /*CXXDirectInit=*/true);
4294 if (TempInit.isInvalid()) {
4299 // Instantiate the base type.
4300 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4302 Init->getSourceLocation(),
4303 New->getDeclName());
4309 // Build the initializer.
4310 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4311 BaseTInfo, TempInit.get(),
4314 if (NewInit.isInvalid()) {
4319 NewInits.push_back(NewInit.get());
4325 // Instantiate the initializer.
4326 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4327 /*CXXDirectInit=*/true);
4328 if (TempInit.isInvalid()) {
4333 MemInitResult NewInit;
4334 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4335 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4337 Init->getSourceLocation(),
4338 New->getDeclName());
4341 New->setInvalidDecl();
4345 if (Init->isBaseInitializer())
4346 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
4347 New->getParent(), EllipsisLoc);
4349 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
4350 cast<CXXRecordDecl>(CurContext->getParent()));
4351 } else if (Init->isMemberInitializer()) {
4352 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
4353 Init->getMemberLocation(),
4358 New->setInvalidDecl();
4362 NewInit = BuildMemberInitializer(Member, TempInit.get(),
4363 Init->getSourceLocation());
4364 } else if (Init->isIndirectMemberInitializer()) {
4365 IndirectFieldDecl *IndirectMember =
4366 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
4367 Init->getMemberLocation(),
4368 Init->getIndirectMember(), TemplateArgs));
4370 if (!IndirectMember) {
4372 New->setInvalidDecl();
4376 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
4377 Init->getSourceLocation());
4380 if (NewInit.isInvalid()) {
4382 New->setInvalidDecl();
4384 NewInits.push_back(NewInit.get());
4388 // Assign all the initializers to the new constructor.
4389 ActOnMemInitializers(New,
4390 /*FIXME: ColonLoc */
4396 // TODO: this could be templated if the various decl types used the
4397 // same method name.
4398 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4399 ClassTemplateDecl *Instance) {
4400 Pattern = Pattern->getCanonicalDecl();
4403 Instance = Instance->getCanonicalDecl();
4404 if (Pattern == Instance) return true;
4405 Instance = Instance->getInstantiatedFromMemberTemplate();
4411 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4412 FunctionTemplateDecl *Instance) {
4413 Pattern = Pattern->getCanonicalDecl();
4416 Instance = Instance->getCanonicalDecl();
4417 if (Pattern == Instance) return true;
4418 Instance = Instance->getInstantiatedFromMemberTemplate();
4425 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4426 ClassTemplatePartialSpecializationDecl *Instance) {
4428 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4430 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4431 Instance->getCanonicalDecl());
4432 if (Pattern == Instance)
4434 Instance = Instance->getInstantiatedFromMember();
4440 static bool isInstantiationOf(CXXRecordDecl *Pattern,
4441 CXXRecordDecl *Instance) {
4442 Pattern = Pattern->getCanonicalDecl();
4445 Instance = Instance->getCanonicalDecl();
4446 if (Pattern == Instance) return true;
4447 Instance = Instance->getInstantiatedFromMemberClass();
4453 static bool isInstantiationOf(FunctionDecl *Pattern,
4454 FunctionDecl *Instance) {
4455 Pattern = Pattern->getCanonicalDecl();
4458 Instance = Instance->getCanonicalDecl();
4459 if (Pattern == Instance) return true;
4460 Instance = Instance->getInstantiatedFromMemberFunction();
4466 static bool isInstantiationOf(EnumDecl *Pattern,
4467 EnumDecl *Instance) {
4468 Pattern = Pattern->getCanonicalDecl();
4471 Instance = Instance->getCanonicalDecl();
4472 if (Pattern == Instance) return true;
4473 Instance = Instance->getInstantiatedFromMemberEnum();
4479 static bool isInstantiationOf(UsingShadowDecl *Pattern,
4480 UsingShadowDecl *Instance,
4482 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
4486 static bool isInstantiationOf(UsingDecl *Pattern,
4487 UsingDecl *Instance,
4489 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4492 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4493 UsingDecl *Instance,
4495 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4498 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
4499 UsingDecl *Instance,
4501 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4504 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4505 VarDecl *Instance) {
4506 assert(Instance->isStaticDataMember());
4508 Pattern = Pattern->getCanonicalDecl();
4511 Instance = Instance->getCanonicalDecl();
4512 if (Pattern == Instance) return true;
4513 Instance = Instance->getInstantiatedFromStaticDataMember();
4519 // Other is the prospective instantiation
4520 // D is the prospective pattern
4521 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
4522 if (D->getKind() != Other->getKind()) {
4523 if (UnresolvedUsingTypenameDecl *UUD
4524 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4525 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4526 return isInstantiationOf(UUD, UD, Ctx);
4530 if (UnresolvedUsingValueDecl *UUD
4531 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4532 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4533 return isInstantiationOf(UUD, UD, Ctx);
4540 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4541 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
4543 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4544 return isInstantiationOf(cast<FunctionDecl>(D), Function);
4546 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4547 return isInstantiationOf(cast<EnumDecl>(D), Enum);
4549 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
4550 if (Var->isStaticDataMember())
4551 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4553 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4554 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
4556 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4557 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4559 if (ClassTemplatePartialSpecializationDecl *PartialSpec
4560 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4561 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4564 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4565 if (!Field->getDeclName()) {
4566 // This is an unnamed field.
4567 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
4568 cast<FieldDecl>(D));
4572 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4573 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4575 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4576 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4578 return D->getDeclName() && isa<NamedDecl>(Other) &&
4579 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4582 template<typename ForwardIterator>
4583 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
4585 ForwardIterator first,
4586 ForwardIterator last) {
4587 for (; first != last; ++first)
4588 if (isInstantiationOf(Ctx, D, *first))
4589 return cast<NamedDecl>(*first);
4594 /// \brief Finds the instantiation of the given declaration context
4595 /// within the current instantiation.
4597 /// \returns NULL if there was an error
4598 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
4599 const MultiLevelTemplateArgumentList &TemplateArgs) {
4600 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
4601 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
4602 return cast_or_null<DeclContext>(ID);
4606 /// \brief Find the instantiation of the given declaration within the
4607 /// current instantiation.
4609 /// This routine is intended to be used when \p D is a declaration
4610 /// referenced from within a template, that needs to mapped into the
4611 /// corresponding declaration within an instantiation. For example,
4615 /// template<typename T>
4618 /// KnownValue = sizeof(T)
4621 /// bool getKind() const { return KnownValue; }
4624 /// template struct X<int>;
4627 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4628 /// \p EnumConstantDecl for \p KnownValue (which refers to
4629 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4630 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4631 /// this mapping from within the instantiation of <tt>X<int></tt>.
4632 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4633 const MultiLevelTemplateArgumentList &TemplateArgs) {
4634 DeclContext *ParentDC = D->getDeclContext();
4635 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4636 // parameters (p below) can have their ParentDC set to the translation-unit
4637 // - thus we can not consistently check if the ParentDC of such a parameter
4638 // is Dependent or/and a FunctionOrMethod.
4639 // For e.g. this code, during Template argument deduction tries to
4640 // find an instantiated decl for (T y) when the ParentDC for y is
4641 // the translation unit.
4642 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
4643 // float baz(float(*)()) { return 0.0; }
4645 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4646 // it gets here, always has a FunctionOrMethod as its ParentDC??
4648 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4649 // whose type is not instantiation dependent, do nothing to the decl
4650 // - otherwise find its instantiated decl.
4651 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4652 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4654 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
4655 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
4656 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4657 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
4658 // D is a local of some kind. Look into the map of local
4659 // declarations to their instantiations.
4660 if (CurrentInstantiationScope) {
4661 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
4662 if (Decl *FD = Found->dyn_cast<Decl *>())
4663 return cast<NamedDecl>(FD);
4665 int PackIdx = ArgumentPackSubstitutionIndex;
4666 assert(PackIdx != -1 &&
4667 "found declaration pack but not pack expanding");
4668 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4669 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4673 // If we're performing a partial substitution during template argument
4674 // deduction, we may not have values for template parameters yet. They
4675 // just map to themselves.
4676 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4677 isa<TemplateTemplateParmDecl>(D))
4680 if (D->isInvalidDecl())
4683 // Normally this function only searches for already instantiated declaration
4684 // however we have to make an exclusion for local types used before
4685 // definition as in the code:
4687 // template<typename T> void f1() {
4688 // void g1(struct x1);
4692 // In this case instantiation of the type of 'g1' requires definition of
4693 // 'x1', which is defined later. Error recovery may produce an enum used
4694 // before definition. In these cases we need to instantiate relevant
4695 // declarations here.
4696 bool NeedInstantiate = false;
4697 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4698 NeedInstantiate = RD->isLocalClass();
4700 NeedInstantiate = isa<EnumDecl>(D);
4701 if (NeedInstantiate) {
4702 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4703 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4704 return cast<TypeDecl>(Inst);
4707 // If we didn't find the decl, then we must have a label decl that hasn't
4708 // been found yet. Lazily instantiate it and return it now.
4709 assert(isa<LabelDecl>(D));
4711 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4712 assert(Inst && "Failed to instantiate label??");
4714 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4715 return cast<LabelDecl>(Inst);
4718 // For variable template specializations, update those that are still
4720 if (VarTemplateSpecializationDecl *VarSpec =
4721 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4722 bool InstantiationDependent = false;
4723 const TemplateArgumentListInfo &VarTemplateArgs =
4724 VarSpec->getTemplateArgsInfo();
4725 if (TemplateSpecializationType::anyDependentTemplateArguments(
4726 VarTemplateArgs, InstantiationDependent))
4727 D = cast<NamedDecl>(
4728 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4732 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4733 if (!Record->isDependentContext())
4736 // Determine whether this record is the "templated" declaration describing
4737 // a class template or class template partial specialization.
4738 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
4740 ClassTemplate = ClassTemplate->getCanonicalDecl();
4741 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4742 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4743 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
4745 // Walk the current context to find either the record or an instantiation of
4747 DeclContext *DC = CurContext;
4748 while (!DC->isFileContext()) {
4749 // If we're performing substitution while we're inside the template
4750 // definition, we'll find our own context. We're done.
4751 if (DC->Equals(Record))
4754 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4755 // Check whether we're in the process of instantiating a class template
4756 // specialization of the template we're mapping.
4757 if (ClassTemplateSpecializationDecl *InstSpec
4758 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4759 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4760 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4764 // Check whether we're in the process of instantiating a member class.
4765 if (isInstantiationOf(Record, InstRecord))
4769 // Move to the outer template scope.
4770 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4771 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4772 DC = FD->getLexicalDeclContext();
4777 DC = DC->getParent();
4780 // Fall through to deal with other dependent record types (e.g.,
4781 // anonymous unions in class templates).
4784 if (!ParentDC->isDependentContext())
4787 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
4791 if (ParentDC != D->getDeclContext()) {
4792 // We performed some kind of instantiation in the parent context,
4793 // so now we need to look into the instantiated parent context to
4794 // find the instantiation of the declaration D.
4796 // If our context used to be dependent, we may need to instantiate
4797 // it before performing lookup into that context.
4798 bool IsBeingInstantiated = false;
4799 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
4800 if (!Spec->isDependentContext()) {
4801 QualType T = Context.getTypeDeclType(Spec);
4802 const RecordType *Tag = T->getAs<RecordType>();
4803 assert(Tag && "type of non-dependent record is not a RecordType");
4804 if (Tag->isBeingDefined())
4805 IsBeingInstantiated = true;
4806 if (!Tag->isBeingDefined() &&
4807 RequireCompleteType(Loc, T, diag::err_incomplete_type))
4810 ParentDC = Tag->getDecl();
4814 NamedDecl *Result = nullptr;
4815 if (D->getDeclName()) {
4816 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
4817 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
4819 // Since we don't have a name for the entity we're looking for,
4820 // our only option is to walk through all of the declarations to
4821 // find that name. This will occur in a few cases:
4823 // - anonymous struct/union within a template
4824 // - unnamed class/struct/union/enum within a template
4826 // FIXME: Find a better way to find these instantiations!
4827 Result = findInstantiationOf(Context, D,
4828 ParentDC->decls_begin(),
4829 ParentDC->decls_end());
4833 if (isa<UsingShadowDecl>(D)) {
4834 // UsingShadowDecls can instantiate to nothing because of using hiding.
4835 } else if (Diags.hasErrorOccurred()) {
4836 // We've already complained about something, so most likely this
4837 // declaration failed to instantiate. There's no point in complaining
4838 // further, since this is normal in invalid code.
4839 } else if (IsBeingInstantiated) {
4840 // The class in which this member exists is currently being
4841 // instantiated, and we haven't gotten around to instantiating this
4842 // member yet. This can happen when the code uses forward declarations
4843 // of member classes, and introduces ordering dependencies via
4844 // template instantiation.
4845 Diag(Loc, diag::err_member_not_yet_instantiated)
4847 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4848 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
4849 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4850 // This enumeration constant was found when the template was defined,
4851 // but can't be found in the instantiation. This can happen if an
4852 // unscoped enumeration member is explicitly specialized.
4853 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4854 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4856 assert(Spec->getTemplateSpecializationKind() ==
4857 TSK_ExplicitSpecialization);
4858 Diag(Loc, diag::err_enumerator_does_not_exist)
4860 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4861 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4862 << Context.getTypeDeclType(Spec);
4864 // We should have found something, but didn't.
4865 llvm_unreachable("Unable to find instantiation of declaration!");
4875 /// \brief Performs template instantiation for all implicit template
4876 /// instantiations we have seen until this point.
4877 void Sema::PerformPendingInstantiations(bool LocalOnly) {
4878 while (!PendingLocalImplicitInstantiations.empty() ||
4879 (!LocalOnly && !PendingInstantiations.empty())) {
4880 PendingImplicitInstantiation Inst;
4882 if (PendingLocalImplicitInstantiations.empty()) {
4883 Inst = PendingInstantiations.front();
4884 PendingInstantiations.pop_front();
4886 Inst = PendingLocalImplicitInstantiations.front();
4887 PendingLocalImplicitInstantiations.pop_front();
4890 // Instantiate function definitions
4891 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
4892 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4893 TSK_ExplicitInstantiationDefinition;
4894 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4895 DefinitionRequired, true);
4899 // Instantiate variable definitions
4900 VarDecl *Var = cast<VarDecl>(Inst.first);
4902 assert((Var->isStaticDataMember() ||
4903 isa<VarTemplateSpecializationDecl>(Var)) &&
4904 "Not a static data member, nor a variable template"
4905 " specialization?");
4907 // Don't try to instantiate declarations if the most recent redeclaration
4909 if (Var->getMostRecentDecl()->isInvalidDecl())
4912 // Check if the most recent declaration has changed the specialization kind
4913 // and removed the need for implicit instantiation.
4914 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
4915 case TSK_Undeclared:
4916 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
4917 case TSK_ExplicitInstantiationDeclaration:
4918 case TSK_ExplicitSpecialization:
4919 continue; // No longer need to instantiate this type.
4920 case TSK_ExplicitInstantiationDefinition:
4921 // We only need an instantiation if the pending instantiation *is* the
4922 // explicit instantiation.
4923 if (Var != Var->getMostRecentDecl()) continue;
4924 case TSK_ImplicitInstantiation:
4928 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4929 "instantiating variable definition");
4930 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4931 TSK_ExplicitInstantiationDefinition;
4933 // Instantiate static data member definitions or variable template
4935 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4936 DefinitionRequired, true);
4940 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4941 const MultiLevelTemplateArgumentList &TemplateArgs) {
4942 for (auto DD : Pattern->ddiags()) {
4943 switch (DD->getKind()) {
4944 case DependentDiagnostic::Access:
4945 HandleDependentAccessCheck(*DD, TemplateArgs);