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/Initialization.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/PrettyDeclStackTrace.h"
25 #include "clang/Sema/Template.h"
27 using namespace clang;
29 static bool isDeclWithinFunction(const Decl *D) {
30 const DeclContext *DC = D->getDeclContext();
31 if (DC->isFunctionOrMethod())
35 return cast<CXXRecordDecl>(DC)->isLocalClass();
40 template<typename DeclT>
41 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
42 const MultiLevelTemplateArgumentList &TemplateArgs) {
43 if (!OldDecl->getQualifierLoc())
46 assert((NewDecl->getFriendObjectKind() ||
47 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
48 "non-friend with qualified name defined in dependent context");
49 Sema::ContextRAII SavedContext(
51 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
52 ? NewDecl->getLexicalDeclContext()
53 : OldDecl->getLexicalDeclContext()));
55 NestedNameSpecifierLoc NewQualifierLoc
56 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
62 NewDecl->setQualifierInfo(NewQualifierLoc);
66 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
67 DeclaratorDecl *NewDecl) {
68 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
71 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
73 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
76 // Include attribute instantiation code.
77 #include "clang/Sema/AttrTemplateInstantiate.inc"
79 static void instantiateDependentAlignedAttr(
80 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
81 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
82 if (Aligned->isAlignmentExpr()) {
83 // The alignment expression is a constant expression.
84 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
85 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
86 if (!Result.isInvalid())
87 S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
88 Aligned->getSpellingListIndex(), IsPackExpansion);
90 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
91 TemplateArgs, Aligned->getLocation(),
94 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
95 Aligned->getSpellingListIndex(), IsPackExpansion);
99 static void instantiateDependentAlignedAttr(
100 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
101 const AlignedAttr *Aligned, Decl *New) {
102 if (!Aligned->isPackExpansion()) {
103 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
107 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
108 if (Aligned->isAlignmentExpr())
109 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
112 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
114 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
116 // Determine whether we can expand this attribute pack yet.
117 bool Expand = true, RetainExpansion = false;
118 Optional<unsigned> NumExpansions;
119 // FIXME: Use the actual location of the ellipsis.
120 SourceLocation EllipsisLoc = Aligned->getLocation();
121 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
122 Unexpanded, TemplateArgs, Expand,
123 RetainExpansion, NumExpansions))
127 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
128 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
130 for (unsigned I = 0; I != *NumExpansions; ++I) {
131 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
132 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
137 static void instantiateDependentAssumeAlignedAttr(
138 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
139 const AssumeAlignedAttr *Aligned, Decl *New) {
140 // The alignment expression is a constant expression.
141 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
143 Expr *E, *OE = nullptr;
144 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
145 if (Result.isInvalid())
147 E = Result.getAs<Expr>();
149 if (Aligned->getOffset()) {
150 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
151 if (Result.isInvalid())
153 OE = Result.getAs<Expr>();
156 S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
157 Aligned->getSpellingListIndex());
160 static void instantiateDependentAlignValueAttr(
161 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
162 const AlignValueAttr *Aligned, Decl *New) {
163 // The alignment expression is a constant expression.
164 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
165 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
166 if (!Result.isInvalid())
167 S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
168 Aligned->getSpellingListIndex());
171 static void instantiateDependentEnableIfAttr(
172 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
173 const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
174 Expr *Cond = nullptr;
176 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
177 ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
178 if (Result.isInvalid())
180 Cond = Result.getAs<Expr>();
182 if (!Cond->isTypeDependent()) {
183 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
184 if (Converted.isInvalid())
186 Cond = Converted.get();
189 SmallVector<PartialDiagnosticAt, 8> Diags;
190 if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
191 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(New),
193 S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
194 for (int I = 0, N = Diags.size(); I != N; ++I)
195 S.Diag(Diags[I].first, Diags[I].second);
199 EnableIfAttr *EIA = new (S.getASTContext())
200 EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
202 A->getSpellingListIndex());
206 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
207 // template A as the base and arguments from TemplateArgs.
208 static void instantiateDependentCUDALaunchBoundsAttr(
209 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
210 const CUDALaunchBoundsAttr &Attr, Decl *New) {
211 // The alignment expression is a constant expression.
212 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
214 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
215 if (Result.isInvalid())
217 Expr *MaxThreads = Result.getAs<Expr>();
219 Expr *MinBlocks = nullptr;
220 if (Attr.getMinBlocks()) {
221 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
222 if (Result.isInvalid())
224 MinBlocks = Result.getAs<Expr>();
227 S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks,
228 Attr.getSpellingListIndex());
232 instantiateDependentModeAttr(Sema &S,
233 const MultiLevelTemplateArgumentList &TemplateArgs,
234 const ModeAttr &Attr, Decl *New) {
235 S.AddModeAttr(Attr.getRange(), New, Attr.getMode(),
236 Attr.getSpellingListIndex(), /*InInstantiation=*/true);
239 /// Instantiation of 'declare simd' attribute and its arguments.
240 static void instantiateOMPDeclareSimdDeclAttr(
241 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
242 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
243 // Allow 'this' in clauses with varlists.
244 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
245 New = FTD->getTemplatedDecl();
246 auto *FD = cast<FunctionDecl>(New);
247 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
248 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
249 SmallVector<unsigned, 4> LinModifiers;
251 auto &&Subst = [&](Expr *E) -> ExprResult {
252 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
253 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
254 Sema::ContextRAII SavedContext(S, FD);
255 LocalInstantiationScope Local(S);
256 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
257 Local.InstantiatedLocal(
258 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
259 return S.SubstExpr(E, TemplateArgs);
261 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, /*TypeQuals=*/0,
262 FD->isCXXInstanceMember());
263 return S.SubstExpr(E, TemplateArgs);
267 if (auto *E = Attr.getSimdlen())
270 if (Attr.uniforms_size() > 0) {
271 for(auto *E : Attr.uniforms()) {
272 ExprResult Inst = Subst(E);
273 if (Inst.isInvalid())
275 Uniforms.push_back(Inst.get());
279 auto AI = Attr.alignments_begin();
280 for (auto *E : Attr.aligneds()) {
281 ExprResult Inst = Subst(E);
282 if (Inst.isInvalid())
284 Aligneds.push_back(Inst.get());
287 Inst = S.SubstExpr(*AI, TemplateArgs);
288 Alignments.push_back(Inst.get());
292 auto SI = Attr.steps_begin();
293 for (auto *E : Attr.linears()) {
294 ExprResult Inst = Subst(E);
295 if (Inst.isInvalid())
297 Linears.push_back(Inst.get());
300 Inst = S.SubstExpr(*SI, TemplateArgs);
301 Steps.push_back(Inst.get());
304 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
305 (void)S.ActOnOpenMPDeclareSimdDirective(
306 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
307 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
311 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
312 const Decl *Tmpl, Decl *New,
313 LateInstantiatedAttrVec *LateAttrs,
314 LocalInstantiationScope *OuterMostScope) {
315 for (const auto *TmplAttr : Tmpl->attrs()) {
316 // FIXME: This should be generalized to more than just the AlignedAttr.
317 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
318 if (Aligned && Aligned->isAlignmentDependent()) {
319 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
323 const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
325 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
329 const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
331 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
335 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
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::VisitBindingDecl(BindingDecl *D) {
602 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
604 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
608 Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
609 // Transform the bindings first.
610 SmallVector<BindingDecl*, 16> NewBindings;
611 for (auto *OldBD : D->bindings())
612 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
613 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
615 auto *NewDD = cast_or_null<DecompositionDecl>(
616 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
618 if (!NewDD || NewDD->isInvalidDecl())
619 for (auto *NewBD : NewBindings)
620 NewBD->setInvalidDecl();
625 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
626 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
629 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
630 bool InstantiatingVarTemplate,
631 ArrayRef<BindingDecl*> *Bindings) {
633 // Do substitution on the type of the declaration
634 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
636 D->getTypeSpecStartLoc(),
641 if (DI->getType()->isFunctionType()) {
642 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
643 << D->isStaticDataMember() << DI->getType();
647 DeclContext *DC = Owner;
648 if (D->isLocalExternDecl())
649 SemaRef.adjustContextForLocalExternDecl(DC);
651 // Build the instantiated declaration.
654 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
655 D->getLocation(), DI->getType(), DI,
656 D->getStorageClass(), *Bindings);
658 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
659 D->getLocation(), D->getIdentifier(), DI->getType(),
660 DI, D->getStorageClass());
662 // In ARC, infer 'retaining' for variables of retainable type.
663 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
664 SemaRef.inferObjCARCLifetime(Var))
665 Var->setInvalidDecl();
667 // Substitute the nested name specifier, if any.
668 if (SubstQualifier(D, Var))
671 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
672 StartingScope, InstantiatingVarTemplate);
674 if (D->isNRVOVariable()) {
675 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
676 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
677 Var->setNRVOVariable(true);
680 Var->setImplicit(D->isImplicit());
685 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
687 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
688 D->getAccessSpecifierLoc(), D->getColonLoc());
689 Owner->addHiddenDecl(AD);
693 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
694 bool Invalid = false;
695 TypeSourceInfo *DI = D->getTypeSourceInfo();
696 if (DI->getType()->isInstantiationDependentType() ||
697 DI->getType()->isVariablyModifiedType()) {
698 DI = SemaRef.SubstType(DI, TemplateArgs,
699 D->getLocation(), D->getDeclName());
701 DI = D->getTypeSourceInfo();
703 } else if (DI->getType()->isFunctionType()) {
704 // C++ [temp.arg.type]p3:
705 // If a declaration acquires a function type through a type
706 // dependent on a template-parameter and this causes a
707 // declaration that does not use the syntactic form of a
708 // function declarator to have function type, the program is
710 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
715 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
718 Expr *BitWidth = D->getBitWidth();
722 // The bit-width expression is a constant expression.
723 EnterExpressionEvaluationContext Unevaluated(SemaRef,
724 Sema::ConstantEvaluated);
726 ExprResult InstantiatedBitWidth
727 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
728 if (InstantiatedBitWidth.isInvalid()) {
732 BitWidth = InstantiatedBitWidth.getAs<Expr>();
735 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
737 cast<RecordDecl>(Owner),
741 D->getInClassInitStyle(),
742 D->getInnerLocStart(),
746 cast<Decl>(Owner)->setInvalidDecl();
750 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
752 if (Field->hasAttrs())
753 SemaRef.CheckAlignasUnderalignment(Field);
756 Field->setInvalidDecl();
758 if (!Field->getDeclName()) {
759 // Keep track of where this decl came from.
760 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
762 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
763 if (Parent->isAnonymousStructOrUnion() &&
764 Parent->getRedeclContext()->isFunctionOrMethod())
765 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
768 Field->setImplicit(D->isImplicit());
769 Field->setAccess(D->getAccess());
770 Owner->addDecl(Field);
775 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
776 bool Invalid = false;
777 TypeSourceInfo *DI = D->getTypeSourceInfo();
779 if (DI->getType()->isVariablyModifiedType()) {
780 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
783 } else if (DI->getType()->isInstantiationDependentType()) {
784 DI = SemaRef.SubstType(DI, TemplateArgs,
785 D->getLocation(), D->getDeclName());
787 DI = D->getTypeSourceInfo();
789 } else if (DI->getType()->isFunctionType()) {
790 // C++ [temp.arg.type]p3:
791 // If a declaration acquires a function type through a type
792 // dependent on a template-parameter and this causes a
793 // declaration that does not use the syntactic form of a
794 // function declarator to have function type, the program is
796 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
801 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
804 MSPropertyDecl *Property = MSPropertyDecl::Create(
805 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
806 DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
808 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
812 Property->setInvalidDecl();
814 Property->setAccess(D->getAccess());
815 Owner->addDecl(Property);
820 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
821 NamedDecl **NamedChain =
822 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
825 for (auto *PI : D->chain()) {
826 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
831 NamedChain[i++] = Next;
834 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
835 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
836 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
837 {NamedChain, D->getChainingSize()});
839 for (const auto *Attr : D->attrs())
840 IndirectField->addAttr(Attr->clone(SemaRef.Context));
842 IndirectField->setImplicit(D->isImplicit());
843 IndirectField->setAccess(D->getAccess());
844 Owner->addDecl(IndirectField);
845 return IndirectField;
848 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
849 // Handle friend type expressions by simply substituting template
850 // parameters into the pattern type and checking the result.
851 if (TypeSourceInfo *Ty = D->getFriendType()) {
852 TypeSourceInfo *InstTy;
853 // If this is an unsupported friend, don't bother substituting template
854 // arguments into it. The actual type referred to won't be used by any
855 // parts of Clang, and may not be valid for instantiating. Just use the
856 // same info for the instantiated friend.
857 if (D->isUnsupportedFriend()) {
860 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
861 D->getLocation(), DeclarationName());
866 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
867 D->getFriendLoc(), InstTy);
871 FD->setAccess(AS_public);
872 FD->setUnsupportedFriend(D->isUnsupportedFriend());
877 NamedDecl *ND = D->getFriendDecl();
878 assert(ND && "friend decl must be a decl or a type!");
880 // All of the Visit implementations for the various potential friend
881 // declarations have to be carefully written to work for friend
882 // objects, with the most important detail being that the target
883 // decl should almost certainly not be placed in Owner.
884 Decl *NewND = Visit(ND);
885 if (!NewND) return nullptr;
888 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
889 cast<NamedDecl>(NewND), D->getFriendLoc());
890 FD->setAccess(AS_public);
891 FD->setUnsupportedFriend(D->isUnsupportedFriend());
896 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
897 Expr *AssertExpr = D->getAssertExpr();
899 // The expression in a static assertion is a constant expression.
900 EnterExpressionEvaluationContext Unevaluated(SemaRef,
901 Sema::ConstantEvaluated);
903 ExprResult InstantiatedAssertExpr
904 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
905 if (InstantiatedAssertExpr.isInvalid())
908 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
909 InstantiatedAssertExpr.get(),
915 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
916 EnumDecl *PrevDecl = nullptr;
917 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
918 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
921 if (!Prev) return nullptr;
922 PrevDecl = cast<EnumDecl>(Prev);
925 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
926 D->getLocation(), D->getIdentifier(),
927 PrevDecl, D->isScoped(),
928 D->isScopedUsingClassTag(), D->isFixed());
930 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
931 // If we have type source information for the underlying type, it means it
932 // has been explicitly set by the user. Perform substitution on it before
934 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
935 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
937 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
938 Enum->setIntegerType(SemaRef.Context.IntTy);
940 Enum->setIntegerTypeSourceInfo(NewTI);
942 assert(!D->getIntegerType()->isDependentType()
943 && "Dependent type without type source info");
944 Enum->setIntegerType(D->getIntegerType());
948 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
950 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
951 Enum->setAccess(D->getAccess());
952 // Forward the mangling number from the template to the instantiated decl.
953 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
954 // See if the old tag was defined along with a declarator.
955 // If it did, mark the new tag as being associated with that declarator.
956 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
957 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
958 // See if the old tag was defined along with a typedef.
959 // If it did, mark the new tag as being associated with that typedef.
960 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
961 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
962 if (SubstQualifier(D, Enum)) return nullptr;
963 Owner->addDecl(Enum);
965 EnumDecl *Def = D->getDefinition();
966 if (Def && Def != D) {
967 // If this is an out-of-line definition of an enum member template, check
968 // that the underlying types match in the instantiation of both
970 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
971 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
972 QualType DefnUnderlying =
973 SemaRef.SubstType(TI->getType(), TemplateArgs,
974 UnderlyingLoc, DeclarationName());
975 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
977 /*EnumUnderlyingIsImplicit=*/false, Enum);
981 // C++11 [temp.inst]p1: The implicit instantiation of a class template
982 // specialization causes the implicit instantiation of the declarations, but
983 // not the definitions of scoped member enumerations.
985 // DR1484 clarifies that enumeration definitions inside of a template
986 // declaration aren't considered entities that can be separately instantiated
987 // from the rest of the entity they are declared inside of.
988 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
989 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
990 InstantiateEnumDefinition(Enum, Def);
996 void TemplateDeclInstantiator::InstantiateEnumDefinition(
997 EnumDecl *Enum, EnumDecl *Pattern) {
998 Enum->startDefinition();
1000 // Update the location to refer to the definition.
1001 Enum->setLocation(Pattern->getLocation());
1003 SmallVector<Decl*, 4> Enumerators;
1005 EnumConstantDecl *LastEnumConst = nullptr;
1006 for (auto *EC : Pattern->enumerators()) {
1007 // The specified value for the enumerator.
1008 ExprResult Value((Expr *)nullptr);
1009 if (Expr *UninstValue = EC->getInitExpr()) {
1010 // The enumerator's value expression is a constant expression.
1011 EnterExpressionEvaluationContext Unevaluated(SemaRef,
1012 Sema::ConstantEvaluated);
1014 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1017 // Drop the initial value and continue.
1018 bool isInvalid = false;
1019 if (Value.isInvalid()) {
1024 EnumConstantDecl *EnumConst
1025 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1026 EC->getLocation(), EC->getIdentifier(),
1031 EnumConst->setInvalidDecl();
1032 Enum->setInvalidDecl();
1036 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1038 EnumConst->setAccess(Enum->getAccess());
1039 Enum->addDecl(EnumConst);
1040 Enumerators.push_back(EnumConst);
1041 LastEnumConst = EnumConst;
1043 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1044 !Enum->isScoped()) {
1045 // If the enumeration is within a function or method, record the enum
1046 // constant as a local.
1047 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1052 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1057 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1058 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1062 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1063 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1066 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1067 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1069 // Create a local instantiation scope for this class template, which
1070 // will contain the instantiations of the template parameters.
1071 LocalInstantiationScope Scope(SemaRef);
1072 TemplateParameterList *TempParams = D->getTemplateParameters();
1073 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1077 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1079 // Instantiate the qualifier. We have to do this first in case
1080 // we're a friend declaration, because if we are then we need to put
1081 // the new declaration in the appropriate context.
1082 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1084 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1090 CXXRecordDecl *PrevDecl = nullptr;
1091 ClassTemplateDecl *PrevClassTemplate = nullptr;
1093 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1094 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1095 if (!Found.empty()) {
1096 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1097 if (PrevClassTemplate)
1098 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1102 // If this isn't a friend, then it's a member template, in which
1103 // case we just want to build the instantiation in the
1104 // specialization. If it is a friend, we want to build it in
1105 // the appropriate context.
1106 DeclContext *DC = Owner;
1110 SS.Adopt(QualifierLoc);
1111 DC = SemaRef.computeDeclContext(SS);
1112 if (!DC) return nullptr;
1114 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1115 Pattern->getDeclContext(),
1119 // Look for a previous declaration of the template in the owning
1121 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1122 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1123 SemaRef.LookupQualifiedName(R, DC);
1125 if (R.isSingleResult()) {
1126 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1127 if (PrevClassTemplate)
1128 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1131 if (!PrevClassTemplate && QualifierLoc) {
1132 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1133 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1134 << QualifierLoc.getSourceRange();
1138 bool AdoptedPreviousTemplateParams = false;
1139 if (PrevClassTemplate) {
1140 bool Complain = true;
1142 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1143 // template for struct std::tr1::__detail::_Map_base, where the
1144 // template parameters of the friend declaration don't match the
1145 // template parameters of the original declaration. In this one
1146 // case, we don't complain about the ill-formed friend
1148 if (isFriend && Pattern->getIdentifier() &&
1149 Pattern->getIdentifier()->isStr("_Map_base") &&
1150 DC->isNamespace() &&
1151 cast<NamespaceDecl>(DC)->getIdentifier() &&
1152 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
1153 DeclContext *DCParent = DC->getParent();
1154 if (DCParent->isNamespace() &&
1155 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1156 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
1157 if (cast<Decl>(DCParent)->isInStdNamespace())
1162 TemplateParameterList *PrevParams
1163 = PrevClassTemplate->getTemplateParameters();
1165 // Make sure the parameter lists match.
1166 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
1168 Sema::TPL_TemplateMatch)) {
1172 AdoptedPreviousTemplateParams = true;
1173 InstParams = PrevParams;
1176 // Do some additional validation, then merge default arguments
1177 // from the existing declarations.
1178 if (!AdoptedPreviousTemplateParams &&
1179 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1180 Sema::TPC_ClassTemplate))
1185 CXXRecordDecl *RecordInst
1186 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
1187 Pattern->getLocStart(), Pattern->getLocation(),
1188 Pattern->getIdentifier(), PrevDecl,
1189 /*DelayTypeCreation=*/true);
1192 RecordInst->setQualifierInfo(QualifierLoc);
1194 ClassTemplateDecl *Inst
1195 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1196 D->getIdentifier(), InstParams, RecordInst,
1198 RecordInst->setDescribedClassTemplate(Inst);
1201 if (PrevClassTemplate)
1202 Inst->setAccess(PrevClassTemplate->getAccess());
1204 Inst->setAccess(D->getAccess());
1206 Inst->setObjectOfFriendDecl();
1207 // TODO: do we want to track the instantiation progeny of this
1208 // friend target decl?
1210 Inst->setAccess(D->getAccess());
1211 if (!PrevClassTemplate)
1212 Inst->setInstantiatedFromMemberTemplate(D);
1215 // Trigger creation of the type for the instantiation.
1216 SemaRef.Context.getInjectedClassNameType(RecordInst,
1217 Inst->getInjectedClassNameSpecialization());
1219 // Finish handling of friends.
1221 DC->makeDeclVisibleInContext(Inst);
1222 Inst->setLexicalDeclContext(Owner);
1223 RecordInst->setLexicalDeclContext(Owner);
1227 if (D->isOutOfLine()) {
1228 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1229 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1232 Owner->addDecl(Inst);
1234 if (!PrevClassTemplate) {
1235 // Queue up any out-of-line partial specializations of this member
1236 // class template; the client will force their instantiation once
1237 // the enclosing class has been instantiated.
1238 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1239 D->getPartialSpecializations(PartialSpecs);
1240 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1241 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1242 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1249 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1250 ClassTemplatePartialSpecializationDecl *D) {
1251 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1253 // Lookup the already-instantiated declaration in the instantiation
1254 // of the class template and return that.
1255 DeclContext::lookup_result Found
1256 = Owner->lookup(ClassTemplate->getDeclName());
1260 ClassTemplateDecl *InstClassTemplate
1261 = dyn_cast<ClassTemplateDecl>(Found.front());
1262 if (!InstClassTemplate)
1265 if (ClassTemplatePartialSpecializationDecl *Result
1266 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1269 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1272 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1273 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1274 "Only static data member templates are allowed.");
1276 // Create a local instantiation scope for this variable template, which
1277 // will contain the instantiations of the template parameters.
1278 LocalInstantiationScope Scope(SemaRef);
1279 TemplateParameterList *TempParams = D->getTemplateParameters();
1280 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1284 VarDecl *Pattern = D->getTemplatedDecl();
1285 VarTemplateDecl *PrevVarTemplate = nullptr;
1287 if (getPreviousDeclForInstantiation(Pattern)) {
1288 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1290 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1294 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1295 /*InstantiatingVarTemplate=*/true));
1296 if (!VarInst) return nullptr;
1298 DeclContext *DC = Owner;
1300 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1301 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1303 VarInst->setDescribedVarTemplate(Inst);
1304 Inst->setPreviousDecl(PrevVarTemplate);
1306 Inst->setAccess(D->getAccess());
1307 if (!PrevVarTemplate)
1308 Inst->setInstantiatedFromMemberTemplate(D);
1310 if (D->isOutOfLine()) {
1311 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1312 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1315 Owner->addDecl(Inst);
1317 if (!PrevVarTemplate) {
1318 // Queue up any out-of-line partial specializations of this member
1319 // variable template; the client will force their instantiation once
1320 // the enclosing class has been instantiated.
1321 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1322 D->getPartialSpecializations(PartialSpecs);
1323 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1324 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1325 OutOfLineVarPartialSpecs.push_back(
1326 std::make_pair(Inst, PartialSpecs[I]));
1332 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1333 VarTemplatePartialSpecializationDecl *D) {
1334 assert(D->isStaticDataMember() &&
1335 "Only static data member templates are allowed.");
1337 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1339 // Lookup the already-instantiated declaration and return that.
1340 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1341 assert(!Found.empty() && "Instantiation found nothing?");
1343 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1344 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1346 if (VarTemplatePartialSpecializationDecl *Result =
1347 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1350 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1354 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1355 // Create a local instantiation scope for this function template, which
1356 // will contain the instantiations of the template parameters and then get
1357 // merged with the local instantiation scope for the function template
1359 LocalInstantiationScope Scope(SemaRef);
1361 TemplateParameterList *TempParams = D->getTemplateParameters();
1362 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1366 FunctionDecl *Instantiated = nullptr;
1367 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1368 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1371 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1372 D->getTemplatedDecl(),
1378 // Link the instantiated function template declaration to the function
1379 // template from which it was instantiated.
1380 FunctionTemplateDecl *InstTemplate
1381 = Instantiated->getDescribedFunctionTemplate();
1382 InstTemplate->setAccess(D->getAccess());
1383 assert(InstTemplate &&
1384 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1386 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1388 // Link the instantiation back to the pattern *unless* this is a
1389 // non-definition friend declaration.
1390 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1391 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1392 InstTemplate->setInstantiatedFromMemberTemplate(D);
1394 // Make declarations visible in the appropriate context.
1396 Owner->addDecl(InstTemplate);
1397 } else if (InstTemplate->getDeclContext()->isRecord() &&
1398 !getPreviousDeclForInstantiation(D)) {
1399 SemaRef.CheckFriendAccess(InstTemplate);
1402 return InstTemplate;
1405 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1406 CXXRecordDecl *PrevDecl = nullptr;
1407 if (D->isInjectedClassName())
1408 PrevDecl = cast<CXXRecordDecl>(Owner);
1409 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1410 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1413 if (!Prev) return nullptr;
1414 PrevDecl = cast<CXXRecordDecl>(Prev);
1417 CXXRecordDecl *Record
1418 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1419 D->getLocStart(), D->getLocation(),
1420 D->getIdentifier(), PrevDecl);
1422 // Substitute the nested name specifier, if any.
1423 if (SubstQualifier(D, Record))
1426 Record->setImplicit(D->isImplicit());
1427 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1428 // the tag decls introduced by friend class declarations don't have an access
1429 // specifier. Remove once this area of the code gets sorted out.
1430 if (D->getAccess() != AS_none)
1431 Record->setAccess(D->getAccess());
1432 if (!D->isInjectedClassName())
1433 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1435 // If the original function was part of a friend declaration,
1436 // inherit its namespace state.
1437 if (D->getFriendObjectKind())
1438 Record->setObjectOfFriendDecl();
1440 // Make sure that anonymous structs and unions are recorded.
1441 if (D->isAnonymousStructOrUnion())
1442 Record->setAnonymousStructOrUnion(true);
1444 if (D->isLocalClass())
1445 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1447 // Forward the mangling number from the template to the instantiated decl.
1448 SemaRef.Context.setManglingNumber(Record,
1449 SemaRef.Context.getManglingNumber(D));
1451 // See if the old tag was defined along with a declarator.
1452 // If it did, mark the new tag as being associated with that declarator.
1453 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1454 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1456 // See if the old tag was defined along with a typedef.
1457 // If it did, mark the new tag as being associated with that typedef.
1458 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1459 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1461 Owner->addDecl(Record);
1463 // DR1484 clarifies that the members of a local class are instantiated as part
1464 // of the instantiation of their enclosing entity.
1465 if (D->isCompleteDefinition() && D->isLocalClass()) {
1466 Sema::SavePendingLocalImplicitInstantiationsRAII
1467 SavedPendingLocalImplicitInstantiations(SemaRef);
1469 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1470 TSK_ImplicitInstantiation,
1473 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1474 TSK_ImplicitInstantiation);
1476 // This class may have local implicit instantiations that need to be
1477 // performed within this scope.
1478 SemaRef.PerformPendingInstantiations(/*LocalOnly=*/true);
1481 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1486 /// \brief Adjust the given function type for an instantiation of the
1487 /// given declaration, to cope with modifications to the function's type that
1488 /// aren't reflected in the type-source information.
1490 /// \param D The declaration we're instantiating.
1491 /// \param TInfo The already-instantiated type.
1492 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1494 TypeSourceInfo *TInfo) {
1495 const FunctionProtoType *OrigFunc
1496 = D->getType()->castAs<FunctionProtoType>();
1497 const FunctionProtoType *NewFunc
1498 = TInfo->getType()->castAs<FunctionProtoType>();
1499 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1500 return TInfo->getType();
1502 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1503 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1504 return Context.getFunctionType(NewFunc->getReturnType(),
1505 NewFunc->getParamTypes(), NewEPI);
1508 /// Normal class members are of more specific types and therefore
1509 /// don't make it here. This function serves two purposes:
1510 /// 1) instantiating function templates
1511 /// 2) substituting friend declarations
1512 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1513 TemplateParameterList *TemplateParams) {
1514 // Check whether there is already a function template specialization for
1515 // this declaration.
1516 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1517 if (FunctionTemplate && !TemplateParams) {
1518 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1520 void *InsertPos = nullptr;
1521 FunctionDecl *SpecFunc
1522 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1524 // If we already have a function template specialization, return it.
1530 if (FunctionTemplate)
1531 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1533 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1535 bool MergeWithParentScope = (TemplateParams != nullptr) ||
1536 Owner->isFunctionOrMethod() ||
1537 !(isa<Decl>(Owner) &&
1538 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1539 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1541 SmallVector<ParmVarDecl *, 4> Params;
1542 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1545 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1547 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1549 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1555 // If we're instantiating a local function declaration, put the result
1556 // in the enclosing namespace; otherwise we need to find the instantiated
1559 if (D->isLocalExternDecl()) {
1561 SemaRef.adjustContextForLocalExternDecl(DC);
1562 } else if (isFriend && QualifierLoc) {
1564 SS.Adopt(QualifierLoc);
1565 DC = SemaRef.computeDeclContext(SS);
1566 if (!DC) return nullptr;
1568 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1572 FunctionDecl *Function =
1573 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1574 D->getNameInfo(), T, TInfo,
1575 D->getCanonicalDecl()->getStorageClass(),
1576 D->isInlineSpecified(), D->hasWrittenPrototype(),
1578 Function->setRangeEnd(D->getSourceRange().getEnd());
1581 Function->setImplicitlyInline();
1584 Function->setQualifierInfo(QualifierLoc);
1586 if (D->isLocalExternDecl())
1587 Function->setLocalExternDecl();
1589 DeclContext *LexicalDC = Owner;
1590 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1591 assert(D->getDeclContext()->isFileContext());
1592 LexicalDC = D->getDeclContext();
1595 Function->setLexicalDeclContext(LexicalDC);
1597 // Attach the parameters
1598 for (unsigned P = 0; P < Params.size(); ++P)
1600 Params[P]->setOwningFunction(Function);
1601 Function->setParams(Params);
1603 SourceLocation InstantiateAtPOI;
1604 if (TemplateParams) {
1605 // Our resulting instantiation is actually a function template, since we
1606 // are substituting only the outer template parameters. For example, given
1608 // template<typename T>
1610 // template<typename U> friend void f(T, U);
1615 // We are instantiating the friend function template "f" within X<int>,
1616 // which means substituting int for T, but leaving "f" as a friend function
1618 // Build the function template itself.
1619 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1620 Function->getLocation(),
1621 Function->getDeclName(),
1622 TemplateParams, Function);
1623 Function->setDescribedFunctionTemplate(FunctionTemplate);
1625 FunctionTemplate->setLexicalDeclContext(LexicalDC);
1627 if (isFriend && D->isThisDeclarationADefinition()) {
1628 // TODO: should we remember this connection regardless of whether
1629 // the friend declaration provided a body?
1630 FunctionTemplate->setInstantiatedFromMemberTemplate(
1631 D->getDescribedFunctionTemplate());
1633 } else if (FunctionTemplate) {
1634 // Record this function template specialization.
1635 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1636 Function->setFunctionTemplateSpecialization(FunctionTemplate,
1637 TemplateArgumentList::CreateCopy(SemaRef.Context,
1639 /*InsertPos=*/nullptr);
1640 } else if (isFriend) {
1641 // Note, we need this connection even if the friend doesn't have a body.
1642 // Its body may exist but not have been attached yet due to deferred
1644 // FIXME: It might be cleaner to set this when attaching the body to the
1645 // friend function declaration, however that would require finding all the
1646 // instantiations and modifying them.
1647 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1650 if (InitFunctionInstantiation(Function, D))
1651 Function->setInvalidDecl();
1653 bool isExplicitSpecialization = false;
1655 LookupResult Previous(
1656 SemaRef, Function->getDeclName(), SourceLocation(),
1657 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1658 : Sema::LookupOrdinaryName,
1659 Sema::ForRedeclaration);
1661 if (DependentFunctionTemplateSpecializationInfo *Info
1662 = D->getDependentSpecializationInfo()) {
1663 assert(isFriend && "non-friend has dependent specialization info?");
1665 // This needs to be set now for future sanity.
1666 Function->setObjectOfFriendDecl();
1668 // Instantiate the explicit template arguments.
1669 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1670 Info->getRAngleLoc());
1671 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1672 ExplicitArgs, TemplateArgs))
1675 // Map the candidate templates to their instantiations.
1676 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1677 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1678 Info->getTemplate(I),
1680 if (!Temp) return nullptr;
1682 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1685 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1688 Function->setInvalidDecl();
1690 isExplicitSpecialization = true;
1692 } else if (TemplateParams || !FunctionTemplate) {
1693 // Look only into the namespace where the friend would be declared to
1694 // find a previous declaration. This is the innermost enclosing namespace,
1695 // as described in ActOnFriendFunctionDecl.
1696 SemaRef.LookupQualifiedName(Previous, DC);
1698 // In C++, the previous declaration we find might be a tag type
1699 // (class or enum). In this case, the new declaration will hide the
1700 // tag type. Note that this does does not apply if we're declaring a
1701 // typedef (C++ [dcl.typedef]p4).
1702 if (Previous.isSingleTagDecl())
1706 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
1707 isExplicitSpecialization);
1709 NamedDecl *PrincipalDecl = (TemplateParams
1710 ? cast<NamedDecl>(FunctionTemplate)
1713 // If the original function was part of a friend declaration,
1714 // inherit its namespace state and add it to the owner.
1716 PrincipalDecl->setObjectOfFriendDecl();
1717 DC->makeDeclVisibleInContext(PrincipalDecl);
1719 bool QueuedInstantiation = false;
1721 // C++11 [temp.friend]p4 (DR329):
1722 // When a function is defined in a friend function declaration in a class
1723 // template, the function is instantiated when the function is odr-used.
1724 // The same restrictions on multiple declarations and definitions that
1725 // apply to non-template function declarations and definitions also apply
1726 // to these implicit definitions.
1727 if (D->isThisDeclarationADefinition()) {
1728 // Check for a function body.
1729 const FunctionDecl *Definition = nullptr;
1730 if (Function->isDefined(Definition) &&
1731 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1732 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1733 << Function->getDeclName();
1734 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1736 // Check for redefinitions due to other instantiations of this or
1737 // a similar friend function.
1738 else for (auto R : Function->redecls()) {
1742 // If some prior declaration of this function has been used, we need
1743 // to instantiate its definition.
1744 if (!QueuedInstantiation && R->isUsed(false)) {
1745 if (MemberSpecializationInfo *MSInfo =
1746 Function->getMemberSpecializationInfo()) {
1747 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1748 SourceLocation Loc = R->getLocation(); // FIXME
1749 MSInfo->setPointOfInstantiation(Loc);
1750 SemaRef.PendingLocalImplicitInstantiations.push_back(
1751 std::make_pair(Function, Loc));
1752 QueuedInstantiation = true;
1757 // If some prior declaration of this function was a friend with an
1758 // uninstantiated definition, reject it.
1759 if (R->getFriendObjectKind()) {
1760 if (const FunctionDecl *RPattern =
1761 R->getTemplateInstantiationPattern()) {
1762 if (RPattern->isDefined(RPattern)) {
1763 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1764 << Function->getDeclName();
1765 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1774 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1775 DC->makeDeclVisibleInContext(PrincipalDecl);
1777 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1778 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1779 PrincipalDecl->setNonMemberOperator();
1781 assert(!D->isDefaulted() && "only methods should be defaulted");
1786 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1787 TemplateParameterList *TemplateParams,
1788 bool IsClassScopeSpecialization) {
1789 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1790 if (FunctionTemplate && !TemplateParams) {
1791 // We are creating a function template specialization from a function
1792 // template. Check whether there is already a function template
1793 // specialization for this particular set of template arguments.
1794 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1796 void *InsertPos = nullptr;
1797 FunctionDecl *SpecFunc
1798 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1800 // If we already have a function template specialization, return it.
1806 if (FunctionTemplate)
1807 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1809 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1811 bool MergeWithParentScope = (TemplateParams != nullptr) ||
1812 !(isa<Decl>(Owner) &&
1813 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1814 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1816 // Instantiate enclosing template arguments for friends.
1817 SmallVector<TemplateParameterList *, 4> TempParamLists;
1818 unsigned NumTempParamLists = 0;
1819 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1820 TempParamLists.resize(NumTempParamLists);
1821 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1822 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1823 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1826 TempParamLists[I] = InstParams;
1830 SmallVector<ParmVarDecl *, 4> Params;
1831 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1834 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1836 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1838 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1844 DeclContext *DC = Owner;
1848 SS.Adopt(QualifierLoc);
1849 DC = SemaRef.computeDeclContext(SS);
1851 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1854 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1855 D->getDeclContext(),
1858 if (!DC) return nullptr;
1861 // Build the instantiated method declaration.
1862 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1863 CXXMethodDecl *Method = nullptr;
1865 SourceLocation StartLoc = D->getInnerLocStart();
1866 DeclarationNameInfo NameInfo
1867 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1868 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1869 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1870 StartLoc, NameInfo, T, TInfo,
1871 Constructor->isExplicit(),
1872 Constructor->isInlineSpecified(),
1873 false, Constructor->isConstexpr());
1874 Method->setRangeEnd(Constructor->getLocEnd());
1875 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1876 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1877 StartLoc, NameInfo, T, TInfo,
1878 Destructor->isInlineSpecified(),
1880 Method->setRangeEnd(Destructor->getLocEnd());
1881 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1882 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1883 StartLoc, NameInfo, T, TInfo,
1884 Conversion->isInlineSpecified(),
1885 Conversion->isExplicit(),
1886 Conversion->isConstexpr(),
1887 Conversion->getLocEnd());
1889 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
1890 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1891 StartLoc, NameInfo, T, TInfo,
1892 SC, D->isInlineSpecified(),
1893 D->isConstexpr(), D->getLocEnd());
1897 Method->setImplicitlyInline();
1900 Method->setQualifierInfo(QualifierLoc);
1902 if (TemplateParams) {
1903 // Our resulting instantiation is actually a function template, since we
1904 // are substituting only the outer template parameters. For example, given
1906 // template<typename T>
1908 // template<typename U> void f(T, U);
1913 // We are instantiating the member template "f" within X<int>, which means
1914 // substituting int for T, but leaving "f" as a member function template.
1915 // Build the function template itself.
1916 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1917 Method->getLocation(),
1918 Method->getDeclName(),
1919 TemplateParams, Method);
1921 FunctionTemplate->setLexicalDeclContext(Owner);
1922 FunctionTemplate->setObjectOfFriendDecl();
1923 } else if (D->isOutOfLine())
1924 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1925 Method->setDescribedFunctionTemplate(FunctionTemplate);
1926 } else if (FunctionTemplate) {
1927 // Record this function template specialization.
1928 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1929 Method->setFunctionTemplateSpecialization(FunctionTemplate,
1930 TemplateArgumentList::CreateCopy(SemaRef.Context,
1932 /*InsertPos=*/nullptr);
1933 } else if (!isFriend) {
1934 // Record that this is an instantiation of a member function.
1935 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1938 // If we are instantiating a member function defined
1939 // out-of-line, the instantiation will have the same lexical
1940 // context (which will be a namespace scope) as the template.
1942 if (NumTempParamLists)
1943 Method->setTemplateParameterListsInfo(
1945 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
1947 Method->setLexicalDeclContext(Owner);
1948 Method->setObjectOfFriendDecl();
1949 } else if (D->isOutOfLine())
1950 Method->setLexicalDeclContext(D->getLexicalDeclContext());
1952 // Attach the parameters
1953 for (unsigned P = 0; P < Params.size(); ++P)
1954 Params[P]->setOwningFunction(Method);
1955 Method->setParams(Params);
1957 if (InitMethodInstantiation(Method, D))
1958 Method->setInvalidDecl();
1960 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1961 Sema::ForRedeclaration);
1963 if (!FunctionTemplate || TemplateParams || isFriend) {
1964 SemaRef.LookupQualifiedName(Previous, Record);
1966 // In C++, the previous declaration we find might be a tag type
1967 // (class or enum). In this case, the new declaration will hide the
1968 // tag type. Note that this does does not apply if we're declaring a
1969 // typedef (C++ [dcl.typedef]p4).
1970 if (Previous.isSingleTagDecl())
1974 if (!IsClassScopeSpecialization)
1975 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
1978 SemaRef.CheckPureMethod(Method, SourceRange());
1980 // Propagate access. For a non-friend declaration, the access is
1981 // whatever we're propagating from. For a friend, it should be the
1982 // previous declaration we just found.
1983 if (isFriend && Method->getPreviousDecl())
1984 Method->setAccess(Method->getPreviousDecl()->getAccess());
1986 Method->setAccess(D->getAccess());
1987 if (FunctionTemplate)
1988 FunctionTemplate->setAccess(Method->getAccess());
1990 SemaRef.CheckOverrideControl(Method);
1992 // If a function is defined as defaulted or deleted, mark it as such now.
1993 if (D->isExplicitlyDefaulted())
1994 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1995 if (D->isDeletedAsWritten())
1996 SemaRef.SetDeclDeleted(Method, Method->getLocation());
1998 // If there's a function template, let our caller handle it.
1999 if (FunctionTemplate) {
2002 // Don't hide a (potentially) valid declaration with an invalid one.
2003 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2006 // Otherwise, check access to friends and make them visible.
2007 } else if (isFriend) {
2008 // We only need to re-check access for methods which we didn't
2009 // manage to match during parsing.
2010 if (!D->getPreviousDecl())
2011 SemaRef.CheckFriendAccess(Method);
2013 Record->makeDeclVisibleInContext(Method);
2015 // Otherwise, add the declaration. We don't need to do this for
2016 // class-scope specializations because we'll have matched them with
2017 // the appropriate template.
2018 } else if (!IsClassScopeSpecialization) {
2019 Owner->addDecl(Method);
2025 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2026 return VisitCXXMethodDecl(D);
2029 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2030 return VisitCXXMethodDecl(D);
2033 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2034 return VisitCXXMethodDecl(D);
2037 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2038 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2039 /*ExpectParameterPack=*/ false);
2042 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2043 TemplateTypeParmDecl *D) {
2044 // TODO: don't always clone when decls are refcounted.
2045 assert(D->getTypeForDecl()->isTemplateTypeParmType());
2047 TemplateTypeParmDecl *Inst =
2048 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
2049 D->getLocStart(), D->getLocation(),
2050 D->getDepth() - TemplateArgs.getNumLevels(),
2051 D->getIndex(), D->getIdentifier(),
2052 D->wasDeclaredWithTypename(),
2053 D->isParameterPack());
2054 Inst->setAccess(AS_public);
2056 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2057 TypeSourceInfo *InstantiatedDefaultArg =
2058 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2059 D->getDefaultArgumentLoc(), D->getDeclName());
2060 if (InstantiatedDefaultArg)
2061 Inst->setDefaultArgument(InstantiatedDefaultArg);
2064 // Introduce this template parameter's instantiation into the instantiation
2066 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2071 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2072 NonTypeTemplateParmDecl *D) {
2073 // Substitute into the type of the non-type template parameter.
2074 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2075 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2076 SmallVector<QualType, 4> ExpandedParameterPackTypes;
2077 bool IsExpandedParameterPack = false;
2080 bool Invalid = false;
2082 if (D->isExpandedParameterPack()) {
2083 // The non-type template parameter pack is an already-expanded pack
2084 // expansion of types. Substitute into each of the expanded types.
2085 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2086 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2087 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2088 TypeSourceInfo *NewDI =
2089 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2090 D->getLocation(), D->getDeclName());
2095 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2099 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2100 ExpandedParameterPackTypes.push_back(NewT);
2103 IsExpandedParameterPack = true;
2104 DI = D->getTypeSourceInfo();
2106 } else if (D->isPackExpansion()) {
2107 // The non-type template parameter pack's type is a pack expansion of types.
2108 // Determine whether we need to expand this parameter pack into separate
2110 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2111 TypeLoc Pattern = Expansion.getPatternLoc();
2112 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2113 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2115 // Determine whether the set of unexpanded parameter packs can and should
2118 bool RetainExpansion = false;
2119 Optional<unsigned> OrigNumExpansions
2120 = Expansion.getTypePtr()->getNumExpansions();
2121 Optional<unsigned> NumExpansions = OrigNumExpansions;
2122 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2123 Pattern.getSourceRange(),
2126 Expand, RetainExpansion,
2131 for (unsigned I = 0; I != *NumExpansions; ++I) {
2132 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2133 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2140 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2144 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2145 ExpandedParameterPackTypes.push_back(NewT);
2148 // Note that we have an expanded parameter pack. The "type" of this
2149 // expanded parameter pack is the original expansion type, but callers
2150 // will end up using the expanded parameter pack types for type-checking.
2151 IsExpandedParameterPack = true;
2152 DI = D->getTypeSourceInfo();
2155 // We cannot fully expand the pack expansion now, so substitute into the
2156 // pattern and create a new pack expansion type.
2157 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2158 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2164 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
2165 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2173 // Simple case: substitution into a parameter that is not a parameter pack.
2174 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2175 D->getLocation(), D->getDeclName());
2179 // Check that this type is acceptable for a non-type template parameter.
2180 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
2182 T = SemaRef.Context.IntTy;
2187 NonTypeTemplateParmDecl *Param;
2188 if (IsExpandedParameterPack)
2189 Param = NonTypeTemplateParmDecl::Create(
2190 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2191 D->getDepth() - TemplateArgs.getNumLevels(), D->getPosition(),
2192 D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
2193 ExpandedParameterPackTypesAsWritten);
2195 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
2196 D->getInnerLocStart(),
2198 D->getDepth() - TemplateArgs.getNumLevels(),
2200 D->getIdentifier(), T,
2201 D->isParameterPack(), DI);
2203 Param->setAccess(AS_public);
2205 Param->setInvalidDecl();
2207 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2208 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
2209 Sema::ConstantEvaluated);
2210 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2211 if (!Value.isInvalid())
2212 Param->setDefaultArgument(Value.get());
2215 // Introduce this template parameter's instantiation into the instantiation
2217 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2221 static void collectUnexpandedParameterPacks(
2223 TemplateParameterList *Params,
2224 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2225 for (const auto &P : *Params) {
2226 if (P->isTemplateParameterPack())
2228 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
2229 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2231 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
2232 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2238 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2239 TemplateTemplateParmDecl *D) {
2240 // Instantiate the template parameter list of the template template parameter.
2241 TemplateParameterList *TempParams = D->getTemplateParameters();
2242 TemplateParameterList *InstParams;
2243 SmallVector<TemplateParameterList*, 8> ExpandedParams;
2245 bool IsExpandedParameterPack = false;
2247 if (D->isExpandedParameterPack()) {
2248 // The template template parameter pack is an already-expanded pack
2249 // expansion of template parameters. Substitute into each of the expanded
2251 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2252 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2254 LocalInstantiationScope Scope(SemaRef);
2255 TemplateParameterList *Expansion =
2256 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2259 ExpandedParams.push_back(Expansion);
2262 IsExpandedParameterPack = true;
2263 InstParams = TempParams;
2264 } else if (D->isPackExpansion()) {
2265 // The template template parameter pack expands to a pack of template
2266 // template parameters. Determine whether we need to expand this parameter
2267 // pack into separate parameters.
2268 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2269 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2272 // Determine whether the set of unexpanded parameter packs can and should
2275 bool RetainExpansion = false;
2276 Optional<unsigned> NumExpansions;
2277 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2278 TempParams->getSourceRange(),
2281 Expand, RetainExpansion,
2286 for (unsigned I = 0; I != *NumExpansions; ++I) {
2287 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2288 LocalInstantiationScope Scope(SemaRef);
2289 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2292 ExpandedParams.push_back(Expansion);
2295 // Note that we have an expanded parameter pack. The "type" of this
2296 // expanded parameter pack is the original expansion type, but callers
2297 // will end up using the expanded parameter pack types for type-checking.
2298 IsExpandedParameterPack = true;
2299 InstParams = TempParams;
2301 // We cannot fully expand the pack expansion now, so just substitute
2302 // into the pattern.
2303 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2305 LocalInstantiationScope Scope(SemaRef);
2306 InstParams = SubstTemplateParams(TempParams);
2311 // Perform the actual substitution of template parameters within a new,
2312 // local instantiation scope.
2313 LocalInstantiationScope Scope(SemaRef);
2314 InstParams = SubstTemplateParams(TempParams);
2319 // Build the template template parameter.
2320 TemplateTemplateParmDecl *Param;
2321 if (IsExpandedParameterPack)
2322 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2324 D->getDepth() - TemplateArgs.getNumLevels(),
2326 D->getIdentifier(), InstParams,
2329 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2331 D->getDepth() - TemplateArgs.getNumLevels(),
2333 D->isParameterPack(),
2334 D->getIdentifier(), InstParams);
2335 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2336 NestedNameSpecifierLoc QualifierLoc =
2337 D->getDefaultArgument().getTemplateQualifierLoc();
2339 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2340 TemplateName TName = SemaRef.SubstTemplateName(
2341 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2342 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2343 if (!TName.isNull())
2344 Param->setDefaultArgument(
2346 TemplateArgumentLoc(TemplateArgument(TName),
2347 D->getDefaultArgument().getTemplateQualifierLoc(),
2348 D->getDefaultArgument().getTemplateNameLoc()));
2350 Param->setAccess(AS_public);
2352 // Introduce this template parameter's instantiation into the instantiation
2354 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2359 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2360 // Using directives are never dependent (and never contain any types or
2361 // expressions), so they require no explicit instantiation work.
2363 UsingDirectiveDecl *Inst
2364 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2365 D->getNamespaceKeyLocation(),
2366 D->getQualifierLoc(),
2367 D->getIdentLocation(),
2368 D->getNominatedNamespace(),
2369 D->getCommonAncestor());
2371 // Add the using directive to its declaration context
2372 // only if this is not a function or method.
2373 if (!Owner->isFunctionOrMethod())
2374 Owner->addDecl(Inst);
2379 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2381 // The nested name specifier may be dependent, for example
2382 // template <typename T> struct t {
2383 // struct s1 { T f1(); };
2384 // struct s2 : s1 { using s1::f1; };
2386 // template struct t<int>;
2387 // Here, in using s1::f1, s1 refers to t<T>::s1;
2388 // we need to substitute for t<int>::s1.
2389 NestedNameSpecifierLoc QualifierLoc
2390 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2395 // For an inheriting constructor declaration, the name of the using
2396 // declaration is the name of a constructor in this class, not in the
2398 DeclarationNameInfo NameInfo = D->getNameInfo();
2399 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2400 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
2401 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
2402 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
2404 // We only need to do redeclaration lookups if we're in a class
2405 // scope (in fact, it's not really even possible in non-class
2407 bool CheckRedeclaration = Owner->isRecord();
2409 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2410 Sema::ForRedeclaration);
2412 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2419 SS.Adopt(QualifierLoc);
2420 if (CheckRedeclaration) {
2421 Prev.setHideTags(false);
2422 SemaRef.LookupQualifiedName(Prev, Owner);
2424 // Check for invalid redeclarations.
2425 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2426 D->hasTypename(), SS,
2427 D->getLocation(), Prev))
2428 NewUD->setInvalidDecl();
2432 if (!NewUD->isInvalidDecl() &&
2433 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
2434 SS, NameInfo, D->getLocation()))
2435 NewUD->setInvalidDecl();
2437 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2438 NewUD->setAccess(D->getAccess());
2439 Owner->addDecl(NewUD);
2441 // Don't process the shadow decls for an invalid decl.
2442 if (NewUD->isInvalidDecl())
2445 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2446 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
2448 bool isFunctionScope = Owner->isFunctionOrMethod();
2450 // Process the shadow decls.
2451 for (auto *Shadow : D->shadows()) {
2452 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
2453 // reconstruct it in the case where it matters.
2454 NamedDecl *OldTarget = Shadow->getTargetDecl();
2455 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
2456 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
2457 OldTarget = BaseShadow;
2459 NamedDecl *InstTarget =
2460 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2461 Shadow->getLocation(), OldTarget, TemplateArgs));
2465 UsingShadowDecl *PrevDecl = nullptr;
2466 if (CheckRedeclaration) {
2467 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2469 } else if (UsingShadowDecl *OldPrev =
2470 getPreviousDeclForInstantiation(Shadow)) {
2471 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2472 Shadow->getLocation(), OldPrev, TemplateArgs));
2475 UsingShadowDecl *InstShadow =
2476 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2478 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2480 if (isFunctionScope)
2481 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2487 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2488 // Ignore these; we handle them in bulk when processing the UsingDecl.
2492 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
2493 ConstructorUsingShadowDecl *D) {
2494 // Ignore these; we handle them in bulk when processing the UsingDecl.
2498 template <typename T>
2499 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
2500 T *D, bool InstantiatingPackElement) {
2501 // If this is a pack expansion, expand it now.
2502 if (D->isPackExpansion() && !InstantiatingPackElement) {
2503 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2504 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
2505 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
2507 // Determine whether the set of unexpanded parameter packs can and should
2510 bool RetainExpansion = false;
2511 Optional<unsigned> NumExpansions;
2512 if (SemaRef.CheckParameterPacksForExpansion(
2513 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
2514 Expand, RetainExpansion, NumExpansions))
2517 // This declaration cannot appear within a function template signature,
2518 // so we can't have a partial argument list for a parameter pack.
2519 assert(!RetainExpansion &&
2520 "should never need to retain an expansion for UsingPackDecl");
2523 // We cannot fully expand the pack expansion now, so substitute into the
2524 // pattern and create a new pack expansion.
2525 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2526 return instantiateUnresolvedUsingDecl(D, true);
2529 // Within a function, we don't have any normal way to check for conflicts
2530 // between shadow declarations from different using declarations in the
2531 // same pack expansion, but this is always ill-formed because all expansions
2532 // must produce (conflicting) enumerators.
2534 // Sadly we can't just reject this in the template definition because it
2535 // could be valid if the pack is empty or has exactly one expansion.
2536 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
2537 SemaRef.Diag(D->getEllipsisLoc(),
2538 diag::err_using_decl_redeclaration_expansion);
2542 // Instantiate the slices of this pack and build a UsingPackDecl.
2543 SmallVector<NamedDecl*, 8> Expansions;
2544 for (unsigned I = 0; I != *NumExpansions; ++I) {
2545 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2546 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
2549 // Note that we can still get unresolved using declarations here, if we
2550 // had arguments for all packs but the pattern also contained other
2551 // template arguments (this only happens during partial substitution, eg
2552 // into the body of a generic lambda in a function template).
2553 Expansions.push_back(cast<NamedDecl>(Slice));
2556 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2557 if (isDeclWithinFunction(D))
2558 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2562 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
2563 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
2565 NestedNameSpecifierLoc QualifierLoc
2566 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2572 SS.Adopt(QualifierLoc);
2574 DeclarationNameInfo NameInfo
2575 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2577 // Produce a pack expansion only if we're not instantiating a particular
2578 // slice of a pack expansion.
2579 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
2580 SemaRef.ArgumentPackSubstitutionIndex != -1;
2581 SourceLocation EllipsisLoc =
2582 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
2584 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
2585 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
2586 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc, nullptr,
2587 /*IsInstantiation*/ true);
2589 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
2594 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
2595 UnresolvedUsingTypenameDecl *D) {
2596 return instantiateUnresolvedUsingDecl(D);
2599 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
2600 UnresolvedUsingValueDecl *D) {
2601 return instantiateUnresolvedUsingDecl(D);
2604 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
2605 SmallVector<NamedDecl*, 8> Expansions;
2606 for (auto *UD : D->expansions()) {
2608 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
2609 Expansions.push_back(cast<NamedDecl>(NewUD));
2614 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2615 if (isDeclWithinFunction(D))
2616 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2620 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2621 ClassScopeFunctionSpecializationDecl *Decl) {
2622 CXXMethodDecl *OldFD = Decl->getSpecialization();
2623 CXXMethodDecl *NewFD =
2624 cast_or_null<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, nullptr, true));
2628 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2629 Sema::ForRedeclaration);
2631 TemplateArgumentListInfo TemplateArgs;
2632 TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
2633 if (Decl->hasExplicitTemplateArgs()) {
2634 TemplateArgs = Decl->templateArgs();
2635 TemplateArgsPtr = &TemplateArgs;
2638 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
2639 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2641 NewFD->setInvalidDecl();
2645 // Associate the specialization with the pattern.
2646 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2647 assert(Specialization && "Class scope Specialization is null");
2648 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2653 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2654 OMPThreadPrivateDecl *D) {
2655 SmallVector<Expr *, 5> Vars;
2656 for (auto *I : D->varlists()) {
2657 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2658 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2659 Vars.push_back(Var);
2662 OMPThreadPrivateDecl *TD =
2663 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2665 TD->setAccess(AS_public);
2671 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
2672 OMPDeclareReductionDecl *D) {
2673 // Instantiate type and check if it is allowed.
2674 QualType SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
2676 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
2677 D->getLocation(), DeclarationName())));
2678 if (SubstReductionType.isNull())
2680 bool IsCorrect = !SubstReductionType.isNull();
2681 // Create instantiated copy.
2682 std::pair<QualType, SourceLocation> ReductionTypes[] = {
2683 std::make_pair(SubstReductionType, D->getLocation())};
2684 auto *PrevDeclInScope = D->getPrevDeclInScope();
2685 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
2686 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
2687 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
2690 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
2691 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
2693 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
2694 if (isDeclWithinFunction(NewDRD))
2695 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
2696 Expr *SubstCombiner = nullptr;
2697 Expr *SubstInitializer = nullptr;
2698 // Combiners instantiation sequence.
2699 if (D->getCombiner()) {
2700 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
2701 /*S=*/nullptr, NewDRD);
2702 const char *Names[] = {"omp_in", "omp_out"};
2703 for (auto &Name : Names) {
2704 DeclarationName DN(&SemaRef.Context.Idents.get(Name));
2705 auto OldLookup = D->lookup(DN);
2706 auto Lookup = NewDRD->lookup(DN);
2707 if (!OldLookup.empty() && !Lookup.empty()) {
2708 assert(Lookup.size() == 1 && OldLookup.size() == 1);
2709 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldLookup.front(),
2713 SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
2714 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
2715 // Initializers instantiation sequence.
2716 if (D->getInitializer()) {
2717 SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
2718 /*S=*/nullptr, NewDRD);
2719 const char *Names[] = {"omp_orig", "omp_priv"};
2720 for (auto &Name : Names) {
2721 DeclarationName DN(&SemaRef.Context.Idents.get(Name));
2722 auto OldLookup = D->lookup(DN);
2723 auto Lookup = NewDRD->lookup(DN);
2724 if (!OldLookup.empty() && !Lookup.empty()) {
2725 assert(Lookup.size() == 1 && OldLookup.size() == 1);
2726 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
2727 OldLookup.front(), Lookup.front());
2731 SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
2732 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD,
2735 IsCorrect = IsCorrect && SubstCombiner &&
2736 (!D->getInitializer() || SubstInitializer);
2740 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
2746 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
2747 OMPCapturedExprDecl * /*D*/) {
2748 llvm_unreachable("Should not be met in templates");
2751 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2752 return VisitFunctionDecl(D, nullptr);
2755 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2756 return VisitCXXMethodDecl(D, nullptr);
2759 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2760 llvm_unreachable("There are only CXXRecordDecls in C++");
2764 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2765 ClassTemplateSpecializationDecl *D) {
2766 // As a MS extension, we permit class-scope explicit specialization
2767 // of member class templates.
2768 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2769 assert(ClassTemplate->getDeclContext()->isRecord() &&
2770 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2771 "can only instantiate an explicit specialization "
2772 "for a member class template");
2774 // Lookup the already-instantiated declaration in the instantiation
2775 // of the class template. FIXME: Diagnose or assert if this fails?
2776 DeclContext::lookup_result Found
2777 = Owner->lookup(ClassTemplate->getDeclName());
2780 ClassTemplateDecl *InstClassTemplate
2781 = dyn_cast<ClassTemplateDecl>(Found.front());
2782 if (!InstClassTemplate)
2785 // Substitute into the template arguments of the class template explicit
2787 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2788 castAs<TemplateSpecializationTypeLoc>();
2789 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2790 Loc.getRAngleLoc());
2791 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2792 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2793 ArgLocs.push_back(Loc.getArgLoc(I));
2794 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2795 InstTemplateArgs, TemplateArgs))
2798 // Check that the template argument list is well-formed for this
2800 SmallVector<TemplateArgument, 4> Converted;
2801 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2808 // Figure out where to insert this class template explicit specialization
2809 // in the member template's set of class template explicit specializations.
2810 void *InsertPos = nullptr;
2811 ClassTemplateSpecializationDecl *PrevDecl =
2812 InstClassTemplate->findSpecialization(Converted, InsertPos);
2814 // Check whether we've already seen a conflicting instantiation of this
2815 // declaration (for instance, if there was a prior implicit instantiation).
2818 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2819 D->getSpecializationKind(),
2821 PrevDecl->getSpecializationKind(),
2822 PrevDecl->getPointOfInstantiation(),
2826 // If PrevDecl was a definition and D is also a definition, diagnose.
2827 // This happens in cases like:
2829 // template<typename T, typename U>
2831 // template<typename X> struct Inner;
2832 // template<> struct Inner<T> {};
2833 // template<> struct Inner<U> {};
2836 // Outer<int, int> outer; // error: the explicit specializations of Inner
2837 // // have the same signature.
2838 if (PrevDecl && PrevDecl->getDefinition() &&
2839 D->isThisDeclarationADefinition()) {
2840 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2841 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2842 diag::note_previous_definition);
2846 // Create the class template partial specialization declaration.
2847 ClassTemplateSpecializationDecl *InstD
2848 = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2857 // Add this partial specialization to the set of class template partial
2860 InstClassTemplate->AddSpecialization(InstD, InsertPos);
2862 // Substitute the nested name specifier, if any.
2863 if (SubstQualifier(D, InstD))
2866 // Build the canonical type that describes the converted template
2867 // arguments of the class template explicit specialization.
2868 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2869 TemplateName(InstClassTemplate), Converted,
2870 SemaRef.Context.getRecordType(InstD));
2872 // Build the fully-sugared type for this class template
2873 // specialization as the user wrote in the specialization
2874 // itself. This means that we'll pretty-print the type retrieved
2875 // from the specialization's declaration the way that the user
2876 // actually wrote the specialization, rather than formatting the
2877 // name based on the "canonical" representation used to store the
2878 // template arguments in the specialization.
2879 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2880 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2883 InstD->setAccess(D->getAccess());
2884 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2885 InstD->setSpecializationKind(D->getSpecializationKind());
2886 InstD->setTypeAsWritten(WrittenTy);
2887 InstD->setExternLoc(D->getExternLoc());
2888 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2890 Owner->addDecl(InstD);
2892 // Instantiate the members of the class-scope explicit specialization eagerly.
2893 // We don't have support for lazy instantiation of an explicit specialization
2894 // yet, and MSVC eagerly instantiates in this case.
2895 if (D->isThisDeclarationADefinition() &&
2896 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2897 TSK_ImplicitInstantiation,
2904 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2905 VarTemplateSpecializationDecl *D) {
2907 TemplateArgumentListInfo VarTemplateArgsInfo;
2908 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2909 assert(VarTemplate &&
2910 "A template specialization without specialized template?");
2912 // Substitute the current template arguments.
2913 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2914 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2915 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2917 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2918 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2921 // Check that the template argument list is well-formed for this template.
2922 SmallVector<TemplateArgument, 4> Converted;
2923 if (SemaRef.CheckTemplateArgumentList(
2924 VarTemplate, VarTemplate->getLocStart(),
2925 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2929 // Find the variable template specialization declaration that
2930 // corresponds to these arguments.
2931 void *InsertPos = nullptr;
2932 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2933 Converted, InsertPos))
2934 // If we already have a variable template specialization, return it.
2937 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2938 VarTemplateArgsInfo, Converted);
2941 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2942 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2943 const TemplateArgumentListInfo &TemplateArgsInfo,
2944 ArrayRef<TemplateArgument> Converted) {
2946 // Do substitution on the type of the declaration
2947 TypeSourceInfo *DI =
2948 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2949 D->getTypeSpecStartLoc(), D->getDeclName());
2953 if (DI->getType()->isFunctionType()) {
2954 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2955 << D->isStaticDataMember() << DI->getType();
2959 // Build the instantiated declaration
2960 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2961 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2962 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
2963 Var->setTemplateArgsInfo(TemplateArgsInfo);
2965 VarTemplate->AddSpecialization(Var, InsertPos);
2967 // Substitute the nested name specifier, if any.
2968 if (SubstQualifier(D, Var))
2971 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
2972 Owner, StartingScope);
2977 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2978 llvm_unreachable("@defs is not supported in Objective-C++");
2981 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2982 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2983 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2984 DiagnosticsEngine::Error,
2985 "cannot instantiate %0 yet");
2986 SemaRef.Diag(D->getLocation(), DiagID)
2987 << D->getDeclKindName();
2992 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2993 llvm_unreachable("Unexpected decl");
2996 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
2997 const MultiLevelTemplateArgumentList &TemplateArgs) {
2998 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
2999 if (D->isInvalidDecl())
3002 return Instantiator.Visit(D);
3005 /// \brief Instantiates a nested template parameter list in the current
3006 /// instantiation context.
3008 /// \param L The parameter list to instantiate
3010 /// \returns NULL if there was an error
3011 TemplateParameterList *
3012 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
3013 // Get errors for all the parameters before bailing out.
3014 bool Invalid = false;
3016 unsigned N = L->size();
3017 typedef SmallVector<NamedDecl *, 8> ParamVector;
3020 for (auto &P : *L) {
3021 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
3022 Params.push_back(D);
3023 Invalid = Invalid || !D || D->isInvalidDecl();
3026 // Clean up if we had an error.
3030 // Note: we substitute into associated constraints later
3031 Expr *const UninstantiatedRequiresClause = L->getRequiresClause();
3033 TemplateParameterList *InstL
3034 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
3035 L->getLAngleLoc(), Params,
3037 UninstantiatedRequiresClause);
3041 /// \brief Instantiate the declaration of a class template partial
3044 /// \param ClassTemplate the (instantiated) class template that is partially
3045 // specialized by the instantiation of \p PartialSpec.
3047 /// \param PartialSpec the (uninstantiated) class template partial
3048 /// specialization that we are instantiating.
3050 /// \returns The instantiated partial specialization, if successful; otherwise,
3051 /// NULL to indicate an error.
3052 ClassTemplatePartialSpecializationDecl *
3053 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
3054 ClassTemplateDecl *ClassTemplate,
3055 ClassTemplatePartialSpecializationDecl *PartialSpec) {
3056 // Create a local instantiation scope for this class template partial
3057 // specialization, which will contain the instantiations of the template
3059 LocalInstantiationScope Scope(SemaRef);
3061 // Substitute into the template parameters of the class template partial
3063 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3064 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3068 // Substitute into the template arguments of the class template partial
3070 const ASTTemplateArgumentListInfo *TemplArgInfo
3071 = PartialSpec->getTemplateArgsAsWritten();
3072 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3073 TemplArgInfo->RAngleLoc);
3074 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3075 TemplArgInfo->NumTemplateArgs,
3076 InstTemplateArgs, TemplateArgs))
3079 // Check that the template argument list is well-formed for this
3081 SmallVector<TemplateArgument, 4> Converted;
3082 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
3083 PartialSpec->getLocation(),
3089 // Check these arguments are valid for a template partial specialization.
3090 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3091 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
3095 // Figure out where to insert this class template partial specialization
3096 // in the member template's set of class template partial specializations.
3097 void *InsertPos = nullptr;
3098 ClassTemplateSpecializationDecl *PrevDecl
3099 = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
3101 // Build the canonical type that describes the converted template
3102 // arguments of the class template partial specialization.
3104 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
3107 // Build the fully-sugared type for this class template
3108 // specialization as the user wrote in the specialization
3109 // itself. This means that we'll pretty-print the type retrieved
3110 // from the specialization's declaration the way that the user
3111 // actually wrote the specialization, rather than formatting the
3112 // name based on the "canonical" representation used to store the
3113 // template arguments in the specialization.
3114 TypeSourceInfo *WrittenTy
3115 = SemaRef.Context.getTemplateSpecializationTypeInfo(
3116 TemplateName(ClassTemplate),
3117 PartialSpec->getLocation(),
3122 // We've already seen a partial specialization with the same template
3123 // parameters and template arguments. This can happen, for example, when
3124 // substituting the outer template arguments ends up causing two
3125 // class template partial specializations of a member class template
3126 // to have identical forms, e.g.,
3128 // template<typename T, typename U>
3130 // template<typename X, typename Y> struct Inner;
3131 // template<typename Y> struct Inner<T, Y>;
3132 // template<typename Y> struct Inner<U, Y>;
3135 // Outer<int, int> outer; // error: the partial specializations of Inner
3136 // // have the same signature.
3137 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
3138 << WrittenTy->getType();
3139 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3140 << SemaRef.Context.getTypeDeclType(PrevDecl);
3145 // Create the class template partial specialization declaration.
3146 ClassTemplatePartialSpecializationDecl *InstPartialSpec
3147 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
3148 PartialSpec->getTagKind(),
3150 PartialSpec->getLocStart(),
3151 PartialSpec->getLocation(),
3158 // Substitute the nested name specifier, if any.
3159 if (SubstQualifier(PartialSpec, InstPartialSpec))
3162 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3163 InstPartialSpec->setTypeAsWritten(WrittenTy);
3165 // Check the completed partial specialization.
3166 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3168 // Add this partial specialization to the set of class template partial
3170 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3171 /*InsertPos=*/nullptr);
3172 return InstPartialSpec;
3175 /// \brief Instantiate the declaration of a variable template partial
3178 /// \param VarTemplate the (instantiated) variable template that is partially
3179 /// specialized by the instantiation of \p PartialSpec.
3181 /// \param PartialSpec the (uninstantiated) variable template partial
3182 /// specialization that we are instantiating.
3184 /// \returns The instantiated partial specialization, if successful; otherwise,
3185 /// NULL to indicate an error.
3186 VarTemplatePartialSpecializationDecl *
3187 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3188 VarTemplateDecl *VarTemplate,
3189 VarTemplatePartialSpecializationDecl *PartialSpec) {
3190 // Create a local instantiation scope for this variable template partial
3191 // specialization, which will contain the instantiations of the template
3193 LocalInstantiationScope Scope(SemaRef);
3195 // Substitute into the template parameters of the variable template partial
3197 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3198 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3202 // Substitute into the template arguments of the variable template partial
3204 const ASTTemplateArgumentListInfo *TemplArgInfo
3205 = PartialSpec->getTemplateArgsAsWritten();
3206 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3207 TemplArgInfo->RAngleLoc);
3208 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3209 TemplArgInfo->NumTemplateArgs,
3210 InstTemplateArgs, TemplateArgs))
3213 // Check that the template argument list is well-formed for this
3215 SmallVector<TemplateArgument, 4> Converted;
3216 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3217 InstTemplateArgs, false, Converted))
3220 // Check these arguments are valid for a template partial specialization.
3221 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3222 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
3226 // Figure out where to insert this variable template partial specialization
3227 // in the member template's set of variable template partial specializations.
3228 void *InsertPos = nullptr;
3229 VarTemplateSpecializationDecl *PrevDecl =
3230 VarTemplate->findPartialSpecialization(Converted, InsertPos);
3232 // Build the canonical type that describes the converted template
3233 // arguments of the variable template partial specialization.
3234 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3235 TemplateName(VarTemplate), Converted);
3237 // Build the fully-sugared type for this variable template
3238 // specialization as the user wrote in the specialization
3239 // itself. This means that we'll pretty-print the type retrieved
3240 // from the specialization's declaration the way that the user
3241 // actually wrote the specialization, rather than formatting the
3242 // name based on the "canonical" representation used to store the
3243 // template arguments in the specialization.
3244 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3245 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3249 // We've already seen a partial specialization with the same template
3250 // parameters and template arguments. This can happen, for example, when
3251 // substituting the outer template arguments ends up causing two
3252 // variable template partial specializations of a member variable template
3253 // to have identical forms, e.g.,
3255 // template<typename T, typename U>
3257 // template<typename X, typename Y> pair<X,Y> p;
3258 // template<typename Y> pair<T, Y> p;
3259 // template<typename Y> pair<U, Y> p;
3262 // Outer<int, int> outer; // error: the partial specializations of Inner
3263 // // have the same signature.
3264 SemaRef.Diag(PartialSpec->getLocation(),
3265 diag::err_var_partial_spec_redeclared)
3266 << WrittenTy->getType();
3267 SemaRef.Diag(PrevDecl->getLocation(),
3268 diag::note_var_prev_partial_spec_here);
3272 // Do substitution on the type of the declaration
3273 TypeSourceInfo *DI = SemaRef.SubstType(
3274 PartialSpec->getTypeSourceInfo(), TemplateArgs,
3275 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3279 if (DI->getType()->isFunctionType()) {
3280 SemaRef.Diag(PartialSpec->getLocation(),
3281 diag::err_variable_instantiates_to_function)
3282 << PartialSpec->isStaticDataMember() << DI->getType();
3286 // Create the variable template partial specialization declaration.
3287 VarTemplatePartialSpecializationDecl *InstPartialSpec =
3288 VarTemplatePartialSpecializationDecl::Create(
3289 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3290 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
3291 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
3293 // Substitute the nested name specifier, if any.
3294 if (SubstQualifier(PartialSpec, InstPartialSpec))
3297 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3298 InstPartialSpec->setTypeAsWritten(WrittenTy);
3300 // Check the completed partial specialization.
3301 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3303 // Add this partial specialization to the set of variable template partial
3304 // specializations. The instantiation of the initializer is not necessary.
3305 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
3307 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
3308 LateAttrs, Owner, StartingScope);
3310 return InstPartialSpec;
3314 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
3315 SmallVectorImpl<ParmVarDecl *> &Params) {
3316 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3317 assert(OldTInfo && "substituting function without type source info");
3318 assert(Params.empty() && "parameter vector is non-empty at start");
3320 CXXRecordDecl *ThisContext = nullptr;
3321 unsigned ThisTypeQuals = 0;
3322 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3323 ThisContext = cast<CXXRecordDecl>(Owner);
3324 ThisTypeQuals = Method->getTypeQualifiers();
3327 TypeSourceInfo *NewTInfo
3328 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3329 D->getTypeSpecStartLoc(),
3331 ThisContext, ThisTypeQuals);
3335 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3336 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3337 if (NewTInfo != OldTInfo) {
3338 // Get parameters from the new type info.
3339 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
3340 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
3341 unsigned NewIdx = 0;
3342 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
3343 OldIdx != NumOldParams; ++OldIdx) {
3344 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
3345 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3347 Optional<unsigned> NumArgumentsInExpansion;
3348 if (OldParam->isParameterPack())
3349 NumArgumentsInExpansion =
3350 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3352 if (!NumArgumentsInExpansion) {
3353 // Simple case: normal parameter, or a parameter pack that's
3354 // instantiated to a (still-dependent) parameter pack.
3355 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3356 Params.push_back(NewParam);
3357 Scope->InstantiatedLocal(OldParam, NewParam);
3359 // Parameter pack expansion: make the instantiation an argument pack.
3360 Scope->MakeInstantiatedLocalArgPack(OldParam);
3361 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
3362 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3363 Params.push_back(NewParam);
3364 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3369 // The function type itself was not dependent and therefore no
3370 // substitution occurred. However, we still need to instantiate
3371 // the function parameters themselves.
3372 const FunctionProtoType *OldProto =
3373 cast<FunctionProtoType>(OldProtoLoc.getType());
3374 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3376 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
3378 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
3379 D, D->getLocation(), OldProto->getParamType(i)));
3384 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
3387 Params.push_back(Parm);
3391 // If the type of this function, after ignoring parentheses, is not
3392 // *directly* a function type, then we're instantiating a function that
3393 // was declared via a typedef or with attributes, e.g.,
3395 // typedef int functype(int, int);
3397 // int __cdecl meth(int, int);
3399 // In this case, we'll just go instantiate the ParmVarDecls that we
3400 // synthesized in the method declaration.
3401 SmallVector<QualType, 4> ParamTypes;
3402 Sema::ExtParameterInfoBuilder ExtParamInfos;
3403 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
3404 TemplateArgs, ParamTypes, &Params,
3412 /// Introduce the instantiated function parameters into the local
3413 /// instantiation scope, and set the parameter names to those used
3414 /// in the template.
3415 static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
3416 const FunctionDecl *PatternDecl,
3417 LocalInstantiationScope &Scope,
3418 const MultiLevelTemplateArgumentList &TemplateArgs) {
3419 unsigned FParamIdx = 0;
3420 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3421 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3422 if (!PatternParam->isParameterPack()) {
3423 // Simple case: not a parameter pack.
3424 assert(FParamIdx < Function->getNumParams());
3425 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3426 FunctionParam->setDeclName(PatternParam->getDeclName());
3427 // If the parameter's type is not dependent, update it to match the type
3428 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3429 // the pattern's type here. If the type is dependent, they can't differ,
3430 // per core issue 1668. Substitute into the type from the pattern, in case
3431 // it's instantiation-dependent.
3432 // FIXME: Updating the type to work around this is at best fragile.
3433 if (!PatternDecl->getType()->isDependentType()) {
3434 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3435 FunctionParam->getLocation(),
3436 FunctionParam->getDeclName());
3439 FunctionParam->setType(T);
3442 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3447 // Expand the parameter pack.
3448 Scope.MakeInstantiatedLocalArgPack(PatternParam);
3449 Optional<unsigned> NumArgumentsInExpansion
3450 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
3451 assert(NumArgumentsInExpansion &&
3452 "should only be called when all template arguments are known");
3453 QualType PatternType =
3454 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
3455 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3456 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3457 FunctionParam->setDeclName(PatternParam->getDeclName());
3458 if (!PatternDecl->getType()->isDependentType()) {
3459 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3460 QualType T = S.SubstType(PatternType, TemplateArgs,
3461 FunctionParam->getLocation(),
3462 FunctionParam->getDeclName());
3465 FunctionParam->setType(T);
3468 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3476 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3477 FunctionDecl *Decl) {
3478 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3479 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3482 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3483 InstantiatingTemplate::ExceptionSpecification());
3484 if (Inst.isInvalid()) {
3485 // We hit the instantiation depth limit. Clear the exception specification
3486 // so that our callers don't have to cope with EST_Uninstantiated.
3487 UpdateExceptionSpec(Decl, EST_None);
3490 if (Inst.isAlreadyInstantiating()) {
3491 // This exception specification indirectly depends on itself. Reject.
3492 // FIXME: Corresponding rule in the standard?
3493 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
3494 UpdateExceptionSpec(Decl, EST_None);
3498 // Enter the scope of this instantiation. We don't use
3499 // PushDeclContext because we don't have a scope.
3500 Sema::ContextRAII savedContext(*this, Decl);
3501 LocalInstantiationScope Scope(*this);
3503 MultiLevelTemplateArgumentList TemplateArgs =
3504 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
3506 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3507 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3509 UpdateExceptionSpec(Decl, EST_None);
3513 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3517 /// \brief Initializes the common fields of an instantiation function
3518 /// declaration (New) from the corresponding fields of its template (Tmpl).
3520 /// \returns true if there was an error
3522 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3523 FunctionDecl *Tmpl) {
3524 if (Tmpl->isDeleted())
3525 New->setDeletedAsWritten();
3527 // Forward the mangling number from the template to the instantiated decl.
3528 SemaRef.Context.setManglingNumber(New,
3529 SemaRef.Context.getManglingNumber(Tmpl));
3531 // If we are performing substituting explicitly-specified template arguments
3532 // or deduced template arguments into a function template and we reach this
3533 // point, we are now past the point where SFINAE applies and have committed
3534 // to keeping the new function template specialization. We therefore
3535 // convert the active template instantiation for the function template
3536 // into a template instantiation for this specific function template
3537 // specialization, which is not a SFINAE context, so that we diagnose any
3538 // further errors in the declaration itself.
3539 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3540 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3541 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3542 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
3543 if (FunctionTemplateDecl *FunTmpl
3544 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3545 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
3546 "Deduction from the wrong function template?");
3548 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3549 ActiveInst.Entity = New;
3553 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3554 assert(Proto && "Function template without prototype?");
3556 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3557 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3559 // DR1330: In C++11, defer instantiation of a non-trivial
3560 // exception specification.
3561 // DR1484: Local classes and their members are instantiated along with the
3562 // containing function.
3563 if (SemaRef.getLangOpts().CPlusPlus11 &&
3564 EPI.ExceptionSpec.Type != EST_None &&
3565 EPI.ExceptionSpec.Type != EST_DynamicNone &&
3566 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
3567 !Tmpl->isLexicallyWithinFunctionOrMethod()) {
3568 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3569 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3570 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
3571 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3572 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
3573 NewEST = EST_Unevaluated;
3575 // Mark the function has having an uninstantiated exception specification.
3576 const FunctionProtoType *NewProto
3577 = New->getType()->getAs<FunctionProtoType>();
3578 assert(NewProto && "Template instantiation without function prototype?");
3579 EPI = NewProto->getExtProtoInfo();
3580 EPI.ExceptionSpec.Type = NewEST;
3581 EPI.ExceptionSpec.SourceDecl = New;
3582 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
3583 New->setType(SemaRef.Context.getFunctionType(
3584 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
3586 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
3590 // Get the definition. Leaves the variable unchanged if undefined.
3591 const FunctionDecl *Definition = Tmpl;
3592 Tmpl->isDefined(Definition);
3594 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3595 LateAttrs, StartingScope);
3600 /// \brief Initializes common fields of an instantiated method
3601 /// declaration (New) from the corresponding fields of its template
3604 /// \returns true if there was an error
3606 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
3607 CXXMethodDecl *Tmpl) {
3608 if (InitFunctionInstantiation(New, Tmpl))
3611 New->setAccess(Tmpl->getAccess());
3612 if (Tmpl->isVirtualAsWritten())
3613 New->setVirtualAsWritten(true);
3615 // FIXME: New needs a pointer to Tmpl
3619 /// \brief Instantiate the definition of the given function from its
3622 /// \param PointOfInstantiation the point at which the instantiation was
3623 /// required. Note that this is not precisely a "point of instantiation"
3624 /// for the function, but it's close.
3626 /// \param Function the already-instantiated declaration of a
3627 /// function template specialization or member function of a class template
3630 /// \param Recursive if true, recursively instantiates any functions that
3631 /// are required by this instantiation.
3633 /// \param DefinitionRequired if true, then we are performing an explicit
3634 /// instantiation where the body of the function is required. Complain if
3635 /// there is no such body.
3636 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
3637 FunctionDecl *Function,
3639 bool DefinitionRequired,
3641 if (Function->isInvalidDecl() || Function->isDefined())
3644 // Never instantiate an explicit specialization except if it is a class scope
3645 // explicit specialization.
3646 TemplateSpecializationKind TSK = Function->getTemplateSpecializationKind();
3647 if (TSK == TSK_ExplicitSpecialization &&
3648 !Function->getClassScopeSpecializationPattern())
3651 // Find the function body that we'll be substituting.
3652 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
3653 assert(PatternDecl && "instantiating a non-template");
3655 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
3656 Stmt *Pattern = nullptr;
3658 Pattern = PatternDef->getBody(PatternDef);
3659 PatternDecl = PatternDef;
3662 // FIXME: We need to track the instantiation stack in order to know which
3663 // definitions should be visible within this instantiation.
3664 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
3665 Function->getInstantiatedFromMemberFunction(),
3666 PatternDecl, PatternDef, TSK,
3667 /*Complain*/DefinitionRequired)) {
3668 if (DefinitionRequired)
3669 Function->setInvalidDecl();
3670 else if (TSK == TSK_ExplicitInstantiationDefinition) {
3671 // Try again at the end of the translation unit (at which point a
3672 // definition will be required).
3674 PendingInstantiations.push_back(
3675 std::make_pair(Function, PointOfInstantiation));
3676 } else if (TSK == TSK_ImplicitInstantiation) {
3677 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred()) {
3678 Diag(PointOfInstantiation, diag::warn_func_template_missing)
3680 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
3681 if (getLangOpts().CPlusPlus11)
3682 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
3690 // Postpone late parsed template instantiations.
3691 if (PatternDecl->isLateTemplateParsed() &&
3692 !LateTemplateParser) {
3693 PendingInstantiations.push_back(
3694 std::make_pair(Function, PointOfInstantiation));
3698 // If we're performing recursive template instantiation, create our own
3699 // queue of pending implicit instantiations that we will instantiate later,
3700 // while we're still within our own instantiation context.
3701 // This has to happen before LateTemplateParser below is called, so that
3702 // it marks vtables used in late parsed templates as used.
3703 SavePendingLocalImplicitInstantiationsRAII
3704 SavedPendingLocalImplicitInstantiations(*this);
3705 SavePendingInstantiationsAndVTableUsesRAII
3706 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
3708 // Call the LateTemplateParser callback if there is a need to late parse
3709 // a templated function definition.
3710 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
3711 LateTemplateParser) {
3712 // FIXME: Optimize to allow individual templates to be deserialized.
3713 if (PatternDecl->isFromASTFile())
3714 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3716 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
3717 assert(LPTIter != LateParsedTemplateMap.end() &&
3718 "missing LateParsedTemplate");
3719 LateTemplateParser(OpaqueParser, *LPTIter->second);
3720 Pattern = PatternDecl->getBody(PatternDecl);
3723 // Note, we should never try to instantiate a deleted function template.
3724 assert((Pattern || PatternDecl->isDefaulted()) &&
3725 "unexpected kind of function template definition");
3727 // C++1y [temp.explicit]p10:
3728 // Except for inline functions, declarations with types deduced from their
3729 // initializer or return value, and class template specializations, other
3730 // explicit instantiation declarations have the effect of suppressing the
3731 // implicit instantiation of the entity to which they refer.
3732 if (TSK == TSK_ExplicitInstantiationDeclaration &&
3733 !PatternDecl->isInlined() &&
3734 !PatternDecl->getReturnType()->getContainedAutoType())
3737 if (PatternDecl->isInlined()) {
3738 // Function, and all later redeclarations of it (from imported modules,
3739 // for instance), are now implicitly inline.
3740 for (auto *D = Function->getMostRecentDecl(); /**/;
3741 D = D->getPreviousDecl()) {
3742 D->setImplicitlyInline();
3748 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3749 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
3751 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3752 "instantiating function definition");
3754 // The instantiation is visible here, even if it was first declared in an
3755 // unimported module.
3756 Function->setHidden(false);
3758 // Copy the inner loc start from the pattern.
3759 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3761 EnterExpressionEvaluationContext EvalContext(*this,
3762 Sema::PotentiallyEvaluated);
3764 // Introduce a new scope where local variable instantiations will be
3765 // recorded, unless we're actually a member function within a local
3766 // class, in which case we need to merge our results with the parent
3767 // scope (of the enclosing function).
3768 bool MergeWithParentScope = false;
3769 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3770 MergeWithParentScope = Rec->isLocalClass();
3772 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3774 if (PatternDecl->isDefaulted())
3775 SetDeclDefaulted(Function, PatternDecl->getLocation());
3777 MultiLevelTemplateArgumentList TemplateArgs =
3778 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
3780 // Substitute into the qualifier; we can get a substitution failure here
3781 // through evil use of alias templates.
3782 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
3783 // of the) lexical context of the pattern?
3784 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
3786 ActOnStartOfFunctionDef(nullptr, Function);
3788 // Enter the scope of this instantiation. We don't use
3789 // PushDeclContext because we don't have a scope.
3790 Sema::ContextRAII savedContext(*this, Function);
3792 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3796 // If this is a constructor, instantiate the member initializers.
3797 if (const CXXConstructorDecl *Ctor =
3798 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3799 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3803 // Instantiate the function body.
3804 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3806 if (Body.isInvalid())
3807 Function->setInvalidDecl();
3809 ActOnFinishFunctionBody(Function, Body.get(),
3810 /*IsInstantiation=*/true);
3812 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3814 if (auto *Listener = getASTMutationListener())
3815 Listener->FunctionDefinitionInstantiated(Function);
3820 DeclGroupRef DG(Function);
3821 Consumer.HandleTopLevelDecl(DG);
3823 // This class may have local implicit instantiations that need to be
3824 // instantiation within this scope.
3825 PerformPendingInstantiations(/*LocalOnly=*/true);
3829 // Define any pending vtables.
3830 DefineUsedVTables();
3832 // Instantiate any pending implicit instantiations found during the
3833 // instantiation of this template.
3834 PerformPendingInstantiations();
3836 // PendingInstantiations and VTableUses are restored through
3837 // SavePendingInstantiationsAndVTableUses's destructor.
3841 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3842 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3843 const TemplateArgumentList &TemplateArgList,
3844 const TemplateArgumentListInfo &TemplateArgsInfo,
3845 SmallVectorImpl<TemplateArgument> &Converted,
3846 SourceLocation PointOfInstantiation, void *InsertPos,
3847 LateInstantiatedAttrVec *LateAttrs,
3848 LocalInstantiationScope *StartingScope) {
3849 if (FromVar->isInvalidDecl())
3852 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3853 if (Inst.isInvalid())
3856 MultiLevelTemplateArgumentList TemplateArgLists;
3857 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3859 // Instantiate the first declaration of the variable template: for a partial
3860 // specialization of a static data member template, the first declaration may
3861 // or may not be the declaration in the class; if it's in the class, we want
3862 // to instantiate a member in the class (a declaration), and if it's outside,
3863 // we want to instantiate a definition.
3865 // If we're instantiating an explicitly-specialized member template or member
3866 // partial specialization, don't do this. The member specialization completely
3867 // replaces the original declaration in this case.
3868 bool IsMemberSpec = false;
3869 if (VarTemplatePartialSpecializationDecl *PartialSpec =
3870 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3871 IsMemberSpec = PartialSpec->isMemberSpecialization();
3872 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3873 IsMemberSpec = FromTemplate->isMemberSpecialization();
3875 FromVar = FromVar->getFirstDecl();
3877 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3878 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3881 // TODO: Set LateAttrs and StartingScope ...
3883 return cast_or_null<VarTemplateSpecializationDecl>(
3884 Instantiator.VisitVarTemplateSpecializationDecl(
3885 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3888 /// \brief Instantiates a variable template specialization by completing it
3889 /// with appropriate type information and initializer.
3890 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3891 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3892 const MultiLevelTemplateArgumentList &TemplateArgs) {
3894 // Do substitution on the type of the declaration
3895 TypeSourceInfo *DI =
3896 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
3897 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3901 // Update the type of this variable template specialization.
3902 VarSpec->setType(DI->getType());
3904 // Instantiate the initializer.
3905 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3910 /// BuildVariableInstantiation - Used after a new variable has been created.
3911 /// Sets basic variable data and decides whether to postpone the
3912 /// variable instantiation.
3913 void Sema::BuildVariableInstantiation(
3914 VarDecl *NewVar, VarDecl *OldVar,
3915 const MultiLevelTemplateArgumentList &TemplateArgs,
3916 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3917 LocalInstantiationScope *StartingScope,
3918 bool InstantiatingVarTemplate) {
3920 // If we are instantiating a local extern declaration, the
3921 // instantiation belongs lexically to the containing function.
3922 // If we are instantiating a static data member defined
3923 // out-of-line, the instantiation will have the same lexical
3924 // context (which will be a namespace scope) as the template.
3925 if (OldVar->isLocalExternDecl()) {
3926 NewVar->setLocalExternDecl();
3927 NewVar->setLexicalDeclContext(Owner);
3928 } else if (OldVar->isOutOfLine())
3929 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3930 NewVar->setTSCSpec(OldVar->getTSCSpec());
3931 NewVar->setInitStyle(OldVar->getInitStyle());
3932 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3933 NewVar->setConstexpr(OldVar->isConstexpr());
3934 NewVar->setInitCapture(OldVar->isInitCapture());
3935 NewVar->setPreviousDeclInSameBlockScope(
3936 OldVar->isPreviousDeclInSameBlockScope());
3937 NewVar->setAccess(OldVar->getAccess());
3939 if (!OldVar->isStaticDataMember()) {
3940 if (OldVar->isUsed(false))
3941 NewVar->setIsUsed();
3942 NewVar->setReferenced(OldVar->isReferenced());
3945 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3947 LookupResult Previous(
3948 *this, NewVar->getDeclName(), NewVar->getLocation(),
3949 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3950 : Sema::LookupOrdinaryName,
3951 Sema::ForRedeclaration);
3953 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3954 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3955 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
3956 // We have a previous declaration. Use that one, so we merge with the
3958 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3959 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3960 Previous.addDecl(NewPrev);
3961 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3962 OldVar->hasLinkage())
3963 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
3964 CheckVariableDeclaration(NewVar, Previous);
3966 if (!InstantiatingVarTemplate) {
3967 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3968 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
3969 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3972 if (!OldVar->isOutOfLine()) {
3973 if (NewVar->getDeclContext()->isFunctionOrMethod())
3974 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3977 // Link instantiations of static data members back to the template from
3978 // which they were instantiated.
3979 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
3980 NewVar->setInstantiationOfStaticDataMember(OldVar,
3981 TSK_ImplicitInstantiation);
3983 // Forward the mangling number from the template to the instantiated decl.
3984 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
3985 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
3987 // Delay instantiation of the initializer for variable templates or inline
3988 // static data members until a definition of the variable is needed. We need
3989 // it right away if the type contains 'auto'.
3990 if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
3991 !InstantiatingVarTemplate &&
3992 !(OldVar->isInline() && OldVar->isThisDeclarationADefinition())) ||
3993 NewVar->getType()->isUndeducedType())
3994 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3996 // Diagnose unused local variables with dependent types, where the diagnostic
3997 // will have been deferred.
3998 if (!NewVar->isInvalidDecl() &&
3999 NewVar->getDeclContext()->isFunctionOrMethod() &&
4000 OldVar->getType()->isDependentType())
4001 DiagnoseUnusedDecl(NewVar);
4004 /// \brief Instantiate the initializer of a variable.
4005 void Sema::InstantiateVariableInitializer(
4006 VarDecl *Var, VarDecl *OldVar,
4007 const MultiLevelTemplateArgumentList &TemplateArgs) {
4008 // We propagate the 'inline' flag with the initializer, because it
4009 // would otherwise imply that the variable is a definition for a
4010 // non-static data member.
4011 if (OldVar->isInlineSpecified())
4012 Var->setInlineSpecified();
4013 else if (OldVar->isInline())
4014 Var->setImplicitlyInline();
4016 if (OldVar->getInit()) {
4017 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
4018 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
4020 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
4022 // Instantiate the initializer.
4026 ContextRAII SwitchContext(*this, Var->getDeclContext());
4027 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
4028 OldVar->getInitStyle() == VarDecl::CallInit);
4031 if (!Init.isInvalid()) {
4032 bool TypeMayContainAuto = true;
4033 Expr *InitExpr = Init.get();
4035 if (Var->hasAttr<DLLImportAttr>() &&
4037 !InitExpr->isConstantInitializer(getASTContext(), false))) {
4038 // Do not dynamically initialize dllimport variables.
4039 } else if (InitExpr) {
4040 bool DirectInit = OldVar->isDirectInit();
4041 AddInitializerToDecl(Var, InitExpr, DirectInit, TypeMayContainAuto);
4043 ActOnUninitializedDecl(Var, TypeMayContainAuto);
4045 // FIXME: Not too happy about invalidating the declaration
4046 // because of a bogus initializer.
4047 Var->setInvalidDecl();
4050 PopExpressionEvaluationContext();
4052 if (Var->isStaticDataMember()) {
4053 if (!Var->isOutOfLine())
4056 // If the declaration inside the class had an initializer, don't add
4057 // another one to the out-of-line definition.
4058 if (OldVar->getFirstDecl()->hasInit())
4062 // We'll add an initializer to a for-range declaration later.
4063 if (Var->isCXXForRangeDecl())
4066 ActOnUninitializedDecl(Var, false);
4070 /// \brief Instantiate the definition of the given variable from its
4073 /// \param PointOfInstantiation the point at which the instantiation was
4074 /// required. Note that this is not precisely a "point of instantiation"
4075 /// for the function, but it's close.
4077 /// \param Var the already-instantiated declaration of a static member
4078 /// variable of a class template specialization.
4080 /// \param Recursive if true, recursively instantiates any functions that
4081 /// are required by this instantiation.
4083 /// \param DefinitionRequired if true, then we are performing an explicit
4084 /// instantiation where an out-of-line definition of the member variable
4085 /// is required. Complain if there is no such definition.
4086 void Sema::InstantiateStaticDataMemberDefinition(
4087 SourceLocation PointOfInstantiation,
4090 bool DefinitionRequired) {
4091 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
4092 DefinitionRequired);
4095 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
4096 VarDecl *Var, bool Recursive,
4097 bool DefinitionRequired, bool AtEndOfTU) {
4098 if (Var->isInvalidDecl())
4101 VarTemplateSpecializationDecl *VarSpec =
4102 dyn_cast<VarTemplateSpecializationDecl>(Var);
4103 VarDecl *PatternDecl = nullptr, *Def = nullptr;
4104 MultiLevelTemplateArgumentList TemplateArgs =
4105 getTemplateInstantiationArgs(Var);
4108 // If this is a variable template specialization, make sure that it is
4109 // non-dependent, then find its instantiation pattern.
4110 bool InstantiationDependent = false;
4111 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
4112 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
4113 "Only instantiate variable template specializations that are "
4114 "not type-dependent");
4115 (void)InstantiationDependent;
4117 // Find the variable initialization that we'll be substituting. If the
4118 // pattern was instantiated from a member template, look back further to
4119 // find the real pattern.
4120 assert(VarSpec->getSpecializedTemplate() &&
4121 "Specialization without specialized template?");
4122 llvm::PointerUnion<VarTemplateDecl *,
4123 VarTemplatePartialSpecializationDecl *> PatternPtr =
4124 VarSpec->getSpecializedTemplateOrPartial();
4125 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
4126 VarTemplatePartialSpecializationDecl *Tmpl =
4127 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
4128 while (VarTemplatePartialSpecializationDecl *From =
4129 Tmpl->getInstantiatedFromMember()) {
4130 if (Tmpl->isMemberSpecialization())
4137 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
4138 while (VarTemplateDecl *From =
4139 Tmpl->getInstantiatedFromMemberTemplate()) {
4140 if (Tmpl->isMemberSpecialization())
4145 PatternDecl = Tmpl->getTemplatedDecl();
4148 // If this is a static data member template, there might be an
4149 // uninstantiated initializer on the declaration. If so, instantiate
4151 if (PatternDecl->isStaticDataMember() &&
4152 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
4154 // FIXME: Factor out the duplicated instantiation context setup/tear down
4156 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4157 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4159 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4160 "instantiating variable initializer");
4162 // The instantiation is visible here, even if it was first declared in an
4163 // unimported module.
4164 Var->setHidden(false);
4166 // If we're performing recursive template instantiation, create our own
4167 // queue of pending implicit instantiations that we will instantiate
4168 // later, while we're still within our own instantiation context.
4169 SavePendingInstantiationsAndVTableUsesRAII
4170 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
4172 LocalInstantiationScope Local(*this);
4174 // Enter the scope of this instantiation. We don't use
4175 // PushDeclContext because we don't have a scope.
4176 ContextRAII PreviousContext(*this, Var->getDeclContext());
4177 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4178 PreviousContext.pop();
4180 // FIXME: Need to inform the ASTConsumer that we instantiated the
4183 // This variable may have local implicit instantiations that need to be
4184 // instantiated within this scope.
4185 PerformPendingInstantiations(/*LocalOnly=*/true);
4190 // Define any newly required vtables.
4191 DefineUsedVTables();
4193 // Instantiate any pending implicit instantiations found during the
4194 // instantiation of this template.
4195 PerformPendingInstantiations();
4197 // PendingInstantiations and VTableUses are restored through
4198 // SavePendingInstantiationsAndVTableUses's destructor.
4202 // Find actual definition
4203 Def = PatternDecl->getDefinition(getASTContext());
4205 // If this is a static data member, find its out-of-line definition.
4206 assert(Var->isStaticDataMember() && "not a static data member?");
4207 PatternDecl = Var->getInstantiatedFromStaticDataMember();
4209 assert(PatternDecl && "data member was not instantiated from a template?");
4210 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
4211 Def = PatternDecl->getDefinition();
4214 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
4216 // If we don't have a definition of the variable template, we won't perform
4217 // any instantiation. Rather, we rely on the user to instantiate this
4218 // definition (or provide a specialization for it) in another translation
4220 if (!Def && !DefinitionRequired) {
4221 if (TSK == TSK_ExplicitInstantiationDefinition) {
4222 PendingInstantiations.push_back(
4223 std::make_pair(Var, PointOfInstantiation));
4224 } else if (TSK == TSK_ImplicitInstantiation) {
4225 // Warn about missing definition at the end of translation unit.
4226 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred()) {
4227 Diag(PointOfInstantiation, diag::warn_var_template_missing)
4229 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4230 if (getLangOpts().CPlusPlus11)
4231 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
4238 // FIXME: We need to track the instantiation stack in order to know which
4239 // definitions should be visible within this instantiation.
4240 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
4241 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
4242 /*InstantiatedFromMember*/false,
4243 PatternDecl, Def, TSK,
4244 /*Complain*/DefinitionRequired))
4248 // Never instantiate an explicit specialization.
4249 if (TSK == TSK_ExplicitSpecialization)
4252 // C++11 [temp.explicit]p10:
4253 // Except for inline functions, [...] explicit instantiation declarations
4254 // have the effect of suppressing the implicit instantiation of the entity
4255 // to which they refer.
4256 if (TSK == TSK_ExplicitInstantiationDeclaration)
4259 // Make sure to pass the instantiated variable to the consumer at the end.
4260 struct PassToConsumerRAII {
4261 ASTConsumer &Consumer;
4264 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4265 : Consumer(Consumer), Var(Var) { }
4267 ~PassToConsumerRAII() {
4268 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
4270 } PassToConsumerRAII(Consumer, Var);
4272 // If we already have a definition, we're done.
4273 if (VarDecl *Def = Var->getDefinition()) {
4274 // We may be explicitly instantiating something we've already implicitly
4276 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
4277 PointOfInstantiation);
4281 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4282 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4284 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4285 "instantiating variable definition");
4287 // If we're performing recursive template instantiation, create our own
4288 // queue of pending implicit instantiations that we will instantiate later,
4289 // while we're still within our own instantiation context.
4290 SavePendingLocalImplicitInstantiationsRAII
4291 SavedPendingLocalImplicitInstantiations(*this);
4292 SavePendingInstantiationsAndVTableUsesRAII
4293 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
4295 // Enter the scope of this instantiation. We don't use
4296 // PushDeclContext because we don't have a scope.
4297 ContextRAII PreviousContext(*this, Var->getDeclContext());
4298 LocalInstantiationScope Local(*this);
4300 VarDecl *OldVar = Var;
4301 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
4302 // We're instantiating an inline static data member whose definition was
4303 // provided inside the class.
4304 // FIXME: Update record?
4305 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4306 } else if (!VarSpec) {
4307 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
4309 } else if (Var->isStaticDataMember() &&
4310 Var->getLexicalDeclContext()->isRecord()) {
4311 // We need to instantiate the definition of a static data member template,
4312 // and all we have is the in-class declaration of it. Instantiate a separate
4313 // declaration of the definition.
4314 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
4316 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
4317 VarSpec->getSpecializedTemplate(), Def, nullptr,
4318 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
4320 llvm::PointerUnion<VarTemplateDecl *,
4321 VarTemplatePartialSpecializationDecl *> PatternPtr =
4322 VarSpec->getSpecializedTemplateOrPartial();
4323 if (VarTemplatePartialSpecializationDecl *Partial =
4324 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4325 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4326 Partial, &VarSpec->getTemplateInstantiationArgs());
4328 // Merge the definition with the declaration.
4329 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
4330 LookupOrdinaryName, ForRedeclaration);
4332 MergeVarDecl(Var, R);
4334 // Attach the initializer.
4335 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4338 // Complete the existing variable's definition with an appropriately
4339 // substituted type and initializer.
4340 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
4342 PreviousContext.pop();
4345 PassToConsumerRAII.Var = Var;
4346 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
4347 OldVar->getPointOfInstantiation());
4350 // This variable may have local implicit instantiations that need to be
4351 // instantiated within this scope.
4352 PerformPendingInstantiations(/*LocalOnly=*/true);
4357 // Define any newly required vtables.
4358 DefineUsedVTables();
4360 // Instantiate any pending implicit instantiations found during the
4361 // instantiation of this template.
4362 PerformPendingInstantiations();
4364 // PendingInstantiations and VTableUses are restored through
4365 // SavePendingInstantiationsAndVTableUses's destructor.
4370 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4371 const CXXConstructorDecl *Tmpl,
4372 const MultiLevelTemplateArgumentList &TemplateArgs) {
4374 SmallVector<CXXCtorInitializer*, 4> NewInits;
4375 bool AnyErrors = Tmpl->isInvalidDecl();
4377 // Instantiate all the initializers.
4378 for (const auto *Init : Tmpl->inits()) {
4379 // Only instantiate written initializers, let Sema re-construct implicit
4381 if (!Init->isWritten())
4384 SourceLocation EllipsisLoc;
4386 if (Init->isPackExpansion()) {
4387 // This is a pack expansion. We should expand it now.
4388 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
4389 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4390 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
4391 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
4392 bool ShouldExpand = false;
4393 bool RetainExpansion = false;
4394 Optional<unsigned> NumExpansions;
4395 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
4396 BaseTL.getSourceRange(),
4398 TemplateArgs, ShouldExpand,
4402 New->setInvalidDecl();
4405 assert(ShouldExpand && "Partial instantiation of base initializer?");
4407 // Loop over all of the arguments in the argument pack(s),
4408 for (unsigned I = 0; I != *NumExpansions; ++I) {
4409 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4411 // Instantiate the initializer.
4412 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4413 /*CXXDirectInit=*/true);
4414 if (TempInit.isInvalid()) {
4419 // Instantiate the base type.
4420 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4422 Init->getSourceLocation(),
4423 New->getDeclName());
4429 // Build the initializer.
4430 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4431 BaseTInfo, TempInit.get(),
4434 if (NewInit.isInvalid()) {
4439 NewInits.push_back(NewInit.get());
4445 // Instantiate the initializer.
4446 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4447 /*CXXDirectInit=*/true);
4448 if (TempInit.isInvalid()) {
4453 MemInitResult NewInit;
4454 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4455 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4457 Init->getSourceLocation(),
4458 New->getDeclName());
4461 New->setInvalidDecl();
4465 if (Init->isBaseInitializer())
4466 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
4467 New->getParent(), EllipsisLoc);
4469 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
4470 cast<CXXRecordDecl>(CurContext->getParent()));
4471 } else if (Init->isMemberInitializer()) {
4472 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
4473 Init->getMemberLocation(),
4478 New->setInvalidDecl();
4482 NewInit = BuildMemberInitializer(Member, TempInit.get(),
4483 Init->getSourceLocation());
4484 } else if (Init->isIndirectMemberInitializer()) {
4485 IndirectFieldDecl *IndirectMember =
4486 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
4487 Init->getMemberLocation(),
4488 Init->getIndirectMember(), TemplateArgs));
4490 if (!IndirectMember) {
4492 New->setInvalidDecl();
4496 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
4497 Init->getSourceLocation());
4500 if (NewInit.isInvalid()) {
4502 New->setInvalidDecl();
4504 NewInits.push_back(NewInit.get());
4508 // Assign all the initializers to the new constructor.
4509 ActOnMemInitializers(New,
4510 /*FIXME: ColonLoc */
4516 // TODO: this could be templated if the various decl types used the
4517 // same method name.
4518 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4519 ClassTemplateDecl *Instance) {
4520 Pattern = Pattern->getCanonicalDecl();
4523 Instance = Instance->getCanonicalDecl();
4524 if (Pattern == Instance) return true;
4525 Instance = Instance->getInstantiatedFromMemberTemplate();
4531 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4532 FunctionTemplateDecl *Instance) {
4533 Pattern = Pattern->getCanonicalDecl();
4536 Instance = Instance->getCanonicalDecl();
4537 if (Pattern == Instance) return true;
4538 Instance = Instance->getInstantiatedFromMemberTemplate();
4545 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4546 ClassTemplatePartialSpecializationDecl *Instance) {
4548 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4550 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4551 Instance->getCanonicalDecl());
4552 if (Pattern == Instance)
4554 Instance = Instance->getInstantiatedFromMember();
4560 static bool isInstantiationOf(CXXRecordDecl *Pattern,
4561 CXXRecordDecl *Instance) {
4562 Pattern = Pattern->getCanonicalDecl();
4565 Instance = Instance->getCanonicalDecl();
4566 if (Pattern == Instance) return true;
4567 Instance = Instance->getInstantiatedFromMemberClass();
4573 static bool isInstantiationOf(FunctionDecl *Pattern,
4574 FunctionDecl *Instance) {
4575 Pattern = Pattern->getCanonicalDecl();
4578 Instance = Instance->getCanonicalDecl();
4579 if (Pattern == Instance) return true;
4580 Instance = Instance->getInstantiatedFromMemberFunction();
4586 static bool isInstantiationOf(EnumDecl *Pattern,
4587 EnumDecl *Instance) {
4588 Pattern = Pattern->getCanonicalDecl();
4591 Instance = Instance->getCanonicalDecl();
4592 if (Pattern == Instance) return true;
4593 Instance = Instance->getInstantiatedFromMemberEnum();
4599 static bool isInstantiationOf(UsingShadowDecl *Pattern,
4600 UsingShadowDecl *Instance,
4602 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
4606 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
4608 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4611 template<typename T>
4612 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
4614 // An unresolved using declaration can instantiate to an unresolved using
4615 // declaration, or to a using declaration or a using declaration pack.
4617 // Multiple declarations can claim to be instantiated from an unresolved
4618 // using declaration if it's a pack expansion. We want the UsingPackDecl
4619 // in that case, not the individual UsingDecls within the pack.
4620 bool OtherIsPackExpansion;
4621 NamedDecl *OtherFrom;
4622 if (auto *OtherUUD = dyn_cast<T>(Other)) {
4623 OtherIsPackExpansion = OtherUUD->isPackExpansion();
4624 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
4625 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
4626 OtherIsPackExpansion = true;
4627 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
4628 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
4629 OtherIsPackExpansion = false;
4630 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
4634 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
4635 declaresSameEntity(OtherFrom, Pattern);
4638 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4639 VarDecl *Instance) {
4640 assert(Instance->isStaticDataMember());
4642 Pattern = Pattern->getCanonicalDecl();
4645 Instance = Instance->getCanonicalDecl();
4646 if (Pattern == Instance) return true;
4647 Instance = Instance->getInstantiatedFromStaticDataMember();
4653 // Other is the prospective instantiation
4654 // D is the prospective pattern
4655 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
4656 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
4657 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
4659 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
4660 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
4662 if (D->getKind() != Other->getKind())
4665 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
4666 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
4668 if (auto *Function = dyn_cast<FunctionDecl>(Other))
4669 return isInstantiationOf(cast<FunctionDecl>(D), Function);
4671 if (auto *Enum = dyn_cast<EnumDecl>(Other))
4672 return isInstantiationOf(cast<EnumDecl>(D), Enum);
4674 if (auto *Var = dyn_cast<VarDecl>(Other))
4675 if (Var->isStaticDataMember())
4676 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4678 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
4679 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
4681 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4682 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4684 if (auto *PartialSpec =
4685 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4686 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4689 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
4690 if (!Field->getDeclName()) {
4691 // This is an unnamed field.
4692 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
4693 cast<FieldDecl>(D));
4697 if (auto *Using = dyn_cast<UsingDecl>(Other))
4698 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4700 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
4701 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4703 return D->getDeclName() &&
4704 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4707 template<typename ForwardIterator>
4708 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
4710 ForwardIterator first,
4711 ForwardIterator last) {
4712 for (; first != last; ++first)
4713 if (isInstantiationOf(Ctx, D, *first))
4714 return cast<NamedDecl>(*first);
4719 /// \brief Finds the instantiation of the given declaration context
4720 /// within the current instantiation.
4722 /// \returns NULL if there was an error
4723 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
4724 const MultiLevelTemplateArgumentList &TemplateArgs) {
4725 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
4726 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
4727 return cast_or_null<DeclContext>(ID);
4731 /// \brief Find the instantiation of the given declaration within the
4732 /// current instantiation.
4734 /// This routine is intended to be used when \p D is a declaration
4735 /// referenced from within a template, that needs to mapped into the
4736 /// corresponding declaration within an instantiation. For example,
4740 /// template<typename T>
4743 /// KnownValue = sizeof(T)
4746 /// bool getKind() const { return KnownValue; }
4749 /// template struct X<int>;
4752 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4753 /// \p EnumConstantDecl for \p KnownValue (which refers to
4754 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4755 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4756 /// this mapping from within the instantiation of <tt>X<int></tt>.
4757 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4758 const MultiLevelTemplateArgumentList &TemplateArgs) {
4759 DeclContext *ParentDC = D->getDeclContext();
4760 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4761 // parameters (p below) can have their ParentDC set to the translation-unit
4762 // - thus we can not consistently check if the ParentDC of such a parameter
4763 // is Dependent or/and a FunctionOrMethod.
4764 // For e.g. this code, during Template argument deduction tries to
4765 // find an instantiated decl for (T y) when the ParentDC for y is
4766 // the translation unit.
4767 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
4768 // float baz(float(*)()) { return 0.0; }
4770 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4771 // it gets here, always has a FunctionOrMethod as its ParentDC??
4773 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4774 // whose type is not instantiation dependent, do nothing to the decl
4775 // - otherwise find its instantiated decl.
4776 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4777 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4779 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
4780 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
4781 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4782 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
4783 // D is a local of some kind. Look into the map of local
4784 // declarations to their instantiations.
4785 if (CurrentInstantiationScope) {
4786 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
4787 if (Decl *FD = Found->dyn_cast<Decl *>())
4788 return cast<NamedDecl>(FD);
4790 int PackIdx = ArgumentPackSubstitutionIndex;
4791 assert(PackIdx != -1 &&
4792 "found declaration pack but not pack expanding");
4793 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4794 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4798 // If we're performing a partial substitution during template argument
4799 // deduction, we may not have values for template parameters yet. They
4800 // just map to themselves.
4801 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4802 isa<TemplateTemplateParmDecl>(D))
4805 if (D->isInvalidDecl())
4808 // Normally this function only searches for already instantiated declaration
4809 // however we have to make an exclusion for local types used before
4810 // definition as in the code:
4812 // template<typename T> void f1() {
4813 // void g1(struct x1);
4817 // In this case instantiation of the type of 'g1' requires definition of
4818 // 'x1', which is defined later. Error recovery may produce an enum used
4819 // before definition. In these cases we need to instantiate relevant
4820 // declarations here.
4821 bool NeedInstantiate = false;
4822 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4823 NeedInstantiate = RD->isLocalClass();
4825 NeedInstantiate = isa<EnumDecl>(D);
4826 if (NeedInstantiate) {
4827 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4828 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4829 return cast<TypeDecl>(Inst);
4832 // If we didn't find the decl, then we must have a label decl that hasn't
4833 // been found yet. Lazily instantiate it and return it now.
4834 assert(isa<LabelDecl>(D));
4836 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4837 assert(Inst && "Failed to instantiate label??");
4839 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4840 return cast<LabelDecl>(Inst);
4843 // For variable template specializations, update those that are still
4845 if (VarTemplateSpecializationDecl *VarSpec =
4846 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4847 bool InstantiationDependent = false;
4848 const TemplateArgumentListInfo &VarTemplateArgs =
4849 VarSpec->getTemplateArgsInfo();
4850 if (TemplateSpecializationType::anyDependentTemplateArguments(
4851 VarTemplateArgs, InstantiationDependent))
4852 D = cast<NamedDecl>(
4853 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4857 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4858 if (!Record->isDependentContext())
4861 // Determine whether this record is the "templated" declaration describing
4862 // a class template or class template partial specialization.
4863 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
4865 ClassTemplate = ClassTemplate->getCanonicalDecl();
4866 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4867 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4868 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
4870 // Walk the current context to find either the record or an instantiation of
4872 DeclContext *DC = CurContext;
4873 while (!DC->isFileContext()) {
4874 // If we're performing substitution while we're inside the template
4875 // definition, we'll find our own context. We're done.
4876 if (DC->Equals(Record))
4879 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4880 // Check whether we're in the process of instantiating a class template
4881 // specialization of the template we're mapping.
4882 if (ClassTemplateSpecializationDecl *InstSpec
4883 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4884 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4885 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4889 // Check whether we're in the process of instantiating a member class.
4890 if (isInstantiationOf(Record, InstRecord))
4894 // Move to the outer template scope.
4895 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4896 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4897 DC = FD->getLexicalDeclContext();
4902 DC = DC->getParent();
4905 // Fall through to deal with other dependent record types (e.g.,
4906 // anonymous unions in class templates).
4909 if (!ParentDC->isDependentContext())
4912 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
4916 if (ParentDC != D->getDeclContext()) {
4917 // We performed some kind of instantiation in the parent context,
4918 // so now we need to look into the instantiated parent context to
4919 // find the instantiation of the declaration D.
4921 // If our context used to be dependent, we may need to instantiate
4922 // it before performing lookup into that context.
4923 bool IsBeingInstantiated = false;
4924 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
4925 if (!Spec->isDependentContext()) {
4926 QualType T = Context.getTypeDeclType(Spec);
4927 const RecordType *Tag = T->getAs<RecordType>();
4928 assert(Tag && "type of non-dependent record is not a RecordType");
4929 if (Tag->isBeingDefined())
4930 IsBeingInstantiated = true;
4931 if (!Tag->isBeingDefined() &&
4932 RequireCompleteType(Loc, T, diag::err_incomplete_type))
4935 ParentDC = Tag->getDecl();
4939 NamedDecl *Result = nullptr;
4940 // FIXME: If the name is a dependent name, this lookup won't necessarily
4941 // find it. Does that ever matter?
4942 if (D->getDeclName()) {
4943 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
4944 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
4946 // Since we don't have a name for the entity we're looking for,
4947 // our only option is to walk through all of the declarations to
4948 // find that name. This will occur in a few cases:
4950 // - anonymous struct/union within a template
4951 // - unnamed class/struct/union/enum within a template
4953 // FIXME: Find a better way to find these instantiations!
4954 Result = findInstantiationOf(Context, D,
4955 ParentDC->decls_begin(),
4956 ParentDC->decls_end());
4960 if (isa<UsingShadowDecl>(D)) {
4961 // UsingShadowDecls can instantiate to nothing because of using hiding.
4962 } else if (Diags.hasErrorOccurred()) {
4963 // We've already complained about something, so most likely this
4964 // declaration failed to instantiate. There's no point in complaining
4965 // further, since this is normal in invalid code.
4966 } else if (IsBeingInstantiated) {
4967 // The class in which this member exists is currently being
4968 // instantiated, and we haven't gotten around to instantiating this
4969 // member yet. This can happen when the code uses forward declarations
4970 // of member classes, and introduces ordering dependencies via
4971 // template instantiation.
4972 Diag(Loc, diag::err_member_not_yet_instantiated)
4974 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4975 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
4976 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4977 // This enumeration constant was found when the template was defined,
4978 // but can't be found in the instantiation. This can happen if an
4979 // unscoped enumeration member is explicitly specialized.
4980 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4981 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4983 assert(Spec->getTemplateSpecializationKind() ==
4984 TSK_ExplicitSpecialization);
4985 Diag(Loc, diag::err_enumerator_does_not_exist)
4987 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4988 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4989 << Context.getTypeDeclType(Spec);
4991 // We should have found something, but didn't.
4992 llvm_unreachable("Unable to find instantiation of declaration!");
5002 /// \brief Performs template instantiation for all implicit template
5003 /// instantiations we have seen until this point.
5004 void Sema::PerformPendingInstantiations(bool LocalOnly) {
5005 while (!PendingLocalImplicitInstantiations.empty() ||
5006 (!LocalOnly && !PendingInstantiations.empty())) {
5007 PendingImplicitInstantiation Inst;
5009 if (PendingLocalImplicitInstantiations.empty()) {
5010 Inst = PendingInstantiations.front();
5011 PendingInstantiations.pop_front();
5013 Inst = PendingLocalImplicitInstantiations.front();
5014 PendingLocalImplicitInstantiations.pop_front();
5017 // Instantiate function definitions
5018 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
5019 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
5020 TSK_ExplicitInstantiationDefinition;
5021 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
5022 DefinitionRequired, true);
5026 // Instantiate variable definitions
5027 VarDecl *Var = cast<VarDecl>(Inst.first);
5029 assert((Var->isStaticDataMember() ||
5030 isa<VarTemplateSpecializationDecl>(Var)) &&
5031 "Not a static data member, nor a variable template"
5032 " specialization?");
5034 // Don't try to instantiate declarations if the most recent redeclaration
5036 if (Var->getMostRecentDecl()->isInvalidDecl())
5039 // Check if the most recent declaration has changed the specialization kind
5040 // and removed the need for implicit instantiation.
5041 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
5042 case TSK_Undeclared:
5043 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
5044 case TSK_ExplicitInstantiationDeclaration:
5045 case TSK_ExplicitSpecialization:
5046 continue; // No longer need to instantiate this type.
5047 case TSK_ExplicitInstantiationDefinition:
5048 // We only need an instantiation if the pending instantiation *is* the
5049 // explicit instantiation.
5050 if (Var != Var->getMostRecentDecl()) continue;
5051 case TSK_ImplicitInstantiation:
5055 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
5056 "instantiating variable definition");
5057 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
5058 TSK_ExplicitInstantiationDefinition;
5060 // Instantiate static data member definitions or variable template
5062 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
5063 DefinitionRequired, true);
5067 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
5068 const MultiLevelTemplateArgumentList &TemplateArgs) {
5069 for (auto DD : Pattern->ddiags()) {
5070 switch (DD->getKind()) {
5071 case DependentDiagnostic::Access:
5072 HandleDependentAccessCheck(*DD, TemplateArgs);