1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===/
8 // This file implements C++ template instantiation for declarations.
10 //===----------------------------------------------------------------------===/
11 #include "clang/Sema/SemaInternal.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/ASTMutationListener.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/DeclVisitor.h"
17 #include "clang/AST/DependentDiagnostic.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/PrettyDeclStackTrace.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/Sema/Initialization.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/Template.h"
25 #include "clang/Sema/TemplateInstCallback.h"
26 #include "llvm/Support/TimeProfiler.h"
28 using namespace clang;
30 static bool isDeclWithinFunction(const Decl *D) {
31 const DeclContext *DC = D->getDeclContext();
32 if (DC->isFunctionOrMethod())
36 return cast<CXXRecordDecl>(DC)->isLocalClass();
41 template<typename DeclT>
42 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
43 const MultiLevelTemplateArgumentList &TemplateArgs) {
44 if (!OldDecl->getQualifierLoc())
47 assert((NewDecl->getFriendObjectKind() ||
48 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
49 "non-friend with qualified name defined in dependent context");
50 Sema::ContextRAII SavedContext(
52 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
53 ? NewDecl->getLexicalDeclContext()
54 : OldDecl->getLexicalDeclContext()));
56 NestedNameSpecifierLoc NewQualifierLoc
57 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
63 NewDecl->setQualifierInfo(NewQualifierLoc);
67 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
68 DeclaratorDecl *NewDecl) {
69 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
72 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
74 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
77 // Include attribute instantiation code.
78 #include "clang/Sema/AttrTemplateInstantiate.inc"
80 static void instantiateDependentAlignedAttr(
81 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
82 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
83 if (Aligned->isAlignmentExpr()) {
84 // The alignment expression is a constant expression.
85 EnterExpressionEvaluationContext Unevaluated(
86 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
87 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
88 if (!Result.isInvalid())
89 S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
91 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
92 TemplateArgs, Aligned->getLocation(),
95 S.AddAlignedAttr(New, *Aligned, Result, 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(
142 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
144 Expr *E, *OE = nullptr;
145 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
146 if (Result.isInvalid())
148 E = Result.getAs<Expr>();
150 if (Aligned->getOffset()) {
151 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
152 if (Result.isInvalid())
154 OE = Result.getAs<Expr>();
157 S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
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(
165 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
166 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
167 if (!Result.isInvalid())
168 S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
171 static void instantiateDependentAllocAlignAttr(
172 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
173 const AllocAlignAttr *Align, Decl *New) {
174 Expr *Param = IntegerLiteral::Create(
176 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
177 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
178 S.AddAllocAlignAttr(New, *Align, Param);
181 static Expr *instantiateDependentFunctionAttrCondition(
182 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
183 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
184 Expr *Cond = nullptr;
186 Sema::ContextRAII SwitchContext(S, New);
187 EnterExpressionEvaluationContext Unevaluated(
188 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
189 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
190 if (Result.isInvalid())
192 Cond = Result.getAs<Expr>();
194 if (!Cond->isTypeDependent()) {
195 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
196 if (Converted.isInvalid())
198 Cond = Converted.get();
201 SmallVector<PartialDiagnosticAt, 8> Diags;
202 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
203 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
204 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
205 for (const auto &P : Diags)
206 S.Diag(P.first, P.second);
212 static void instantiateDependentEnableIfAttr(
213 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
214 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
215 Expr *Cond = instantiateDependentFunctionAttrCondition(
216 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
219 New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
220 Cond, EIA->getMessage()));
223 static void instantiateDependentDiagnoseIfAttr(
224 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
225 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
226 Expr *Cond = instantiateDependentFunctionAttrCondition(
227 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
230 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
231 S.getASTContext(), *DIA, Cond, DIA->getMessage(),
232 DIA->getDiagnosticType(), DIA->getArgDependent(), New));
235 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
236 // template A as the base and arguments from TemplateArgs.
237 static void instantiateDependentCUDALaunchBoundsAttr(
238 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
239 const CUDALaunchBoundsAttr &Attr, Decl *New) {
240 // The alignment expression is a constant expression.
241 EnterExpressionEvaluationContext Unevaluated(
242 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
244 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
245 if (Result.isInvalid())
247 Expr *MaxThreads = Result.getAs<Expr>();
249 Expr *MinBlocks = nullptr;
250 if (Attr.getMinBlocks()) {
251 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
252 if (Result.isInvalid())
254 MinBlocks = Result.getAs<Expr>();
257 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks);
261 instantiateDependentModeAttr(Sema &S,
262 const MultiLevelTemplateArgumentList &TemplateArgs,
263 const ModeAttr &Attr, Decl *New) {
264 S.AddModeAttr(New, Attr, Attr.getMode(),
265 /*InInstantiation=*/true);
268 /// Instantiation of 'declare simd' attribute and its arguments.
269 static void instantiateOMPDeclareSimdDeclAttr(
270 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
271 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
272 // Allow 'this' in clauses with varlists.
273 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
274 New = FTD->getTemplatedDecl();
275 auto *FD = cast<FunctionDecl>(New);
276 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
277 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
278 SmallVector<unsigned, 4> LinModifiers;
280 auto SubstExpr = [&](Expr *E) -> ExprResult {
281 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
282 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
283 Sema::ContextRAII SavedContext(S, FD);
284 LocalInstantiationScope Local(S);
285 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
286 Local.InstantiatedLocal(
287 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
288 return S.SubstExpr(E, TemplateArgs);
290 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
291 FD->isCXXInstanceMember());
292 return S.SubstExpr(E, TemplateArgs);
295 // Substitute a single OpenMP clause, which is a potentially-evaluated
297 auto Subst = [&](Expr *E) -> ExprResult {
298 EnterExpressionEvaluationContext Evaluated(
299 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
300 ExprResult Res = SubstExpr(E);
303 return S.ActOnFinishFullExpr(Res.get(), false);
307 if (auto *E = Attr.getSimdlen())
310 if (Attr.uniforms_size() > 0) {
311 for(auto *E : Attr.uniforms()) {
312 ExprResult Inst = Subst(E);
313 if (Inst.isInvalid())
315 Uniforms.push_back(Inst.get());
319 auto AI = Attr.alignments_begin();
320 for (auto *E : Attr.aligneds()) {
321 ExprResult Inst = Subst(E);
322 if (Inst.isInvalid())
324 Aligneds.push_back(Inst.get());
327 Inst = S.SubstExpr(*AI, TemplateArgs);
328 Alignments.push_back(Inst.get());
332 auto SI = Attr.steps_begin();
333 for (auto *E : Attr.linears()) {
334 ExprResult Inst = Subst(E);
335 if (Inst.isInvalid())
337 Linears.push_back(Inst.get());
340 Inst = S.SubstExpr(*SI, TemplateArgs);
341 Steps.push_back(Inst.get());
344 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
345 (void)S.ActOnOpenMPDeclareSimdDirective(
346 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
347 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
351 /// Instantiation of 'declare variant' attribute and its arguments.
352 static void instantiateOMPDeclareVariantAttr(
353 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
354 const OMPDeclareVariantAttr &Attr, Decl *New) {
355 // Allow 'this' in clauses with varlists.
356 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
357 New = FTD->getTemplatedDecl();
358 auto *FD = cast<FunctionDecl>(New);
359 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
361 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
362 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
363 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
364 Sema::ContextRAII SavedContext(S, FD);
365 LocalInstantiationScope Local(S);
366 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
367 Local.InstantiatedLocal(
368 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
369 return S.SubstExpr(E, TemplateArgs);
371 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
372 FD->isCXXInstanceMember());
373 return S.SubstExpr(E, TemplateArgs);
376 // Substitute a single OpenMP clause, which is a potentially-evaluated
378 auto &&Subst = [&SubstExpr, &S](Expr *E) {
379 EnterExpressionEvaluationContext Evaluated(
380 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
381 ExprResult Res = SubstExpr(E);
384 return S.ActOnFinishFullExpr(Res.get(), false);
387 ExprResult VariantFuncRef;
388 if (Expr *E = Attr.getVariantFuncRef()) {
389 // Do not mark function as is used to prevent its emission if this is the
390 // only place where it is used.
391 EnterExpressionEvaluationContext Unevaluated(
392 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
393 VariantFuncRef = Subst(E);
396 // Check function/variant ref.
397 Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
398 S.checkOpenMPDeclareVariantFunction(
399 S.ConvertDeclToDeclGroup(New), VariantFuncRef.get(), Attr.getRange());
402 SmallVector<Sema::OMPCtxSelectorData, 4> Data;
403 for (unsigned I = 0, E = Attr.scores_size(); I < E; ++I) {
405 if (Expr *E = *std::next(Attr.scores_begin(), I))
407 // Instantiate the attribute.
408 auto CtxSet = static_cast<OpenMPContextSelectorSetKind>(
409 *std::next(Attr.ctxSelectorSets_begin(), I));
410 auto Ctx = static_cast<OpenMPContextSelectorKind>(
411 *std::next(Attr.ctxSelectors_begin(), I));
413 case OMP_CTX_SET_implementation:
416 Data.emplace_back(CtxSet, Ctx, Score, Attr.implVendors());
419 case OMP_CTX_unknown:
420 llvm_unreachable("Unexpected context selector kind.");
423 case OMP_CTX_SET_device:
426 Data.emplace_back(CtxSet, Ctx, Score, Attr.deviceKinds());
429 case OMP_CTX_unknown:
430 llvm_unreachable("Unexpected context selector kind.");
433 case OMP_CTX_SET_unknown:
434 llvm_unreachable("Unexpected context selector set kind.");
437 S.ActOnOpenMPDeclareVariantDirective(DeclVarData.getValue().first,
438 DeclVarData.getValue().second,
439 Attr.getRange(), Data);
442 static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
443 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
444 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
445 // Both min and max expression are constant expressions.
446 EnterExpressionEvaluationContext Unevaluated(
447 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
449 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
450 if (Result.isInvalid())
452 Expr *MinExpr = Result.getAs<Expr>();
454 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
455 if (Result.isInvalid())
457 Expr *MaxExpr = Result.getAs<Expr>();
459 S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
462 static ExplicitSpecifier
463 instantiateExplicitSpecifier(Sema &S,
464 const MultiLevelTemplateArgumentList &TemplateArgs,
465 ExplicitSpecifier ES, FunctionDecl *New) {
468 Expr *OldCond = ES.getExpr();
469 Expr *Cond = nullptr;
471 EnterExpressionEvaluationContext Unevaluated(
472 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
473 ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
474 if (SubstResult.isInvalid()) {
475 return ExplicitSpecifier::Invalid();
477 Cond = SubstResult.get();
479 ExplicitSpecifier Result(Cond, ES.getKind());
480 if (!Cond->isTypeDependent())
481 S.tryResolveExplicitSpecifier(Result);
485 static void instantiateDependentAMDGPUWavesPerEUAttr(
486 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
487 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
488 // Both min and max expression are constant expressions.
489 EnterExpressionEvaluationContext Unevaluated(
490 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
492 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
493 if (Result.isInvalid())
495 Expr *MinExpr = Result.getAs<Expr>();
497 Expr *MaxExpr = nullptr;
498 if (auto Max = Attr.getMax()) {
499 Result = S.SubstExpr(Max, TemplateArgs);
500 if (Result.isInvalid())
502 MaxExpr = Result.getAs<Expr>();
505 S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
508 void Sema::InstantiateAttrsForDecl(
509 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
510 Decl *New, LateInstantiatedAttrVec *LateAttrs,
511 LocalInstantiationScope *OuterMostScope) {
512 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
513 for (const auto *TmplAttr : Tmpl->attrs()) {
514 // FIXME: If any of the special case versions from InstantiateAttrs become
515 // applicable to template declaration, we'll need to add them here.
516 CXXThisScopeRAII ThisScope(
517 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
518 Qualifiers(), ND->isCXXInstanceMember());
520 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
521 TmplAttr, Context, *this, TemplateArgs);
523 New->addAttr(NewAttr);
528 static Sema::RetainOwnershipKind
529 attrToRetainOwnershipKind(const Attr *A) {
530 switch (A->getKind()) {
531 case clang::attr::CFConsumed:
532 return Sema::RetainOwnershipKind::CF;
533 case clang::attr::OSConsumed:
534 return Sema::RetainOwnershipKind::OS;
535 case clang::attr::NSConsumed:
536 return Sema::RetainOwnershipKind::NS;
538 llvm_unreachable("Wrong argument supplied");
542 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
543 const Decl *Tmpl, Decl *New,
544 LateInstantiatedAttrVec *LateAttrs,
545 LocalInstantiationScope *OuterMostScope) {
546 for (const auto *TmplAttr : Tmpl->attrs()) {
547 // FIXME: This should be generalized to more than just the AlignedAttr.
548 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
549 if (Aligned && Aligned->isAlignmentDependent()) {
550 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
554 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
555 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
559 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
560 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
564 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
565 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
570 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
571 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
572 cast<FunctionDecl>(New));
576 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
577 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
578 cast<FunctionDecl>(New));
582 if (const auto *CUDALaunchBounds =
583 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
584 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
585 *CUDALaunchBounds, New);
589 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
590 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
594 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
595 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
599 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
600 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
604 if (const auto *AMDGPUFlatWorkGroupSize =
605 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
606 instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
607 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
610 if (const auto *AMDGPUFlatWorkGroupSize =
611 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
612 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
613 *AMDGPUFlatWorkGroupSize, New);
616 // Existing DLL attribute on the instantiation takes precedence.
617 if (TmplAttr->getKind() == attr::DLLExport ||
618 TmplAttr->getKind() == attr::DLLImport) {
619 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
624 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
625 AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
629 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
630 isa<CFConsumedAttr>(TmplAttr)) {
631 AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
632 /*template instantiation=*/true);
636 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
637 if (!New->hasAttr<PointerAttr>())
638 New->addAttr(A->clone(Context));
642 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
643 if (!New->hasAttr<OwnerAttr>())
644 New->addAttr(A->clone(Context));
648 assert(!TmplAttr->isPackExpansion());
649 if (TmplAttr->isLateParsed() && LateAttrs) {
650 // Late parsed attributes must be instantiated and attached after the
651 // enclosing class has been instantiated. See Sema::InstantiateClass.
652 LocalInstantiationScope *Saved = nullptr;
653 if (CurrentInstantiationScope)
654 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
655 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
657 // Allow 'this' within late-parsed attributes.
658 auto *ND = cast<NamedDecl>(New);
659 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
660 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
661 ND->isCXXInstanceMember());
663 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
664 *this, TemplateArgs);
666 New->addAttr(NewAttr);
671 /// Get the previous declaration of a declaration for the purposes of template
672 /// instantiation. If this finds a previous declaration, then the previous
673 /// declaration of the instantiation of D should be an instantiation of the
674 /// result of this function.
675 template<typename DeclT>
676 static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
677 DeclT *Result = D->getPreviousDecl();
679 // If the declaration is within a class, and the previous declaration was
680 // merged from a different definition of that class, then we don't have a
681 // previous declaration for the purpose of template instantiation.
682 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
683 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
690 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
691 llvm_unreachable("Translation units cannot be instantiated");
695 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
696 llvm_unreachable("pragma comment cannot be instantiated");
699 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
700 PragmaDetectMismatchDecl *D) {
701 llvm_unreachable("pragma comment cannot be instantiated");
705 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
706 llvm_unreachable("extern \"C\" context cannot be instantiated");
710 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
711 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
713 Owner->addDecl(Inst);
718 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
719 llvm_unreachable("Namespaces cannot be instantiated");
723 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
724 NamespaceAliasDecl *Inst
725 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
726 D->getNamespaceLoc(),
729 D->getQualifierLoc(),
730 D->getTargetNameLoc(),
732 Owner->addDecl(Inst);
736 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
738 bool Invalid = false;
739 TypeSourceInfo *DI = D->getTypeSourceInfo();
740 if (DI->getType()->isInstantiationDependentType() ||
741 DI->getType()->isVariablyModifiedType()) {
742 DI = SemaRef.SubstType(DI, TemplateArgs,
743 D->getLocation(), D->getDeclName());
746 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
749 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
752 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
753 // libstdc++ relies upon this bug in its implementation of common_type.
754 // If we happen to be processing that implementation, fake up the g++ ?:
755 // semantics. See LWG issue 2141 for more information on the bug.
756 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
757 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
758 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
759 DT->isReferenceType() &&
760 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
761 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
762 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
763 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
764 // Fold it to the (non-reference) type which g++ would have produced.
765 DI = SemaRef.Context.getTrivialTypeSourceInfo(
766 DI->getType().getNonReferenceType());
768 // Create the new typedef
769 TypedefNameDecl *Typedef;
771 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
772 D->getLocation(), D->getIdentifier(), DI);
774 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
775 D->getLocation(), D->getIdentifier(), DI);
777 Typedef->setInvalidDecl();
779 // If the old typedef was the name for linkage purposes of an anonymous
780 // tag decl, re-establish that relationship for the new typedef.
781 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
782 TagDecl *oldTag = oldTagType->getDecl();
783 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
784 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
785 assert(!newTag->hasNameForLinkage());
786 newTag->setTypedefNameForAnonDecl(Typedef);
790 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
791 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
796 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
798 // If the typedef types are not identical, reject them.
799 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
801 Typedef->setPreviousDecl(InstPrevTypedef);
804 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
806 if (D->getUnderlyingType()->getAs<DependentNameType>())
807 SemaRef.inferGslPointerAttribute(Typedef);
809 Typedef->setAccess(D->getAccess());
814 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
815 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
817 Owner->addDecl(Typedef);
821 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
822 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
824 Owner->addDecl(Typedef);
829 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
830 // Create a local instantiation scope for this type alias template, which
831 // will contain the instantiations of the template parameters.
832 LocalInstantiationScope Scope(SemaRef);
834 TemplateParameterList *TempParams = D->getTemplateParameters();
835 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
839 TypeAliasDecl *Pattern = D->getTemplatedDecl();
841 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
842 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
843 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
844 if (!Found.empty()) {
845 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
849 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
850 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
854 TypeAliasTemplateDecl *Inst
855 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
856 D->getDeclName(), InstParams, AliasInst);
857 AliasInst->setDescribedAliasTemplate(Inst);
858 if (PrevAliasTemplate)
859 Inst->setPreviousDecl(PrevAliasTemplate);
861 Inst->setAccess(D->getAccess());
863 if (!PrevAliasTemplate)
864 Inst->setInstantiatedFromMemberTemplate(D);
866 Owner->addDecl(Inst);
871 Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
872 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
874 NewBD->setReferenced(D->isReferenced());
875 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
879 Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
880 // Transform the bindings first.
881 SmallVector<BindingDecl*, 16> NewBindings;
882 for (auto *OldBD : D->bindings())
883 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
884 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
886 auto *NewDD = cast_or_null<DecompositionDecl>(
887 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
889 if (!NewDD || NewDD->isInvalidDecl())
890 for (auto *NewBD : NewBindings)
891 NewBD->setInvalidDecl();
896 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
897 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
900 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
901 bool InstantiatingVarTemplate,
902 ArrayRef<BindingDecl*> *Bindings) {
904 // Do substitution on the type of the declaration
905 TypeSourceInfo *DI = SemaRef.SubstType(
906 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
907 D->getDeclName(), /*AllowDeducedTST*/true);
911 if (DI->getType()->isFunctionType()) {
912 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
913 << D->isStaticDataMember() << DI->getType();
917 DeclContext *DC = Owner;
918 if (D->isLocalExternDecl())
919 SemaRef.adjustContextForLocalExternDecl(DC);
921 // Build the instantiated declaration.
924 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
925 D->getLocation(), DI->getType(), DI,
926 D->getStorageClass(), *Bindings);
928 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
929 D->getLocation(), D->getIdentifier(), DI->getType(),
930 DI, D->getStorageClass());
932 // In ARC, infer 'retaining' for variables of retainable type.
933 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
934 SemaRef.inferObjCARCLifetime(Var))
935 Var->setInvalidDecl();
937 if (SemaRef.getLangOpts().OpenCL)
938 SemaRef.deduceOpenCLAddressSpace(Var);
940 // Substitute the nested name specifier, if any.
941 if (SubstQualifier(D, Var))
944 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
945 StartingScope, InstantiatingVarTemplate);
947 if (D->isNRVOVariable()) {
948 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
949 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict))
950 Var->setNRVOVariable(true);
953 Var->setImplicit(D->isImplicit());
955 if (Var->isStaticLocal())
956 SemaRef.CheckStaticLocalForDllExport(Var);
961 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
963 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
964 D->getAccessSpecifierLoc(), D->getColonLoc());
965 Owner->addHiddenDecl(AD);
969 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
970 bool Invalid = false;
971 TypeSourceInfo *DI = D->getTypeSourceInfo();
972 if (DI->getType()->isInstantiationDependentType() ||
973 DI->getType()->isVariablyModifiedType()) {
974 DI = SemaRef.SubstType(DI, TemplateArgs,
975 D->getLocation(), D->getDeclName());
977 DI = D->getTypeSourceInfo();
979 } else if (DI->getType()->isFunctionType()) {
980 // C++ [temp.arg.type]p3:
981 // If a declaration acquires a function type through a type
982 // dependent on a template-parameter and this causes a
983 // declaration that does not use the syntactic form of a
984 // function declarator to have function type, the program is
986 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
991 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
994 Expr *BitWidth = D->getBitWidth();
998 // The bit-width expression is a constant expression.
999 EnterExpressionEvaluationContext Unevaluated(
1000 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1002 ExprResult InstantiatedBitWidth
1003 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1004 if (InstantiatedBitWidth.isInvalid()) {
1008 BitWidth = InstantiatedBitWidth.getAs<Expr>();
1011 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1013 cast<RecordDecl>(Owner),
1017 D->getInClassInitStyle(),
1018 D->getInnerLocStart(),
1022 cast<Decl>(Owner)->setInvalidDecl();
1026 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1028 if (Field->hasAttrs())
1029 SemaRef.CheckAlignasUnderalignment(Field);
1032 Field->setInvalidDecl();
1034 if (!Field->getDeclName()) {
1035 // Keep track of where this decl came from.
1036 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1038 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1039 if (Parent->isAnonymousStructOrUnion() &&
1040 Parent->getRedeclContext()->isFunctionOrMethod())
1041 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1044 Field->setImplicit(D->isImplicit());
1045 Field->setAccess(D->getAccess());
1046 Owner->addDecl(Field);
1051 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1052 bool Invalid = false;
1053 TypeSourceInfo *DI = D->getTypeSourceInfo();
1055 if (DI->getType()->isVariablyModifiedType()) {
1056 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1059 } else if (DI->getType()->isInstantiationDependentType()) {
1060 DI = SemaRef.SubstType(DI, TemplateArgs,
1061 D->getLocation(), D->getDeclName());
1063 DI = D->getTypeSourceInfo();
1065 } else if (DI->getType()->isFunctionType()) {
1066 // C++ [temp.arg.type]p3:
1067 // If a declaration acquires a function type through a type
1068 // dependent on a template-parameter and this causes a
1069 // declaration that does not use the syntactic form of a
1070 // function declarator to have function type, the program is
1072 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1077 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1080 MSPropertyDecl *Property = MSPropertyDecl::Create(
1081 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1082 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1084 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1088 Property->setInvalidDecl();
1090 Property->setAccess(D->getAccess());
1091 Owner->addDecl(Property);
1096 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1097 NamedDecl **NamedChain =
1098 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1101 for (auto *PI : D->chain()) {
1102 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1107 NamedChain[i++] = Next;
1110 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1111 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1112 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1113 {NamedChain, D->getChainingSize()});
1115 for (const auto *Attr : D->attrs())
1116 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1118 IndirectField->setImplicit(D->isImplicit());
1119 IndirectField->setAccess(D->getAccess());
1120 Owner->addDecl(IndirectField);
1121 return IndirectField;
1124 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1125 // Handle friend type expressions by simply substituting template
1126 // parameters into the pattern type and checking the result.
1127 if (TypeSourceInfo *Ty = D->getFriendType()) {
1128 TypeSourceInfo *InstTy;
1129 // If this is an unsupported friend, don't bother substituting template
1130 // arguments into it. The actual type referred to won't be used by any
1131 // parts of Clang, and may not be valid for instantiating. Just use the
1132 // same info for the instantiated friend.
1133 if (D->isUnsupportedFriend()) {
1136 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1137 D->getLocation(), DeclarationName());
1142 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
1143 D->getFriendLoc(), InstTy);
1147 FD->setAccess(AS_public);
1148 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1153 NamedDecl *ND = D->getFriendDecl();
1154 assert(ND && "friend decl must be a decl or a type!");
1156 // All of the Visit implementations for the various potential friend
1157 // declarations have to be carefully written to work for friend
1158 // objects, with the most important detail being that the target
1159 // decl should almost certainly not be placed in Owner.
1160 Decl *NewND = Visit(ND);
1161 if (!NewND) return nullptr;
1164 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1165 cast<NamedDecl>(NewND), D->getFriendLoc());
1166 FD->setAccess(AS_public);
1167 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1172 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1173 Expr *AssertExpr = D->getAssertExpr();
1175 // The expression in a static assertion is a constant expression.
1176 EnterExpressionEvaluationContext Unevaluated(
1177 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1179 ExprResult InstantiatedAssertExpr
1180 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1181 if (InstantiatedAssertExpr.isInvalid())
1184 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
1185 InstantiatedAssertExpr.get(),
1191 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1192 EnumDecl *PrevDecl = nullptr;
1193 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1194 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1197 if (!Prev) return nullptr;
1198 PrevDecl = cast<EnumDecl>(Prev);
1202 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1203 D->getLocation(), D->getIdentifier(), PrevDecl,
1204 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1206 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1207 // If we have type source information for the underlying type, it means it
1208 // has been explicitly set by the user. Perform substitution on it before
1210 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1211 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1213 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1214 Enum->setIntegerType(SemaRef.Context.IntTy);
1216 Enum->setIntegerTypeSourceInfo(NewTI);
1218 assert(!D->getIntegerType()->isDependentType()
1219 && "Dependent type without type source info");
1220 Enum->setIntegerType(D->getIntegerType());
1224 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1226 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1227 Enum->setAccess(D->getAccess());
1228 // Forward the mangling number from the template to the instantiated decl.
1229 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1230 // See if the old tag was defined along with a declarator.
1231 // If it did, mark the new tag as being associated with that declarator.
1232 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1233 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1234 // See if the old tag was defined along with a typedef.
1235 // If it did, mark the new tag as being associated with that typedef.
1236 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1237 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1238 if (SubstQualifier(D, Enum)) return nullptr;
1239 Owner->addDecl(Enum);
1241 EnumDecl *Def = D->getDefinition();
1242 if (Def && Def != D) {
1243 // If this is an out-of-line definition of an enum member template, check
1244 // that the underlying types match in the instantiation of both
1246 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1247 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1248 QualType DefnUnderlying =
1249 SemaRef.SubstType(TI->getType(), TemplateArgs,
1250 UnderlyingLoc, DeclarationName());
1251 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1252 DefnUnderlying, /*IsFixed=*/true, Enum);
1256 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1257 // specialization causes the implicit instantiation of the declarations, but
1258 // not the definitions of scoped member enumerations.
1260 // DR1484 clarifies that enumeration definitions inside of a template
1261 // declaration aren't considered entities that can be separately instantiated
1262 // from the rest of the entity they are declared inside of.
1263 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1264 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1265 InstantiateEnumDefinition(Enum, Def);
1271 void TemplateDeclInstantiator::InstantiateEnumDefinition(
1272 EnumDecl *Enum, EnumDecl *Pattern) {
1273 Enum->startDefinition();
1275 // Update the location to refer to the definition.
1276 Enum->setLocation(Pattern->getLocation());
1278 SmallVector<Decl*, 4> Enumerators;
1280 EnumConstantDecl *LastEnumConst = nullptr;
1281 for (auto *EC : Pattern->enumerators()) {
1282 // The specified value for the enumerator.
1283 ExprResult Value((Expr *)nullptr);
1284 if (Expr *UninstValue = EC->getInitExpr()) {
1285 // The enumerator's value expression is a constant expression.
1286 EnterExpressionEvaluationContext Unevaluated(
1287 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1289 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1292 // Drop the initial value and continue.
1293 bool isInvalid = false;
1294 if (Value.isInvalid()) {
1299 EnumConstantDecl *EnumConst
1300 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1301 EC->getLocation(), EC->getIdentifier(),
1306 EnumConst->setInvalidDecl();
1307 Enum->setInvalidDecl();
1311 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1313 EnumConst->setAccess(Enum->getAccess());
1314 Enum->addDecl(EnumConst);
1315 Enumerators.push_back(EnumConst);
1316 LastEnumConst = EnumConst;
1318 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1319 !Enum->isScoped()) {
1320 // If the enumeration is within a function or method, record the enum
1321 // constant as a local.
1322 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1327 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1328 Enumerators, nullptr, ParsedAttributesView());
1331 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1332 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1336 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1337 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1340 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1341 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1343 // Create a local instantiation scope for this class template, which
1344 // will contain the instantiations of the template parameters.
1345 LocalInstantiationScope Scope(SemaRef);
1346 TemplateParameterList *TempParams = D->getTemplateParameters();
1347 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1351 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1353 // Instantiate the qualifier. We have to do this first in case
1354 // we're a friend declaration, because if we are then we need to put
1355 // the new declaration in the appropriate context.
1356 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1358 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1364 CXXRecordDecl *PrevDecl = nullptr;
1365 ClassTemplateDecl *PrevClassTemplate = nullptr;
1367 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1368 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1369 if (!Found.empty()) {
1370 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1371 if (PrevClassTemplate)
1372 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1376 // If this isn't a friend, then it's a member template, in which
1377 // case we just want to build the instantiation in the
1378 // specialization. If it is a friend, we want to build it in
1379 // the appropriate context.
1380 DeclContext *DC = Owner;
1384 SS.Adopt(QualifierLoc);
1385 DC = SemaRef.computeDeclContext(SS);
1386 if (!DC) return nullptr;
1388 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1389 Pattern->getDeclContext(),
1393 // Look for a previous declaration of the template in the owning
1395 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1396 Sema::LookupOrdinaryName,
1397 SemaRef.forRedeclarationInCurContext());
1398 SemaRef.LookupQualifiedName(R, DC);
1400 if (R.isSingleResult()) {
1401 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1402 if (PrevClassTemplate)
1403 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1406 if (!PrevClassTemplate && QualifierLoc) {
1407 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1408 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1409 << QualifierLoc.getSourceRange();
1413 bool AdoptedPreviousTemplateParams = false;
1414 if (PrevClassTemplate) {
1415 bool Complain = true;
1417 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1418 // template for struct std::tr1::__detail::_Map_base, where the
1419 // template parameters of the friend declaration don't match the
1420 // template parameters of the original declaration. In this one
1421 // case, we don't complain about the ill-formed friend
1423 if (isFriend && Pattern->getIdentifier() &&
1424 Pattern->getIdentifier()->isStr("_Map_base") &&
1425 DC->isNamespace() &&
1426 cast<NamespaceDecl>(DC)->getIdentifier() &&
1427 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
1428 DeclContext *DCParent = DC->getParent();
1429 if (DCParent->isNamespace() &&
1430 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1431 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
1432 if (cast<Decl>(DCParent)->isInStdNamespace())
1437 TemplateParameterList *PrevParams
1438 = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
1440 // Make sure the parameter lists match.
1441 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
1443 Sema::TPL_TemplateMatch)) {
1447 AdoptedPreviousTemplateParams = true;
1448 InstParams = PrevParams;
1451 // Do some additional validation, then merge default arguments
1452 // from the existing declarations.
1453 if (!AdoptedPreviousTemplateParams &&
1454 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1455 Sema::TPC_ClassTemplate))
1460 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1461 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1462 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1463 /*DelayTypeCreation=*/true);
1466 RecordInst->setQualifierInfo(QualifierLoc);
1468 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1471 ClassTemplateDecl *Inst
1472 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1473 D->getIdentifier(), InstParams, RecordInst);
1474 assert(!(isFriend && Owner->isDependentContext()));
1475 Inst->setPreviousDecl(PrevClassTemplate);
1477 RecordInst->setDescribedClassTemplate(Inst);
1480 if (PrevClassTemplate)
1481 Inst->setAccess(PrevClassTemplate->getAccess());
1483 Inst->setAccess(D->getAccess());
1485 Inst->setObjectOfFriendDecl();
1486 // TODO: do we want to track the instantiation progeny of this
1487 // friend target decl?
1489 Inst->setAccess(D->getAccess());
1490 if (!PrevClassTemplate)
1491 Inst->setInstantiatedFromMemberTemplate(D);
1494 // Trigger creation of the type for the instantiation.
1495 SemaRef.Context.getInjectedClassNameType(RecordInst,
1496 Inst->getInjectedClassNameSpecialization());
1498 // Finish handling of friends.
1500 DC->makeDeclVisibleInContext(Inst);
1501 Inst->setLexicalDeclContext(Owner);
1502 RecordInst->setLexicalDeclContext(Owner);
1506 if (D->isOutOfLine()) {
1507 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1508 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1511 Owner->addDecl(Inst);
1513 if (!PrevClassTemplate) {
1514 // Queue up any out-of-line partial specializations of this member
1515 // class template; the client will force their instantiation once
1516 // the enclosing class has been instantiated.
1517 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1518 D->getPartialSpecializations(PartialSpecs);
1519 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1520 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1521 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1528 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1529 ClassTemplatePartialSpecializationDecl *D) {
1530 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1532 // Lookup the already-instantiated declaration in the instantiation
1533 // of the class template and return that.
1534 DeclContext::lookup_result Found
1535 = Owner->lookup(ClassTemplate->getDeclName());
1539 ClassTemplateDecl *InstClassTemplate
1540 = dyn_cast<ClassTemplateDecl>(Found.front());
1541 if (!InstClassTemplate)
1544 if (ClassTemplatePartialSpecializationDecl *Result
1545 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1548 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1551 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1552 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1553 "Only static data member templates are allowed.");
1555 // Create a local instantiation scope for this variable template, which
1556 // will contain the instantiations of the template parameters.
1557 LocalInstantiationScope Scope(SemaRef);
1558 TemplateParameterList *TempParams = D->getTemplateParameters();
1559 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1563 VarDecl *Pattern = D->getTemplatedDecl();
1564 VarTemplateDecl *PrevVarTemplate = nullptr;
1566 if (getPreviousDeclForInstantiation(Pattern)) {
1567 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1569 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1573 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1574 /*InstantiatingVarTemplate=*/true));
1575 if (!VarInst) return nullptr;
1577 DeclContext *DC = Owner;
1579 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1580 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1582 VarInst->setDescribedVarTemplate(Inst);
1583 Inst->setPreviousDecl(PrevVarTemplate);
1585 Inst->setAccess(D->getAccess());
1586 if (!PrevVarTemplate)
1587 Inst->setInstantiatedFromMemberTemplate(D);
1589 if (D->isOutOfLine()) {
1590 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1591 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1594 Owner->addDecl(Inst);
1596 if (!PrevVarTemplate) {
1597 // Queue up any out-of-line partial specializations of this member
1598 // variable template; the client will force their instantiation once
1599 // the enclosing class has been instantiated.
1600 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1601 D->getPartialSpecializations(PartialSpecs);
1602 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1603 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1604 OutOfLineVarPartialSpecs.push_back(
1605 std::make_pair(Inst, PartialSpecs[I]));
1611 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1612 VarTemplatePartialSpecializationDecl *D) {
1613 assert(D->isStaticDataMember() &&
1614 "Only static data member templates are allowed.");
1616 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1618 // Lookup the already-instantiated declaration and return that.
1619 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1620 assert(!Found.empty() && "Instantiation found nothing?");
1622 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1623 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1625 if (VarTemplatePartialSpecializationDecl *Result =
1626 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1629 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1633 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1634 // Create a local instantiation scope for this function template, which
1635 // will contain the instantiations of the template parameters and then get
1636 // merged with the local instantiation scope for the function template
1638 LocalInstantiationScope Scope(SemaRef);
1640 TemplateParameterList *TempParams = D->getTemplateParameters();
1641 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1645 FunctionDecl *Instantiated = nullptr;
1646 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1647 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1650 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1651 D->getTemplatedDecl(),
1657 // Link the instantiated function template declaration to the function
1658 // template from which it was instantiated.
1659 FunctionTemplateDecl *InstTemplate
1660 = Instantiated->getDescribedFunctionTemplate();
1661 InstTemplate->setAccess(D->getAccess());
1662 assert(InstTemplate &&
1663 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1665 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1667 // Link the instantiation back to the pattern *unless* this is a
1668 // non-definition friend declaration.
1669 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1670 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1671 InstTemplate->setInstantiatedFromMemberTemplate(D);
1673 // Make declarations visible in the appropriate context.
1675 Owner->addDecl(InstTemplate);
1676 } else if (InstTemplate->getDeclContext()->isRecord() &&
1677 !getPreviousDeclForInstantiation(D)) {
1678 SemaRef.CheckFriendAccess(InstTemplate);
1681 return InstTemplate;
1684 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1685 CXXRecordDecl *PrevDecl = nullptr;
1686 if (D->isInjectedClassName())
1687 PrevDecl = cast<CXXRecordDecl>(Owner);
1688 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1689 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1692 if (!Prev) return nullptr;
1693 PrevDecl = cast<CXXRecordDecl>(Prev);
1696 CXXRecordDecl *Record = CXXRecordDecl::Create(
1697 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
1698 D->getLocation(), D->getIdentifier(), PrevDecl);
1700 // Substitute the nested name specifier, if any.
1701 if (SubstQualifier(D, Record))
1704 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1707 Record->setImplicit(D->isImplicit());
1708 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1709 // the tag decls introduced by friend class declarations don't have an access
1710 // specifier. Remove once this area of the code gets sorted out.
1711 if (D->getAccess() != AS_none)
1712 Record->setAccess(D->getAccess());
1713 if (!D->isInjectedClassName())
1714 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1716 // If the original function was part of a friend declaration,
1717 // inherit its namespace state.
1718 if (D->getFriendObjectKind())
1719 Record->setObjectOfFriendDecl();
1721 // Make sure that anonymous structs and unions are recorded.
1722 if (D->isAnonymousStructOrUnion())
1723 Record->setAnonymousStructOrUnion(true);
1725 if (D->isLocalClass())
1726 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1728 // Forward the mangling number from the template to the instantiated decl.
1729 SemaRef.Context.setManglingNumber(Record,
1730 SemaRef.Context.getManglingNumber(D));
1732 // See if the old tag was defined along with a declarator.
1733 // If it did, mark the new tag as being associated with that declarator.
1734 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1735 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1737 // See if the old tag was defined along with a typedef.
1738 // If it did, mark the new tag as being associated with that typedef.
1739 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1740 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1742 Owner->addDecl(Record);
1744 // DR1484 clarifies that the members of a local class are instantiated as part
1745 // of the instantiation of their enclosing entity.
1746 if (D->isCompleteDefinition() && D->isLocalClass()) {
1747 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
1749 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1750 TSK_ImplicitInstantiation,
1753 // For nested local classes, we will instantiate the members when we
1754 // reach the end of the outermost (non-nested) local class.
1755 if (!D->isCXXClassMember())
1756 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1757 TSK_ImplicitInstantiation);
1759 // This class may have local implicit instantiations that need to be
1760 // performed within this scope.
1761 LocalInstantiations.perform();
1764 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1769 /// Adjust the given function type for an instantiation of the
1770 /// given declaration, to cope with modifications to the function's type that
1771 /// aren't reflected in the type-source information.
1773 /// \param D The declaration we're instantiating.
1774 /// \param TInfo The already-instantiated type.
1775 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1777 TypeSourceInfo *TInfo) {
1778 const FunctionProtoType *OrigFunc
1779 = D->getType()->castAs<FunctionProtoType>();
1780 const FunctionProtoType *NewFunc
1781 = TInfo->getType()->castAs<FunctionProtoType>();
1782 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1783 return TInfo->getType();
1785 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1786 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1787 return Context.getFunctionType(NewFunc->getReturnType(),
1788 NewFunc->getParamTypes(), NewEPI);
1791 /// Normal class members are of more specific types and therefore
1792 /// don't make it here. This function serves three purposes:
1793 /// 1) instantiating function templates
1794 /// 2) substituting friend declarations
1795 /// 3) substituting deduction guide declarations for nested class templates
1796 Decl *TemplateDeclInstantiator::VisitFunctionDecl(
1797 FunctionDecl *D, TemplateParameterList *TemplateParams,
1798 RewriteKind FunctionRewriteKind) {
1799 // Check whether there is already a function template specialization for
1800 // this declaration.
1801 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1802 if (FunctionTemplate && !TemplateParams) {
1803 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1805 void *InsertPos = nullptr;
1806 FunctionDecl *SpecFunc
1807 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1809 // If we already have a function template specialization, return it.
1815 if (FunctionTemplate)
1816 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1818 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1820 bool MergeWithParentScope = (TemplateParams != nullptr) ||
1821 Owner->isFunctionOrMethod() ||
1822 !(isa<Decl>(Owner) &&
1823 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1824 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1826 ExplicitSpecifier InstantiatedExplicitSpecifier;
1827 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
1828 InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
1829 SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
1830 if (InstantiatedExplicitSpecifier.isInvalid())
1834 SmallVector<ParmVarDecl *, 4> Params;
1835 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1838 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1840 if (TemplateParams && TemplateParams->size()) {
1842 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
1843 if (LastParam && LastParam->isImplicit() &&
1844 LastParam->hasTypeConstraint()) {
1845 // In abbreviated templates, the type-constraints of invented template
1846 // type parameters are instantiated with the function type, invalidating
1847 // the TemplateParameterList which relied on the template type parameter
1848 // not having a type constraint. Recreate the TemplateParameterList with
1849 // the updated parameter list.
1850 TemplateParams = TemplateParameterList::Create(
1851 SemaRef.Context, TemplateParams->getTemplateLoc(),
1852 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
1853 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
1857 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1859 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1865 // FIXME: Concepts: Do not substitute into constraint expressions
1866 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
1867 if (TrailingRequiresClause) {
1868 EnterExpressionEvaluationContext ConstantEvaluated(
1869 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
1870 ExprResult SubstRC = SemaRef.SubstExpr(TrailingRequiresClause,
1872 if (SubstRC.isInvalid())
1874 TrailingRequiresClause = SubstRC.get();
1875 if (!SemaRef.CheckConstraintExpression(TrailingRequiresClause))
1879 // If we're instantiating a local function declaration, put the result
1880 // in the enclosing namespace; otherwise we need to find the instantiated
1883 if (D->isLocalExternDecl()) {
1885 SemaRef.adjustContextForLocalExternDecl(DC);
1886 } else if (isFriend && QualifierLoc) {
1888 SS.Adopt(QualifierLoc);
1889 DC = SemaRef.computeDeclContext(SS);
1890 if (!DC) return nullptr;
1892 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1896 DeclarationNameInfo NameInfo
1897 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1899 if (FunctionRewriteKind != RewriteKind::None)
1900 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
1902 FunctionDecl *Function;
1903 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
1904 Function = CXXDeductionGuideDecl::Create(
1905 SemaRef.Context, DC, D->getInnerLocStart(),
1906 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
1907 D->getSourceRange().getEnd());
1908 if (DGuide->isCopyDeductionCandidate())
1909 cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
1910 Function->setAccess(D->getAccess());
1912 Function = FunctionDecl::Create(
1913 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
1914 D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(),
1915 D->hasWrittenPrototype(), D->getConstexprKind(),
1916 TrailingRequiresClause);
1917 Function->setRangeEnd(D->getSourceRange().getEnd());
1921 Function->setImplicitlyInline();
1924 Function->setQualifierInfo(QualifierLoc);
1926 if (D->isLocalExternDecl())
1927 Function->setLocalExternDecl();
1929 DeclContext *LexicalDC = Owner;
1930 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1931 assert(D->getDeclContext()->isFileContext());
1932 LexicalDC = D->getDeclContext();
1935 Function->setLexicalDeclContext(LexicalDC);
1937 // Attach the parameters
1938 for (unsigned P = 0; P < Params.size(); ++P)
1940 Params[P]->setOwningFunction(Function);
1941 Function->setParams(Params);
1943 if (TrailingRequiresClause)
1944 Function->setTrailingRequiresClause(TrailingRequiresClause);
1946 if (TemplateParams) {
1947 // Our resulting instantiation is actually a function template, since we
1948 // are substituting only the outer template parameters. For example, given
1950 // template<typename T>
1952 // template<typename U> friend void f(T, U);
1957 // We are instantiating the friend function template "f" within X<int>,
1958 // which means substituting int for T, but leaving "f" as a friend function
1960 // Build the function template itself.
1961 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1962 Function->getLocation(),
1963 Function->getDeclName(),
1964 TemplateParams, Function);
1965 Function->setDescribedFunctionTemplate(FunctionTemplate);
1967 FunctionTemplate->setLexicalDeclContext(LexicalDC);
1969 if (isFriend && D->isThisDeclarationADefinition()) {
1970 FunctionTemplate->setInstantiatedFromMemberTemplate(
1971 D->getDescribedFunctionTemplate());
1973 } else if (FunctionTemplate) {
1974 // Record this function template specialization.
1975 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1976 Function->setFunctionTemplateSpecialization(FunctionTemplate,
1977 TemplateArgumentList::CreateCopy(SemaRef.Context,
1979 /*InsertPos=*/nullptr);
1980 } else if (isFriend && D->isThisDeclarationADefinition()) {
1981 // Do not connect the friend to the template unless it's actually a
1982 // definition. We don't want non-template functions to be marked as being
1983 // template instantiations.
1984 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1988 Function->setObjectOfFriendDecl();
1990 if (InitFunctionInstantiation(Function, D))
1991 Function->setInvalidDecl();
1993 bool IsExplicitSpecialization = false;
1995 LookupResult Previous(
1996 SemaRef, Function->getDeclName(), SourceLocation(),
1997 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1998 : Sema::LookupOrdinaryName,
1999 D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
2000 : SemaRef.forRedeclarationInCurContext());
2002 if (DependentFunctionTemplateSpecializationInfo *Info
2003 = D->getDependentSpecializationInfo()) {
2004 assert(isFriend && "non-friend has dependent specialization info?");
2006 // Instantiate the explicit template arguments.
2007 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2008 Info->getRAngleLoc());
2009 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2010 ExplicitArgs, TemplateArgs))
2013 // Map the candidate templates to their instantiations.
2014 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2015 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2016 Info->getTemplate(I),
2018 if (!Temp) return nullptr;
2020 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2023 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2026 Function->setInvalidDecl();
2028 IsExplicitSpecialization = true;
2029 } else if (const ASTTemplateArgumentListInfo *Info =
2030 D->getTemplateSpecializationArgsAsWritten()) {
2031 // The name of this function was written as a template-id.
2032 SemaRef.LookupQualifiedName(Previous, DC);
2034 // Instantiate the explicit template arguments.
2035 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2036 Info->getRAngleLoc());
2037 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2038 ExplicitArgs, TemplateArgs))
2041 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2044 Function->setInvalidDecl();
2046 IsExplicitSpecialization = true;
2047 } else if (TemplateParams || !FunctionTemplate) {
2048 // Look only into the namespace where the friend would be declared to
2049 // find a previous declaration. This is the innermost enclosing namespace,
2050 // as described in ActOnFriendFunctionDecl.
2051 SemaRef.LookupQualifiedName(Previous, DC);
2053 // In C++, the previous declaration we find might be a tag type
2054 // (class or enum). In this case, the new declaration will hide the
2055 // tag type. Note that this does does not apply if we're declaring a
2056 // typedef (C++ [dcl.typedef]p4).
2057 if (Previous.isSingleTagDecl())
2061 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2062 IsExplicitSpecialization);
2064 NamedDecl *PrincipalDecl = (TemplateParams
2065 ? cast<NamedDecl>(FunctionTemplate)
2068 // If the original function was part of a friend declaration,
2069 // inherit its namespace state and add it to the owner.
2071 Function->setObjectOfFriendDecl();
2072 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2073 FT->setObjectOfFriendDecl();
2074 DC->makeDeclVisibleInContext(PrincipalDecl);
2076 bool QueuedInstantiation = false;
2078 // C++11 [temp.friend]p4 (DR329):
2079 // When a function is defined in a friend function declaration in a class
2080 // template, the function is instantiated when the function is odr-used.
2081 // The same restrictions on multiple declarations and definitions that
2082 // apply to non-template function declarations and definitions also apply
2083 // to these implicit definitions.
2084 if (D->isThisDeclarationADefinition()) {
2085 SemaRef.CheckForFunctionRedefinition(Function);
2086 if (!Function->isInvalidDecl()) {
2087 for (auto R : Function->redecls()) {
2091 // If some prior declaration of this function has been used, we need
2092 // to instantiate its definition.
2093 if (!QueuedInstantiation && R->isUsed(false)) {
2094 if (MemberSpecializationInfo *MSInfo =
2095 Function->getMemberSpecializationInfo()) {
2096 if (MSInfo->getPointOfInstantiation().isInvalid()) {
2097 SourceLocation Loc = R->getLocation(); // FIXME
2098 MSInfo->setPointOfInstantiation(Loc);
2099 SemaRef.PendingLocalImplicitInstantiations.push_back(
2100 std::make_pair(Function, Loc));
2101 QueuedInstantiation = true;
2109 // Check the template parameter list against the previous declaration. The
2110 // goal here is to pick up default arguments added since the friend was
2111 // declared; we know the template parameter lists match, since otherwise
2112 // we would not have picked this template as the previous declaration.
2113 if (TemplateParams && FunctionTemplate->getPreviousDecl()) {
2114 SemaRef.CheckTemplateParameterList(
2116 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2117 Function->isThisDeclarationADefinition()
2118 ? Sema::TPC_FriendFunctionTemplateDefinition
2119 : Sema::TPC_FriendFunctionTemplate);
2123 if (D->isExplicitlyDefaulted()) {
2124 if (SubstDefaultedFunction(Function, D))
2128 SemaRef.SetDeclDeleted(Function, D->getLocation());
2130 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
2131 DC->makeDeclVisibleInContext(PrincipalDecl);
2133 if (Function->isOverloadedOperator() && !DC->isRecord() &&
2134 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
2135 PrincipalDecl->setNonMemberOperator();
2140 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
2141 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2142 Optional<const ASTTemplateArgumentListInfo *> ClassScopeSpecializationArgs,
2143 RewriteKind FunctionRewriteKind) {
2144 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2145 if (FunctionTemplate && !TemplateParams) {
2146 // We are creating a function template specialization from a function
2147 // template. Check whether there is already a function template
2148 // specialization for this particular set of template arguments.
2149 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2151 void *InsertPos = nullptr;
2152 FunctionDecl *SpecFunc
2153 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2155 // If we already have a function template specialization, return it.
2161 if (FunctionTemplate)
2162 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2164 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2166 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2167 !(isa<Decl>(Owner) &&
2168 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2169 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2171 // Instantiate enclosing template arguments for friends.
2172 SmallVector<TemplateParameterList *, 4> TempParamLists;
2173 unsigned NumTempParamLists = 0;
2174 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2175 TempParamLists.resize(NumTempParamLists);
2176 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2177 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2178 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2181 TempParamLists[I] = InstParams;
2185 ExplicitSpecifier InstantiatedExplicitSpecifier =
2186 instantiateExplicitSpecifier(SemaRef, TemplateArgs,
2187 ExplicitSpecifier::getFromDecl(D), D);
2188 if (InstantiatedExplicitSpecifier.isInvalid())
2191 SmallVector<ParmVarDecl *, 4> Params;
2192 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2195 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2197 if (TemplateParams && TemplateParams->size()) {
2199 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2200 if (LastParam && LastParam->isImplicit() &&
2201 LastParam->hasTypeConstraint()) {
2202 // In abbreviated templates, the type-constraints of invented template
2203 // type parameters are instantiated with the function type, invalidating
2204 // the TemplateParameterList which relied on the template type parameter
2205 // not having a type constraint. Recreate the TemplateParameterList with
2206 // the updated parameter list.
2207 TemplateParams = TemplateParameterList::Create(
2208 SemaRef.Context, TemplateParams->getTemplateLoc(),
2209 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2210 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2214 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2216 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2222 // FIXME: Concepts: Do not substitute into constraint expressions
2223 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2224 if (TrailingRequiresClause) {
2225 EnterExpressionEvaluationContext ConstantEvaluated(
2226 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
2227 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
2228 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext,
2229 D->getMethodQualifiers(), ThisContext);
2230 ExprResult SubstRC = SemaRef.SubstExpr(TrailingRequiresClause,
2232 if (SubstRC.isInvalid())
2234 TrailingRequiresClause = SubstRC.get();
2235 if (!SemaRef.CheckConstraintExpression(TrailingRequiresClause))
2239 DeclContext *DC = Owner;
2243 SS.Adopt(QualifierLoc);
2244 DC = SemaRef.computeDeclContext(SS);
2246 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2249 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2250 D->getDeclContext(),
2253 if (!DC) return nullptr;
2256 DeclarationNameInfo NameInfo
2257 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2259 if (FunctionRewriteKind != RewriteKind::None)
2260 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2262 // Build the instantiated method declaration.
2263 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2264 CXXMethodDecl *Method = nullptr;
2266 SourceLocation StartLoc = D->getInnerLocStart();
2267 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2268 Method = CXXConstructorDecl::Create(
2269 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2270 InstantiatedExplicitSpecifier, Constructor->isInlineSpecified(), false,
2271 Constructor->getConstexprKind(), InheritedConstructor(),
2272 TrailingRequiresClause);
2273 Method->setRangeEnd(Constructor->getEndLoc());
2274 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2275 Method = CXXDestructorDecl::Create(
2276 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2277 Destructor->isInlineSpecified(), false, Destructor->getConstexprKind(),
2278 TrailingRequiresClause);
2279 Method->setRangeEnd(Destructor->getEndLoc());
2280 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2281 Method = CXXConversionDecl::Create(
2282 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2283 Conversion->isInlineSpecified(), InstantiatedExplicitSpecifier,
2284 Conversion->getConstexprKind(), Conversion->getEndLoc(),
2285 TrailingRequiresClause);
2287 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2288 Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo,
2289 T, TInfo, SC, D->isInlineSpecified(),
2290 D->getConstexprKind(), D->getEndLoc(),
2291 TrailingRequiresClause);
2295 Method->setImplicitlyInline();
2298 Method->setQualifierInfo(QualifierLoc);
2300 if (TemplateParams) {
2301 // Our resulting instantiation is actually a function template, since we
2302 // are substituting only the outer template parameters. For example, given
2304 // template<typename T>
2306 // template<typename U> void f(T, U);
2311 // We are instantiating the member template "f" within X<int>, which means
2312 // substituting int for T, but leaving "f" as a member function template.
2313 // Build the function template itself.
2314 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2315 Method->getLocation(),
2316 Method->getDeclName(),
2317 TemplateParams, Method);
2319 FunctionTemplate->setLexicalDeclContext(Owner);
2320 FunctionTemplate->setObjectOfFriendDecl();
2321 } else if (D->isOutOfLine())
2322 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2323 Method->setDescribedFunctionTemplate(FunctionTemplate);
2324 } else if (FunctionTemplate) {
2325 // Record this function template specialization.
2326 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2327 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2328 TemplateArgumentList::CreateCopy(SemaRef.Context,
2330 /*InsertPos=*/nullptr);
2331 } else if (!isFriend) {
2332 // Record that this is an instantiation of a member function.
2333 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2336 // If we are instantiating a member function defined
2337 // out-of-line, the instantiation will have the same lexical
2338 // context (which will be a namespace scope) as the template.
2340 if (NumTempParamLists)
2341 Method->setTemplateParameterListsInfo(
2343 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
2345 Method->setLexicalDeclContext(Owner);
2346 Method->setObjectOfFriendDecl();
2347 } else if (D->isOutOfLine())
2348 Method->setLexicalDeclContext(D->getLexicalDeclContext());
2350 // Attach the parameters
2351 for (unsigned P = 0; P < Params.size(); ++P)
2352 Params[P]->setOwningFunction(Method);
2353 Method->setParams(Params);
2355 if (InitMethodInstantiation(Method, D))
2356 Method->setInvalidDecl();
2358 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2359 Sema::ForExternalRedeclaration);
2361 bool IsExplicitSpecialization = false;
2363 // If the name of this function was written as a template-id, instantiate
2364 // the explicit template arguments.
2365 if (DependentFunctionTemplateSpecializationInfo *Info
2366 = D->getDependentSpecializationInfo()) {
2367 assert(isFriend && "non-friend has dependent specialization info?");
2369 // Instantiate the explicit template arguments.
2370 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2371 Info->getRAngleLoc());
2372 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2373 ExplicitArgs, TemplateArgs))
2376 // Map the candidate templates to their instantiations.
2377 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2378 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2379 Info->getTemplate(I),
2381 if (!Temp) return nullptr;
2383 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2386 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2389 Method->setInvalidDecl();
2391 IsExplicitSpecialization = true;
2392 } else if (const ASTTemplateArgumentListInfo *Info =
2393 ClassScopeSpecializationArgs.getValueOr(
2394 D->getTemplateSpecializationArgsAsWritten())) {
2395 SemaRef.LookupQualifiedName(Previous, DC);
2397 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2398 Info->getRAngleLoc());
2399 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2400 ExplicitArgs, TemplateArgs))
2403 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2406 Method->setInvalidDecl();
2408 IsExplicitSpecialization = true;
2409 } else if (ClassScopeSpecializationArgs) {
2410 // Class-scope explicit specialization written without explicit template
2412 SemaRef.LookupQualifiedName(Previous, DC);
2413 if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
2414 Method->setInvalidDecl();
2416 IsExplicitSpecialization = true;
2417 } else if (!FunctionTemplate || TemplateParams || isFriend) {
2418 SemaRef.LookupQualifiedName(Previous, Record);
2420 // In C++, the previous declaration we find might be a tag type
2421 // (class or enum). In this case, the new declaration will hide the
2422 // tag type. Note that this does does not apply if we're declaring a
2423 // typedef (C++ [dcl.typedef]p4).
2424 if (Previous.isSingleTagDecl())
2428 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2429 IsExplicitSpecialization);
2432 SemaRef.CheckPureMethod(Method, SourceRange());
2434 // Propagate access. For a non-friend declaration, the access is
2435 // whatever we're propagating from. For a friend, it should be the
2436 // previous declaration we just found.
2437 if (isFriend && Method->getPreviousDecl())
2438 Method->setAccess(Method->getPreviousDecl()->getAccess());
2440 Method->setAccess(D->getAccess());
2441 if (FunctionTemplate)
2442 FunctionTemplate->setAccess(Method->getAccess());
2444 SemaRef.CheckOverrideControl(Method);
2446 // If a function is defined as defaulted or deleted, mark it as such now.
2447 if (D->isExplicitlyDefaulted()) {
2448 if (SubstDefaultedFunction(Method, D))
2451 if (D->isDeletedAsWritten())
2452 SemaRef.SetDeclDeleted(Method, Method->getLocation());
2454 // If this is an explicit specialization, mark the implicitly-instantiated
2455 // template specialization as being an explicit specialization too.
2456 // FIXME: Is this necessary?
2457 if (IsExplicitSpecialization && !isFriend)
2458 SemaRef.CompleteMemberSpecialization(Method, Previous);
2460 // If there's a function template, let our caller handle it.
2461 if (FunctionTemplate) {
2464 // Don't hide a (potentially) valid declaration with an invalid one.
2465 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2468 // Otherwise, check access to friends and make them visible.
2469 } else if (isFriend) {
2470 // We only need to re-check access for methods which we didn't
2471 // manage to match during parsing.
2472 if (!D->getPreviousDecl())
2473 SemaRef.CheckFriendAccess(Method);
2475 Record->makeDeclVisibleInContext(Method);
2477 // Otherwise, add the declaration. We don't need to do this for
2478 // class-scope specializations because we'll have matched them with
2479 // the appropriate template.
2481 Owner->addDecl(Method);
2484 // PR17480: Honor the used attribute to instantiate member function
2486 if (Method->hasAttr<UsedAttr>()) {
2487 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2489 if (const MemberSpecializationInfo *MSInfo =
2490 A->getMemberSpecializationInfo())
2491 Loc = MSInfo->getPointOfInstantiation();
2492 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2493 Loc = Spec->getPointOfInstantiation();
2494 SemaRef.MarkFunctionReferenced(Loc, Method);
2501 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2502 return VisitCXXMethodDecl(D);
2505 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2506 return VisitCXXMethodDecl(D);
2509 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2510 return VisitCXXMethodDecl(D);
2513 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2514 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2515 /*ExpectParameterPack=*/ false);
2518 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2519 TemplateTypeParmDecl *D) {
2520 // TODO: don't always clone when decls are refcounted.
2521 assert(D->getTypeForDecl()->isTemplateTypeParmType());
2523 Optional<unsigned> NumExpanded;
2525 if (const TypeConstraint *TC = D->getTypeConstraint()) {
2526 if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2527 assert(TC->getTemplateArgsAsWritten() &&
2528 "type parameter can only be an expansion when explicit arguments "
2530 // The template type parameter pack's type is a pack expansion of types.
2531 // Determine whether we need to expand this parameter pack into separate
2533 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2534 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2535 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2537 // Determine whether the set of unexpanded parameter packs can and should
2540 bool RetainExpansion = false;
2541 if (SemaRef.CheckParameterPacksForExpansion(
2542 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2544 SourceRange(TC->getConceptNameLoc(),
2545 TC->hasExplicitTemplateArgs() ?
2546 TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2547 TC->getConceptNameInfo().getEndLoc()),
2548 Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2553 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2554 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2555 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2556 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
2557 D->hasTypeConstraint(), NumExpanded);
2559 Inst->setAccess(AS_public);
2560 Inst->setImplicit(D->isImplicit());
2561 if (auto *TC = D->getTypeConstraint()) {
2562 if (!D->isImplicit()) {
2563 // Invented template parameter type constraints will be instantiated with
2564 // the corresponding auto-typed parameter as it might reference other
2567 // TODO: Concepts: do not instantiate the constraint (delayed constraint
2569 const ASTTemplateArgumentListInfo *TemplArgInfo
2570 = TC->getTemplateArgsAsWritten();
2571 TemplateArgumentListInfo InstArgs;
2574 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
2575 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
2576 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2577 TemplArgInfo->NumTemplateArgs,
2578 InstArgs, TemplateArgs))
2581 if (SemaRef.AttachTypeConstraint(
2582 TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2583 TC->getNamedConcept(), &InstArgs, Inst,
2584 D->isParameterPack()
2585 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2587 : SourceLocation()))
2591 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2592 TypeSourceInfo *InstantiatedDefaultArg =
2593 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2594 D->getDefaultArgumentLoc(), D->getDeclName());
2595 if (InstantiatedDefaultArg)
2596 Inst->setDefaultArgument(InstantiatedDefaultArg);
2599 // Introduce this template parameter's instantiation into the instantiation
2601 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2606 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2607 NonTypeTemplateParmDecl *D) {
2608 // Substitute into the type of the non-type template parameter.
2609 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2610 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2611 SmallVector<QualType, 4> ExpandedParameterPackTypes;
2612 bool IsExpandedParameterPack = false;
2615 bool Invalid = false;
2617 if (D->isExpandedParameterPack()) {
2618 // The non-type template parameter pack is an already-expanded pack
2619 // expansion of types. Substitute into each of the expanded types.
2620 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2621 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2622 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2623 TypeSourceInfo *NewDI =
2624 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2625 D->getLocation(), D->getDeclName());
2630 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2634 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2635 ExpandedParameterPackTypes.push_back(NewT);
2638 IsExpandedParameterPack = true;
2639 DI = D->getTypeSourceInfo();
2641 } else if (D->isPackExpansion()) {
2642 // The non-type template parameter pack's type is a pack expansion of types.
2643 // Determine whether we need to expand this parameter pack into separate
2645 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2646 TypeLoc Pattern = Expansion.getPatternLoc();
2647 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2648 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2650 // Determine whether the set of unexpanded parameter packs can and should
2653 bool RetainExpansion = false;
2654 Optional<unsigned> OrigNumExpansions
2655 = Expansion.getTypePtr()->getNumExpansions();
2656 Optional<unsigned> NumExpansions = OrigNumExpansions;
2657 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2658 Pattern.getSourceRange(),
2661 Expand, RetainExpansion,
2666 for (unsigned I = 0; I != *NumExpansions; ++I) {
2667 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2668 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2675 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2679 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2680 ExpandedParameterPackTypes.push_back(NewT);
2683 // Note that we have an expanded parameter pack. The "type" of this
2684 // expanded parameter pack is the original expansion type, but callers
2685 // will end up using the expanded parameter pack types for type-checking.
2686 IsExpandedParameterPack = true;
2687 DI = D->getTypeSourceInfo();
2690 // We cannot fully expand the pack expansion now, so substitute into the
2691 // pattern and create a new pack expansion type.
2692 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2693 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2699 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
2700 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2708 // Simple case: substitution into a parameter that is not a parameter pack.
2709 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2710 D->getLocation(), D->getDeclName());
2714 // Check that this type is acceptable for a non-type template parameter.
2715 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
2717 T = SemaRef.Context.IntTy;
2722 NonTypeTemplateParmDecl *Param;
2723 if (IsExpandedParameterPack)
2724 Param = NonTypeTemplateParmDecl::Create(
2725 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2726 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2727 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
2728 ExpandedParameterPackTypesAsWritten);
2730 Param = NonTypeTemplateParmDecl::Create(
2731 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2732 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2733 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
2735 if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
2736 if (AutoLoc.isConstrained())
2737 if (SemaRef.AttachTypeConstraint(
2739 IsExpandedParameterPack
2740 ? DI->getTypeLoc().getAs<PackExpansionTypeLoc>()
2742 : SourceLocation()))
2745 Param->setAccess(AS_public);
2746 Param->setImplicit(D->isImplicit());
2748 Param->setInvalidDecl();
2750 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2751 EnterExpressionEvaluationContext ConstantEvaluated(
2752 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2753 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2754 if (!Value.isInvalid())
2755 Param->setDefaultArgument(Value.get());
2758 // Introduce this template parameter's instantiation into the instantiation
2760 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2764 static void collectUnexpandedParameterPacks(
2766 TemplateParameterList *Params,
2767 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2768 for (const auto &P : *Params) {
2769 if (P->isTemplateParameterPack())
2771 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
2772 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2774 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
2775 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2781 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2782 TemplateTemplateParmDecl *D) {
2783 // Instantiate the template parameter list of the template template parameter.
2784 TemplateParameterList *TempParams = D->getTemplateParameters();
2785 TemplateParameterList *InstParams;
2786 SmallVector<TemplateParameterList*, 8> ExpandedParams;
2788 bool IsExpandedParameterPack = false;
2790 if (D->isExpandedParameterPack()) {
2791 // The template template parameter pack is an already-expanded pack
2792 // expansion of template parameters. Substitute into each of the expanded
2794 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2795 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2797 LocalInstantiationScope Scope(SemaRef);
2798 TemplateParameterList *Expansion =
2799 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2802 ExpandedParams.push_back(Expansion);
2805 IsExpandedParameterPack = true;
2806 InstParams = TempParams;
2807 } else if (D->isPackExpansion()) {
2808 // The template template parameter pack expands to a pack of template
2809 // template parameters. Determine whether we need to expand this parameter
2810 // pack into separate parameters.
2811 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2812 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2815 // Determine whether the set of unexpanded parameter packs can and should
2818 bool RetainExpansion = false;
2819 Optional<unsigned> NumExpansions;
2820 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2821 TempParams->getSourceRange(),
2824 Expand, RetainExpansion,
2829 for (unsigned I = 0; I != *NumExpansions; ++I) {
2830 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2831 LocalInstantiationScope Scope(SemaRef);
2832 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2835 ExpandedParams.push_back(Expansion);
2838 // Note that we have an expanded parameter pack. The "type" of this
2839 // expanded parameter pack is the original expansion type, but callers
2840 // will end up using the expanded parameter pack types for type-checking.
2841 IsExpandedParameterPack = true;
2842 InstParams = TempParams;
2844 // We cannot fully expand the pack expansion now, so just substitute
2845 // into the pattern.
2846 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2848 LocalInstantiationScope Scope(SemaRef);
2849 InstParams = SubstTemplateParams(TempParams);
2854 // Perform the actual substitution of template parameters within a new,
2855 // local instantiation scope.
2856 LocalInstantiationScope Scope(SemaRef);
2857 InstParams = SubstTemplateParams(TempParams);
2862 // Build the template template parameter.
2863 TemplateTemplateParmDecl *Param;
2864 if (IsExpandedParameterPack)
2865 Param = TemplateTemplateParmDecl::Create(
2866 SemaRef.Context, Owner, D->getLocation(),
2867 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2868 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
2870 Param = TemplateTemplateParmDecl::Create(
2871 SemaRef.Context, Owner, D->getLocation(),
2872 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2873 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
2874 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2875 NestedNameSpecifierLoc QualifierLoc =
2876 D->getDefaultArgument().getTemplateQualifierLoc();
2878 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2879 TemplateName TName = SemaRef.SubstTemplateName(
2880 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2881 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2882 if (!TName.isNull())
2883 Param->setDefaultArgument(
2885 TemplateArgumentLoc(TemplateArgument(TName),
2886 D->getDefaultArgument().getTemplateQualifierLoc(),
2887 D->getDefaultArgument().getTemplateNameLoc()));
2889 Param->setAccess(AS_public);
2890 Param->setImplicit(D->isImplicit());
2892 // Introduce this template parameter's instantiation into the instantiation
2894 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2899 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2900 // Using directives are never dependent (and never contain any types or
2901 // expressions), so they require no explicit instantiation work.
2903 UsingDirectiveDecl *Inst
2904 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2905 D->getNamespaceKeyLocation(),
2906 D->getQualifierLoc(),
2907 D->getIdentLocation(),
2908 D->getNominatedNamespace(),
2909 D->getCommonAncestor());
2911 // Add the using directive to its declaration context
2912 // only if this is not a function or method.
2913 if (!Owner->isFunctionOrMethod())
2914 Owner->addDecl(Inst);
2919 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2921 // The nested name specifier may be dependent, for example
2922 // template <typename T> struct t {
2923 // struct s1 { T f1(); };
2924 // struct s2 : s1 { using s1::f1; };
2926 // template struct t<int>;
2927 // Here, in using s1::f1, s1 refers to t<T>::s1;
2928 // we need to substitute for t<int>::s1.
2929 NestedNameSpecifierLoc QualifierLoc
2930 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2935 // For an inheriting constructor declaration, the name of the using
2936 // declaration is the name of a constructor in this class, not in the
2938 DeclarationNameInfo NameInfo = D->getNameInfo();
2939 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2940 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
2941 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
2942 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
2944 // We only need to do redeclaration lookups if we're in a class
2945 // scope (in fact, it's not really even possible in non-class
2947 bool CheckRedeclaration = Owner->isRecord();
2949 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2950 Sema::ForVisibleRedeclaration);
2952 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2959 SS.Adopt(QualifierLoc);
2960 if (CheckRedeclaration) {
2961 Prev.setHideTags(false);
2962 SemaRef.LookupQualifiedName(Prev, Owner);
2964 // Check for invalid redeclarations.
2965 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2966 D->hasTypename(), SS,
2967 D->getLocation(), Prev))
2968 NewUD->setInvalidDecl();
2972 if (!NewUD->isInvalidDecl() &&
2973 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
2974 SS, NameInfo, D->getLocation()))
2975 NewUD->setInvalidDecl();
2977 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2978 NewUD->setAccess(D->getAccess());
2979 Owner->addDecl(NewUD);
2981 // Don't process the shadow decls for an invalid decl.
2982 if (NewUD->isInvalidDecl())
2985 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2986 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
2988 bool isFunctionScope = Owner->isFunctionOrMethod();
2990 // Process the shadow decls.
2991 for (auto *Shadow : D->shadows()) {
2992 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
2993 // reconstruct it in the case where it matters.
2994 NamedDecl *OldTarget = Shadow->getTargetDecl();
2995 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
2996 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
2997 OldTarget = BaseShadow;
2999 NamedDecl *InstTarget =
3000 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3001 Shadow->getLocation(), OldTarget, TemplateArgs));
3005 UsingShadowDecl *PrevDecl = nullptr;
3006 if (CheckRedeclaration) {
3007 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
3009 } else if (UsingShadowDecl *OldPrev =
3010 getPreviousDeclForInstantiation(Shadow)) {
3011 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3012 Shadow->getLocation(), OldPrev, TemplateArgs));
3015 UsingShadowDecl *InstShadow =
3016 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
3018 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3020 if (isFunctionScope)
3021 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3027 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3028 // Ignore these; we handle them in bulk when processing the UsingDecl.
3032 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3033 ConstructorUsingShadowDecl *D) {
3034 // Ignore these; we handle them in bulk when processing the UsingDecl.
3038 template <typename T>
3039 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3040 T *D, bool InstantiatingPackElement) {
3041 // If this is a pack expansion, expand it now.
3042 if (D->isPackExpansion() && !InstantiatingPackElement) {
3043 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3044 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3045 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3047 // Determine whether the set of unexpanded parameter packs can and should
3050 bool RetainExpansion = false;
3051 Optional<unsigned> NumExpansions;
3052 if (SemaRef.CheckParameterPacksForExpansion(
3053 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3054 Expand, RetainExpansion, NumExpansions))
3057 // This declaration cannot appear within a function template signature,
3058 // so we can't have a partial argument list for a parameter pack.
3059 assert(!RetainExpansion &&
3060 "should never need to retain an expansion for UsingPackDecl");
3063 // We cannot fully expand the pack expansion now, so substitute into the
3064 // pattern and create a new pack expansion.
3065 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3066 return instantiateUnresolvedUsingDecl(D, true);
3069 // Within a function, we don't have any normal way to check for conflicts
3070 // between shadow declarations from different using declarations in the
3071 // same pack expansion, but this is always ill-formed because all expansions
3072 // must produce (conflicting) enumerators.
3074 // Sadly we can't just reject this in the template definition because it
3075 // could be valid if the pack is empty or has exactly one expansion.
3076 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3077 SemaRef.Diag(D->getEllipsisLoc(),
3078 diag::err_using_decl_redeclaration_expansion);
3082 // Instantiate the slices of this pack and build a UsingPackDecl.
3083 SmallVector<NamedDecl*, 8> Expansions;
3084 for (unsigned I = 0; I != *NumExpansions; ++I) {
3085 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3086 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3089 // Note that we can still get unresolved using declarations here, if we
3090 // had arguments for all packs but the pattern also contained other
3091 // template arguments (this only happens during partial substitution, eg
3092 // into the body of a generic lambda in a function template).
3093 Expansions.push_back(cast<NamedDecl>(Slice));
3096 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3097 if (isDeclWithinFunction(D))
3098 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3102 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3103 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3105 NestedNameSpecifierLoc QualifierLoc
3106 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3112 SS.Adopt(QualifierLoc);
3114 DeclarationNameInfo NameInfo
3115 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3117 // Produce a pack expansion only if we're not instantiating a particular
3118 // slice of a pack expansion.
3119 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3120 SemaRef.ArgumentPackSubstitutionIndex != -1;
3121 SourceLocation EllipsisLoc =
3122 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3124 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3125 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3126 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3127 ParsedAttributesView(),
3128 /*IsInstantiation*/ true);
3130 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3135 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3136 UnresolvedUsingTypenameDecl *D) {
3137 return instantiateUnresolvedUsingDecl(D);
3140 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3141 UnresolvedUsingValueDecl *D) {
3142 return instantiateUnresolvedUsingDecl(D);
3145 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3146 SmallVector<NamedDecl*, 8> Expansions;
3147 for (auto *UD : D->expansions()) {
3148 if (NamedDecl *NewUD =
3149 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3150 Expansions.push_back(NewUD);
3155 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3156 if (isDeclWithinFunction(D))
3157 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3161 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
3162 ClassScopeFunctionSpecializationDecl *Decl) {
3163 CXXMethodDecl *OldFD = Decl->getSpecialization();
3164 return cast_or_null<CXXMethodDecl>(
3165 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
3168 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3169 OMPThreadPrivateDecl *D) {
3170 SmallVector<Expr *, 5> Vars;
3171 for (auto *I : D->varlists()) {
3172 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3173 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3174 Vars.push_back(Var);
3177 OMPThreadPrivateDecl *TD =
3178 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3180 TD->setAccess(AS_public);
3186 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3187 SmallVector<Expr *, 5> Vars;
3188 for (auto *I : D->varlists()) {
3189 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3190 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3191 Vars.push_back(Var);
3193 SmallVector<OMPClause *, 4> Clauses;
3194 // Copy map clauses from the original mapper.
3195 for (OMPClause *C : D->clauselists()) {
3196 auto *AC = cast<OMPAllocatorClause>(C);
3197 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3198 if (!NewE.isUsable())
3200 OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause(
3201 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3202 Clauses.push_back(IC);
3205 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
3206 D->getLocation(), Vars, Clauses, Owner);
3207 if (Res.get().isNull())
3209 return Res.get().getSingleDecl();
3212 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3214 "Requires directive cannot be instantiated within a dependent context");
3217 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3218 OMPDeclareReductionDecl *D) {
3219 // Instantiate type and check if it is allowed.
3220 const bool RequiresInstantiation =
3221 D->getType()->isDependentType() ||
3222 D->getType()->isInstantiationDependentType() ||
3223 D->getType()->containsUnexpandedParameterPack();
3224 QualType SubstReductionType;
3225 if (RequiresInstantiation) {
3226 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
3228 ParsedType::make(SemaRef.SubstType(
3229 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3231 SubstReductionType = D->getType();
3233 if (SubstReductionType.isNull())
3235 Expr *Combiner = D->getCombiner();
3236 Expr *Init = D->getInitializer();
3237 bool IsCorrect = true;
3238 // Create instantiated copy.
3239 std::pair<QualType, SourceLocation> ReductionTypes[] = {
3240 std::make_pair(SubstReductionType, D->getLocation())};
3241 auto *PrevDeclInScope = D->getPrevDeclInScope();
3242 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3243 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3244 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3247 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
3248 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3250 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3251 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3252 Expr *SubstCombiner = nullptr;
3253 Expr *SubstInitializer = nullptr;
3254 // Combiners instantiation sequence.
3256 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
3257 /*S=*/nullptr, NewDRD);
3258 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3259 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3260 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3261 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3262 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3263 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3264 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3265 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3267 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3268 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3270 // Initializers instantiation sequence.
3272 VarDecl *OmpPrivParm = SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
3273 /*S=*/nullptr, NewDRD);
3274 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3275 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3276 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3277 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3278 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3279 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3280 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3281 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3284 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3285 IsCorrect = IsCorrect && OldPrivParm->hasInit();
3287 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3290 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD, SubstInitializer,
3293 IsCorrect = IsCorrect && SubstCombiner &&
3295 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
3296 SubstInitializer) ||
3297 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
3298 !SubstInitializer));
3300 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
3301 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3307 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3308 // Instantiate type and check if it is allowed.
3309 const bool RequiresInstantiation =
3310 D->getType()->isDependentType() ||
3311 D->getType()->isInstantiationDependentType() ||
3312 D->getType()->containsUnexpandedParameterPack();
3313 QualType SubstMapperTy;
3314 DeclarationName VN = D->getVarName();
3315 if (RequiresInstantiation) {
3316 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3318 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3319 D->getLocation(), VN)));
3321 SubstMapperTy = D->getType();
3323 if (SubstMapperTy.isNull())
3325 // Create an instantiated copy of mapper.
3326 auto *PrevDeclInScope = D->getPrevDeclInScope();
3327 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3328 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3329 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3332 OMPDeclareMapperDecl *NewDMD = SemaRef.ActOnOpenMPDeclareMapperDirectiveStart(
3333 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3334 VN, D->getAccess(), PrevDeclInScope);
3335 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3336 SmallVector<OMPClause *, 6> Clauses;
3337 bool IsCorrect = true;
3338 if (!RequiresInstantiation) {
3339 // Copy the mapper variable.
3340 NewDMD->setMapperVarRef(D->getMapperVarRef());
3341 // Copy map clauses from the original mapper.
3342 for (OMPClause *C : D->clauselists())
3343 Clauses.push_back(C);
3345 // Instantiate the mapper variable.
3346 DeclarationNameInfo DirName;
3347 SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3349 (*D->clauselist_begin())->getBeginLoc());
3350 SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3351 NewDMD, /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3352 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3353 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3354 cast<DeclRefExpr>(NewDMD->getMapperVarRef())->getDecl());
3355 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3356 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3358 // Instantiate map clauses.
3359 for (OMPClause *C : D->clauselists()) {
3360 auto *OldC = cast<OMPMapClause>(C);
3361 SmallVector<Expr *, 4> NewVars;
3362 for (Expr *OE : OldC->varlists()) {
3363 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3368 NewVars.push_back(NE);
3372 NestedNameSpecifierLoc NewQualifierLoc =
3373 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3376 SS.Adopt(NewQualifierLoc);
3377 DeclarationNameInfo NewNameInfo = SemaRef.SubstDeclarationNameInfo(
3378 OldC->getMapperIdInfo(), TemplateArgs);
3379 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3381 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
3382 OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
3383 NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
3384 OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
3385 Clauses.push_back(NewC);
3387 SemaRef.EndOpenMPDSABlock(nullptr);
3389 (void)SemaRef.ActOnOpenMPDeclareMapperDirectiveEnd(NewDMD, /*S=*/nullptr,
3396 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3397 OMPCapturedExprDecl * /*D*/) {
3398 llvm_unreachable("Should not be met in templates");
3401 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3402 return VisitFunctionDecl(D, nullptr);
3406 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3407 Decl *Inst = VisitFunctionDecl(D, nullptr);
3408 if (Inst && !D->getDescribedFunctionTemplate())
3409 Owner->addDecl(Inst);
3413 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3414 return VisitCXXMethodDecl(D, nullptr);
3417 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3418 llvm_unreachable("There are only CXXRecordDecls in C++");
3422 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3423 ClassTemplateSpecializationDecl *D) {
3424 // As a MS extension, we permit class-scope explicit specialization
3425 // of member class templates.
3426 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3427 assert(ClassTemplate->getDeclContext()->isRecord() &&
3428 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3429 "can only instantiate an explicit specialization "
3430 "for a member class template");
3432 // Lookup the already-instantiated declaration in the instantiation
3433 // of the class template.
3434 ClassTemplateDecl *InstClassTemplate =
3435 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3436 D->getLocation(), ClassTemplate, TemplateArgs));
3437 if (!InstClassTemplate)
3440 // Substitute into the template arguments of the class template explicit
3442 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3443 castAs<TemplateSpecializationTypeLoc>();
3444 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3445 Loc.getRAngleLoc());
3446 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3447 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
3448 ArgLocs.push_back(Loc.getArgLoc(I));
3449 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
3450 InstTemplateArgs, TemplateArgs))
3453 // Check that the template argument list is well-formed for this
3455 SmallVector<TemplateArgument, 4> Converted;
3456 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
3461 /*UpdateArgsWithConversion=*/true))
3464 // Figure out where to insert this class template explicit specialization
3465 // in the member template's set of class template explicit specializations.
3466 void *InsertPos = nullptr;
3467 ClassTemplateSpecializationDecl *PrevDecl =
3468 InstClassTemplate->findSpecialization(Converted, InsertPos);
3470 // Check whether we've already seen a conflicting instantiation of this
3471 // declaration (for instance, if there was a prior implicit instantiation).
3474 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3475 D->getSpecializationKind(),
3477 PrevDecl->getSpecializationKind(),
3478 PrevDecl->getPointOfInstantiation(),
3482 // If PrevDecl was a definition and D is also a definition, diagnose.
3483 // This happens in cases like:
3485 // template<typename T, typename U>
3487 // template<typename X> struct Inner;
3488 // template<> struct Inner<T> {};
3489 // template<> struct Inner<U> {};
3492 // Outer<int, int> outer; // error: the explicit specializations of Inner
3493 // // have the same signature.
3494 if (PrevDecl && PrevDecl->getDefinition() &&
3495 D->isThisDeclarationADefinition()) {
3496 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3497 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3498 diag::note_previous_definition);
3502 // Create the class template partial specialization declaration.
3503 ClassTemplateSpecializationDecl *InstD =
3504 ClassTemplateSpecializationDecl::Create(
3505 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3506 D->getLocation(), InstClassTemplate, Converted, PrevDecl);
3508 // Add this partial specialization to the set of class template partial
3511 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3513 // Substitute the nested name specifier, if any.
3514 if (SubstQualifier(D, InstD))
3517 // Build the canonical type that describes the converted template
3518 // arguments of the class template explicit specialization.
3519 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3520 TemplateName(InstClassTemplate), Converted,
3521 SemaRef.Context.getRecordType(InstD));
3523 // Build the fully-sugared type for this class template
3524 // specialization as the user wrote in the specialization
3525 // itself. This means that we'll pretty-print the type retrieved
3526 // from the specialization's declaration the way that the user
3527 // actually wrote the specialization, rather than formatting the
3528 // name based on the "canonical" representation used to store the
3529 // template arguments in the specialization.
3530 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3531 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3534 InstD->setAccess(D->getAccess());
3535 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3536 InstD->setSpecializationKind(D->getSpecializationKind());
3537 InstD->setTypeAsWritten(WrittenTy);
3538 InstD->setExternLoc(D->getExternLoc());
3539 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3541 Owner->addDecl(InstD);
3543 // Instantiate the members of the class-scope explicit specialization eagerly.
3544 // We don't have support for lazy instantiation of an explicit specialization
3545 // yet, and MSVC eagerly instantiates in this case.
3546 // FIXME: This is wrong in standard C++.
3547 if (D->isThisDeclarationADefinition() &&
3548 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3549 TSK_ImplicitInstantiation,
3556 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3557 VarTemplateSpecializationDecl *D) {
3559 TemplateArgumentListInfo VarTemplateArgsInfo;
3560 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3561 assert(VarTemplate &&
3562 "A template specialization without specialized template?");
3564 VarTemplateDecl *InstVarTemplate =
3565 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3566 D->getLocation(), VarTemplate, TemplateArgs));
3567 if (!InstVarTemplate)
3570 // Substitute the current template arguments.
3571 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
3572 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
3573 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
3575 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
3576 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
3579 // Check that the template argument list is well-formed for this template.
3580 SmallVector<TemplateArgument, 4> Converted;
3581 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3582 VarTemplateArgsInfo, false, Converted,
3583 /*UpdateArgsWithConversion=*/true))
3586 // Check whether we've already seen a declaration of this specialization.
3587 void *InsertPos = nullptr;
3588 VarTemplateSpecializationDecl *PrevDecl =
3589 InstVarTemplate->findSpecialization(Converted, InsertPos);
3591 // Check whether we've already seen a conflicting instantiation of this
3592 // declaration (for instance, if there was a prior implicit instantiation).
3594 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3595 D->getLocation(), D->getSpecializationKind(), PrevDecl,
3596 PrevDecl->getSpecializationKind(),
3597 PrevDecl->getPointOfInstantiation(), Ignored))
3600 return VisitVarTemplateSpecializationDecl(
3601 InstVarTemplate, D, InsertPos, VarTemplateArgsInfo, Converted, PrevDecl);
3604 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3605 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
3606 const TemplateArgumentListInfo &TemplateArgsInfo,
3607 ArrayRef<TemplateArgument> Converted,
3608 VarTemplateSpecializationDecl *PrevDecl) {
3610 // Do substitution on the type of the declaration
3611 TypeSourceInfo *DI =
3612 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3613 D->getTypeSpecStartLoc(), D->getDeclName());
3617 if (DI->getType()->isFunctionType()) {
3618 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3619 << D->isStaticDataMember() << DI->getType();
3623 // Build the instantiated declaration
3624 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3625 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3626 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
3627 Var->setTemplateArgsInfo(TemplateArgsInfo);
3629 VarTemplate->AddSpecialization(Var, InsertPos);
3631 // Substitute the nested name specifier, if any.
3632 if (SubstQualifier(D, Var))
3635 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
3636 StartingScope, false, PrevDecl);
3641 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3642 llvm_unreachable("@defs is not supported in Objective-C++");
3645 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3646 // FIXME: We need to be able to instantiate FriendTemplateDecls.
3647 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3648 DiagnosticsEngine::Error,
3649 "cannot instantiate %0 yet");
3650 SemaRef.Diag(D->getLocation(), DiagID)
3651 << D->getDeclKindName();
3656 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
3657 llvm_unreachable("Concept definitions cannot reside inside a template");
3661 TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
3662 return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
3666 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
3667 llvm_unreachable("Unexpected decl");
3670 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
3671 const MultiLevelTemplateArgumentList &TemplateArgs) {
3672 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3673 if (D->isInvalidDecl())
3677 runWithSufficientStackSpace(D->getLocation(), [&] {
3678 SubstD = Instantiator.Visit(D);
3683 void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
3684 FunctionDecl *Orig, QualType &T,
3685 TypeSourceInfo *&TInfo,
3686 DeclarationNameInfo &NameInfo) {
3687 assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual);
3689 // C++2a [class.compare.default]p3:
3690 // the return type is replaced with bool
3691 auto *FPT = T->castAs<FunctionProtoType>();
3692 T = SemaRef.Context.getFunctionType(
3693 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
3695 // Update the return type in the source info too. The most straightforward
3696 // way is to create new TypeSourceInfo for the new type. Use the location of
3697 // the '= default' as the location of the new type.
3699 // FIXME: Set the correct return type when we initially transform the type,
3700 // rather than delaying it to now.
3701 TypeSourceInfo *NewTInfo =
3702 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
3703 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
3704 assert(OldLoc && "type of function is not a function type?");
3705 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
3706 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
3707 NewLoc.setParam(I, OldLoc.getParam(I));
3710 // and the declarator-id is replaced with operator==
3712 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
3715 FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
3716 FunctionDecl *Spaceship) {
3717 if (Spaceship->isInvalidDecl())
3720 // C++2a [class.compare.default]p3:
3721 // an == operator function is declared implicitly [...] with the same
3722 // access and function-definition and in the same class scope as the
3723 // three-way comparison operator function
3724 MultiLevelTemplateArgumentList NoTemplateArgs;
3725 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
3727 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
3728 R = Instantiator.VisitCXXMethodDecl(
3730 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
3732 assert(Spaceship->getFriendObjectKind() &&
3733 "defaulted spaceship is neither a member nor a friend");
3735 R = Instantiator.VisitFunctionDecl(
3737 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
3742 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
3743 cast<NamedDecl>(R), Spaceship->getBeginLoc());
3744 FD->setAccess(AS_public);
3747 return cast_or_null<FunctionDecl>(R);
3750 /// Instantiates a nested template parameter list in the current
3751 /// instantiation context.
3753 /// \param L The parameter list to instantiate
3755 /// \returns NULL if there was an error
3756 TemplateParameterList *
3757 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
3758 // Get errors for all the parameters before bailing out.
3759 bool Invalid = false;
3761 unsigned N = L->size();
3762 typedef SmallVector<NamedDecl *, 8> ParamVector;
3765 for (auto &P : *L) {
3766 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
3767 Params.push_back(D);
3768 Invalid = Invalid || !D || D->isInvalidDecl();
3771 // Clean up if we had an error.
3775 // FIXME: Concepts: Substitution into requires clause should only happen when
3776 // checking satisfaction.
3777 Expr *InstRequiresClause = nullptr;
3778 if (Expr *E = L->getRequiresClause()) {
3779 EnterExpressionEvaluationContext ConstantEvaluated(
3780 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
3781 ExprResult Res = SemaRef.SubstExpr(E, TemplateArgs);
3782 if (Res.isInvalid() || !Res.isUsable()) {
3785 InstRequiresClause = Res.get();
3788 TemplateParameterList *InstL
3789 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
3790 L->getLAngleLoc(), Params,
3791 L->getRAngleLoc(), InstRequiresClause);
3795 TemplateParameterList *
3796 Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
3797 const MultiLevelTemplateArgumentList &TemplateArgs) {
3798 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3799 return Instantiator.SubstTemplateParams(Params);
3802 /// Instantiate the declaration of a class template partial
3805 /// \param ClassTemplate the (instantiated) class template that is partially
3806 // specialized by the instantiation of \p PartialSpec.
3808 /// \param PartialSpec the (uninstantiated) class template partial
3809 /// specialization that we are instantiating.
3811 /// \returns The instantiated partial specialization, if successful; otherwise,
3812 /// NULL to indicate an error.
3813 ClassTemplatePartialSpecializationDecl *
3814 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
3815 ClassTemplateDecl *ClassTemplate,
3816 ClassTemplatePartialSpecializationDecl *PartialSpec) {
3817 // Create a local instantiation scope for this class template partial
3818 // specialization, which will contain the instantiations of the template
3820 LocalInstantiationScope Scope(SemaRef);
3822 // Substitute into the template parameters of the class template partial
3824 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3825 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3829 // Substitute into the template arguments of the class template partial
3831 const ASTTemplateArgumentListInfo *TemplArgInfo
3832 = PartialSpec->getTemplateArgsAsWritten();
3833 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3834 TemplArgInfo->RAngleLoc);
3835 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3836 TemplArgInfo->NumTemplateArgs,
3837 InstTemplateArgs, TemplateArgs))
3840 // Check that the template argument list is well-formed for this
3842 SmallVector<TemplateArgument, 4> Converted;
3843 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
3844 PartialSpec->getLocation(),
3850 // Check these arguments are valid for a template partial specialization.
3851 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3852 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
3856 // Figure out where to insert this class template partial specialization
3857 // in the member template's set of class template partial specializations.
3858 void *InsertPos = nullptr;
3859 ClassTemplateSpecializationDecl *PrevDecl
3860 = ClassTemplate->findPartialSpecialization(Converted, InstParams,
3863 // Build the canonical type that describes the converted template
3864 // arguments of the class template partial specialization.
3866 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
3869 // Build the fully-sugared type for this class template
3870 // specialization as the user wrote in the specialization
3871 // itself. This means that we'll pretty-print the type retrieved
3872 // from the specialization's declaration the way that the user
3873 // actually wrote the specialization, rather than formatting the
3874 // name based on the "canonical" representation used to store the
3875 // template arguments in the specialization.
3876 TypeSourceInfo *WrittenTy
3877 = SemaRef.Context.getTemplateSpecializationTypeInfo(
3878 TemplateName(ClassTemplate),
3879 PartialSpec->getLocation(),
3884 // We've already seen a partial specialization with the same template
3885 // parameters and template arguments. This can happen, for example, when
3886 // substituting the outer template arguments ends up causing two
3887 // class template partial specializations of a member class template
3888 // to have identical forms, e.g.,
3890 // template<typename T, typename U>
3892 // template<typename X, typename Y> struct Inner;
3893 // template<typename Y> struct Inner<T, Y>;
3894 // template<typename Y> struct Inner<U, Y>;
3897 // Outer<int, int> outer; // error: the partial specializations of Inner
3898 // // have the same signature.
3899 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
3900 << WrittenTy->getType();
3901 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3902 << SemaRef.Context.getTypeDeclType(PrevDecl);
3907 // Create the class template partial specialization declaration.
3908 ClassTemplatePartialSpecializationDecl *InstPartialSpec =
3909 ClassTemplatePartialSpecializationDecl::Create(
3910 SemaRef.Context, PartialSpec->getTagKind(), Owner,
3911 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
3912 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
3913 // Substitute the nested name specifier, if any.
3914 if (SubstQualifier(PartialSpec, InstPartialSpec))
3917 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3918 InstPartialSpec->setTypeAsWritten(WrittenTy);
3920 // Check the completed partial specialization.
3921 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3923 // Add this partial specialization to the set of class template partial
3925 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3926 /*InsertPos=*/nullptr);
3927 return InstPartialSpec;
3930 /// Instantiate the declaration of a variable template partial
3933 /// \param VarTemplate the (instantiated) variable template that is partially
3934 /// specialized by the instantiation of \p PartialSpec.
3936 /// \param PartialSpec the (uninstantiated) variable template partial
3937 /// specialization that we are instantiating.
3939 /// \returns The instantiated partial specialization, if successful; otherwise,
3940 /// NULL to indicate an error.
3941 VarTemplatePartialSpecializationDecl *
3942 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3943 VarTemplateDecl *VarTemplate,
3944 VarTemplatePartialSpecializationDecl *PartialSpec) {
3945 // Create a local instantiation scope for this variable template partial
3946 // specialization, which will contain the instantiations of the template
3948 LocalInstantiationScope Scope(SemaRef);
3950 // Substitute into the template parameters of the variable template partial
3952 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3953 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3957 // Substitute into the template arguments of the variable template partial
3959 const ASTTemplateArgumentListInfo *TemplArgInfo
3960 = PartialSpec->getTemplateArgsAsWritten();
3961 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3962 TemplArgInfo->RAngleLoc);
3963 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3964 TemplArgInfo->NumTemplateArgs,
3965 InstTemplateArgs, TemplateArgs))
3968 // Check that the template argument list is well-formed for this
3970 SmallVector<TemplateArgument, 4> Converted;
3971 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3972 InstTemplateArgs, false, Converted))
3975 // Check these arguments are valid for a template partial specialization.
3976 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3977 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
3981 // Figure out where to insert this variable template partial specialization
3982 // in the member template's set of variable template partial specializations.
3983 void *InsertPos = nullptr;
3984 VarTemplateSpecializationDecl *PrevDecl =
3985 VarTemplate->findPartialSpecialization(Converted, InstParams, InsertPos);
3987 // Build the canonical type that describes the converted template
3988 // arguments of the variable template partial specialization.
3989 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3990 TemplateName(VarTemplate), Converted);
3992 // Build the fully-sugared type for this variable template
3993 // specialization as the user wrote in the specialization
3994 // itself. This means that we'll pretty-print the type retrieved
3995 // from the specialization's declaration the way that the user
3996 // actually wrote the specialization, rather than formatting the
3997 // name based on the "canonical" representation used to store the
3998 // template arguments in the specialization.
3999 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
4000 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
4004 // We've already seen a partial specialization with the same template
4005 // parameters and template arguments. This can happen, for example, when
4006 // substituting the outer template arguments ends up causing two
4007 // variable template partial specializations of a member variable template
4008 // to have identical forms, e.g.,
4010 // template<typename T, typename U>
4012 // template<typename X, typename Y> pair<X,Y> p;
4013 // template<typename Y> pair<T, Y> p;
4014 // template<typename Y> pair<U, Y> p;
4017 // Outer<int, int> outer; // error: the partial specializations of Inner
4018 // // have the same signature.
4019 SemaRef.Diag(PartialSpec->getLocation(),
4020 diag::err_var_partial_spec_redeclared)
4021 << WrittenTy->getType();
4022 SemaRef.Diag(PrevDecl->getLocation(),
4023 diag::note_var_prev_partial_spec_here);
4027 // Do substitution on the type of the declaration
4028 TypeSourceInfo *DI = SemaRef.SubstType(
4029 PartialSpec->getTypeSourceInfo(), TemplateArgs,
4030 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4034 if (DI->getType()->isFunctionType()) {
4035 SemaRef.Diag(PartialSpec->getLocation(),
4036 diag::err_variable_instantiates_to_function)
4037 << PartialSpec->isStaticDataMember() << DI->getType();
4041 // Create the variable template partial specialization declaration.
4042 VarTemplatePartialSpecializationDecl *InstPartialSpec =
4043 VarTemplatePartialSpecializationDecl::Create(
4044 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4045 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4046 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
4048 // Substitute the nested name specifier, if any.
4049 if (SubstQualifier(PartialSpec, InstPartialSpec))
4052 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4053 InstPartialSpec->setTypeAsWritten(WrittenTy);
4055 // Check the completed partial specialization.
4056 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4058 // Add this partial specialization to the set of variable template partial
4059 // specializations. The instantiation of the initializer is not necessary.
4060 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4062 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4063 LateAttrs, Owner, StartingScope);
4065 return InstPartialSpec;
4069 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
4070 SmallVectorImpl<ParmVarDecl *> &Params) {
4071 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4072 assert(OldTInfo && "substituting function without type source info");
4073 assert(Params.empty() && "parameter vector is non-empty at start");
4075 CXXRecordDecl *ThisContext = nullptr;
4076 Qualifiers ThisTypeQuals;
4077 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4078 ThisContext = cast<CXXRecordDecl>(Owner);
4079 ThisTypeQuals = Method->getMethodQualifiers();
4082 TypeSourceInfo *NewTInfo
4083 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
4084 D->getTypeSpecStartLoc(),
4086 ThisContext, ThisTypeQuals);
4090 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4091 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4092 if (NewTInfo != OldTInfo) {
4093 // Get parameters from the new type info.
4094 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4095 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4096 unsigned NewIdx = 0;
4097 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4098 OldIdx != NumOldParams; ++OldIdx) {
4099 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4100 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
4102 Optional<unsigned> NumArgumentsInExpansion;
4103 if (OldParam->isParameterPack())
4104 NumArgumentsInExpansion =
4105 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4107 if (!NumArgumentsInExpansion) {
4108 // Simple case: normal parameter, or a parameter pack that's
4109 // instantiated to a (still-dependent) parameter pack.
4110 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4111 Params.push_back(NewParam);
4112 Scope->InstantiatedLocal(OldParam, NewParam);
4114 // Parameter pack expansion: make the instantiation an argument pack.
4115 Scope->MakeInstantiatedLocalArgPack(OldParam);
4116 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4117 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4118 Params.push_back(NewParam);
4119 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4124 // The function type itself was not dependent and therefore no
4125 // substitution occurred. However, we still need to instantiate
4126 // the function parameters themselves.
4127 const FunctionProtoType *OldProto =
4128 cast<FunctionProtoType>(OldProtoLoc.getType());
4129 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4131 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4133 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4134 D, D->getLocation(), OldProto->getParamType(i)));
4139 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4142 Params.push_back(Parm);
4146 // If the type of this function, after ignoring parentheses, is not
4147 // *directly* a function type, then we're instantiating a function that
4148 // was declared via a typedef or with attributes, e.g.,
4150 // typedef int functype(int, int);
4152 // int __cdecl meth(int, int);
4154 // In this case, we'll just go instantiate the ParmVarDecls that we
4155 // synthesized in the method declaration.
4156 SmallVector<QualType, 4> ParamTypes;
4157 Sema::ExtParameterInfoBuilder ExtParamInfos;
4158 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4159 TemplateArgs, ParamTypes, &Params,
4167 /// Introduce the instantiated function parameters into the local
4168 /// instantiation scope, and set the parameter names to those used
4169 /// in the template.
4170 static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
4171 const FunctionDecl *PatternDecl,
4172 LocalInstantiationScope &Scope,
4173 const MultiLevelTemplateArgumentList &TemplateArgs) {
4174 unsigned FParamIdx = 0;
4175 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4176 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4177 if (!PatternParam->isParameterPack()) {
4178 // Simple case: not a parameter pack.
4179 assert(FParamIdx < Function->getNumParams());
4180 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4181 FunctionParam->setDeclName(PatternParam->getDeclName());
4182 // If the parameter's type is not dependent, update it to match the type
4183 // in the pattern. They can differ in top-level cv-qualifiers, and we want
4184 // the pattern's type here. If the type is dependent, they can't differ,
4185 // per core issue 1668. Substitute into the type from the pattern, in case
4186 // it's instantiation-dependent.
4187 // FIXME: Updating the type to work around this is at best fragile.
4188 if (!PatternDecl->getType()->isDependentType()) {
4189 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
4190 FunctionParam->getLocation(),
4191 FunctionParam->getDeclName());
4194 FunctionParam->setType(T);
4197 Scope.InstantiatedLocal(PatternParam, FunctionParam);
4202 // Expand the parameter pack.
4203 Scope.MakeInstantiatedLocalArgPack(PatternParam);
4204 Optional<unsigned> NumArgumentsInExpansion
4205 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4206 if (NumArgumentsInExpansion) {
4207 QualType PatternType =
4208 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4209 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4210 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4211 FunctionParam->setDeclName(PatternParam->getDeclName());
4212 if (!PatternDecl->getType()->isDependentType()) {
4213 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
4214 QualType T = S.SubstType(PatternType, TemplateArgs,
4215 FunctionParam->getLocation(),
4216 FunctionParam->getDeclName());
4219 FunctionParam->setType(T);
4222 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4231 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
4232 FunctionDecl *Decl) {
4233 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4234 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
4237 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4238 InstantiatingTemplate::ExceptionSpecification());
4239 if (Inst.isInvalid()) {
4240 // We hit the instantiation depth limit. Clear the exception specification
4241 // so that our callers don't have to cope with EST_Uninstantiated.
4242 UpdateExceptionSpec(Decl, EST_None);
4245 if (Inst.isAlreadyInstantiating()) {
4246 // This exception specification indirectly depends on itself. Reject.
4247 // FIXME: Corresponding rule in the standard?
4248 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4249 UpdateExceptionSpec(Decl, EST_None);
4253 // Enter the scope of this instantiation. We don't use
4254 // PushDeclContext because we don't have a scope.
4255 Sema::ContextRAII savedContext(*this, Decl);
4256 LocalInstantiationScope Scope(*this);
4258 MultiLevelTemplateArgumentList TemplateArgs =
4259 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
4261 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4262 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
4264 UpdateExceptionSpec(Decl, EST_None);
4268 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
4272 bool Sema::CheckInstantiatedFunctionTemplateConstraints(
4273 SourceLocation PointOfInstantiation, FunctionDecl *Decl,
4274 ArrayRef<TemplateArgument> TemplateArgs,
4275 ConstraintSatisfaction &Satisfaction) {
4276 // In most cases we're not going to have constraints, so check for that first.
4277 FunctionTemplateDecl *Template = Decl->getPrimaryTemplate();
4278 // Note - code synthesis context for the constraints check is created
4279 // inside CheckConstraintsSatisfaction.
4280 SmallVector<const Expr *, 3> TemplateAC;
4281 Template->getAssociatedConstraints(TemplateAC);
4282 if (TemplateAC.empty()) {
4283 Satisfaction.IsSatisfied = true;
4287 // Enter the scope of this instantiation. We don't use
4288 // PushDeclContext because we don't have a scope.
4289 Sema::ContextRAII savedContext(*this, Decl);
4290 LocalInstantiationScope Scope(*this);
4292 // If this is not an explicit specialization - we need to get the instantiated
4293 // version of the template arguments and add them to scope for the
4295 if (Decl->isTemplateInstantiation()) {
4296 InstantiatingTemplate Inst(*this, Decl->getPointOfInstantiation(),
4297 InstantiatingTemplate::ConstraintsCheck{}, Decl->getPrimaryTemplate(),
4298 TemplateArgs, SourceRange());
4299 if (Inst.isInvalid())
4301 MultiLevelTemplateArgumentList MLTAL(
4302 *Decl->getTemplateSpecializationArgs());
4303 if (addInstantiatedParametersToScope(
4304 *this, Decl, Decl->getPrimaryTemplate()->getTemplatedDecl(),
4308 Qualifiers ThisQuals;
4309 CXXRecordDecl *Record = nullptr;
4310 if (auto *Method = dyn_cast<CXXMethodDecl>(Decl)) {
4311 ThisQuals = Method->getMethodQualifiers();
4312 Record = Method->getParent();
4314 CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
4315 return CheckConstraintSatisfaction(Template, TemplateAC, TemplateArgs,
4316 PointOfInstantiation, Satisfaction);
4319 /// Initializes the common fields of an instantiation function
4320 /// declaration (New) from the corresponding fields of its template (Tmpl).
4322 /// \returns true if there was an error
4324 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
4325 FunctionDecl *Tmpl) {
4326 New->setImplicit(Tmpl->isImplicit());
4328 // Forward the mangling number from the template to the instantiated decl.
4329 SemaRef.Context.setManglingNumber(New,
4330 SemaRef.Context.getManglingNumber(Tmpl));
4332 // If we are performing substituting explicitly-specified template arguments
4333 // or deduced template arguments into a function template and we reach this
4334 // point, we are now past the point where SFINAE applies and have committed
4335 // to keeping the new function template specialization. We therefore
4336 // convert the active template instantiation for the function template
4337 // into a template instantiation for this specific function template
4338 // specialization, which is not a SFINAE context, so that we diagnose any
4339 // further errors in the declaration itself.
4340 typedef Sema::CodeSynthesisContext ActiveInstType;
4341 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4342 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4343 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4344 if (FunctionTemplateDecl *FunTmpl
4345 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
4346 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
4347 "Deduction from the wrong function template?");
4349 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4350 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4351 ActiveInst.Entity = New;
4352 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4356 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4357 assert(Proto && "Function template without prototype?");
4359 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4360 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4362 // DR1330: In C++11, defer instantiation of a non-trivial
4363 // exception specification.
4364 // DR1484: Local classes and their members are instantiated along with the
4365 // containing function.
4366 if (SemaRef.getLangOpts().CPlusPlus11 &&
4367 EPI.ExceptionSpec.Type != EST_None &&
4368 EPI.ExceptionSpec.Type != EST_DynamicNone &&
4369 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
4370 !Tmpl->isLexicallyWithinFunctionOrMethod()) {
4371 FunctionDecl *ExceptionSpecTemplate = Tmpl;
4372 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
4373 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4374 ExceptionSpecificationType NewEST = EST_Uninstantiated;
4375 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
4376 NewEST = EST_Unevaluated;
4378 // Mark the function has having an uninstantiated exception specification.
4379 const FunctionProtoType *NewProto
4380 = New->getType()->getAs<FunctionProtoType>();
4381 assert(NewProto && "Template instantiation without function prototype?");
4382 EPI = NewProto->getExtProtoInfo();
4383 EPI.ExceptionSpec.Type = NewEST;
4384 EPI.ExceptionSpec.SourceDecl = New;
4385 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4386 New->setType(SemaRef.Context.getFunctionType(
4387 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4389 Sema::ContextRAII SwitchContext(SemaRef, New);
4390 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4394 // Get the definition. Leaves the variable unchanged if undefined.
4395 const FunctionDecl *Definition = Tmpl;
4396 Tmpl->isDefined(Definition);
4398 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4399 LateAttrs, StartingScope);
4404 /// Initializes common fields of an instantiated method
4405 /// declaration (New) from the corresponding fields of its template
4408 /// \returns true if there was an error
4410 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4411 CXXMethodDecl *Tmpl) {
4412 if (InitFunctionInstantiation(New, Tmpl))
4415 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4416 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4418 New->setAccess(Tmpl->getAccess());
4419 if (Tmpl->isVirtualAsWritten())
4420 New->setVirtualAsWritten(true);
4422 // FIXME: New needs a pointer to Tmpl
4426 bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
4427 FunctionDecl *Tmpl) {
4428 // Transfer across any unqualified lookups.
4429 if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) {
4430 SmallVector<DeclAccessPair, 32> Lookups;
4431 Lookups.reserve(DFI->getUnqualifiedLookups().size());
4432 bool AnyChanged = false;
4433 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4434 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4435 DA.getDecl(), TemplateArgs);
4438 AnyChanged |= (D != DA.getDecl());
4439 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4442 // It's unlikely that substitution will change any declarations. Don't
4443 // store an unnecessary copy in that case.
4444 New->setDefaultedFunctionInfo(
4445 AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create(
4446 SemaRef.Context, Lookups)
4450 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4454 /// Instantiate (or find existing instantiation of) a function template with a
4455 /// given set of template arguments.
4457 /// Usually this should not be used, and template argument deduction should be
4458 /// used in its place.
4460 Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4461 const TemplateArgumentList *Args,
4462 SourceLocation Loc) {
4463 FunctionDecl *FD = FTD->getTemplatedDecl();
4465 sema::TemplateDeductionInfo Info(Loc);
4466 InstantiatingTemplate Inst(
4467 *this, Loc, FTD, Args->asArray(),
4468 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
4469 if (Inst.isInvalid())
4472 ContextRAII SavedContext(*this, FD);
4473 MultiLevelTemplateArgumentList MArgs(*Args);
4475 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4478 /// In the MS ABI, we need to instantiate default arguments of dllexported
4479 /// default constructors along with the constructor definition. This allows IR
4480 /// gen to emit a constructor closure which calls the default constructor with
4481 /// its default arguments.
4482 static void InstantiateDefaultCtorDefaultArgs(Sema &S,
4483 CXXConstructorDecl *Ctor) {
4484 assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4485 Ctor->isDefaultConstructor());
4486 unsigned NumParams = Ctor->getNumParams();
4489 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
4492 for (unsigned I = 0; I != NumParams; ++I) {
4493 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
4494 Ctor->getParamDecl(I));
4495 S.DiscardCleanupsInEvaluationContext();
4499 /// Instantiate the definition of the given function from its
4502 /// \param PointOfInstantiation the point at which the instantiation was
4503 /// required. Note that this is not precisely a "point of instantiation"
4504 /// for the function, but it's close.
4506 /// \param Function the already-instantiated declaration of a
4507 /// function template specialization or member function of a class template
4510 /// \param Recursive if true, recursively instantiates any functions that
4511 /// are required by this instantiation.
4513 /// \param DefinitionRequired if true, then we are performing an explicit
4514 /// instantiation where the body of the function is required. Complain if
4515 /// there is no such body.
4516 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4517 FunctionDecl *Function,
4519 bool DefinitionRequired,
4521 if (Function->isInvalidDecl() || Function->isDefined() ||
4522 isa<CXXDeductionGuideDecl>(Function))
4525 // Never instantiate an explicit specialization except if it is a class scope
4526 // explicit specialization.
4527 TemplateSpecializationKind TSK =
4528 Function->getTemplateSpecializationKindForInstantiation();
4529 if (TSK == TSK_ExplicitSpecialization)
4532 // Find the function body that we'll be substituting.
4533 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4534 assert(PatternDecl && "instantiating a non-template");
4536 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4537 Stmt *Pattern = nullptr;
4539 Pattern = PatternDef->getBody(PatternDef);
4540 PatternDecl = PatternDef;
4541 if (PatternDef->willHaveBody())
4542 PatternDef = nullptr;
4545 // FIXME: We need to track the instantiation stack in order to know which
4546 // definitions should be visible within this instantiation.
4547 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4548 Function->getInstantiatedFromMemberFunction(),
4549 PatternDecl, PatternDef, TSK,
4550 /*Complain*/DefinitionRequired)) {
4551 if (DefinitionRequired)
4552 Function->setInvalidDecl();
4553 else if (TSK == TSK_ExplicitInstantiationDefinition) {
4554 // Try again at the end of the translation unit (at which point a
4555 // definition will be required).
4557 Function->setInstantiationIsPending(true);
4558 PendingInstantiations.push_back(
4559 std::make_pair(Function, PointOfInstantiation));
4560 } else if (TSK == TSK_ImplicitInstantiation) {
4561 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4562 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4563 Diag(PointOfInstantiation, diag::warn_func_template_missing)
4565 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4566 if (getLangOpts().CPlusPlus11)
4567 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4575 // Postpone late parsed template instantiations.
4576 if (PatternDecl->isLateTemplateParsed() &&
4577 !LateTemplateParser) {
4578 Function->setInstantiationIsPending(true);
4579 LateParsedInstantiations.push_back(
4580 std::make_pair(Function, PointOfInstantiation));
4584 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
4586 llvm::raw_string_ostream OS(Name);
4587 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4588 /*Qualified=*/true);
4592 // If we're performing recursive template instantiation, create our own
4593 // queue of pending implicit instantiations that we will instantiate later,
4594 // while we're still within our own instantiation context.
4595 // This has to happen before LateTemplateParser below is called, so that
4596 // it marks vtables used in late parsed templates as used.
4597 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4598 /*Enabled=*/Recursive);
4599 LocalEagerInstantiationScope LocalInstantiations(*this);
4601 // Call the LateTemplateParser callback if there is a need to late parse
4602 // a templated function definition.
4603 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
4604 LateTemplateParser) {
4605 // FIXME: Optimize to allow individual templates to be deserialized.
4606 if (PatternDecl->isFromASTFile())
4607 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4609 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
4610 assert(LPTIter != LateParsedTemplateMap.end() &&
4611 "missing LateParsedTemplate");
4612 LateTemplateParser(OpaqueParser, *LPTIter->second);
4613 Pattern = PatternDecl->getBody(PatternDecl);
4616 // Note, we should never try to instantiate a deleted function template.
4617 assert((Pattern || PatternDecl->isDefaulted() ||
4618 PatternDecl->hasSkippedBody()) &&
4619 "unexpected kind of function template definition");
4621 // C++1y [temp.explicit]p10:
4622 // Except for inline functions, declarations with types deduced from their
4623 // initializer or return value, and class template specializations, other
4624 // explicit instantiation declarations have the effect of suppressing the
4625 // implicit instantiation of the entity to which they refer.
4626 if (TSK == TSK_ExplicitInstantiationDeclaration &&
4627 !PatternDecl->isInlined() &&
4628 !PatternDecl->getReturnType()->getContainedAutoType())
4631 if (PatternDecl->isInlined()) {
4632 // Function, and all later redeclarations of it (from imported modules,
4633 // for instance), are now implicitly inline.
4634 for (auto *D = Function->getMostRecentDecl(); /**/;
4635 D = D->getPreviousDecl()) {
4636 D->setImplicitlyInline();
4642 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
4643 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4645 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
4646 "instantiating function definition");
4648 // The instantiation is visible here, even if it was first declared in an
4649 // unimported module.
4650 Function->setVisibleDespiteOwningModule();
4652 // Copy the inner loc start from the pattern.
4653 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4655 EnterExpressionEvaluationContext EvalContext(
4656 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4658 // Introduce a new scope where local variable instantiations will be
4659 // recorded, unless we're actually a member function within a local
4660 // class, in which case we need to merge our results with the parent
4661 // scope (of the enclosing function).
4662 bool MergeWithParentScope = false;
4663 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
4664 MergeWithParentScope = Rec->isLocalClass();
4666 LocalInstantiationScope Scope(*this, MergeWithParentScope);
4668 if (PatternDecl->isDefaulted())
4669 SetDeclDefaulted(Function, PatternDecl->getLocation());
4671 MultiLevelTemplateArgumentList TemplateArgs =
4672 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
4674 // Substitute into the qualifier; we can get a substitution failure here
4675 // through evil use of alias templates.
4676 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
4677 // of the) lexical context of the pattern?
4678 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
4680 ActOnStartOfFunctionDef(nullptr, Function);
4682 // Enter the scope of this instantiation. We don't use
4683 // PushDeclContext because we don't have a scope.
4684 Sema::ContextRAII savedContext(*this, Function);
4686 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
4691 if (PatternDecl->hasSkippedBody()) {
4692 ActOnSkippedFunctionBody(Function);
4695 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
4696 // If this is a constructor, instantiate the member initializers.
4697 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
4700 // If this is an MS ABI dllexport default constructor, instantiate any
4701 // default arguments.
4702 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4703 Ctor->isDefaultConstructor()) {
4704 InstantiateDefaultCtorDefaultArgs(*this, Ctor);
4708 // Instantiate the function body.
4709 Body = SubstStmt(Pattern, TemplateArgs);
4711 if (Body.isInvalid())
4712 Function->setInvalidDecl();
4714 // FIXME: finishing the function body while in an expression evaluation
4715 // context seems wrong. Investigate more.
4716 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
4718 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
4720 if (auto *Listener = getASTMutationListener())
4721 Listener->FunctionDefinitionInstantiated(Function);
4726 DeclGroupRef DG(Function);
4727 Consumer.HandleTopLevelDecl(DG);
4729 // This class may have local implicit instantiations that need to be
4730 // instantiation within this scope.
4731 LocalInstantiations.perform();
4733 GlobalInstantiations.perform();
4736 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
4737 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
4738 const TemplateArgumentList &TemplateArgList,
4739 const TemplateArgumentListInfo &TemplateArgsInfo,
4740 SmallVectorImpl<TemplateArgument> &Converted,
4741 SourceLocation PointOfInstantiation, void *InsertPos,
4742 LateInstantiatedAttrVec *LateAttrs,
4743 LocalInstantiationScope *StartingScope) {
4744 if (FromVar->isInvalidDecl())
4747 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
4748 if (Inst.isInvalid())
4751 MultiLevelTemplateArgumentList TemplateArgLists;
4752 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
4754 // Instantiate the first declaration of the variable template: for a partial
4755 // specialization of a static data member template, the first declaration may
4756 // or may not be the declaration in the class; if it's in the class, we want
4757 // to instantiate a member in the class (a declaration), and if it's outside,
4758 // we want to instantiate a definition.
4760 // If we're instantiating an explicitly-specialized member template or member
4761 // partial specialization, don't do this. The member specialization completely
4762 // replaces the original declaration in this case.
4763 bool IsMemberSpec = false;
4764 if (VarTemplatePartialSpecializationDecl *PartialSpec =
4765 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
4766 IsMemberSpec = PartialSpec->isMemberSpecialization();
4767 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
4768 IsMemberSpec = FromTemplate->isMemberSpecialization();
4770 FromVar = FromVar->getFirstDecl();
4772 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
4773 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
4776 // TODO: Set LateAttrs and StartingScope ...
4778 return cast_or_null<VarTemplateSpecializationDecl>(
4779 Instantiator.VisitVarTemplateSpecializationDecl(
4780 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
4783 /// Instantiates a variable template specialization by completing it
4784 /// with appropriate type information and initializer.
4785 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
4786 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
4787 const MultiLevelTemplateArgumentList &TemplateArgs) {
4788 assert(PatternDecl->isThisDeclarationADefinition() &&
4789 "don't have a definition to instantiate from");
4791 // Do substitution on the type of the declaration
4792 TypeSourceInfo *DI =
4793 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
4794 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
4798 // Update the type of this variable template specialization.
4799 VarSpec->setType(DI->getType());
4801 // Convert the declaration into a definition now.
4802 VarSpec->setCompleteDefinition();
4804 // Instantiate the initializer.
4805 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
4810 /// BuildVariableInstantiation - Used after a new variable has been created.
4811 /// Sets basic variable data and decides whether to postpone the
4812 /// variable instantiation.
4813 void Sema::BuildVariableInstantiation(
4814 VarDecl *NewVar, VarDecl *OldVar,
4815 const MultiLevelTemplateArgumentList &TemplateArgs,
4816 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
4817 LocalInstantiationScope *StartingScope,
4818 bool InstantiatingVarTemplate,
4819 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
4820 // Instantiating a partial specialization to produce a partial
4822 bool InstantiatingVarTemplatePartialSpec =
4823 isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
4824 isa<VarTemplatePartialSpecializationDecl>(NewVar);
4825 // Instantiating from a variable template (or partial specialization) to
4826 // produce a variable template specialization.
4827 bool InstantiatingSpecFromTemplate =
4828 isa<VarTemplateSpecializationDecl>(NewVar) &&
4829 (OldVar->getDescribedVarTemplate() ||
4830 isa<VarTemplatePartialSpecializationDecl>(OldVar));
4832 // If we are instantiating a local extern declaration, the
4833 // instantiation belongs lexically to the containing function.
4834 // If we are instantiating a static data member defined
4835 // out-of-line, the instantiation will have the same lexical
4836 // context (which will be a namespace scope) as the template.
4837 if (OldVar->isLocalExternDecl()) {
4838 NewVar->setLocalExternDecl();
4839 NewVar->setLexicalDeclContext(Owner);
4840 } else if (OldVar->isOutOfLine())
4841 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
4842 NewVar->setTSCSpec(OldVar->getTSCSpec());
4843 NewVar->setInitStyle(OldVar->getInitStyle());
4844 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
4845 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
4846 NewVar->setConstexpr(OldVar->isConstexpr());
4847 NewVar->setInitCapture(OldVar->isInitCapture());
4848 NewVar->setPreviousDeclInSameBlockScope(
4849 OldVar->isPreviousDeclInSameBlockScope());
4850 NewVar->setAccess(OldVar->getAccess());
4852 if (!OldVar->isStaticDataMember()) {
4853 if (OldVar->isUsed(false))
4854 NewVar->setIsUsed();
4855 NewVar->setReferenced(OldVar->isReferenced());
4858 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
4860 LookupResult Previous(
4861 *this, NewVar->getDeclName(), NewVar->getLocation(),
4862 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
4863 : Sema::LookupOrdinaryName,
4864 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
4865 : forRedeclarationInCurContext());
4867 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
4868 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
4869 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
4870 // We have a previous declaration. Use that one, so we merge with the
4872 if (NamedDecl *NewPrev = FindInstantiatedDecl(
4873 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
4874 Previous.addDecl(NewPrev);
4875 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
4876 OldVar->hasLinkage()) {
4877 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
4878 } else if (PrevDeclForVarTemplateSpecialization) {
4879 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
4881 CheckVariableDeclaration(NewVar, Previous);
4883 if (!InstantiatingVarTemplate) {
4884 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
4885 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
4886 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
4889 if (!OldVar->isOutOfLine()) {
4890 if (NewVar->getDeclContext()->isFunctionOrMethod())
4891 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
4894 // Link instantiations of static data members back to the template from
4895 // which they were instantiated.
4897 // Don't do this when instantiating a template (we link the template itself
4898 // back in that case) nor when instantiating a static data member template
4899 // (that's not a member specialization).
4900 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
4901 !InstantiatingSpecFromTemplate)
4902 NewVar->setInstantiationOfStaticDataMember(OldVar,
4903 TSK_ImplicitInstantiation);
4905 // If the pattern is an (in-class) explicit specialization, then the result
4906 // is also an explicit specialization.
4907 if (VarTemplateSpecializationDecl *OldVTSD =
4908 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
4909 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
4910 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
4911 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
4912 TSK_ExplicitSpecialization);
4915 // Forward the mangling number from the template to the instantiated decl.
4916 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
4917 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
4919 // Figure out whether to eagerly instantiate the initializer.
4920 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
4921 // We're producing a template. Don't instantiate the initializer yet.
4922 } else if (NewVar->getType()->isUndeducedType()) {
4923 // We need the type to complete the declaration of the variable.
4924 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4925 } else if (InstantiatingSpecFromTemplate ||
4926 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
4927 !NewVar->isThisDeclarationADefinition())) {
4928 // Delay instantiation of the initializer for variable template
4929 // specializations or inline static data members until a definition of the
4930 // variable is needed.
4932 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4935 // Diagnose unused local variables with dependent types, where the diagnostic
4936 // will have been deferred.
4937 if (!NewVar->isInvalidDecl() &&
4938 NewVar->getDeclContext()->isFunctionOrMethod() &&
4939 OldVar->getType()->isDependentType())
4940 DiagnoseUnusedDecl(NewVar);
4943 /// Instantiate the initializer of a variable.
4944 void Sema::InstantiateVariableInitializer(
4945 VarDecl *Var, VarDecl *OldVar,
4946 const MultiLevelTemplateArgumentList &TemplateArgs) {
4947 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4948 L->VariableDefinitionInstantiated(Var);
4950 // We propagate the 'inline' flag with the initializer, because it
4951 // would otherwise imply that the variable is a definition for a
4952 // non-static data member.
4953 if (OldVar->isInlineSpecified())
4954 Var->setInlineSpecified();
4955 else if (OldVar->isInline())
4956 Var->setImplicitlyInline();
4958 if (OldVar->getInit()) {
4959 EnterExpressionEvaluationContext Evaluated(
4960 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
4962 // Instantiate the initializer.
4966 ContextRAII SwitchContext(*this, Var->getDeclContext());
4967 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
4968 OldVar->getInitStyle() == VarDecl::CallInit);
4971 if (!Init.isInvalid()) {
4972 Expr *InitExpr = Init.get();
4974 if (Var->hasAttr<DLLImportAttr>() &&
4976 !InitExpr->isConstantInitializer(getASTContext(), false))) {
4977 // Do not dynamically initialize dllimport variables.
4978 } else if (InitExpr) {
4979 bool DirectInit = OldVar->isDirectInit();
4980 AddInitializerToDecl(Var, InitExpr, DirectInit);
4982 ActOnUninitializedDecl(Var);
4984 // FIXME: Not too happy about invalidating the declaration
4985 // because of a bogus initializer.
4986 Var->setInvalidDecl();
4989 // `inline` variables are a definition and declaration all in one; we won't
4990 // pick up an initializer from anywhere else.
4991 if (Var->isStaticDataMember() && !Var->isInline()) {
4992 if (!Var->isOutOfLine())
4995 // If the declaration inside the class had an initializer, don't add
4996 // another one to the out-of-line definition.
4997 if (OldVar->getFirstDecl()->hasInit())
5001 // We'll add an initializer to a for-range declaration later.
5002 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
5005 ActOnUninitializedDecl(Var);
5008 if (getLangOpts().CUDA)
5009 checkAllowedCUDAInitializer(Var);
5012 /// Instantiate the definition of the given variable from its
5015 /// \param PointOfInstantiation the point at which the instantiation was
5016 /// required. Note that this is not precisely a "point of instantiation"
5017 /// for the variable, but it's close.
5019 /// \param Var the already-instantiated declaration of a templated variable.
5021 /// \param Recursive if true, recursively instantiates any functions that
5022 /// are required by this instantiation.
5024 /// \param DefinitionRequired if true, then we are performing an explicit
5025 /// instantiation where a definition of the variable is required. Complain
5026 /// if there is no such definition.
5027 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
5028 VarDecl *Var, bool Recursive,
5029 bool DefinitionRequired, bool AtEndOfTU) {
5030 if (Var->isInvalidDecl())
5033 // Never instantiate an explicitly-specialized entity.
5034 TemplateSpecializationKind TSK =
5035 Var->getTemplateSpecializationKindForInstantiation();
5036 if (TSK == TSK_ExplicitSpecialization)
5039 // Find the pattern and the arguments to substitute into it.
5040 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
5041 assert(PatternDecl && "no pattern for templated variable");
5042 MultiLevelTemplateArgumentList TemplateArgs =
5043 getTemplateInstantiationArgs(Var);
5045 VarTemplateSpecializationDecl *VarSpec =
5046 dyn_cast<VarTemplateSpecializationDecl>(Var);
5048 // If this is a variable template specialization, make sure that it is
5050 bool InstantiationDependent = false;
5051 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
5052 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
5053 "Only instantiate variable template specializations that are "
5054 "not type-dependent");
5055 (void)InstantiationDependent;
5057 // If this is a static data member template, there might be an
5058 // uninstantiated initializer on the declaration. If so, instantiate
5061 // FIXME: This largely duplicates what we would do below. The difference
5062 // is that along this path we may instantiate an initializer from an
5063 // in-class declaration of the template and instantiate the definition
5064 // from a separate out-of-class definition.
5065 if (PatternDecl->isStaticDataMember() &&
5066 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
5068 // FIXME: Factor out the duplicated instantiation context setup/tear down
5070 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5071 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5073 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5074 "instantiating variable initializer");
5076 // The instantiation is visible here, even if it was first declared in an
5077 // unimported module.
5078 Var->setVisibleDespiteOwningModule();
5080 // If we're performing recursive template instantiation, create our own
5081 // queue of pending implicit instantiations that we will instantiate
5082 // later, while we're still within our own instantiation context.
5083 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5084 /*Enabled=*/Recursive);
5085 LocalInstantiationScope Local(*this);
5086 LocalEagerInstantiationScope LocalInstantiations(*this);
5088 // Enter the scope of this instantiation. We don't use
5089 // PushDeclContext because we don't have a scope.
5090 ContextRAII PreviousContext(*this, Var->getDeclContext());
5091 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
5092 PreviousContext.pop();
5094 // This variable may have local implicit instantiations that need to be
5095 // instantiated within this scope.
5096 LocalInstantiations.perform();
5098 GlobalInstantiations.perform();
5101 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
5102 "not a static data member?");
5105 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
5107 // If we don't have a definition of the variable template, we won't perform
5108 // any instantiation. Rather, we rely on the user to instantiate this
5109 // definition (or provide a specialization for it) in another translation
5111 if (!Def && !DefinitionRequired) {
5112 if (TSK == TSK_ExplicitInstantiationDefinition) {
5113 PendingInstantiations.push_back(
5114 std::make_pair(Var, PointOfInstantiation));
5115 } else if (TSK == TSK_ImplicitInstantiation) {
5116 // Warn about missing definition at the end of translation unit.
5117 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5118 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5119 Diag(PointOfInstantiation, diag::warn_var_template_missing)
5121 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5122 if (getLangOpts().CPlusPlus11)
5123 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
5129 // FIXME: We need to track the instantiation stack in order to know which
5130 // definitions should be visible within this instantiation.
5131 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
5132 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
5133 /*InstantiatedFromMember*/false,
5134 PatternDecl, Def, TSK,
5135 /*Complain*/DefinitionRequired))
5138 // C++11 [temp.explicit]p10:
5139 // Except for inline functions, const variables of literal types, variables
5140 // of reference types, [...] explicit instantiation declarations
5141 // have the effect of suppressing the implicit instantiation of the entity
5142 // to which they refer.
5144 // FIXME: That's not exactly the same as "might be usable in constant
5145 // expressions", which only allows constexpr variables and const integral
5146 // types, not arbitrary const literal types.
5147 if (TSK == TSK_ExplicitInstantiationDeclaration &&
5148 !Var->mightBeUsableInConstantExpressions(getASTContext()))
5151 // Make sure to pass the instantiated variable to the consumer at the end.
5152 struct PassToConsumerRAII {
5153 ASTConsumer &Consumer;
5156 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
5157 : Consumer(Consumer), Var(Var) { }
5159 ~PassToConsumerRAII() {
5160 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
5162 } PassToConsumerRAII(Consumer, Var);
5164 // If we already have a definition, we're done.
5165 if (VarDecl *Def = Var->getDefinition()) {
5166 // We may be explicitly instantiating something we've already implicitly
5168 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
5169 PointOfInstantiation);
5173 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5174 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5176 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5177 "instantiating variable definition");
5179 // If we're performing recursive template instantiation, create our own
5180 // queue of pending implicit instantiations that we will instantiate later,
5181 // while we're still within our own instantiation context.
5182 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5183 /*Enabled=*/Recursive);
5185 // Enter the scope of this instantiation. We don't use
5186 // PushDeclContext because we don't have a scope.
5187 ContextRAII PreviousContext(*this, Var->getDeclContext());
5188 LocalInstantiationScope Local(*this);
5190 LocalEagerInstantiationScope LocalInstantiations(*this);
5192 VarDecl *OldVar = Var;
5193 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
5194 // We're instantiating an inline static data member whose definition was
5195 // provided inside the class.
5196 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5197 } else if (!VarSpec) {
5198 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
5200 } else if (Var->isStaticDataMember() &&
5201 Var->getLexicalDeclContext()->isRecord()) {
5202 // We need to instantiate the definition of a static data member template,
5203 // and all we have is the in-class declaration of it. Instantiate a separate
5204 // declaration of the definition.
5205 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
5207 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5208 VarSpec->getSpecializedTemplate(), Def, nullptr,
5209 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
5211 llvm::PointerUnion<VarTemplateDecl *,
5212 VarTemplatePartialSpecializationDecl *> PatternPtr =
5213 VarSpec->getSpecializedTemplateOrPartial();
5214 if (VarTemplatePartialSpecializationDecl *Partial =
5215 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
5216 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
5217 Partial, &VarSpec->getTemplateInstantiationArgs());
5219 // Merge the definition with the declaration.
5220 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
5221 LookupOrdinaryName, forRedeclarationInCurContext());
5223 MergeVarDecl(Var, R);
5225 // Attach the initializer.
5226 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5229 // Complete the existing variable's definition with an appropriately
5230 // substituted type and initializer.
5231 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
5233 PreviousContext.pop();
5236 PassToConsumerRAII.Var = Var;
5237 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
5238 OldVar->getPointOfInstantiation());
5241 // This variable may have local implicit instantiations that need to be
5242 // instantiated within this scope.
5243 LocalInstantiations.perform();
5245 GlobalInstantiations.perform();
5249 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
5250 const CXXConstructorDecl *Tmpl,
5251 const MultiLevelTemplateArgumentList &TemplateArgs) {
5253 SmallVector<CXXCtorInitializer*, 4> NewInits;
5254 bool AnyErrors = Tmpl->isInvalidDecl();
5256 // Instantiate all the initializers.
5257 for (const auto *Init : Tmpl->inits()) {
5258 // Only instantiate written initializers, let Sema re-construct implicit
5260 if (!Init->isWritten())
5263 SourceLocation EllipsisLoc;
5265 if (Init->isPackExpansion()) {
5266 // This is a pack expansion. We should expand it now.
5267 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
5268 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5269 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
5270 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
5271 bool ShouldExpand = false;
5272 bool RetainExpansion = false;
5273 Optional<unsigned> NumExpansions;
5274 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
5275 BaseTL.getSourceRange(),
5277 TemplateArgs, ShouldExpand,
5281 New->setInvalidDecl();
5284 assert(ShouldExpand && "Partial instantiation of base initializer?");
5286 // Loop over all of the arguments in the argument pack(s),
5287 for (unsigned I = 0; I != *NumExpansions; ++I) {
5288 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
5290 // Instantiate the initializer.
5291 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5292 /*CXXDirectInit=*/true);
5293 if (TempInit.isInvalid()) {
5298 // Instantiate the base type.
5299 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
5301 Init->getSourceLocation(),
5302 New->getDeclName());
5308 // Build the initializer.
5309 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
5310 BaseTInfo, TempInit.get(),
5313 if (NewInit.isInvalid()) {
5318 NewInits.push_back(NewInit.get());
5324 // Instantiate the initializer.
5325 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5326 /*CXXDirectInit=*/true);
5327 if (TempInit.isInvalid()) {
5332 MemInitResult NewInit;
5333 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
5334 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
5336 Init->getSourceLocation(),
5337 New->getDeclName());
5340 New->setInvalidDecl();
5344 if (Init->isBaseInitializer())
5345 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
5346 New->getParent(), EllipsisLoc);
5348 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
5349 cast<CXXRecordDecl>(CurContext->getParent()));
5350 } else if (Init->isMemberInitializer()) {
5351 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
5352 Init->getMemberLocation(),
5357 New->setInvalidDecl();
5361 NewInit = BuildMemberInitializer(Member, TempInit.get(),
5362 Init->getSourceLocation());
5363 } else if (Init->isIndirectMemberInitializer()) {
5364 IndirectFieldDecl *IndirectMember =
5365 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
5366 Init->getMemberLocation(),
5367 Init->getIndirectMember(), TemplateArgs));
5369 if (!IndirectMember) {
5371 New->setInvalidDecl();
5375 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
5376 Init->getSourceLocation());
5379 if (NewInit.isInvalid()) {
5381 New->setInvalidDecl();
5383 NewInits.push_back(NewInit.get());
5387 // Assign all the initializers to the new constructor.
5388 ActOnMemInitializers(New,
5389 /*FIXME: ColonLoc */
5395 // TODO: this could be templated if the various decl types used the
5396 // same method name.
5397 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
5398 ClassTemplateDecl *Instance) {
5399 Pattern = Pattern->getCanonicalDecl();
5402 Instance = Instance->getCanonicalDecl();
5403 if (Pattern == Instance) return true;
5404 Instance = Instance->getInstantiatedFromMemberTemplate();
5410 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
5411 FunctionTemplateDecl *Instance) {
5412 Pattern = Pattern->getCanonicalDecl();
5415 Instance = Instance->getCanonicalDecl();
5416 if (Pattern == Instance) return true;
5417 Instance = Instance->getInstantiatedFromMemberTemplate();
5424 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
5425 ClassTemplatePartialSpecializationDecl *Instance) {
5427 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5429 Instance = cast<ClassTemplatePartialSpecializationDecl>(
5430 Instance->getCanonicalDecl());
5431 if (Pattern == Instance)
5433 Instance = Instance->getInstantiatedFromMember();
5439 static bool isInstantiationOf(CXXRecordDecl *Pattern,
5440 CXXRecordDecl *Instance) {
5441 Pattern = Pattern->getCanonicalDecl();
5444 Instance = Instance->getCanonicalDecl();
5445 if (Pattern == Instance) return true;
5446 Instance = Instance->getInstantiatedFromMemberClass();
5452 static bool isInstantiationOf(FunctionDecl *Pattern,
5453 FunctionDecl *Instance) {
5454 Pattern = Pattern->getCanonicalDecl();
5457 Instance = Instance->getCanonicalDecl();
5458 if (Pattern == Instance) return true;
5459 Instance = Instance->getInstantiatedFromMemberFunction();
5465 static bool isInstantiationOf(EnumDecl *Pattern,
5466 EnumDecl *Instance) {
5467 Pattern = Pattern->getCanonicalDecl();
5470 Instance = Instance->getCanonicalDecl();
5471 if (Pattern == Instance) return true;
5472 Instance = Instance->getInstantiatedFromMemberEnum();
5478 static bool isInstantiationOf(UsingShadowDecl *Pattern,
5479 UsingShadowDecl *Instance,
5481 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
5485 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
5487 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
5490 template<typename T>
5491 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
5493 // An unresolved using declaration can instantiate to an unresolved using
5494 // declaration, or to a using declaration or a using declaration pack.
5496 // Multiple declarations can claim to be instantiated from an unresolved
5497 // using declaration if it's a pack expansion. We want the UsingPackDecl
5498 // in that case, not the individual UsingDecls within the pack.
5499 bool OtherIsPackExpansion;
5500 NamedDecl *OtherFrom;
5501 if (auto *OtherUUD = dyn_cast<T>(Other)) {
5502 OtherIsPackExpansion = OtherUUD->isPackExpansion();
5503 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
5504 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
5505 OtherIsPackExpansion = true;
5506 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
5507 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
5508 OtherIsPackExpansion = false;
5509 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
5513 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
5514 declaresSameEntity(OtherFrom, Pattern);
5517 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
5518 VarDecl *Instance) {
5519 assert(Instance->isStaticDataMember());
5521 Pattern = Pattern->getCanonicalDecl();
5524 Instance = Instance->getCanonicalDecl();
5525 if (Pattern == Instance) return true;
5526 Instance = Instance->getInstantiatedFromStaticDataMember();
5532 // Other is the prospective instantiation
5533 // D is the prospective pattern
5534 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
5535 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
5536 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5538 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
5539 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5541 if (D->getKind() != Other->getKind())
5544 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
5545 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
5547 if (auto *Function = dyn_cast<FunctionDecl>(Other))
5548 return isInstantiationOf(cast<FunctionDecl>(D), Function);
5550 if (auto *Enum = dyn_cast<EnumDecl>(Other))
5551 return isInstantiationOf(cast<EnumDecl>(D), Enum);
5553 if (auto *Var = dyn_cast<VarDecl>(Other))
5554 if (Var->isStaticDataMember())
5555 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
5557 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
5558 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
5560 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
5561 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
5563 if (auto *PartialSpec =
5564 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
5565 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
5568 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
5569 if (!Field->getDeclName()) {
5570 // This is an unnamed field.
5571 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
5572 cast<FieldDecl>(D));
5576 if (auto *Using = dyn_cast<UsingDecl>(Other))
5577 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
5579 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
5580 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
5582 return D->getDeclName() &&
5583 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
5586 template<typename ForwardIterator>
5587 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
5589 ForwardIterator first,
5590 ForwardIterator last) {
5591 for (; first != last; ++first)
5592 if (isInstantiationOf(Ctx, D, *first))
5593 return cast<NamedDecl>(*first);
5598 /// Finds the instantiation of the given declaration context
5599 /// within the current instantiation.
5601 /// \returns NULL if there was an error
5602 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
5603 const MultiLevelTemplateArgumentList &TemplateArgs) {
5604 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
5605 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
5606 return cast_or_null<DeclContext>(ID);
5610 /// Find the instantiation of the given declaration within the
5611 /// current instantiation.
5613 /// This routine is intended to be used when \p D is a declaration
5614 /// referenced from within a template, that needs to mapped into the
5615 /// corresponding declaration within an instantiation. For example,
5619 /// template<typename T>
5622 /// KnownValue = sizeof(T)
5625 /// bool getKind() const { return KnownValue; }
5628 /// template struct X<int>;
5631 /// In the instantiation of X<int>::getKind(), we need to map the \p
5632 /// EnumConstantDecl for \p KnownValue (which refers to
5633 /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
5634 /// \p FindInstantiatedDecl performs this mapping from within the instantiation
5636 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
5637 const MultiLevelTemplateArgumentList &TemplateArgs,
5638 bool FindingInstantiatedContext) {
5639 DeclContext *ParentDC = D->getDeclContext();
5640 // FIXME: Parmeters of pointer to functions (y below) that are themselves
5641 // parameters (p below) can have their ParentDC set to the translation-unit
5642 // - thus we can not consistently check if the ParentDC of such a parameter
5643 // is Dependent or/and a FunctionOrMethod.
5644 // For e.g. this code, during Template argument deduction tries to
5645 // find an instantiated decl for (T y) when the ParentDC for y is
5646 // the translation unit.
5647 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
5648 // float baz(float(*)()) { return 0.0; }
5650 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
5651 // it gets here, always has a FunctionOrMethod as its ParentDC??
5653 // - as long as we have a ParmVarDecl whose parent is non-dependent and
5654 // whose type is not instantiation dependent, do nothing to the decl
5655 // - otherwise find its instantiated decl.
5656 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
5657 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
5659 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
5660 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
5661 ((ParentDC->isFunctionOrMethod() ||
5662 isa<OMPDeclareReductionDecl>(ParentDC) ||
5663 isa<OMPDeclareMapperDecl>(ParentDC)) &&
5664 ParentDC->isDependentContext()) ||
5665 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
5666 // D is a local of some kind. Look into the map of local
5667 // declarations to their instantiations.
5668 if (CurrentInstantiationScope) {
5669 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
5670 if (Decl *FD = Found->dyn_cast<Decl *>())
5671 return cast<NamedDecl>(FD);
5673 int PackIdx = ArgumentPackSubstitutionIndex;
5674 assert(PackIdx != -1 &&
5675 "found declaration pack but not pack expanding");
5676 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
5677 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
5681 // If we're performing a partial substitution during template argument
5682 // deduction, we may not have values for template parameters yet. They
5683 // just map to themselves.
5684 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
5685 isa<TemplateTemplateParmDecl>(D))
5688 if (D->isInvalidDecl())
5691 // Normally this function only searches for already instantiated declaration
5692 // however we have to make an exclusion for local types used before
5693 // definition as in the code:
5695 // template<typename T> void f1() {
5696 // void g1(struct x1);
5700 // In this case instantiation of the type of 'g1' requires definition of
5701 // 'x1', which is defined later. Error recovery may produce an enum used
5702 // before definition. In these cases we need to instantiate relevant
5703 // declarations here.
5704 bool NeedInstantiate = false;
5705 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5706 NeedInstantiate = RD->isLocalClass();
5708 NeedInstantiate = isa<EnumDecl>(D);
5709 if (NeedInstantiate) {
5710 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5711 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5712 return cast<TypeDecl>(Inst);
5715 // If we didn't find the decl, then we must have a label decl that hasn't
5716 // been found yet. Lazily instantiate it and return it now.
5717 assert(isa<LabelDecl>(D));
5719 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5720 assert(Inst && "Failed to instantiate label??");
5722 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5723 return cast<LabelDecl>(Inst);
5726 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
5727 if (!Record->isDependentContext())
5730 // Determine whether this record is the "templated" declaration describing
5731 // a class template or class template partial specialization.
5732 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
5734 ClassTemplate = ClassTemplate->getCanonicalDecl();
5735 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5736 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
5737 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
5739 // Walk the current context to find either the record or an instantiation of
5741 DeclContext *DC = CurContext;
5742 while (!DC->isFileContext()) {
5743 // If we're performing substitution while we're inside the template
5744 // definition, we'll find our own context. We're done.
5745 if (DC->Equals(Record))
5748 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
5749 // Check whether we're in the process of instantiating a class template
5750 // specialization of the template we're mapping.
5751 if (ClassTemplateSpecializationDecl *InstSpec
5752 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
5753 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
5754 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
5758 // Check whether we're in the process of instantiating a member class.
5759 if (isInstantiationOf(Record, InstRecord))
5763 // Move to the outer template scope.
5764 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
5765 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
5766 DC = FD->getLexicalDeclContext();
5769 // An implicit deduction guide acts as if it's within the class template
5770 // specialization described by its name and first N template params.
5771 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
5772 if (Guide && Guide->isImplicit()) {
5773 TemplateDecl *TD = Guide->getDeducedTemplate();
5774 // Convert the arguments to an "as-written" list.
5775 TemplateArgumentListInfo Args(Loc, Loc);
5776 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
5777 TD->getTemplateParameters()->size())) {
5778 ArrayRef<TemplateArgument> Unpacked(Arg);
5779 if (Arg.getKind() == TemplateArgument::Pack)
5780 Unpacked = Arg.pack_elements();
5781 for (TemplateArgument UnpackedArg : Unpacked)
5783 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
5785 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
5788 auto *SubstRecord = T->getAsCXXRecordDecl();
5789 assert(SubstRecord && "class template id not a class type?");
5790 // Check that this template-id names the primary template and not a
5791 // partial or explicit specialization. (In the latter cases, it's
5792 // meaningless to attempt to find an instantiation of D within the
5794 // FIXME: The standard doesn't say what should happen here.
5795 if (FindingInstantiatedContext &&
5796 usesPartialOrExplicitSpecialization(
5797 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
5798 Diag(Loc, diag::err_specialization_not_primary_template)
5799 << T << (SubstRecord->getTemplateSpecializationKind() ==
5800 TSK_ExplicitSpecialization);
5808 DC = DC->getParent();
5811 // Fall through to deal with other dependent record types (e.g.,
5812 // anonymous unions in class templates).
5815 if (!ParentDC->isDependentContext())
5818 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
5822 if (ParentDC != D->getDeclContext()) {
5823 // We performed some kind of instantiation in the parent context,
5824 // so now we need to look into the instantiated parent context to
5825 // find the instantiation of the declaration D.
5827 // If our context used to be dependent, we may need to instantiate
5828 // it before performing lookup into that context.
5829 bool IsBeingInstantiated = false;
5830 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
5831 if (!Spec->isDependentContext()) {
5832 QualType T = Context.getTypeDeclType(Spec);
5833 const RecordType *Tag = T->getAs<RecordType>();
5834 assert(Tag && "type of non-dependent record is not a RecordType");
5835 if (Tag->isBeingDefined())
5836 IsBeingInstantiated = true;
5837 if (!Tag->isBeingDefined() &&
5838 RequireCompleteType(Loc, T, diag::err_incomplete_type))
5841 ParentDC = Tag->getDecl();
5845 NamedDecl *Result = nullptr;
5846 // FIXME: If the name is a dependent name, this lookup won't necessarily
5847 // find it. Does that ever matter?
5848 if (auto Name = D->getDeclName()) {
5849 DeclarationNameInfo NameInfo(Name, D->getLocation());
5850 DeclarationNameInfo NewNameInfo =
5851 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
5852 Name = NewNameInfo.getName();
5855 DeclContext::lookup_result Found = ParentDC->lookup(Name);
5857 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
5858 VarTemplateDecl *Templ = cast_or_null<VarTemplateDecl>(
5859 findInstantiationOf(Context, VTSD->getSpecializedTemplate(),
5860 Found.begin(), Found.end()));
5863 Result = getVarTemplateSpecialization(
5864 Templ, &VTSD->getTemplateArgsInfo(), NewNameInfo, SourceLocation());
5866 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
5868 // Since we don't have a name for the entity we're looking for,
5869 // our only option is to walk through all of the declarations to
5870 // find that name. This will occur in a few cases:
5872 // - anonymous struct/union within a template
5873 // - unnamed class/struct/union/enum within a template
5875 // FIXME: Find a better way to find these instantiations!
5876 Result = findInstantiationOf(Context, D,
5877 ParentDC->decls_begin(),
5878 ParentDC->decls_end());
5882 if (isa<UsingShadowDecl>(D)) {
5883 // UsingShadowDecls can instantiate to nothing because of using hiding.
5884 } else if (Diags.hasErrorOccurred()) {
5885 // We've already complained about something, so most likely this
5886 // declaration failed to instantiate. There's no point in complaining
5887 // further, since this is normal in invalid code.
5888 } else if (IsBeingInstantiated) {
5889 // The class in which this member exists is currently being
5890 // instantiated, and we haven't gotten around to instantiating this
5891 // member yet. This can happen when the code uses forward declarations
5892 // of member classes, and introduces ordering dependencies via
5893 // template instantiation.
5894 Diag(Loc, diag::err_member_not_yet_instantiated)
5896 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
5897 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
5898 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
5899 // This enumeration constant was found when the template was defined,
5900 // but can't be found in the instantiation. This can happen if an
5901 // unscoped enumeration member is explicitly specialized.
5902 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
5903 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
5905 assert(Spec->getTemplateSpecializationKind() ==
5906 TSK_ExplicitSpecialization);
5907 Diag(Loc, diag::err_enumerator_does_not_exist)
5909 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
5910 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
5911 << Context.getTypeDeclType(Spec);
5913 // We should have found something, but didn't.
5914 llvm_unreachable("Unable to find instantiation of declaration!");
5924 /// Performs template instantiation for all implicit template
5925 /// instantiations we have seen until this point.
5926 void Sema::PerformPendingInstantiations(bool LocalOnly) {
5927 while (!PendingLocalImplicitInstantiations.empty() ||
5928 (!LocalOnly && !PendingInstantiations.empty())) {
5929 PendingImplicitInstantiation Inst;
5931 if (PendingLocalImplicitInstantiations.empty()) {
5932 Inst = PendingInstantiations.front();
5933 PendingInstantiations.pop_front();
5935 Inst = PendingLocalImplicitInstantiations.front();
5936 PendingLocalImplicitInstantiations.pop_front();
5939 // Instantiate function definitions
5940 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
5941 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
5942 TSK_ExplicitInstantiationDefinition;
5943 if (Function->isMultiVersion()) {
5944 getASTContext().forEachMultiversionedFunctionVersion(
5945 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
5946 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
5947 DefinitionRequired, true);
5948 if (CurFD->isDefined())
5949 CurFD->setInstantiationIsPending(false);
5952 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
5953 DefinitionRequired, true);
5954 if (Function->isDefined())
5955 Function->setInstantiationIsPending(false);
5960 // Instantiate variable definitions
5961 VarDecl *Var = cast<VarDecl>(Inst.first);
5963 assert((Var->isStaticDataMember() ||
5964 isa<VarTemplateSpecializationDecl>(Var)) &&
5965 "Not a static data member, nor a variable template"
5966 " specialization?");
5968 // Don't try to instantiate declarations if the most recent redeclaration
5970 if (Var->getMostRecentDecl()->isInvalidDecl())
5973 // Check if the most recent declaration has changed the specialization kind
5974 // and removed the need for implicit instantiation.
5975 switch (Var->getMostRecentDecl()
5976 ->getTemplateSpecializationKindForInstantiation()) {
5977 case TSK_Undeclared:
5978 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
5979 case TSK_ExplicitInstantiationDeclaration:
5980 case TSK_ExplicitSpecialization:
5981 continue; // No longer need to instantiate this type.
5982 case TSK_ExplicitInstantiationDefinition:
5983 // We only need an instantiation if the pending instantiation *is* the
5984 // explicit instantiation.
5985 if (Var != Var->getMostRecentDecl())
5988 case TSK_ImplicitInstantiation:
5992 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5993 "instantiating variable definition");
5994 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
5995 TSK_ExplicitInstantiationDefinition;
5997 // Instantiate static data member definitions or variable template
5999 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
6000 DefinitionRequired, true);
6004 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
6005 const MultiLevelTemplateArgumentList &TemplateArgs) {
6006 for (auto DD : Pattern->ddiags()) {
6007 switch (DD->getKind()) {
6008 case DependentDiagnostic::Access:
6009 HandleDependentAccessCheck(*DD, TemplateArgs);