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 //===----------------------------------------------------------------------===/
12 #include "TreeTransform.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTMutationListener.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/DependentDiagnostic.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/PrettyDeclStackTrace.h"
22 #include "clang/AST/TypeLoc.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/EnterExpressionEvaluationContext.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/ScopeInfo.h"
29 #include "clang/Sema/SemaInternal.h"
30 #include "clang/Sema/Template.h"
31 #include "clang/Sema/TemplateInstCallback.h"
32 #include "llvm/Support/TimeProfiler.h"
35 using namespace clang
;
37 static bool isDeclWithinFunction(const Decl
*D
) {
38 const DeclContext
*DC
= D
->getDeclContext();
39 if (DC
->isFunctionOrMethod())
43 return cast
<CXXRecordDecl
>(DC
)->isLocalClass();
48 template<typename DeclT
>
49 static bool SubstQualifier(Sema
&SemaRef
, const DeclT
*OldDecl
, DeclT
*NewDecl
,
50 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
51 if (!OldDecl
->getQualifierLoc())
54 assert((NewDecl
->getFriendObjectKind() ||
55 !OldDecl
->getLexicalDeclContext()->isDependentContext()) &&
56 "non-friend with qualified name defined in dependent context");
57 Sema::ContextRAII
SavedContext(
59 const_cast<DeclContext
*>(NewDecl
->getFriendObjectKind()
60 ? NewDecl
->getLexicalDeclContext()
61 : OldDecl
->getLexicalDeclContext()));
63 NestedNameSpecifierLoc NewQualifierLoc
64 = SemaRef
.SubstNestedNameSpecifierLoc(OldDecl
->getQualifierLoc(),
70 NewDecl
->setQualifierInfo(NewQualifierLoc
);
74 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl
*OldDecl
,
75 DeclaratorDecl
*NewDecl
) {
76 return ::SubstQualifier(SemaRef
, OldDecl
, NewDecl
, TemplateArgs
);
79 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl
*OldDecl
,
81 return ::SubstQualifier(SemaRef
, OldDecl
, NewDecl
, TemplateArgs
);
84 // Include attribute instantiation code.
85 #include "clang/Sema/AttrTemplateInstantiate.inc"
87 static void instantiateDependentAlignedAttr(
88 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
89 const AlignedAttr
*Aligned
, Decl
*New
, bool IsPackExpansion
) {
90 if (Aligned
->isAlignmentExpr()) {
91 // The alignment expression is a constant expression.
92 EnterExpressionEvaluationContext
Unevaluated(
93 S
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
94 ExprResult Result
= S
.SubstExpr(Aligned
->getAlignmentExpr(), TemplateArgs
);
95 if (!Result
.isInvalid())
96 S
.AddAlignedAttr(New
, *Aligned
, Result
.getAs
<Expr
>(), IsPackExpansion
);
98 if (TypeSourceInfo
*Result
=
99 S
.SubstType(Aligned
->getAlignmentType(), TemplateArgs
,
100 Aligned
->getLocation(), DeclarationName())) {
101 if (!S
.CheckAlignasTypeArgument(Aligned
->getSpelling(), Result
,
102 Aligned
->getLocation(),
103 Result
->getTypeLoc().getSourceRange()))
104 S
.AddAlignedAttr(New
, *Aligned
, Result
, IsPackExpansion
);
109 static void instantiateDependentAlignedAttr(
110 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
111 const AlignedAttr
*Aligned
, Decl
*New
) {
112 if (!Aligned
->isPackExpansion()) {
113 instantiateDependentAlignedAttr(S
, TemplateArgs
, Aligned
, New
, false);
117 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
118 if (Aligned
->isAlignmentExpr())
119 S
.collectUnexpandedParameterPacks(Aligned
->getAlignmentExpr(),
122 S
.collectUnexpandedParameterPacks(Aligned
->getAlignmentType()->getTypeLoc(),
124 assert(!Unexpanded
.empty() && "Pack expansion without parameter packs?");
126 // Determine whether we can expand this attribute pack yet.
127 bool Expand
= true, RetainExpansion
= false;
128 std::optional
<unsigned> NumExpansions
;
129 // FIXME: Use the actual location of the ellipsis.
130 SourceLocation EllipsisLoc
= Aligned
->getLocation();
131 if (S
.CheckParameterPacksForExpansion(EllipsisLoc
, Aligned
->getRange(),
132 Unexpanded
, TemplateArgs
, Expand
,
133 RetainExpansion
, NumExpansions
))
137 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(S
, -1);
138 instantiateDependentAlignedAttr(S
, TemplateArgs
, Aligned
, New
, true);
140 for (unsigned I
= 0; I
!= *NumExpansions
; ++I
) {
141 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(S
, I
);
142 instantiateDependentAlignedAttr(S
, TemplateArgs
, Aligned
, New
, false);
147 static void instantiateDependentAssumeAlignedAttr(
148 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
149 const AssumeAlignedAttr
*Aligned
, Decl
*New
) {
150 // The alignment expression is a constant expression.
151 EnterExpressionEvaluationContext
Unevaluated(
152 S
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
154 Expr
*E
, *OE
= nullptr;
155 ExprResult Result
= S
.SubstExpr(Aligned
->getAlignment(), TemplateArgs
);
156 if (Result
.isInvalid())
158 E
= Result
.getAs
<Expr
>();
160 if (Aligned
->getOffset()) {
161 Result
= S
.SubstExpr(Aligned
->getOffset(), TemplateArgs
);
162 if (Result
.isInvalid())
164 OE
= Result
.getAs
<Expr
>();
167 S
.AddAssumeAlignedAttr(New
, *Aligned
, E
, OE
);
170 static void instantiateDependentAlignValueAttr(
171 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
172 const AlignValueAttr
*Aligned
, Decl
*New
) {
173 // The alignment expression is a constant expression.
174 EnterExpressionEvaluationContext
Unevaluated(
175 S
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
176 ExprResult Result
= S
.SubstExpr(Aligned
->getAlignment(), TemplateArgs
);
177 if (!Result
.isInvalid())
178 S
.AddAlignValueAttr(New
, *Aligned
, Result
.getAs
<Expr
>());
181 static void instantiateDependentAllocAlignAttr(
182 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
183 const AllocAlignAttr
*Align
, Decl
*New
) {
184 Expr
*Param
= IntegerLiteral::Create(
186 llvm::APInt(64, Align
->getParamIndex().getSourceIndex()),
187 S
.getASTContext().UnsignedLongLongTy
, Align
->getLocation());
188 S
.AddAllocAlignAttr(New
, *Align
, Param
);
191 static void instantiateDependentAnnotationAttr(
192 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
193 const AnnotateAttr
*Attr
, Decl
*New
) {
194 EnterExpressionEvaluationContext
Unevaluated(
195 S
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
197 // If the attribute has delayed arguments it will have to instantiate those
198 // and handle them as new arguments for the attribute.
199 bool HasDelayedArgs
= Attr
->delayedArgs_size();
201 ArrayRef
<Expr
*> ArgsToInstantiate
=
203 ? ArrayRef
<Expr
*>{Attr
->delayedArgs_begin(), Attr
->delayedArgs_end()}
204 : ArrayRef
<Expr
*>{Attr
->args_begin(), Attr
->args_end()};
206 SmallVector
<Expr
*, 4> Args
;
207 if (S
.SubstExprs(ArgsToInstantiate
,
208 /*IsCall=*/false, TemplateArgs
, Args
))
211 StringRef Str
= Attr
->getAnnotation();
212 if (HasDelayedArgs
) {
213 if (Args
.size() < 1) {
214 S
.Diag(Attr
->getLoc(), diag::err_attribute_too_few_arguments
)
219 if (!S
.checkStringLiteralArgumentAttr(*Attr
, Args
[0], Str
))
222 llvm::SmallVector
<Expr
*, 4> ActualArgs
;
223 ActualArgs
.insert(ActualArgs
.begin(), Args
.begin() + 1, Args
.end());
224 std::swap(Args
, ActualArgs
);
226 S
.AddAnnotationAttr(New
, *Attr
, Str
, Args
);
229 static Expr
*instantiateDependentFunctionAttrCondition(
230 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
231 const Attr
*A
, Expr
*OldCond
, const Decl
*Tmpl
, FunctionDecl
*New
) {
232 Expr
*Cond
= nullptr;
234 Sema::ContextRAII
SwitchContext(S
, New
);
235 EnterExpressionEvaluationContext
Unevaluated(
236 S
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
237 ExprResult Result
= S
.SubstExpr(OldCond
, TemplateArgs
);
238 if (Result
.isInvalid())
240 Cond
= Result
.getAs
<Expr
>();
242 if (!Cond
->isTypeDependent()) {
243 ExprResult Converted
= S
.PerformContextuallyConvertToBool(Cond
);
244 if (Converted
.isInvalid())
246 Cond
= Converted
.get();
249 SmallVector
<PartialDiagnosticAt
, 8> Diags
;
250 if (OldCond
->isValueDependent() && !Cond
->isValueDependent() &&
251 !Expr::isPotentialConstantExprUnevaluated(Cond
, New
, Diags
)) {
252 S
.Diag(A
->getLocation(), diag::err_attr_cond_never_constant_expr
) << A
;
253 for (const auto &P
: Diags
)
254 S
.Diag(P
.first
, P
.second
);
260 static void instantiateDependentEnableIfAttr(
261 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
262 const EnableIfAttr
*EIA
, const Decl
*Tmpl
, FunctionDecl
*New
) {
263 Expr
*Cond
= instantiateDependentFunctionAttrCondition(
264 S
, TemplateArgs
, EIA
, EIA
->getCond(), Tmpl
, New
);
267 New
->addAttr(new (S
.getASTContext()) EnableIfAttr(S
.getASTContext(), *EIA
,
268 Cond
, EIA
->getMessage()));
271 static void instantiateDependentDiagnoseIfAttr(
272 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
273 const DiagnoseIfAttr
*DIA
, const Decl
*Tmpl
, FunctionDecl
*New
) {
274 Expr
*Cond
= instantiateDependentFunctionAttrCondition(
275 S
, TemplateArgs
, DIA
, DIA
->getCond(), Tmpl
, New
);
278 New
->addAttr(new (S
.getASTContext()) DiagnoseIfAttr(
279 S
.getASTContext(), *DIA
, Cond
, DIA
->getMessage(),
280 DIA
->getDiagnosticType(), DIA
->getArgDependent(), New
));
283 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
284 // template A as the base and arguments from TemplateArgs.
285 static void instantiateDependentCUDALaunchBoundsAttr(
286 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
287 const CUDALaunchBoundsAttr
&Attr
, Decl
*New
) {
288 // The alignment expression is a constant expression.
289 EnterExpressionEvaluationContext
Unevaluated(
290 S
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
292 ExprResult Result
= S
.SubstExpr(Attr
.getMaxThreads(), TemplateArgs
);
293 if (Result
.isInvalid())
295 Expr
*MaxThreads
= Result
.getAs
<Expr
>();
297 Expr
*MinBlocks
= nullptr;
298 if (Attr
.getMinBlocks()) {
299 Result
= S
.SubstExpr(Attr
.getMinBlocks(), TemplateArgs
);
300 if (Result
.isInvalid())
302 MinBlocks
= Result
.getAs
<Expr
>();
305 Expr
*MaxBlocks
= nullptr;
306 if (Attr
.getMaxBlocks()) {
307 Result
= S
.SubstExpr(Attr
.getMaxBlocks(), TemplateArgs
);
308 if (Result
.isInvalid())
310 MaxBlocks
= Result
.getAs
<Expr
>();
313 S
.AddLaunchBoundsAttr(New
, Attr
, MaxThreads
, MinBlocks
, MaxBlocks
);
317 instantiateDependentModeAttr(Sema
&S
,
318 const MultiLevelTemplateArgumentList
&TemplateArgs
,
319 const ModeAttr
&Attr
, Decl
*New
) {
320 S
.AddModeAttr(New
, Attr
, Attr
.getMode(),
321 /*InInstantiation=*/true);
324 /// Instantiation of 'declare simd' attribute and its arguments.
325 static void instantiateOMPDeclareSimdDeclAttr(
326 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
327 const OMPDeclareSimdDeclAttr
&Attr
, Decl
*New
) {
328 // Allow 'this' in clauses with varlists.
329 if (auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(New
))
330 New
= FTD
->getTemplatedDecl();
331 auto *FD
= cast
<FunctionDecl
>(New
);
332 auto *ThisContext
= dyn_cast_or_null
<CXXRecordDecl
>(FD
->getDeclContext());
333 SmallVector
<Expr
*, 4> Uniforms
, Aligneds
, Alignments
, Linears
, Steps
;
334 SmallVector
<unsigned, 4> LinModifiers
;
336 auto SubstExpr
= [&](Expr
*E
) -> ExprResult
{
337 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParenImpCasts()))
338 if (auto *PVD
= dyn_cast
<ParmVarDecl
>(DRE
->getDecl())) {
339 Sema::ContextRAII
SavedContext(S
, FD
);
340 LocalInstantiationScope
Local(S
);
341 if (FD
->getNumParams() > PVD
->getFunctionScopeIndex())
342 Local
.InstantiatedLocal(
343 PVD
, FD
->getParamDecl(PVD
->getFunctionScopeIndex()));
344 return S
.SubstExpr(E
, TemplateArgs
);
346 Sema::CXXThisScopeRAII
ThisScope(S
, ThisContext
, Qualifiers(),
347 FD
->isCXXInstanceMember());
348 return S
.SubstExpr(E
, TemplateArgs
);
351 // Substitute a single OpenMP clause, which is a potentially-evaluated
353 auto Subst
= [&](Expr
*E
) -> ExprResult
{
354 EnterExpressionEvaluationContext
Evaluated(
355 S
, Sema::ExpressionEvaluationContext::PotentiallyEvaluated
);
356 ExprResult Res
= SubstExpr(E
);
359 return S
.ActOnFinishFullExpr(Res
.get(), false);
363 if (auto *E
= Attr
.getSimdlen())
366 if (Attr
.uniforms_size() > 0) {
367 for(auto *E
: Attr
.uniforms()) {
368 ExprResult Inst
= Subst(E
);
369 if (Inst
.isInvalid())
371 Uniforms
.push_back(Inst
.get());
375 auto AI
= Attr
.alignments_begin();
376 for (auto *E
: Attr
.aligneds()) {
377 ExprResult Inst
= Subst(E
);
378 if (Inst
.isInvalid())
380 Aligneds
.push_back(Inst
.get());
383 Inst
= S
.SubstExpr(*AI
, TemplateArgs
);
384 Alignments
.push_back(Inst
.get());
388 auto SI
= Attr
.steps_begin();
389 for (auto *E
: Attr
.linears()) {
390 ExprResult Inst
= Subst(E
);
391 if (Inst
.isInvalid())
393 Linears
.push_back(Inst
.get());
396 Inst
= S
.SubstExpr(*SI
, TemplateArgs
);
397 Steps
.push_back(Inst
.get());
400 LinModifiers
.append(Attr
.modifiers_begin(), Attr
.modifiers_end());
401 (void)S
.ActOnOpenMPDeclareSimdDirective(
402 S
.ConvertDeclToDeclGroup(New
), Attr
.getBranchState(), Simdlen
.get(),
403 Uniforms
, Aligneds
, Alignments
, Linears
, LinModifiers
, Steps
,
407 /// Instantiation of 'declare variant' attribute and its arguments.
408 static void instantiateOMPDeclareVariantAttr(
409 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
410 const OMPDeclareVariantAttr
&Attr
, Decl
*New
) {
411 // Allow 'this' in clauses with varlists.
412 if (auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(New
))
413 New
= FTD
->getTemplatedDecl();
414 auto *FD
= cast
<FunctionDecl
>(New
);
415 auto *ThisContext
= dyn_cast_or_null
<CXXRecordDecl
>(FD
->getDeclContext());
417 auto &&SubstExpr
= [FD
, ThisContext
, &S
, &TemplateArgs
](Expr
*E
) {
418 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParenImpCasts()))
419 if (auto *PVD
= dyn_cast
<ParmVarDecl
>(DRE
->getDecl())) {
420 Sema::ContextRAII
SavedContext(S
, FD
);
421 LocalInstantiationScope
Local(S
);
422 if (FD
->getNumParams() > PVD
->getFunctionScopeIndex())
423 Local
.InstantiatedLocal(
424 PVD
, FD
->getParamDecl(PVD
->getFunctionScopeIndex()));
425 return S
.SubstExpr(E
, TemplateArgs
);
427 Sema::CXXThisScopeRAII
ThisScope(S
, ThisContext
, Qualifiers(),
428 FD
->isCXXInstanceMember());
429 return S
.SubstExpr(E
, TemplateArgs
);
432 // Substitute a single OpenMP clause, which is a potentially-evaluated
434 auto &&Subst
= [&SubstExpr
, &S
](Expr
*E
) {
435 EnterExpressionEvaluationContext
Evaluated(
436 S
, Sema::ExpressionEvaluationContext::PotentiallyEvaluated
);
437 ExprResult Res
= SubstExpr(E
);
440 return S
.ActOnFinishFullExpr(Res
.get(), false);
443 ExprResult VariantFuncRef
;
444 if (Expr
*E
= Attr
.getVariantFuncRef()) {
445 // Do not mark function as is used to prevent its emission if this is the
446 // only place where it is used.
447 EnterExpressionEvaluationContext
Unevaluated(
448 S
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
449 VariantFuncRef
= Subst(E
);
452 // Copy the template version of the OMPTraitInfo and run substitute on all
453 // score and condition expressiosn.
454 OMPTraitInfo
&TI
= S
.getASTContext().getNewOMPTraitInfo();
455 TI
= *Attr
.getTraitInfos();
457 // Try to substitute template parameters in score and condition expressions.
458 auto SubstScoreOrConditionExpr
= [&S
, Subst
](Expr
*&E
, bool) {
460 EnterExpressionEvaluationContext
Unevaluated(
461 S
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
462 ExprResult ER
= Subst(E
);
470 if (TI
.anyScoreOrCondition(SubstScoreOrConditionExpr
))
473 Expr
*E
= VariantFuncRef
.get();
475 // Check function/variant ref for `omp declare variant` but not for `omp
476 // begin declare variant` (which use implicit attributes).
477 std::optional
<std::pair
<FunctionDecl
*, Expr
*>> DeclVarData
=
478 S
.checkOpenMPDeclareVariantFunction(S
.ConvertDeclToDeclGroup(New
), E
, TI
,
479 Attr
.appendArgs_size(),
485 E
= DeclVarData
->second
;
486 FD
= DeclVarData
->first
;
488 if (auto *VariantDRE
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParenImpCasts())) {
489 if (auto *VariantFD
= dyn_cast
<FunctionDecl
>(VariantDRE
->getDecl())) {
490 if (auto *VariantFTD
= VariantFD
->getDescribedFunctionTemplate()) {
491 if (!VariantFTD
->isThisDeclarationADefinition())
493 Sema::TentativeAnalysisScope
Trap(S
);
494 const TemplateArgumentList
*TAL
= TemplateArgumentList::CreateCopy(
495 S
.Context
, TemplateArgs
.getInnermost());
497 auto *SubstFD
= S
.InstantiateFunctionDeclaration(VariantFTD
, TAL
,
501 QualType NewType
= S
.Context
.mergeFunctionTypes(
502 SubstFD
->getType(), FD
->getType(),
503 /* OfBlockPointer */ false,
504 /* Unqualified */ false, /* AllowCXX */ true);
505 if (NewType
.isNull())
507 S
.InstantiateFunctionDefinition(
508 New
->getLocation(), SubstFD
, /* Recursive */ true,
509 /* DefinitionRequired */ false, /* AtEndOfTU */ false);
510 SubstFD
->setInstantiationIsPending(!SubstFD
->isDefined());
511 E
= DeclRefExpr::Create(S
.Context
, NestedNameSpecifierLoc(),
512 SourceLocation(), SubstFD
,
513 /* RefersToEnclosingVariableOrCapture */ false,
514 /* NameLoc */ SubstFD
->getLocation(),
515 SubstFD
->getType(), ExprValueKind::VK_PRValue
);
520 SmallVector
<Expr
*, 8> NothingExprs
;
521 SmallVector
<Expr
*, 8> NeedDevicePtrExprs
;
522 SmallVector
<OMPInteropInfo
, 4> AppendArgs
;
524 for (Expr
*E
: Attr
.adjustArgsNothing()) {
525 ExprResult ER
= Subst(E
);
528 NothingExprs
.push_back(ER
.get());
530 for (Expr
*E
: Attr
.adjustArgsNeedDevicePtr()) {
531 ExprResult ER
= Subst(E
);
534 NeedDevicePtrExprs
.push_back(ER
.get());
536 for (OMPInteropInfo
&II
: Attr
.appendArgs()) {
537 // When prefer_type is implemented for append_args handle them here too.
538 AppendArgs
.emplace_back(II
.IsTarget
, II
.IsTargetSync
);
541 S
.ActOnOpenMPDeclareVariantDirective(
542 FD
, E
, TI
, NothingExprs
, NeedDevicePtrExprs
, AppendArgs
, SourceLocation(),
543 SourceLocation(), Attr
.getRange());
546 static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
547 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
548 const AMDGPUFlatWorkGroupSizeAttr
&Attr
, Decl
*New
) {
549 // Both min and max expression are constant expressions.
550 EnterExpressionEvaluationContext
Unevaluated(
551 S
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
553 ExprResult Result
= S
.SubstExpr(Attr
.getMin(), TemplateArgs
);
554 if (Result
.isInvalid())
556 Expr
*MinExpr
= Result
.getAs
<Expr
>();
558 Result
= S
.SubstExpr(Attr
.getMax(), TemplateArgs
);
559 if (Result
.isInvalid())
561 Expr
*MaxExpr
= Result
.getAs
<Expr
>();
563 S
.addAMDGPUFlatWorkGroupSizeAttr(New
, Attr
, MinExpr
, MaxExpr
);
566 ExplicitSpecifier
Sema::instantiateExplicitSpecifier(
567 const MultiLevelTemplateArgumentList
&TemplateArgs
, ExplicitSpecifier ES
) {
570 Expr
*OldCond
= ES
.getExpr();
571 Expr
*Cond
= nullptr;
573 EnterExpressionEvaluationContext
Unevaluated(
574 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
575 ExprResult SubstResult
= SubstExpr(OldCond
, TemplateArgs
);
576 if (SubstResult
.isInvalid()) {
577 return ExplicitSpecifier::Invalid();
579 Cond
= SubstResult
.get();
581 ExplicitSpecifier
Result(Cond
, ES
.getKind());
582 if (!Cond
->isTypeDependent())
583 tryResolveExplicitSpecifier(Result
);
587 static void instantiateDependentAMDGPUWavesPerEUAttr(
588 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
589 const AMDGPUWavesPerEUAttr
&Attr
, Decl
*New
) {
590 // Both min and max expression are constant expressions.
591 EnterExpressionEvaluationContext
Unevaluated(
592 S
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
594 ExprResult Result
= S
.SubstExpr(Attr
.getMin(), TemplateArgs
);
595 if (Result
.isInvalid())
597 Expr
*MinExpr
= Result
.getAs
<Expr
>();
599 Expr
*MaxExpr
= nullptr;
600 if (auto Max
= Attr
.getMax()) {
601 Result
= S
.SubstExpr(Max
, TemplateArgs
);
602 if (Result
.isInvalid())
604 MaxExpr
= Result
.getAs
<Expr
>();
607 S
.addAMDGPUWavesPerEUAttr(New
, Attr
, MinExpr
, MaxExpr
);
610 // This doesn't take any template parameters, but we have a custom action that
611 // needs to happen when the kernel itself is instantiated. We need to run the
612 // ItaniumMangler to mark the names required to name this kernel.
613 static void instantiateDependentSYCLKernelAttr(
614 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
615 const SYCLKernelAttr
&Attr
, Decl
*New
) {
616 New
->addAttr(Attr
.clone(S
.getASTContext()));
619 /// Determine whether the attribute A might be relevant to the declaration D.
620 /// If not, we can skip instantiating it. The attribute may or may not have
621 /// been instantiated yet.
622 static bool isRelevantAttr(Sema
&S
, const Decl
*D
, const Attr
*A
) {
623 // 'preferred_name' is only relevant to the matching specialization of the
625 if (const auto *PNA
= dyn_cast
<PreferredNameAttr
>(A
)) {
626 QualType T
= PNA
->getTypedefType();
627 const auto *RD
= cast
<CXXRecordDecl
>(D
);
628 if (!T
->isDependentType() && !RD
->isDependentContext() &&
629 !declaresSameEntity(T
->getAsCXXRecordDecl(), RD
))
631 for (const auto *ExistingPNA
: D
->specific_attrs
<PreferredNameAttr
>())
632 if (S
.Context
.hasSameType(ExistingPNA
->getTypedefType(),
633 PNA
->getTypedefType()))
638 if (const auto *BA
= dyn_cast
<BuiltinAttr
>(A
)) {
639 const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
);
640 switch (BA
->getID()) {
641 case Builtin::BIforward
:
642 // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
643 // type and returns an lvalue reference type. The library implementation
644 // will produce an error in this case; don't get in its way.
645 if (FD
&& FD
->getNumParams() >= 1 &&
646 FD
->getParamDecl(0)->getType()->isRValueReferenceType() &&
647 FD
->getReturnType()->isLValueReferenceType()) {
651 case Builtin::BImove
:
652 case Builtin::BImove_if_noexcept
:
653 // HACK: Super-old versions of libc++ (3.1 and earlier) provide
654 // std::forward and std::move overloads that sometimes return by value
655 // instead of by reference when building in C++98 mode. Don't treat such
656 // cases as builtins.
657 if (FD
&& !FD
->getReturnType()->isReferenceType())
666 void Sema::InstantiateAttrsForDecl(
667 const MultiLevelTemplateArgumentList
&TemplateArgs
, const Decl
*Tmpl
,
668 Decl
*New
, LateInstantiatedAttrVec
*LateAttrs
,
669 LocalInstantiationScope
*OuterMostScope
) {
670 if (NamedDecl
*ND
= dyn_cast
<NamedDecl
>(New
)) {
671 // FIXME: This function is called multiple times for the same template
672 // specialization. We should only instantiate attributes that were added
673 // since the previous instantiation.
674 for (const auto *TmplAttr
: Tmpl
->attrs()) {
675 if (!isRelevantAttr(*this, New
, TmplAttr
))
678 // FIXME: If any of the special case versions from InstantiateAttrs become
679 // applicable to template declaration, we'll need to add them here.
680 CXXThisScopeRAII
ThisScope(
681 *this, dyn_cast_or_null
<CXXRecordDecl
>(ND
->getDeclContext()),
682 Qualifiers(), ND
->isCXXInstanceMember());
684 Attr
*NewAttr
= sema::instantiateTemplateAttributeForDecl(
685 TmplAttr
, Context
, *this, TemplateArgs
);
686 if (NewAttr
&& isRelevantAttr(*this, New
, NewAttr
))
687 New
->addAttr(NewAttr
);
692 static Sema::RetainOwnershipKind
693 attrToRetainOwnershipKind(const Attr
*A
) {
694 switch (A
->getKind()) {
695 case clang::attr::CFConsumed
:
696 return Sema::RetainOwnershipKind::CF
;
697 case clang::attr::OSConsumed
:
698 return Sema::RetainOwnershipKind::OS
;
699 case clang::attr::NSConsumed
:
700 return Sema::RetainOwnershipKind::NS
;
702 llvm_unreachable("Wrong argument supplied");
706 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList
&TemplateArgs
,
707 const Decl
*Tmpl
, Decl
*New
,
708 LateInstantiatedAttrVec
*LateAttrs
,
709 LocalInstantiationScope
*OuterMostScope
) {
710 for (const auto *TmplAttr
: Tmpl
->attrs()) {
711 if (!isRelevantAttr(*this, New
, TmplAttr
))
714 // FIXME: This should be generalized to more than just the AlignedAttr.
715 const AlignedAttr
*Aligned
= dyn_cast
<AlignedAttr
>(TmplAttr
);
716 if (Aligned
&& Aligned
->isAlignmentDependent()) {
717 instantiateDependentAlignedAttr(*this, TemplateArgs
, Aligned
, New
);
721 if (const auto *AssumeAligned
= dyn_cast
<AssumeAlignedAttr
>(TmplAttr
)) {
722 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs
, AssumeAligned
, New
);
726 if (const auto *AlignValue
= dyn_cast
<AlignValueAttr
>(TmplAttr
)) {
727 instantiateDependentAlignValueAttr(*this, TemplateArgs
, AlignValue
, New
);
731 if (const auto *AllocAlign
= dyn_cast
<AllocAlignAttr
>(TmplAttr
)) {
732 instantiateDependentAllocAlignAttr(*this, TemplateArgs
, AllocAlign
, New
);
736 if (const auto *Annotate
= dyn_cast
<AnnotateAttr
>(TmplAttr
)) {
737 instantiateDependentAnnotationAttr(*this, TemplateArgs
, Annotate
, New
);
741 if (const auto *EnableIf
= dyn_cast
<EnableIfAttr
>(TmplAttr
)) {
742 instantiateDependentEnableIfAttr(*this, TemplateArgs
, EnableIf
, Tmpl
,
743 cast
<FunctionDecl
>(New
));
747 if (const auto *DiagnoseIf
= dyn_cast
<DiagnoseIfAttr
>(TmplAttr
)) {
748 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs
, DiagnoseIf
, Tmpl
,
749 cast
<FunctionDecl
>(New
));
753 if (const auto *CUDALaunchBounds
=
754 dyn_cast
<CUDALaunchBoundsAttr
>(TmplAttr
)) {
755 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs
,
756 *CUDALaunchBounds
, New
);
760 if (const auto *Mode
= dyn_cast
<ModeAttr
>(TmplAttr
)) {
761 instantiateDependentModeAttr(*this, TemplateArgs
, *Mode
, New
);
765 if (const auto *OMPAttr
= dyn_cast
<OMPDeclareSimdDeclAttr
>(TmplAttr
)) {
766 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs
, *OMPAttr
, New
);
770 if (const auto *OMPAttr
= dyn_cast
<OMPDeclareVariantAttr
>(TmplAttr
)) {
771 instantiateOMPDeclareVariantAttr(*this, TemplateArgs
, *OMPAttr
, New
);
775 if (const auto *AMDGPUFlatWorkGroupSize
=
776 dyn_cast
<AMDGPUFlatWorkGroupSizeAttr
>(TmplAttr
)) {
777 instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
778 *this, TemplateArgs
, *AMDGPUFlatWorkGroupSize
, New
);
781 if (const auto *AMDGPUFlatWorkGroupSize
=
782 dyn_cast
<AMDGPUWavesPerEUAttr
>(TmplAttr
)) {
783 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs
,
784 *AMDGPUFlatWorkGroupSize
, New
);
787 // Existing DLL attribute on the instantiation takes precedence.
788 if (TmplAttr
->getKind() == attr::DLLExport
||
789 TmplAttr
->getKind() == attr::DLLImport
) {
790 if (New
->hasAttr
<DLLExportAttr
>() || New
->hasAttr
<DLLImportAttr
>()) {
795 if (const auto *ABIAttr
= dyn_cast
<ParameterABIAttr
>(TmplAttr
)) {
796 AddParameterABIAttr(New
, *ABIAttr
, ABIAttr
->getABI());
800 if (isa
<NSConsumedAttr
>(TmplAttr
) || isa
<OSConsumedAttr
>(TmplAttr
) ||
801 isa
<CFConsumedAttr
>(TmplAttr
)) {
802 AddXConsumedAttr(New
, *TmplAttr
, attrToRetainOwnershipKind(TmplAttr
),
803 /*template instantiation=*/true);
807 if (auto *A
= dyn_cast
<PointerAttr
>(TmplAttr
)) {
808 if (!New
->hasAttr
<PointerAttr
>())
809 New
->addAttr(A
->clone(Context
));
813 if (auto *A
= dyn_cast
<OwnerAttr
>(TmplAttr
)) {
814 if (!New
->hasAttr
<OwnerAttr
>())
815 New
->addAttr(A
->clone(Context
));
819 if (auto *A
= dyn_cast
<SYCLKernelAttr
>(TmplAttr
)) {
820 instantiateDependentSYCLKernelAttr(*this, TemplateArgs
, *A
, New
);
824 assert(!TmplAttr
->isPackExpansion());
825 if (TmplAttr
->isLateParsed() && LateAttrs
) {
826 // Late parsed attributes must be instantiated and attached after the
827 // enclosing class has been instantiated. See Sema::InstantiateClass.
828 LocalInstantiationScope
*Saved
= nullptr;
829 if (CurrentInstantiationScope
)
830 Saved
= CurrentInstantiationScope
->cloneScopes(OuterMostScope
);
831 LateAttrs
->push_back(LateInstantiatedAttribute(TmplAttr
, Saved
, New
));
833 // Allow 'this' within late-parsed attributes.
834 auto *ND
= cast
<NamedDecl
>(New
);
835 auto *ThisContext
= dyn_cast_or_null
<CXXRecordDecl
>(ND
->getDeclContext());
836 CXXThisScopeRAII
ThisScope(*this, ThisContext
, Qualifiers(),
837 ND
->isCXXInstanceMember());
839 Attr
*NewAttr
= sema::instantiateTemplateAttribute(TmplAttr
, Context
,
840 *this, TemplateArgs
);
841 if (NewAttr
&& isRelevantAttr(*this, New
, TmplAttr
))
842 New
->addAttr(NewAttr
);
847 /// Update instantiation attributes after template was late parsed.
849 /// Some attributes are evaluated based on the body of template. If it is
850 /// late parsed, such attributes cannot be evaluated when declaration is
851 /// instantiated. This function is used to update instantiation attributes when
852 /// template definition is ready.
853 void Sema::updateAttrsForLateParsedTemplate(const Decl
*Pattern
, Decl
*Inst
) {
854 for (const auto *Attr
: Pattern
->attrs()) {
855 if (auto *A
= dyn_cast
<StrictFPAttr
>(Attr
)) {
856 if (!Inst
->hasAttr
<StrictFPAttr
>())
857 Inst
->addAttr(A
->clone(getASTContext()));
863 /// In the MS ABI, we need to instantiate default arguments of dllexported
864 /// default constructors along with the constructor definition. This allows IR
865 /// gen to emit a constructor closure which calls the default constructor with
866 /// its default arguments.
867 void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl
*Ctor
) {
868 assert(Context
.getTargetInfo().getCXXABI().isMicrosoft() &&
869 Ctor
->isDefaultConstructor());
870 unsigned NumParams
= Ctor
->getNumParams();
873 DLLExportAttr
*Attr
= Ctor
->getAttr
<DLLExportAttr
>();
876 for (unsigned I
= 0; I
!= NumParams
; ++I
) {
877 (void)CheckCXXDefaultArgExpr(Attr
->getLocation(), Ctor
,
878 Ctor
->getParamDecl(I
));
879 CleanupVarDeclMarking();
883 /// Get the previous declaration of a declaration for the purposes of template
884 /// instantiation. If this finds a previous declaration, then the previous
885 /// declaration of the instantiation of D should be an instantiation of the
886 /// result of this function.
887 template<typename DeclT
>
888 static DeclT
*getPreviousDeclForInstantiation(DeclT
*D
) {
889 DeclT
*Result
= D
->getPreviousDecl();
891 // If the declaration is within a class, and the previous declaration was
892 // merged from a different definition of that class, then we don't have a
893 // previous declaration for the purpose of template instantiation.
894 if (Result
&& isa
<CXXRecordDecl
>(D
->getDeclContext()) &&
895 D
->getLexicalDeclContext() != Result
->getLexicalDeclContext())
902 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl
*D
) {
903 llvm_unreachable("Translation units cannot be instantiated");
906 Decl
*TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl
*Decl
) {
907 llvm_unreachable("HLSL buffer declarations cannot be instantiated");
911 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl
*D
) {
912 llvm_unreachable("pragma comment cannot be instantiated");
915 Decl
*TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
916 PragmaDetectMismatchDecl
*D
) {
917 llvm_unreachable("pragma comment cannot be instantiated");
921 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl
*D
) {
922 llvm_unreachable("extern \"C\" context cannot be instantiated");
925 Decl
*TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl
*D
) {
926 llvm_unreachable("GUID declaration cannot be instantiated");
929 Decl
*TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
930 UnnamedGlobalConstantDecl
*D
) {
931 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
934 Decl
*TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
935 TemplateParamObjectDecl
*D
) {
936 llvm_unreachable("template parameter objects cannot be instantiated");
940 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl
*D
) {
941 LabelDecl
*Inst
= LabelDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
943 Owner
->addDecl(Inst
);
948 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl
*D
) {
949 llvm_unreachable("Namespaces cannot be instantiated");
953 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl
*D
) {
954 NamespaceAliasDecl
*Inst
955 = NamespaceAliasDecl::Create(SemaRef
.Context
, Owner
,
956 D
->getNamespaceLoc(),
959 D
->getQualifierLoc(),
960 D
->getTargetNameLoc(),
962 Owner
->addDecl(Inst
);
966 Decl
*TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl
*D
,
968 bool Invalid
= false;
969 TypeSourceInfo
*DI
= D
->getTypeSourceInfo();
970 if (DI
->getType()->isInstantiationDependentType() ||
971 DI
->getType()->isVariablyModifiedType()) {
972 DI
= SemaRef
.SubstType(DI
, TemplateArgs
,
973 D
->getLocation(), D
->getDeclName());
976 DI
= SemaRef
.Context
.getTrivialTypeSourceInfo(SemaRef
.Context
.IntTy
);
979 SemaRef
.MarkDeclarationsReferencedInType(D
->getLocation(), DI
->getType());
982 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
983 // libstdc++ relies upon this bug in its implementation of common_type. If we
984 // happen to be processing that implementation, fake up the g++ ?:
985 // semantics. See LWG issue 2141 for more information on the bug. The bugs
986 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
987 const DecltypeType
*DT
= DI
->getType()->getAs
<DecltypeType
>();
988 CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(D
->getDeclContext());
989 if (DT
&& RD
&& isa
<ConditionalOperator
>(DT
->getUnderlyingExpr()) &&
990 DT
->isReferenceType() &&
991 RD
->getEnclosingNamespaceContext() == SemaRef
.getStdNamespace() &&
992 RD
->getIdentifier() && RD
->getIdentifier()->isStr("common_type") &&
993 D
->getIdentifier() && D
->getIdentifier()->isStr("type") &&
994 SemaRef
.getSourceManager().isInSystemHeader(D
->getBeginLoc()))
995 // Fold it to the (non-reference) type which g++ would have produced.
996 DI
= SemaRef
.Context
.getTrivialTypeSourceInfo(
997 DI
->getType().getNonReferenceType());
999 // Create the new typedef
1000 TypedefNameDecl
*Typedef
;
1002 Typedef
= TypeAliasDecl::Create(SemaRef
.Context
, Owner
, D
->getBeginLoc(),
1003 D
->getLocation(), D
->getIdentifier(), DI
);
1005 Typedef
= TypedefDecl::Create(SemaRef
.Context
, Owner
, D
->getBeginLoc(),
1006 D
->getLocation(), D
->getIdentifier(), DI
);
1008 Typedef
->setInvalidDecl();
1010 // If the old typedef was the name for linkage purposes of an anonymous
1011 // tag decl, re-establish that relationship for the new typedef.
1012 if (const TagType
*oldTagType
= D
->getUnderlyingType()->getAs
<TagType
>()) {
1013 TagDecl
*oldTag
= oldTagType
->getDecl();
1014 if (oldTag
->getTypedefNameForAnonDecl() == D
&& !Invalid
) {
1015 TagDecl
*newTag
= DI
->getType()->castAs
<TagType
>()->getDecl();
1016 assert(!newTag
->hasNameForLinkage());
1017 newTag
->setTypedefNameForAnonDecl(Typedef
);
1021 if (TypedefNameDecl
*Prev
= getPreviousDeclForInstantiation(D
)) {
1022 NamedDecl
*InstPrev
= SemaRef
.FindInstantiatedDecl(D
->getLocation(), Prev
,
1027 TypedefNameDecl
*InstPrevTypedef
= cast
<TypedefNameDecl
>(InstPrev
);
1029 // If the typedef types are not identical, reject them.
1030 SemaRef
.isIncompatibleTypedef(InstPrevTypedef
, Typedef
);
1032 Typedef
->setPreviousDecl(InstPrevTypedef
);
1035 SemaRef
.InstantiateAttrs(TemplateArgs
, D
, Typedef
);
1037 if (D
->getUnderlyingType()->getAs
<DependentNameType
>())
1038 SemaRef
.inferGslPointerAttribute(Typedef
);
1040 Typedef
->setAccess(D
->getAccess());
1041 Typedef
->setReferenced(D
->isReferenced());
1046 Decl
*TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl
*D
) {
1047 Decl
*Typedef
= InstantiateTypedefNameDecl(D
, /*IsTypeAlias=*/false);
1049 Owner
->addDecl(Typedef
);
1053 Decl
*TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl
*D
) {
1054 Decl
*Typedef
= InstantiateTypedefNameDecl(D
, /*IsTypeAlias=*/true);
1056 Owner
->addDecl(Typedef
);
1061 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl
*D
) {
1062 // Create a local instantiation scope for this type alias template, which
1063 // will contain the instantiations of the template parameters.
1064 LocalInstantiationScope
Scope(SemaRef
);
1066 TemplateParameterList
*TempParams
= D
->getTemplateParameters();
1067 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
1071 TypeAliasDecl
*Pattern
= D
->getTemplatedDecl();
1073 TypeAliasTemplateDecl
*PrevAliasTemplate
= nullptr;
1074 if (getPreviousDeclForInstantiation
<TypedefNameDecl
>(Pattern
)) {
1075 DeclContext::lookup_result Found
= Owner
->lookup(Pattern
->getDeclName());
1076 if (!Found
.empty()) {
1077 PrevAliasTemplate
= dyn_cast
<TypeAliasTemplateDecl
>(Found
.front());
1081 TypeAliasDecl
*AliasInst
= cast_or_null
<TypeAliasDecl
>(
1082 InstantiateTypedefNameDecl(Pattern
, /*IsTypeAlias=*/true));
1086 TypeAliasTemplateDecl
*Inst
1087 = TypeAliasTemplateDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
1088 D
->getDeclName(), InstParams
, AliasInst
);
1089 AliasInst
->setDescribedAliasTemplate(Inst
);
1090 if (PrevAliasTemplate
)
1091 Inst
->setPreviousDecl(PrevAliasTemplate
);
1093 Inst
->setAccess(D
->getAccess());
1095 if (!PrevAliasTemplate
)
1096 Inst
->setInstantiatedFromMemberTemplate(D
);
1098 Owner
->addDecl(Inst
);
1103 Decl
*TemplateDeclInstantiator::VisitBindingDecl(BindingDecl
*D
) {
1104 auto *NewBD
= BindingDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
1105 D
->getIdentifier());
1106 NewBD
->setReferenced(D
->isReferenced());
1107 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, NewBD
);
1111 Decl
*TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl
*D
) {
1112 // Transform the bindings first.
1113 SmallVector
<BindingDecl
*, 16> NewBindings
;
1114 for (auto *OldBD
: D
->bindings())
1115 NewBindings
.push_back(cast
<BindingDecl
>(VisitBindingDecl(OldBD
)));
1116 ArrayRef
<BindingDecl
*> NewBindingArray
= NewBindings
;
1118 auto *NewDD
= cast_or_null
<DecompositionDecl
>(
1119 VisitVarDecl(D
, /*InstantiatingVarTemplate=*/false, &NewBindingArray
));
1121 if (!NewDD
|| NewDD
->isInvalidDecl())
1122 for (auto *NewBD
: NewBindings
)
1123 NewBD
->setInvalidDecl();
1128 Decl
*TemplateDeclInstantiator::VisitVarDecl(VarDecl
*D
) {
1129 return VisitVarDecl(D
, /*InstantiatingVarTemplate=*/false);
1132 Decl
*TemplateDeclInstantiator::VisitVarDecl(VarDecl
*D
,
1133 bool InstantiatingVarTemplate
,
1134 ArrayRef
<BindingDecl
*> *Bindings
) {
1136 // Do substitution on the type of the declaration
1137 TypeSourceInfo
*DI
= SemaRef
.SubstType(
1138 D
->getTypeSourceInfo(), TemplateArgs
, D
->getTypeSpecStartLoc(),
1139 D
->getDeclName(), /*AllowDeducedTST*/true);
1143 if (DI
->getType()->isFunctionType()) {
1144 SemaRef
.Diag(D
->getLocation(), diag::err_variable_instantiates_to_function
)
1145 << D
->isStaticDataMember() << DI
->getType();
1149 DeclContext
*DC
= Owner
;
1150 if (D
->isLocalExternDecl())
1151 SemaRef
.adjustContextForLocalExternDecl(DC
);
1153 // Build the instantiated declaration.
1156 Var
= DecompositionDecl::Create(SemaRef
.Context
, DC
, D
->getInnerLocStart(),
1157 D
->getLocation(), DI
->getType(), DI
,
1158 D
->getStorageClass(), *Bindings
);
1160 Var
= VarDecl::Create(SemaRef
.Context
, DC
, D
->getInnerLocStart(),
1161 D
->getLocation(), D
->getIdentifier(), DI
->getType(),
1162 DI
, D
->getStorageClass());
1164 // In ARC, infer 'retaining' for variables of retainable type.
1165 if (SemaRef
.getLangOpts().ObjCAutoRefCount
&&
1166 SemaRef
.inferObjCARCLifetime(Var
))
1167 Var
->setInvalidDecl();
1169 if (SemaRef
.getLangOpts().OpenCL
)
1170 SemaRef
.deduceOpenCLAddressSpace(Var
);
1172 // Substitute the nested name specifier, if any.
1173 if (SubstQualifier(D
, Var
))
1176 SemaRef
.BuildVariableInstantiation(Var
, D
, TemplateArgs
, LateAttrs
, Owner
,
1177 StartingScope
, InstantiatingVarTemplate
);
1178 if (D
->isNRVOVariable() && !Var
->isInvalidDecl()) {
1180 if (auto *F
= dyn_cast
<FunctionDecl
>(DC
))
1181 RT
= F
->getReturnType();
1182 else if (isa
<BlockDecl
>(DC
))
1183 RT
= cast
<FunctionType
>(SemaRef
.getCurBlock()->FunctionType
)
1186 llvm_unreachable("Unknown context type");
1188 // This is the last chance we have of checking copy elision eligibility
1189 // for functions in dependent contexts. The sema actions for building
1190 // the return statement during template instantiation will have no effect
1191 // regarding copy elision, since NRVO propagation runs on the scope exit
1192 // actions, and these are not run on instantiation.
1193 // This might run through some VarDecls which were returned from non-taken
1194 // 'if constexpr' branches, and these will end up being constructed on the
1195 // return slot even if they will never be returned, as a sort of accidental
1196 // 'optimization'. Notably, functions with 'auto' return types won't have it
1197 // deduced by this point. Coupled with the limitation described
1198 // previously, this makes it very hard to support copy elision for these.
1199 Sema::NamedReturnInfo Info
= SemaRef
.getNamedReturnInfo(Var
);
1200 bool NRVO
= SemaRef
.getCopyElisionCandidate(Info
, RT
) != nullptr;
1201 Var
->setNRVOVariable(NRVO
);
1204 Var
->setImplicit(D
->isImplicit());
1206 if (Var
->isStaticLocal())
1207 SemaRef
.CheckStaticLocalForDllExport(Var
);
1209 if (Var
->getTLSKind())
1210 SemaRef
.CheckThreadLocalForLargeAlignment(Var
);
1215 Decl
*TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl
*D
) {
1217 = AccessSpecDecl::Create(SemaRef
.Context
, D
->getAccess(), Owner
,
1218 D
->getAccessSpecifierLoc(), D
->getColonLoc());
1219 Owner
->addHiddenDecl(AD
);
1223 Decl
*TemplateDeclInstantiator::VisitFieldDecl(FieldDecl
*D
) {
1224 bool Invalid
= false;
1225 TypeSourceInfo
*DI
= D
->getTypeSourceInfo();
1226 if (DI
->getType()->isInstantiationDependentType() ||
1227 DI
->getType()->isVariablyModifiedType()) {
1228 DI
= SemaRef
.SubstType(DI
, TemplateArgs
,
1229 D
->getLocation(), D
->getDeclName());
1231 DI
= D
->getTypeSourceInfo();
1233 } else if (DI
->getType()->isFunctionType()) {
1234 // C++ [temp.arg.type]p3:
1235 // If a declaration acquires a function type through a type
1236 // dependent on a template-parameter and this causes a
1237 // declaration that does not use the syntactic form of a
1238 // function declarator to have function type, the program is
1240 SemaRef
.Diag(D
->getLocation(), diag::err_field_instantiates_to_function
)
1245 SemaRef
.MarkDeclarationsReferencedInType(D
->getLocation(), DI
->getType());
1248 Expr
*BitWidth
= D
->getBitWidth();
1251 else if (BitWidth
) {
1252 // The bit-width expression is a constant expression.
1253 EnterExpressionEvaluationContext
Unevaluated(
1254 SemaRef
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
1256 ExprResult InstantiatedBitWidth
1257 = SemaRef
.SubstExpr(BitWidth
, TemplateArgs
);
1258 if (InstantiatedBitWidth
.isInvalid()) {
1262 BitWidth
= InstantiatedBitWidth
.getAs
<Expr
>();
1265 FieldDecl
*Field
= SemaRef
.CheckFieldDecl(D
->getDeclName(),
1267 cast
<RecordDecl
>(Owner
),
1271 D
->getInClassInitStyle(),
1272 D
->getInnerLocStart(),
1276 cast
<Decl
>(Owner
)->setInvalidDecl();
1280 SemaRef
.InstantiateAttrs(TemplateArgs
, D
, Field
, LateAttrs
, StartingScope
);
1282 if (Field
->hasAttrs())
1283 SemaRef
.CheckAlignasUnderalignment(Field
);
1286 Field
->setInvalidDecl();
1288 if (!Field
->getDeclName()) {
1289 // Keep track of where this decl came from.
1290 SemaRef
.Context
.setInstantiatedFromUnnamedFieldDecl(Field
, D
);
1292 if (CXXRecordDecl
*Parent
= dyn_cast
<CXXRecordDecl
>(Field
->getDeclContext())) {
1293 if (Parent
->isAnonymousStructOrUnion() &&
1294 Parent
->getRedeclContext()->isFunctionOrMethod())
1295 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Field
);
1298 Field
->setImplicit(D
->isImplicit());
1299 Field
->setAccess(D
->getAccess());
1300 Owner
->addDecl(Field
);
1305 Decl
*TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl
*D
) {
1306 bool Invalid
= false;
1307 TypeSourceInfo
*DI
= D
->getTypeSourceInfo();
1309 if (DI
->getType()->isVariablyModifiedType()) {
1310 SemaRef
.Diag(D
->getLocation(), diag::err_property_is_variably_modified
)
1313 } else if (DI
->getType()->isInstantiationDependentType()) {
1314 DI
= SemaRef
.SubstType(DI
, TemplateArgs
,
1315 D
->getLocation(), D
->getDeclName());
1317 DI
= D
->getTypeSourceInfo();
1319 } else if (DI
->getType()->isFunctionType()) {
1320 // C++ [temp.arg.type]p3:
1321 // If a declaration acquires a function type through a type
1322 // dependent on a template-parameter and this causes a
1323 // declaration that does not use the syntactic form of a
1324 // function declarator to have function type, the program is
1326 SemaRef
.Diag(D
->getLocation(), diag::err_field_instantiates_to_function
)
1331 SemaRef
.MarkDeclarationsReferencedInType(D
->getLocation(), DI
->getType());
1334 MSPropertyDecl
*Property
= MSPropertyDecl::Create(
1335 SemaRef
.Context
, Owner
, D
->getLocation(), D
->getDeclName(), DI
->getType(),
1336 DI
, D
->getBeginLoc(), D
->getGetterId(), D
->getSetterId());
1338 SemaRef
.InstantiateAttrs(TemplateArgs
, D
, Property
, LateAttrs
,
1342 Property
->setInvalidDecl();
1344 Property
->setAccess(D
->getAccess());
1345 Owner
->addDecl(Property
);
1350 Decl
*TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl
*D
) {
1351 NamedDecl
**NamedChain
=
1352 new (SemaRef
.Context
)NamedDecl
*[D
->getChainingSize()];
1355 for (auto *PI
: D
->chain()) {
1356 NamedDecl
*Next
= SemaRef
.FindInstantiatedDecl(D
->getLocation(), PI
,
1361 NamedChain
[i
++] = Next
;
1364 QualType T
= cast
<FieldDecl
>(NamedChain
[i
-1])->getType();
1365 IndirectFieldDecl
*IndirectField
= IndirectFieldDecl::Create(
1366 SemaRef
.Context
, Owner
, D
->getLocation(), D
->getIdentifier(), T
,
1367 {NamedChain
, D
->getChainingSize()});
1369 for (const auto *Attr
: D
->attrs())
1370 IndirectField
->addAttr(Attr
->clone(SemaRef
.Context
));
1372 IndirectField
->setImplicit(D
->isImplicit());
1373 IndirectField
->setAccess(D
->getAccess());
1374 Owner
->addDecl(IndirectField
);
1375 return IndirectField
;
1378 Decl
*TemplateDeclInstantiator::VisitFriendDecl(FriendDecl
*D
) {
1379 // Handle friend type expressions by simply substituting template
1380 // parameters into the pattern type and checking the result.
1381 if (TypeSourceInfo
*Ty
= D
->getFriendType()) {
1382 TypeSourceInfo
*InstTy
;
1383 // If this is an unsupported friend, don't bother substituting template
1384 // arguments into it. The actual type referred to won't be used by any
1385 // parts of Clang, and may not be valid for instantiating. Just use the
1386 // same info for the instantiated friend.
1387 if (D
->isUnsupportedFriend()) {
1390 InstTy
= SemaRef
.SubstType(Ty
, TemplateArgs
,
1391 D
->getLocation(), DeclarationName());
1396 FriendDecl
*FD
= SemaRef
.CheckFriendTypeDecl(D
->getBeginLoc(),
1397 D
->getFriendLoc(), InstTy
);
1401 FD
->setAccess(AS_public
);
1402 FD
->setUnsupportedFriend(D
->isUnsupportedFriend());
1407 NamedDecl
*ND
= D
->getFriendDecl();
1408 assert(ND
&& "friend decl must be a decl or a type!");
1410 // All of the Visit implementations for the various potential friend
1411 // declarations have to be carefully written to work for friend
1412 // objects, with the most important detail being that the target
1413 // decl should almost certainly not be placed in Owner.
1414 Decl
*NewND
= Visit(ND
);
1415 if (!NewND
) return nullptr;
1418 FriendDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
1419 cast
<NamedDecl
>(NewND
), D
->getFriendLoc());
1420 FD
->setAccess(AS_public
);
1421 FD
->setUnsupportedFriend(D
->isUnsupportedFriend());
1426 Decl
*TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl
*D
) {
1427 Expr
*AssertExpr
= D
->getAssertExpr();
1429 // The expression in a static assertion is a constant expression.
1430 EnterExpressionEvaluationContext
Unevaluated(
1431 SemaRef
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
1433 ExprResult InstantiatedAssertExpr
1434 = SemaRef
.SubstExpr(AssertExpr
, TemplateArgs
);
1435 if (InstantiatedAssertExpr
.isInvalid())
1438 ExprResult InstantiatedMessageExpr
=
1439 SemaRef
.SubstExpr(D
->getMessage(), TemplateArgs
);
1440 if (InstantiatedMessageExpr
.isInvalid())
1443 return SemaRef
.BuildStaticAssertDeclaration(
1444 D
->getLocation(), InstantiatedAssertExpr
.get(),
1445 InstantiatedMessageExpr
.get(), D
->getRParenLoc(), D
->isFailed());
1448 Decl
*TemplateDeclInstantiator::VisitEnumDecl(EnumDecl
*D
) {
1449 EnumDecl
*PrevDecl
= nullptr;
1450 if (EnumDecl
*PatternPrev
= getPreviousDeclForInstantiation(D
)) {
1451 NamedDecl
*Prev
= SemaRef
.FindInstantiatedDecl(D
->getLocation(),
1454 if (!Prev
) return nullptr;
1455 PrevDecl
= cast
<EnumDecl
>(Prev
);
1459 EnumDecl::Create(SemaRef
.Context
, Owner
, D
->getBeginLoc(),
1460 D
->getLocation(), D
->getIdentifier(), PrevDecl
,
1461 D
->isScoped(), D
->isScopedUsingClassTag(), D
->isFixed());
1463 if (TypeSourceInfo
*TI
= D
->getIntegerTypeSourceInfo()) {
1464 // If we have type source information for the underlying type, it means it
1465 // has been explicitly set by the user. Perform substitution on it before
1467 SourceLocation UnderlyingLoc
= TI
->getTypeLoc().getBeginLoc();
1468 TypeSourceInfo
*NewTI
= SemaRef
.SubstType(TI
, TemplateArgs
, UnderlyingLoc
,
1470 if (!NewTI
|| SemaRef
.CheckEnumUnderlyingType(NewTI
))
1471 Enum
->setIntegerType(SemaRef
.Context
.IntTy
);
1473 Enum
->setIntegerTypeSourceInfo(NewTI
);
1475 assert(!D
->getIntegerType()->isDependentType()
1476 && "Dependent type without type source info");
1477 Enum
->setIntegerType(D
->getIntegerType());
1481 SemaRef
.InstantiateAttrs(TemplateArgs
, D
, Enum
);
1483 Enum
->setInstantiationOfMemberEnum(D
, TSK_ImplicitInstantiation
);
1484 Enum
->setAccess(D
->getAccess());
1485 // Forward the mangling number from the template to the instantiated decl.
1486 SemaRef
.Context
.setManglingNumber(Enum
, SemaRef
.Context
.getManglingNumber(D
));
1487 // See if the old tag was defined along with a declarator.
1488 // If it did, mark the new tag as being associated with that declarator.
1489 if (DeclaratorDecl
*DD
= SemaRef
.Context
.getDeclaratorForUnnamedTagDecl(D
))
1490 SemaRef
.Context
.addDeclaratorForUnnamedTagDecl(Enum
, DD
);
1491 // See if the old tag was defined along with a typedef.
1492 // If it did, mark the new tag as being associated with that typedef.
1493 if (TypedefNameDecl
*TND
= SemaRef
.Context
.getTypedefNameForUnnamedTagDecl(D
))
1494 SemaRef
.Context
.addTypedefNameForUnnamedTagDecl(Enum
, TND
);
1495 if (SubstQualifier(D
, Enum
)) return nullptr;
1496 Owner
->addDecl(Enum
);
1498 EnumDecl
*Def
= D
->getDefinition();
1499 if (Def
&& Def
!= D
) {
1500 // If this is an out-of-line definition of an enum member template, check
1501 // that the underlying types match in the instantiation of both
1503 if (TypeSourceInfo
*TI
= Def
->getIntegerTypeSourceInfo()) {
1504 SourceLocation UnderlyingLoc
= TI
->getTypeLoc().getBeginLoc();
1505 QualType DefnUnderlying
=
1506 SemaRef
.SubstType(TI
->getType(), TemplateArgs
,
1507 UnderlyingLoc
, DeclarationName());
1508 SemaRef
.CheckEnumRedeclaration(Def
->getLocation(), Def
->isScoped(),
1509 DefnUnderlying
, /*IsFixed=*/true, Enum
);
1513 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1514 // specialization causes the implicit instantiation of the declarations, but
1515 // not the definitions of scoped member enumerations.
1517 // DR1484 clarifies that enumeration definitions inside of a template
1518 // declaration aren't considered entities that can be separately instantiated
1519 // from the rest of the entity they are declared inside of.
1520 if (isDeclWithinFunction(D
) ? D
== Def
: Def
&& !Enum
->isScoped()) {
1521 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Enum
);
1522 InstantiateEnumDefinition(Enum
, Def
);
1528 void TemplateDeclInstantiator::InstantiateEnumDefinition(
1529 EnumDecl
*Enum
, EnumDecl
*Pattern
) {
1530 Enum
->startDefinition();
1532 // Update the location to refer to the definition.
1533 Enum
->setLocation(Pattern
->getLocation());
1535 SmallVector
<Decl
*, 4> Enumerators
;
1537 EnumConstantDecl
*LastEnumConst
= nullptr;
1538 for (auto *EC
: Pattern
->enumerators()) {
1539 // The specified value for the enumerator.
1540 ExprResult
Value((Expr
*)nullptr);
1541 if (Expr
*UninstValue
= EC
->getInitExpr()) {
1542 // The enumerator's value expression is a constant expression.
1543 EnterExpressionEvaluationContext
Unevaluated(
1544 SemaRef
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
1546 Value
= SemaRef
.SubstExpr(UninstValue
, TemplateArgs
);
1549 // Drop the initial value and continue.
1550 bool isInvalid
= false;
1551 if (Value
.isInvalid()) {
1556 EnumConstantDecl
*EnumConst
1557 = SemaRef
.CheckEnumConstant(Enum
, LastEnumConst
,
1558 EC
->getLocation(), EC
->getIdentifier(),
1563 EnumConst
->setInvalidDecl();
1564 Enum
->setInvalidDecl();
1568 SemaRef
.InstantiateAttrs(TemplateArgs
, EC
, EnumConst
);
1570 EnumConst
->setAccess(Enum
->getAccess());
1571 Enum
->addDecl(EnumConst
);
1572 Enumerators
.push_back(EnumConst
);
1573 LastEnumConst
= EnumConst
;
1575 if (Pattern
->getDeclContext()->isFunctionOrMethod() &&
1576 !Enum
->isScoped()) {
1577 // If the enumeration is within a function or method, record the enum
1578 // constant as a local.
1579 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(EC
, EnumConst
);
1584 SemaRef
.ActOnEnumBody(Enum
->getLocation(), Enum
->getBraceRange(), Enum
,
1585 Enumerators
, nullptr, ParsedAttributesView());
1588 Decl
*TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl
*D
) {
1589 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1593 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl
*D
) {
1594 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1597 Decl
*TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl
*D
) {
1598 bool isFriend
= (D
->getFriendObjectKind() != Decl::FOK_None
);
1600 // Create a local instantiation scope for this class template, which
1601 // will contain the instantiations of the template parameters.
1602 LocalInstantiationScope
Scope(SemaRef
);
1603 TemplateParameterList
*TempParams
= D
->getTemplateParameters();
1604 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
1608 CXXRecordDecl
*Pattern
= D
->getTemplatedDecl();
1610 // Instantiate the qualifier. We have to do this first in case
1611 // we're a friend declaration, because if we are then we need to put
1612 // the new declaration in the appropriate context.
1613 NestedNameSpecifierLoc QualifierLoc
= Pattern
->getQualifierLoc();
1615 QualifierLoc
= SemaRef
.SubstNestedNameSpecifierLoc(QualifierLoc
,
1621 CXXRecordDecl
*PrevDecl
= nullptr;
1622 ClassTemplateDecl
*PrevClassTemplate
= nullptr;
1624 if (!isFriend
&& getPreviousDeclForInstantiation(Pattern
)) {
1625 DeclContext::lookup_result Found
= Owner
->lookup(Pattern
->getDeclName());
1626 if (!Found
.empty()) {
1627 PrevClassTemplate
= dyn_cast
<ClassTemplateDecl
>(Found
.front());
1628 if (PrevClassTemplate
)
1629 PrevDecl
= PrevClassTemplate
->getTemplatedDecl();
1633 // If this isn't a friend, then it's a member template, in which
1634 // case we just want to build the instantiation in the
1635 // specialization. If it is a friend, we want to build it in
1636 // the appropriate context.
1637 DeclContext
*DC
= Owner
;
1641 SS
.Adopt(QualifierLoc
);
1642 DC
= SemaRef
.computeDeclContext(SS
);
1643 if (!DC
) return nullptr;
1645 DC
= SemaRef
.FindInstantiatedContext(Pattern
->getLocation(),
1646 Pattern
->getDeclContext(),
1650 // Look for a previous declaration of the template in the owning
1652 LookupResult
R(SemaRef
, Pattern
->getDeclName(), Pattern
->getLocation(),
1653 Sema::LookupOrdinaryName
,
1654 SemaRef
.forRedeclarationInCurContext());
1655 SemaRef
.LookupQualifiedName(R
, DC
);
1657 if (R
.isSingleResult()) {
1658 PrevClassTemplate
= R
.getAsSingle
<ClassTemplateDecl
>();
1659 if (PrevClassTemplate
)
1660 PrevDecl
= PrevClassTemplate
->getTemplatedDecl();
1663 if (!PrevClassTemplate
&& QualifierLoc
) {
1664 SemaRef
.Diag(Pattern
->getLocation(), diag::err_not_tag_in_scope
)
1665 << D
->getTemplatedDecl()->getTagKind() << Pattern
->getDeclName() << DC
1666 << QualifierLoc
.getSourceRange();
1671 CXXRecordDecl
*RecordInst
= CXXRecordDecl::Create(
1672 SemaRef
.Context
, Pattern
->getTagKind(), DC
, Pattern
->getBeginLoc(),
1673 Pattern
->getLocation(), Pattern
->getIdentifier(), PrevDecl
,
1674 /*DelayTypeCreation=*/true);
1676 RecordInst
->setQualifierInfo(QualifierLoc
);
1678 SemaRef
.InstantiateAttrsForDecl(TemplateArgs
, Pattern
, RecordInst
, LateAttrs
,
1681 ClassTemplateDecl
*Inst
1682 = ClassTemplateDecl::Create(SemaRef
.Context
, DC
, D
->getLocation(),
1683 D
->getIdentifier(), InstParams
, RecordInst
);
1684 RecordInst
->setDescribedClassTemplate(Inst
);
1687 assert(!Owner
->isDependentContext());
1688 Inst
->setLexicalDeclContext(Owner
);
1689 RecordInst
->setLexicalDeclContext(Owner
);
1691 if (PrevClassTemplate
) {
1692 Inst
->setCommonPtr(PrevClassTemplate
->getCommonPtr());
1693 RecordInst
->setTypeForDecl(
1694 PrevClassTemplate
->getTemplatedDecl()->getTypeForDecl());
1695 const ClassTemplateDecl
*MostRecentPrevCT
=
1696 PrevClassTemplate
->getMostRecentDecl();
1697 TemplateParameterList
*PrevParams
=
1698 MostRecentPrevCT
->getTemplateParameters();
1700 // Make sure the parameter lists match.
1701 if (!SemaRef
.TemplateParameterListsAreEqual(
1702 RecordInst
, InstParams
, MostRecentPrevCT
->getTemplatedDecl(),
1703 PrevParams
, true, Sema::TPL_TemplateMatch
))
1706 // Do some additional validation, then merge default arguments
1707 // from the existing declarations.
1708 if (SemaRef
.CheckTemplateParameterList(InstParams
, PrevParams
,
1709 Sema::TPC_ClassTemplate
))
1712 Inst
->setAccess(PrevClassTemplate
->getAccess());
1714 Inst
->setAccess(D
->getAccess());
1717 Inst
->setObjectOfFriendDecl();
1718 // TODO: do we want to track the instantiation progeny of this
1719 // friend target decl?
1721 Inst
->setAccess(D
->getAccess());
1722 if (!PrevClassTemplate
)
1723 Inst
->setInstantiatedFromMemberTemplate(D
);
1726 Inst
->setPreviousDecl(PrevClassTemplate
);
1728 // Trigger creation of the type for the instantiation.
1729 SemaRef
.Context
.getInjectedClassNameType(
1730 RecordInst
, Inst
->getInjectedClassNameSpecialization());
1732 // Finish handling of friends.
1734 DC
->makeDeclVisibleInContext(Inst
);
1738 if (D
->isOutOfLine()) {
1739 Inst
->setLexicalDeclContext(D
->getLexicalDeclContext());
1740 RecordInst
->setLexicalDeclContext(D
->getLexicalDeclContext());
1743 Owner
->addDecl(Inst
);
1745 if (!PrevClassTemplate
) {
1746 // Queue up any out-of-line partial specializations of this member
1747 // class template; the client will force their instantiation once
1748 // the enclosing class has been instantiated.
1749 SmallVector
<ClassTemplatePartialSpecializationDecl
*, 4> PartialSpecs
;
1750 D
->getPartialSpecializations(PartialSpecs
);
1751 for (unsigned I
= 0, N
= PartialSpecs
.size(); I
!= N
; ++I
)
1752 if (PartialSpecs
[I
]->getFirstDecl()->isOutOfLine())
1753 OutOfLinePartialSpecs
.push_back(std::make_pair(Inst
, PartialSpecs
[I
]));
1760 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1761 ClassTemplatePartialSpecializationDecl
*D
) {
1762 ClassTemplateDecl
*ClassTemplate
= D
->getSpecializedTemplate();
1764 // Lookup the already-instantiated declaration in the instantiation
1765 // of the class template and return that.
1766 DeclContext::lookup_result Found
1767 = Owner
->lookup(ClassTemplate
->getDeclName());
1771 ClassTemplateDecl
*InstClassTemplate
1772 = dyn_cast
<ClassTemplateDecl
>(Found
.front());
1773 if (!InstClassTemplate
)
1776 if (ClassTemplatePartialSpecializationDecl
*Result
1777 = InstClassTemplate
->findPartialSpecInstantiatedFromMember(D
))
1780 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate
, D
);
1783 Decl
*TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl
*D
) {
1784 assert(D
->getTemplatedDecl()->isStaticDataMember() &&
1785 "Only static data member templates are allowed.");
1787 // Create a local instantiation scope for this variable template, which
1788 // will contain the instantiations of the template parameters.
1789 LocalInstantiationScope
Scope(SemaRef
);
1790 TemplateParameterList
*TempParams
= D
->getTemplateParameters();
1791 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
1795 VarDecl
*Pattern
= D
->getTemplatedDecl();
1796 VarTemplateDecl
*PrevVarTemplate
= nullptr;
1798 if (getPreviousDeclForInstantiation(Pattern
)) {
1799 DeclContext::lookup_result Found
= Owner
->lookup(Pattern
->getDeclName());
1801 PrevVarTemplate
= dyn_cast
<VarTemplateDecl
>(Found
.front());
1805 cast_or_null
<VarDecl
>(VisitVarDecl(Pattern
,
1806 /*InstantiatingVarTemplate=*/true));
1807 if (!VarInst
) return nullptr;
1809 DeclContext
*DC
= Owner
;
1811 VarTemplateDecl
*Inst
= VarTemplateDecl::Create(
1812 SemaRef
.Context
, DC
, D
->getLocation(), D
->getIdentifier(), InstParams
,
1814 VarInst
->setDescribedVarTemplate(Inst
);
1815 Inst
->setPreviousDecl(PrevVarTemplate
);
1817 Inst
->setAccess(D
->getAccess());
1818 if (!PrevVarTemplate
)
1819 Inst
->setInstantiatedFromMemberTemplate(D
);
1821 if (D
->isOutOfLine()) {
1822 Inst
->setLexicalDeclContext(D
->getLexicalDeclContext());
1823 VarInst
->setLexicalDeclContext(D
->getLexicalDeclContext());
1826 Owner
->addDecl(Inst
);
1828 if (!PrevVarTemplate
) {
1829 // Queue up any out-of-line partial specializations of this member
1830 // variable template; the client will force their instantiation once
1831 // the enclosing class has been instantiated.
1832 SmallVector
<VarTemplatePartialSpecializationDecl
*, 4> PartialSpecs
;
1833 D
->getPartialSpecializations(PartialSpecs
);
1834 for (unsigned I
= 0, N
= PartialSpecs
.size(); I
!= N
; ++I
)
1835 if (PartialSpecs
[I
]->getFirstDecl()->isOutOfLine())
1836 OutOfLineVarPartialSpecs
.push_back(
1837 std::make_pair(Inst
, PartialSpecs
[I
]));
1843 Decl
*TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1844 VarTemplatePartialSpecializationDecl
*D
) {
1845 assert(D
->isStaticDataMember() &&
1846 "Only static data member templates are allowed.");
1848 VarTemplateDecl
*VarTemplate
= D
->getSpecializedTemplate();
1850 // Lookup the already-instantiated declaration and return that.
1851 DeclContext::lookup_result Found
= Owner
->lookup(VarTemplate
->getDeclName());
1852 assert(!Found
.empty() && "Instantiation found nothing?");
1854 VarTemplateDecl
*InstVarTemplate
= dyn_cast
<VarTemplateDecl
>(Found
.front());
1855 assert(InstVarTemplate
&& "Instantiation did not find a variable template?");
1857 if (VarTemplatePartialSpecializationDecl
*Result
=
1858 InstVarTemplate
->findPartialSpecInstantiatedFromMember(D
))
1861 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate
, D
);
1865 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl
*D
) {
1866 // Create a local instantiation scope for this function template, which
1867 // will contain the instantiations of the template parameters and then get
1868 // merged with the local instantiation scope for the function template
1870 LocalInstantiationScope
Scope(SemaRef
);
1871 Sema::ConstraintEvalRAII
<TemplateDeclInstantiator
> RAII(*this);
1873 TemplateParameterList
*TempParams
= D
->getTemplateParameters();
1874 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
1878 FunctionDecl
*Instantiated
= nullptr;
1879 if (CXXMethodDecl
*DMethod
= dyn_cast
<CXXMethodDecl
>(D
->getTemplatedDecl()))
1880 Instantiated
= cast_or_null
<FunctionDecl
>(VisitCXXMethodDecl(DMethod
,
1883 Instantiated
= cast_or_null
<FunctionDecl
>(VisitFunctionDecl(
1884 D
->getTemplatedDecl(),
1890 // Link the instantiated function template declaration to the function
1891 // template from which it was instantiated.
1892 FunctionTemplateDecl
*InstTemplate
1893 = Instantiated
->getDescribedFunctionTemplate();
1894 InstTemplate
->setAccess(D
->getAccess());
1895 assert(InstTemplate
&&
1896 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1898 bool isFriend
= (InstTemplate
->getFriendObjectKind() != Decl::FOK_None
);
1900 // Link the instantiation back to the pattern *unless* this is a
1901 // non-definition friend declaration.
1902 if (!InstTemplate
->getInstantiatedFromMemberTemplate() &&
1903 !(isFriend
&& !D
->getTemplatedDecl()->isThisDeclarationADefinition()))
1904 InstTemplate
->setInstantiatedFromMemberTemplate(D
);
1906 // Make declarations visible in the appropriate context.
1908 Owner
->addDecl(InstTemplate
);
1909 } else if (InstTemplate
->getDeclContext()->isRecord() &&
1910 !getPreviousDeclForInstantiation(D
)) {
1911 SemaRef
.CheckFriendAccess(InstTemplate
);
1914 return InstTemplate
;
1917 Decl
*TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl
*D
) {
1918 CXXRecordDecl
*PrevDecl
= nullptr;
1919 if (CXXRecordDecl
*PatternPrev
= getPreviousDeclForInstantiation(D
)) {
1920 NamedDecl
*Prev
= SemaRef
.FindInstantiatedDecl(D
->getLocation(),
1923 if (!Prev
) return nullptr;
1924 PrevDecl
= cast
<CXXRecordDecl
>(Prev
);
1927 CXXRecordDecl
*Record
= nullptr;
1928 bool IsInjectedClassName
= D
->isInjectedClassName();
1930 Record
= CXXRecordDecl::CreateLambda(
1931 SemaRef
.Context
, Owner
, D
->getLambdaTypeInfo(), D
->getLocation(),
1932 D
->getLambdaDependencyKind(), D
->isGenericLambda(),
1933 D
->getLambdaCaptureDefault());
1935 Record
= CXXRecordDecl::Create(SemaRef
.Context
, D
->getTagKind(), Owner
,
1936 D
->getBeginLoc(), D
->getLocation(),
1937 D
->getIdentifier(), PrevDecl
,
1938 /*DelayTypeCreation=*/IsInjectedClassName
);
1939 // Link the type of the injected-class-name to that of the outer class.
1940 if (IsInjectedClassName
)
1941 (void)SemaRef
.Context
.getTypeDeclType(Record
, cast
<CXXRecordDecl
>(Owner
));
1943 // Substitute the nested name specifier, if any.
1944 if (SubstQualifier(D
, Record
))
1947 SemaRef
.InstantiateAttrsForDecl(TemplateArgs
, D
, Record
, LateAttrs
,
1950 Record
->setImplicit(D
->isImplicit());
1951 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1952 // the tag decls introduced by friend class declarations don't have an access
1953 // specifier. Remove once this area of the code gets sorted out.
1954 if (D
->getAccess() != AS_none
)
1955 Record
->setAccess(D
->getAccess());
1956 if (!IsInjectedClassName
)
1957 Record
->setInstantiationOfMemberClass(D
, TSK_ImplicitInstantiation
);
1959 // If the original function was part of a friend declaration,
1960 // inherit its namespace state.
1961 if (D
->getFriendObjectKind())
1962 Record
->setObjectOfFriendDecl();
1964 // Make sure that anonymous structs and unions are recorded.
1965 if (D
->isAnonymousStructOrUnion())
1966 Record
->setAnonymousStructOrUnion(true);
1968 if (D
->isLocalClass())
1969 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Record
);
1971 // Forward the mangling number from the template to the instantiated decl.
1972 SemaRef
.Context
.setManglingNumber(Record
,
1973 SemaRef
.Context
.getManglingNumber(D
));
1975 // See if the old tag was defined along with a declarator.
1976 // If it did, mark the new tag as being associated with that declarator.
1977 if (DeclaratorDecl
*DD
= SemaRef
.Context
.getDeclaratorForUnnamedTagDecl(D
))
1978 SemaRef
.Context
.addDeclaratorForUnnamedTagDecl(Record
, DD
);
1980 // See if the old tag was defined along with a typedef.
1981 // If it did, mark the new tag as being associated with that typedef.
1982 if (TypedefNameDecl
*TND
= SemaRef
.Context
.getTypedefNameForUnnamedTagDecl(D
))
1983 SemaRef
.Context
.addTypedefNameForUnnamedTagDecl(Record
, TND
);
1985 Owner
->addDecl(Record
);
1987 // DR1484 clarifies that the members of a local class are instantiated as part
1988 // of the instantiation of their enclosing entity.
1989 if (D
->isCompleteDefinition() && D
->isLocalClass()) {
1990 Sema::LocalEagerInstantiationScope
LocalInstantiations(SemaRef
);
1992 SemaRef
.InstantiateClass(D
->getLocation(), Record
, D
, TemplateArgs
,
1993 TSK_ImplicitInstantiation
,
1996 // For nested local classes, we will instantiate the members when we
1997 // reach the end of the outermost (non-nested) local class.
1998 if (!D
->isCXXClassMember())
1999 SemaRef
.InstantiateClassMembers(D
->getLocation(), Record
, TemplateArgs
,
2000 TSK_ImplicitInstantiation
);
2002 // This class may have local implicit instantiations that need to be
2003 // performed within this scope.
2004 LocalInstantiations
.perform();
2007 SemaRef
.DiagnoseUnusedNestedTypedefs(Record
);
2009 if (IsInjectedClassName
)
2010 assert(Record
->isInjectedClassName() && "Broken injected-class-name");
2015 /// Adjust the given function type for an instantiation of the
2016 /// given declaration, to cope with modifications to the function's type that
2017 /// aren't reflected in the type-source information.
2019 /// \param D The declaration we're instantiating.
2020 /// \param TInfo The already-instantiated type.
2021 static QualType
adjustFunctionTypeForInstantiation(ASTContext
&Context
,
2023 TypeSourceInfo
*TInfo
) {
2024 const FunctionProtoType
*OrigFunc
2025 = D
->getType()->castAs
<FunctionProtoType
>();
2026 const FunctionProtoType
*NewFunc
2027 = TInfo
->getType()->castAs
<FunctionProtoType
>();
2028 if (OrigFunc
->getExtInfo() == NewFunc
->getExtInfo())
2029 return TInfo
->getType();
2031 FunctionProtoType::ExtProtoInfo NewEPI
= NewFunc
->getExtProtoInfo();
2032 NewEPI
.ExtInfo
= OrigFunc
->getExtInfo();
2033 return Context
.getFunctionType(NewFunc
->getReturnType(),
2034 NewFunc
->getParamTypes(), NewEPI
);
2037 /// Normal class members are of more specific types and therefore
2038 /// don't make it here. This function serves three purposes:
2039 /// 1) instantiating function templates
2040 /// 2) substituting friend and local function declarations
2041 /// 3) substituting deduction guide declarations for nested class templates
2042 Decl
*TemplateDeclInstantiator::VisitFunctionDecl(
2043 FunctionDecl
*D
, TemplateParameterList
*TemplateParams
,
2044 RewriteKind FunctionRewriteKind
) {
2045 // Check whether there is already a function template specialization for
2046 // this declaration.
2047 FunctionTemplateDecl
*FunctionTemplate
= D
->getDescribedFunctionTemplate();
2048 if (FunctionTemplate
&& !TemplateParams
) {
2049 ArrayRef
<TemplateArgument
> Innermost
= TemplateArgs
.getInnermost();
2051 void *InsertPos
= nullptr;
2052 FunctionDecl
*SpecFunc
2053 = FunctionTemplate
->findSpecialization(Innermost
, InsertPos
);
2055 // If we already have a function template specialization, return it.
2061 if (FunctionTemplate
)
2062 isFriend
= (FunctionTemplate
->getFriendObjectKind() != Decl::FOK_None
);
2064 isFriend
= (D
->getFriendObjectKind() != Decl::FOK_None
);
2066 bool MergeWithParentScope
= (TemplateParams
!= nullptr) ||
2067 Owner
->isFunctionOrMethod() ||
2068 !(isa
<Decl
>(Owner
) &&
2069 cast
<Decl
>(Owner
)->isDefinedOutsideFunctionOrMethod());
2070 LocalInstantiationScope
Scope(SemaRef
, MergeWithParentScope
);
2072 ExplicitSpecifier InstantiatedExplicitSpecifier
;
2073 if (auto *DGuide
= dyn_cast
<CXXDeductionGuideDecl
>(D
)) {
2074 InstantiatedExplicitSpecifier
= SemaRef
.instantiateExplicitSpecifier(
2075 TemplateArgs
, DGuide
->getExplicitSpecifier());
2076 if (InstantiatedExplicitSpecifier
.isInvalid())
2080 SmallVector
<ParmVarDecl
*, 4> Params
;
2081 TypeSourceInfo
*TInfo
= SubstFunctionType(D
, Params
);
2084 QualType T
= adjustFunctionTypeForInstantiation(SemaRef
.Context
, D
, TInfo
);
2086 if (TemplateParams
&& TemplateParams
->size()) {
2088 dyn_cast
<TemplateTypeParmDecl
>(TemplateParams
->asArray().back());
2089 if (LastParam
&& LastParam
->isImplicit() &&
2090 LastParam
->hasTypeConstraint()) {
2091 // In abbreviated templates, the type-constraints of invented template
2092 // type parameters are instantiated with the function type, invalidating
2093 // the TemplateParameterList which relied on the template type parameter
2094 // not having a type constraint. Recreate the TemplateParameterList with
2095 // the updated parameter list.
2096 TemplateParams
= TemplateParameterList::Create(
2097 SemaRef
.Context
, TemplateParams
->getTemplateLoc(),
2098 TemplateParams
->getLAngleLoc(), TemplateParams
->asArray(),
2099 TemplateParams
->getRAngleLoc(), TemplateParams
->getRequiresClause());
2103 NestedNameSpecifierLoc QualifierLoc
= D
->getQualifierLoc();
2105 QualifierLoc
= SemaRef
.SubstNestedNameSpecifierLoc(QualifierLoc
,
2111 Expr
*TrailingRequiresClause
= D
->getTrailingRequiresClause();
2113 // If we're instantiating a local function declaration, put the result
2114 // in the enclosing namespace; otherwise we need to find the instantiated
2117 if (D
->isLocalExternDecl()) {
2119 SemaRef
.adjustContextForLocalExternDecl(DC
);
2120 } else if (isFriend
&& QualifierLoc
) {
2122 SS
.Adopt(QualifierLoc
);
2123 DC
= SemaRef
.computeDeclContext(SS
);
2124 if (!DC
) return nullptr;
2126 DC
= SemaRef
.FindInstantiatedContext(D
->getLocation(), D
->getDeclContext(),
2130 DeclarationNameInfo NameInfo
2131 = SemaRef
.SubstDeclarationNameInfo(D
->getNameInfo(), TemplateArgs
);
2133 if (FunctionRewriteKind
!= RewriteKind::None
)
2134 adjustForRewrite(FunctionRewriteKind
, D
, T
, TInfo
, NameInfo
);
2136 FunctionDecl
*Function
;
2137 if (auto *DGuide
= dyn_cast
<CXXDeductionGuideDecl
>(D
)) {
2138 Function
= CXXDeductionGuideDecl::Create(
2139 SemaRef
.Context
, DC
, D
->getInnerLocStart(),
2140 InstantiatedExplicitSpecifier
, NameInfo
, T
, TInfo
,
2141 D
->getSourceRange().getEnd(), DGuide
->getCorrespondingConstructor(),
2142 DGuide
->getDeductionCandidateKind());
2143 Function
->setAccess(D
->getAccess());
2145 Function
= FunctionDecl::Create(
2146 SemaRef
.Context
, DC
, D
->getInnerLocStart(), NameInfo
, T
, TInfo
,
2147 D
->getCanonicalDecl()->getStorageClass(), D
->UsesFPIntrin(),
2148 D
->isInlineSpecified(), D
->hasWrittenPrototype(), D
->getConstexprKind(),
2149 TrailingRequiresClause
);
2150 Function
->setFriendConstraintRefersToEnclosingTemplate(
2151 D
->FriendConstraintRefersToEnclosingTemplate());
2152 Function
->setRangeEnd(D
->getSourceRange().getEnd());
2156 Function
->setImplicitlyInline();
2159 Function
->setQualifierInfo(QualifierLoc
);
2161 if (D
->isLocalExternDecl())
2162 Function
->setLocalExternDecl();
2164 DeclContext
*LexicalDC
= Owner
;
2165 if (!isFriend
&& D
->isOutOfLine() && !D
->isLocalExternDecl()) {
2166 assert(D
->getDeclContext()->isFileContext());
2167 LexicalDC
= D
->getDeclContext();
2169 else if (D
->isLocalExternDecl()) {
2170 LexicalDC
= SemaRef
.CurContext
;
2173 Function
->setLexicalDeclContext(LexicalDC
);
2175 // Attach the parameters
2176 for (unsigned P
= 0; P
< Params
.size(); ++P
)
2178 Params
[P
]->setOwningFunction(Function
);
2179 Function
->setParams(Params
);
2181 if (TrailingRequiresClause
)
2182 Function
->setTrailingRequiresClause(TrailingRequiresClause
);
2184 if (TemplateParams
) {
2185 // Our resulting instantiation is actually a function template, since we
2186 // are substituting only the outer template parameters. For example, given
2188 // template<typename T>
2190 // template<typename U> friend void f(T, U);
2195 // We are instantiating the friend function template "f" within X<int>,
2196 // which means substituting int for T, but leaving "f" as a friend function
2198 // Build the function template itself.
2199 FunctionTemplate
= FunctionTemplateDecl::Create(SemaRef
.Context
, DC
,
2200 Function
->getLocation(),
2201 Function
->getDeclName(),
2202 TemplateParams
, Function
);
2203 Function
->setDescribedFunctionTemplate(FunctionTemplate
);
2205 FunctionTemplate
->setLexicalDeclContext(LexicalDC
);
2207 if (isFriend
&& D
->isThisDeclarationADefinition()) {
2208 FunctionTemplate
->setInstantiatedFromMemberTemplate(
2209 D
->getDescribedFunctionTemplate());
2211 } else if (FunctionTemplate
) {
2212 // Record this function template specialization.
2213 ArrayRef
<TemplateArgument
> Innermost
= TemplateArgs
.getInnermost();
2214 Function
->setFunctionTemplateSpecialization(FunctionTemplate
,
2215 TemplateArgumentList::CreateCopy(SemaRef
.Context
,
2217 /*InsertPos=*/nullptr);
2218 } else if (isFriend
&& D
->isThisDeclarationADefinition()) {
2219 // Do not connect the friend to the template unless it's actually a
2220 // definition. We don't want non-template functions to be marked as being
2221 // template instantiations.
2222 Function
->setInstantiationOfMemberFunction(D
, TSK_ImplicitInstantiation
);
2223 } else if (!isFriend
) {
2224 // If this is not a function template, and this is not a friend (that is,
2225 // this is a locally declared function), save the instantiation relationship
2226 // for the purposes of constraint instantiation.
2227 Function
->setInstantiatedFromDecl(D
);
2231 Function
->setObjectOfFriendDecl();
2232 if (FunctionTemplateDecl
*FT
= Function
->getDescribedFunctionTemplate())
2233 FT
->setObjectOfFriendDecl();
2236 if (InitFunctionInstantiation(Function
, D
))
2237 Function
->setInvalidDecl();
2239 bool IsExplicitSpecialization
= false;
2241 LookupResult
Previous(
2242 SemaRef
, Function
->getDeclName(), SourceLocation(),
2243 D
->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
2244 : Sema::LookupOrdinaryName
,
2245 D
->isLocalExternDecl() ? Sema::ForExternalRedeclaration
2246 : SemaRef
.forRedeclarationInCurContext());
2248 if (DependentFunctionTemplateSpecializationInfo
*DFTSI
=
2249 D
->getDependentSpecializationInfo()) {
2250 assert(isFriend
&& "dependent specialization info on "
2251 "non-member non-friend function?");
2253 // Instantiate the explicit template arguments.
2254 TemplateArgumentListInfo ExplicitArgs
;
2255 if (const auto *ArgsWritten
= DFTSI
->TemplateArgumentsAsWritten
) {
2256 ExplicitArgs
.setLAngleLoc(ArgsWritten
->getLAngleLoc());
2257 ExplicitArgs
.setRAngleLoc(ArgsWritten
->getRAngleLoc());
2258 if (SemaRef
.SubstTemplateArguments(ArgsWritten
->arguments(), TemplateArgs
,
2263 // Map the candidates for the primary template to their instantiations.
2264 for (FunctionTemplateDecl
*FTD
: DFTSI
->getCandidates()) {
2266 SemaRef
.FindInstantiatedDecl(D
->getLocation(), FTD
, TemplateArgs
))
2267 Previous
.addDecl(ND
);
2272 if (SemaRef
.CheckFunctionTemplateSpecialization(
2274 DFTSI
->TemplateArgumentsAsWritten
? &ExplicitArgs
: nullptr,
2276 Function
->setInvalidDecl();
2278 IsExplicitSpecialization
= true;
2279 } else if (const ASTTemplateArgumentListInfo
*ArgsWritten
=
2280 D
->getTemplateSpecializationArgsAsWritten()) {
2281 // The name of this function was written as a template-id.
2282 SemaRef
.LookupQualifiedName(Previous
, DC
);
2284 // Instantiate the explicit template arguments.
2285 TemplateArgumentListInfo
ExplicitArgs(ArgsWritten
->getLAngleLoc(),
2286 ArgsWritten
->getRAngleLoc());
2287 if (SemaRef
.SubstTemplateArguments(ArgsWritten
->arguments(), TemplateArgs
,
2291 if (SemaRef
.CheckFunctionTemplateSpecialization(Function
,
2294 Function
->setInvalidDecl();
2296 IsExplicitSpecialization
= true;
2297 } else if (TemplateParams
|| !FunctionTemplate
) {
2298 // Look only into the namespace where the friend would be declared to
2299 // find a previous declaration. This is the innermost enclosing namespace,
2300 // as described in ActOnFriendFunctionDecl.
2301 SemaRef
.LookupQualifiedName(Previous
, DC
->getRedeclContext());
2303 // In C++, the previous declaration we find might be a tag type
2304 // (class or enum). In this case, the new declaration will hide the
2305 // tag type. Note that this does not apply if we're declaring a
2306 // typedef (C++ [dcl.typedef]p4).
2307 if (Previous
.isSingleTagDecl())
2310 // Filter out previous declarations that don't match the scope. The only
2311 // effect this has is to remove declarations found in inline namespaces
2312 // for friend declarations with unqualified names.
2313 if (isFriend
&& !QualifierLoc
) {
2314 SemaRef
.FilterLookupForScope(Previous
, DC
, /*Scope=*/ nullptr,
2315 /*ConsiderLinkage=*/ true,
2316 QualifierLoc
.hasQualifier());
2320 // Per [temp.inst], default arguments in function declarations at local scope
2321 // are instantiated along with the enclosing declaration. For example:
2323 // template<typename T>
2325 // void f(int = []{ return T::value; }());
2327 // template void ft<int>(); // error: type 'int' cannot be used prior
2328 // to '::' because it has no members
2330 // The error is issued during instantiation of ft<int>() because substitution
2331 // into the default argument fails; the default argument is instantiated even
2332 // though it is never used.
2333 if (Function
->isLocalExternDecl()) {
2334 for (ParmVarDecl
*PVD
: Function
->parameters()) {
2335 if (!PVD
->hasDefaultArg())
2337 if (SemaRef
.SubstDefaultArgument(D
->getInnerLocStart(), PVD
, TemplateArgs
)) {
2338 // If substitution fails, the default argument is set to a
2339 // RecoveryExpr that wraps the uninstantiated default argument so
2340 // that downstream diagnostics are omitted.
2341 Expr
*UninstExpr
= PVD
->getUninstantiatedDefaultArg();
2342 ExprResult ErrorResult
= SemaRef
.CreateRecoveryExpr(
2343 UninstExpr
->getBeginLoc(), UninstExpr
->getEndLoc(),
2344 { UninstExpr
}, UninstExpr
->getType());
2345 if (ErrorResult
.isUsable())
2346 PVD
->setDefaultArg(ErrorResult
.get());
2351 SemaRef
.CheckFunctionDeclaration(/*Scope*/ nullptr, Function
, Previous
,
2352 IsExplicitSpecialization
,
2353 Function
->isThisDeclarationADefinition());
2355 // Check the template parameter list against the previous declaration. The
2356 // goal here is to pick up default arguments added since the friend was
2357 // declared; we know the template parameter lists match, since otherwise
2358 // we would not have picked this template as the previous declaration.
2359 if (isFriend
&& TemplateParams
&& FunctionTemplate
->getPreviousDecl()) {
2360 SemaRef
.CheckTemplateParameterList(
2362 FunctionTemplate
->getPreviousDecl()->getTemplateParameters(),
2363 Function
->isThisDeclarationADefinition()
2364 ? Sema::TPC_FriendFunctionTemplateDefinition
2365 : Sema::TPC_FriendFunctionTemplate
);
2368 // If we're introducing a friend definition after the first use, trigger
2370 // FIXME: If this is a friend function template definition, we should check
2371 // to see if any specializations have been used.
2372 if (isFriend
&& D
->isThisDeclarationADefinition() && Function
->isUsed(false)) {
2373 if (MemberSpecializationInfo
*MSInfo
=
2374 Function
->getMemberSpecializationInfo()) {
2375 if (MSInfo
->getPointOfInstantiation().isInvalid()) {
2376 SourceLocation Loc
= D
->getLocation(); // FIXME
2377 MSInfo
->setPointOfInstantiation(Loc
);
2378 SemaRef
.PendingLocalImplicitInstantiations
.push_back(
2379 std::make_pair(Function
, Loc
));
2384 if (D
->isExplicitlyDefaulted()) {
2385 if (SubstDefaultedFunction(Function
, D
))
2389 SemaRef
.SetDeclDeleted(Function
, D
->getLocation());
2391 NamedDecl
*PrincipalDecl
=
2392 (TemplateParams
? cast
<NamedDecl
>(FunctionTemplate
) : Function
);
2394 // If this declaration lives in a different context from its lexical context,
2395 // add it to the corresponding lookup table.
2397 (Function
->isLocalExternDecl() && !Function
->getPreviousDecl()))
2398 DC
->makeDeclVisibleInContext(PrincipalDecl
);
2400 if (Function
->isOverloadedOperator() && !DC
->isRecord() &&
2401 PrincipalDecl
->isInIdentifierNamespace(Decl::IDNS_Ordinary
))
2402 PrincipalDecl
->setNonMemberOperator();
2407 Decl
*TemplateDeclInstantiator::VisitCXXMethodDecl(
2408 CXXMethodDecl
*D
, TemplateParameterList
*TemplateParams
,
2409 RewriteKind FunctionRewriteKind
) {
2410 FunctionTemplateDecl
*FunctionTemplate
= D
->getDescribedFunctionTemplate();
2411 if (FunctionTemplate
&& !TemplateParams
) {
2412 // We are creating a function template specialization from a function
2413 // template. Check whether there is already a function template
2414 // specialization for this particular set of template arguments.
2415 ArrayRef
<TemplateArgument
> Innermost
= TemplateArgs
.getInnermost();
2417 void *InsertPos
= nullptr;
2418 FunctionDecl
*SpecFunc
2419 = FunctionTemplate
->findSpecialization(Innermost
, InsertPos
);
2421 // If we already have a function template specialization, return it.
2427 if (FunctionTemplate
)
2428 isFriend
= (FunctionTemplate
->getFriendObjectKind() != Decl::FOK_None
);
2430 isFriend
= (D
->getFriendObjectKind() != Decl::FOK_None
);
2432 bool MergeWithParentScope
= (TemplateParams
!= nullptr) ||
2433 !(isa
<Decl
>(Owner
) &&
2434 cast
<Decl
>(Owner
)->isDefinedOutsideFunctionOrMethod());
2435 LocalInstantiationScope
Scope(SemaRef
, MergeWithParentScope
);
2437 Sema::LambdaScopeForCallOperatorInstantiationRAII
LambdaScope(
2438 SemaRef
, const_cast<CXXMethodDecl
*>(D
), TemplateArgs
, Scope
);
2440 // Instantiate enclosing template arguments for friends.
2441 SmallVector
<TemplateParameterList
*, 4> TempParamLists
;
2442 unsigned NumTempParamLists
= 0;
2443 if (isFriend
&& (NumTempParamLists
= D
->getNumTemplateParameterLists())) {
2444 TempParamLists
.resize(NumTempParamLists
);
2445 for (unsigned I
= 0; I
!= NumTempParamLists
; ++I
) {
2446 TemplateParameterList
*TempParams
= D
->getTemplateParameterList(I
);
2447 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
2450 TempParamLists
[I
] = InstParams
;
2454 auto InstantiatedExplicitSpecifier
= ExplicitSpecifier::getFromDecl(D
);
2455 // deduction guides need this
2456 const bool CouldInstantiate
=
2457 InstantiatedExplicitSpecifier
.getExpr() == nullptr ||
2458 !InstantiatedExplicitSpecifier
.getExpr()->isValueDependent();
2460 // Delay the instantiation of the explicit-specifier until after the
2461 // constraints are checked during template argument deduction.
2462 if (CouldInstantiate
||
2463 SemaRef
.CodeSynthesisContexts
.back().Kind
!=
2464 Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) {
2465 InstantiatedExplicitSpecifier
= SemaRef
.instantiateExplicitSpecifier(
2466 TemplateArgs
, InstantiatedExplicitSpecifier
);
2468 if (InstantiatedExplicitSpecifier
.isInvalid())
2471 InstantiatedExplicitSpecifier
.setKind(ExplicitSpecKind::Unresolved
);
2474 // Implicit destructors/constructors created for local classes in
2475 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2476 // Unfortunately there isn't enough context in those functions to
2477 // conditionally populate the TSI without breaking non-template related use
2478 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2479 // a proper transformation.
2480 if (cast
<CXXRecordDecl
>(D
->getParent())->isLambda() &&
2481 !D
->getTypeSourceInfo() &&
2482 isa
<CXXConstructorDecl
, CXXDestructorDecl
>(D
)) {
2483 TypeSourceInfo
*TSI
=
2484 SemaRef
.Context
.getTrivialTypeSourceInfo(D
->getType());
2485 D
->setTypeSourceInfo(TSI
);
2488 SmallVector
<ParmVarDecl
*, 4> Params
;
2489 TypeSourceInfo
*TInfo
= SubstFunctionType(D
, Params
);
2492 QualType T
= adjustFunctionTypeForInstantiation(SemaRef
.Context
, D
, TInfo
);
2494 if (TemplateParams
&& TemplateParams
->size()) {
2496 dyn_cast
<TemplateTypeParmDecl
>(TemplateParams
->asArray().back());
2497 if (LastParam
&& LastParam
->isImplicit() &&
2498 LastParam
->hasTypeConstraint()) {
2499 // In abbreviated templates, the type-constraints of invented template
2500 // type parameters are instantiated with the function type, invalidating
2501 // the TemplateParameterList which relied on the template type parameter
2502 // not having a type constraint. Recreate the TemplateParameterList with
2503 // the updated parameter list.
2504 TemplateParams
= TemplateParameterList::Create(
2505 SemaRef
.Context
, TemplateParams
->getTemplateLoc(),
2506 TemplateParams
->getLAngleLoc(), TemplateParams
->asArray(),
2507 TemplateParams
->getRAngleLoc(), TemplateParams
->getRequiresClause());
2511 NestedNameSpecifierLoc QualifierLoc
= D
->getQualifierLoc();
2513 QualifierLoc
= SemaRef
.SubstNestedNameSpecifierLoc(QualifierLoc
,
2519 DeclContext
*DC
= Owner
;
2523 SS
.Adopt(QualifierLoc
);
2524 DC
= SemaRef
.computeDeclContext(SS
);
2526 if (DC
&& SemaRef
.RequireCompleteDeclContext(SS
, DC
))
2529 DC
= SemaRef
.FindInstantiatedContext(D
->getLocation(),
2530 D
->getDeclContext(),
2533 if (!DC
) return nullptr;
2536 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(DC
);
2537 Expr
*TrailingRequiresClause
= D
->getTrailingRequiresClause();
2539 DeclarationNameInfo NameInfo
2540 = SemaRef
.SubstDeclarationNameInfo(D
->getNameInfo(), TemplateArgs
);
2542 if (FunctionRewriteKind
!= RewriteKind::None
)
2543 adjustForRewrite(FunctionRewriteKind
, D
, T
, TInfo
, NameInfo
);
2545 // Build the instantiated method declaration.
2546 CXXMethodDecl
*Method
= nullptr;
2548 SourceLocation StartLoc
= D
->getInnerLocStart();
2549 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(D
)) {
2550 Method
= CXXConstructorDecl::Create(
2551 SemaRef
.Context
, Record
, StartLoc
, NameInfo
, T
, TInfo
,
2552 InstantiatedExplicitSpecifier
, Constructor
->UsesFPIntrin(),
2553 Constructor
->isInlineSpecified(), false,
2554 Constructor
->getConstexprKind(), InheritedConstructor(),
2555 TrailingRequiresClause
);
2556 Method
->setRangeEnd(Constructor
->getEndLoc());
2557 } else if (CXXDestructorDecl
*Destructor
= dyn_cast
<CXXDestructorDecl
>(D
)) {
2558 Method
= CXXDestructorDecl::Create(
2559 SemaRef
.Context
, Record
, StartLoc
, NameInfo
, T
, TInfo
,
2560 Destructor
->UsesFPIntrin(), Destructor
->isInlineSpecified(), false,
2561 Destructor
->getConstexprKind(), TrailingRequiresClause
);
2562 Method
->setIneligibleOrNotSelected(true);
2563 Method
->setRangeEnd(Destructor
->getEndLoc());
2564 Method
->setDeclName(SemaRef
.Context
.DeclarationNames
.getCXXDestructorName(
2565 SemaRef
.Context
.getCanonicalType(
2566 SemaRef
.Context
.getTypeDeclType(Record
))));
2567 } else if (CXXConversionDecl
*Conversion
= dyn_cast
<CXXConversionDecl
>(D
)) {
2568 Method
= CXXConversionDecl::Create(
2569 SemaRef
.Context
, Record
, StartLoc
, NameInfo
, T
, TInfo
,
2570 Conversion
->UsesFPIntrin(), Conversion
->isInlineSpecified(),
2571 InstantiatedExplicitSpecifier
, Conversion
->getConstexprKind(),
2572 Conversion
->getEndLoc(), TrailingRequiresClause
);
2574 StorageClass SC
= D
->isStatic() ? SC_Static
: SC_None
;
2575 Method
= CXXMethodDecl::Create(
2576 SemaRef
.Context
, Record
, StartLoc
, NameInfo
, T
, TInfo
, SC
,
2577 D
->UsesFPIntrin(), D
->isInlineSpecified(), D
->getConstexprKind(),
2578 D
->getEndLoc(), TrailingRequiresClause
);
2582 Method
->setImplicitlyInline();
2585 Method
->setQualifierInfo(QualifierLoc
);
2587 if (TemplateParams
) {
2588 // Our resulting instantiation is actually a function template, since we
2589 // are substituting only the outer template parameters. For example, given
2591 // template<typename T>
2593 // template<typename U> void f(T, U);
2598 // We are instantiating the member template "f" within X<int>, which means
2599 // substituting int for T, but leaving "f" as a member function template.
2600 // Build the function template itself.
2601 FunctionTemplate
= FunctionTemplateDecl::Create(SemaRef
.Context
, Record
,
2602 Method
->getLocation(),
2603 Method
->getDeclName(),
2604 TemplateParams
, Method
);
2606 FunctionTemplate
->setLexicalDeclContext(Owner
);
2607 FunctionTemplate
->setObjectOfFriendDecl();
2608 } else if (D
->isOutOfLine())
2609 FunctionTemplate
->setLexicalDeclContext(D
->getLexicalDeclContext());
2610 Method
->setDescribedFunctionTemplate(FunctionTemplate
);
2611 } else if (FunctionTemplate
) {
2612 // Record this function template specialization.
2613 ArrayRef
<TemplateArgument
> Innermost
= TemplateArgs
.getInnermost();
2614 Method
->setFunctionTemplateSpecialization(FunctionTemplate
,
2615 TemplateArgumentList::CreateCopy(SemaRef
.Context
,
2617 /*InsertPos=*/nullptr);
2618 } else if (!isFriend
) {
2619 // Record that this is an instantiation of a member function.
2620 Method
->setInstantiationOfMemberFunction(D
, TSK_ImplicitInstantiation
);
2623 // If we are instantiating a member function defined
2624 // out-of-line, the instantiation will have the same lexical
2625 // context (which will be a namespace scope) as the template.
2627 if (NumTempParamLists
)
2628 Method
->setTemplateParameterListsInfo(
2630 llvm::ArrayRef(TempParamLists
.data(), NumTempParamLists
));
2632 Method
->setLexicalDeclContext(Owner
);
2633 Method
->setObjectOfFriendDecl();
2634 } else if (D
->isOutOfLine())
2635 Method
->setLexicalDeclContext(D
->getLexicalDeclContext());
2637 // Attach the parameters
2638 for (unsigned P
= 0; P
< Params
.size(); ++P
)
2639 Params
[P
]->setOwningFunction(Method
);
2640 Method
->setParams(Params
);
2642 if (InitMethodInstantiation(Method
, D
))
2643 Method
->setInvalidDecl();
2645 LookupResult
Previous(SemaRef
, NameInfo
, Sema::LookupOrdinaryName
,
2646 Sema::ForExternalRedeclaration
);
2648 bool IsExplicitSpecialization
= false;
2650 // If the name of this function was written as a template-id, instantiate
2651 // the explicit template arguments.
2652 if (DependentFunctionTemplateSpecializationInfo
*DFTSI
=
2653 D
->getDependentSpecializationInfo()) {
2654 // Instantiate the explicit template arguments.
2655 TemplateArgumentListInfo ExplicitArgs
;
2656 if (const auto *ArgsWritten
= DFTSI
->TemplateArgumentsAsWritten
) {
2657 ExplicitArgs
.setLAngleLoc(ArgsWritten
->getLAngleLoc());
2658 ExplicitArgs
.setRAngleLoc(ArgsWritten
->getRAngleLoc());
2659 if (SemaRef
.SubstTemplateArguments(ArgsWritten
->arguments(), TemplateArgs
,
2664 // Map the candidates for the primary template to their instantiations.
2665 for (FunctionTemplateDecl
*FTD
: DFTSI
->getCandidates()) {
2667 SemaRef
.FindInstantiatedDecl(D
->getLocation(), FTD
, TemplateArgs
))
2668 Previous
.addDecl(ND
);
2673 if (SemaRef
.CheckFunctionTemplateSpecialization(
2674 Method
, DFTSI
->TemplateArgumentsAsWritten
? &ExplicitArgs
: nullptr,
2676 Method
->setInvalidDecl();
2678 IsExplicitSpecialization
= true;
2679 } else if (const ASTTemplateArgumentListInfo
*ArgsWritten
=
2680 D
->getTemplateSpecializationArgsAsWritten()) {
2681 SemaRef
.LookupQualifiedName(Previous
, DC
);
2683 TemplateArgumentListInfo
ExplicitArgs(ArgsWritten
->getLAngleLoc(),
2684 ArgsWritten
->getRAngleLoc());
2686 if (SemaRef
.SubstTemplateArguments(ArgsWritten
->arguments(), TemplateArgs
,
2690 if (SemaRef
.CheckFunctionTemplateSpecialization(Method
,
2693 Method
->setInvalidDecl();
2695 IsExplicitSpecialization
= true;
2696 } else if (!FunctionTemplate
|| TemplateParams
|| isFriend
) {
2697 SemaRef
.LookupQualifiedName(Previous
, Record
);
2699 // In C++, the previous declaration we find might be a tag type
2700 // (class or enum). In this case, the new declaration will hide the
2701 // tag type. Note that this does not apply if we're declaring a
2702 // typedef (C++ [dcl.typedef]p4).
2703 if (Previous
.isSingleTagDecl())
2707 // Per [temp.inst], default arguments in member functions of local classes
2708 // are instantiated along with the member function declaration. For example:
2710 // template<typename T>
2713 // int operator()(int p = []{ return T::value; }());
2716 // template void ft<int>(); // error: type 'int' cannot be used prior
2717 // to '::'because it has no members
2719 // The error is issued during instantiation of ft<int>()::lc::operator()
2720 // because substitution into the default argument fails; the default argument
2721 // is instantiated even though it is never used.
2722 if (D
->isInLocalScopeForInstantiation()) {
2723 for (unsigned P
= 0; P
< Params
.size(); ++P
) {
2724 if (!Params
[P
]->hasDefaultArg())
2726 if (SemaRef
.SubstDefaultArgument(StartLoc
, Params
[P
], TemplateArgs
)) {
2727 // If substitution fails, the default argument is set to a
2728 // RecoveryExpr that wraps the uninstantiated default argument so
2729 // that downstream diagnostics are omitted.
2730 Expr
*UninstExpr
= Params
[P
]->getUninstantiatedDefaultArg();
2731 ExprResult ErrorResult
= SemaRef
.CreateRecoveryExpr(
2732 UninstExpr
->getBeginLoc(), UninstExpr
->getEndLoc(),
2733 { UninstExpr
}, UninstExpr
->getType());
2734 if (ErrorResult
.isUsable())
2735 Params
[P
]->setDefaultArg(ErrorResult
.get());
2740 SemaRef
.CheckFunctionDeclaration(nullptr, Method
, Previous
,
2741 IsExplicitSpecialization
,
2742 Method
->isThisDeclarationADefinition());
2745 SemaRef
.CheckPureMethod(Method
, SourceRange());
2747 // Propagate access. For a non-friend declaration, the access is
2748 // whatever we're propagating from. For a friend, it should be the
2749 // previous declaration we just found.
2750 if (isFriend
&& Method
->getPreviousDecl())
2751 Method
->setAccess(Method
->getPreviousDecl()->getAccess());
2753 Method
->setAccess(D
->getAccess());
2754 if (FunctionTemplate
)
2755 FunctionTemplate
->setAccess(Method
->getAccess());
2757 SemaRef
.CheckOverrideControl(Method
);
2759 // If a function is defined as defaulted or deleted, mark it as such now.
2760 if (D
->isExplicitlyDefaulted()) {
2761 if (SubstDefaultedFunction(Method
, D
))
2764 if (D
->isDeletedAsWritten())
2765 SemaRef
.SetDeclDeleted(Method
, Method
->getLocation());
2767 // If this is an explicit specialization, mark the implicitly-instantiated
2768 // template specialization as being an explicit specialization too.
2769 // FIXME: Is this necessary?
2770 if (IsExplicitSpecialization
&& !isFriend
)
2771 SemaRef
.CompleteMemberSpecialization(Method
, Previous
);
2773 // If the method is a special member function, we need to mark it as
2774 // ineligible so that Owner->addDecl() won't mark the class as non trivial.
2775 // At the end of the class instantiation, we calculate eligibility again and
2776 // then we adjust trivility if needed.
2777 // We need this check to happen only after the method parameters are set,
2778 // because being e.g. a copy constructor depends on the instantiated
2780 if (auto *Constructor
= dyn_cast
<CXXConstructorDecl
>(Method
)) {
2781 if (Constructor
->isDefaultConstructor() ||
2782 Constructor
->isCopyOrMoveConstructor())
2783 Method
->setIneligibleOrNotSelected(true);
2784 } else if (Method
->isCopyAssignmentOperator() ||
2785 Method
->isMoveAssignmentOperator()) {
2786 Method
->setIneligibleOrNotSelected(true);
2789 // If there's a function template, let our caller handle it.
2790 if (FunctionTemplate
) {
2793 // Don't hide a (potentially) valid declaration with an invalid one.
2794 } else if (Method
->isInvalidDecl() && !Previous
.empty()) {
2797 // Otherwise, check access to friends and make them visible.
2798 } else if (isFriend
) {
2799 // We only need to re-check access for methods which we didn't
2800 // manage to match during parsing.
2801 if (!D
->getPreviousDecl())
2802 SemaRef
.CheckFriendAccess(Method
);
2804 Record
->makeDeclVisibleInContext(Method
);
2806 // Otherwise, add the declaration. We don't need to do this for
2807 // class-scope specializations because we'll have matched them with
2808 // the appropriate template.
2810 Owner
->addDecl(Method
);
2813 // PR17480: Honor the used attribute to instantiate member function
2815 if (Method
->hasAttr
<UsedAttr
>()) {
2816 if (const auto *A
= dyn_cast
<CXXRecordDecl
>(Owner
)) {
2818 if (const MemberSpecializationInfo
*MSInfo
=
2819 A
->getMemberSpecializationInfo())
2820 Loc
= MSInfo
->getPointOfInstantiation();
2821 else if (const auto *Spec
= dyn_cast
<ClassTemplateSpecializationDecl
>(A
))
2822 Loc
= Spec
->getPointOfInstantiation();
2823 SemaRef
.MarkFunctionReferenced(Loc
, Method
);
2830 Decl
*TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl
*D
) {
2831 return VisitCXXMethodDecl(D
);
2834 Decl
*TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl
*D
) {
2835 return VisitCXXMethodDecl(D
);
2838 Decl
*TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl
*D
) {
2839 return VisitCXXMethodDecl(D
);
2842 Decl
*TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl
*D
) {
2843 return SemaRef
.SubstParmVarDecl(D
, TemplateArgs
, /*indexAdjustment*/ 0,
2845 /*ExpectParameterPack=*/false);
2848 Decl
*TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2849 TemplateTypeParmDecl
*D
) {
2850 assert(D
->getTypeForDecl()->isTemplateTypeParmType());
2852 std::optional
<unsigned> NumExpanded
;
2854 if (const TypeConstraint
*TC
= D
->getTypeConstraint()) {
2855 if (D
->isPackExpansion() && !D
->isExpandedParameterPack()) {
2856 assert(TC
->getTemplateArgsAsWritten() &&
2857 "type parameter can only be an expansion when explicit arguments "
2859 // The template type parameter pack's type is a pack expansion of types.
2860 // Determine whether we need to expand this parameter pack into separate
2862 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
2863 for (auto &ArgLoc
: TC
->getTemplateArgsAsWritten()->arguments())
2864 SemaRef
.collectUnexpandedParameterPacks(ArgLoc
, Unexpanded
);
2866 // Determine whether the set of unexpanded parameter packs can and should
2869 bool RetainExpansion
= false;
2870 if (SemaRef
.CheckParameterPacksForExpansion(
2871 cast
<CXXFoldExpr
>(TC
->getImmediatelyDeclaredConstraint())
2873 SourceRange(TC
->getConceptNameLoc(),
2874 TC
->hasExplicitTemplateArgs() ?
2875 TC
->getTemplateArgsAsWritten()->getRAngleLoc() :
2876 TC
->getConceptNameInfo().getEndLoc()),
2877 Unexpanded
, TemplateArgs
, Expand
, RetainExpansion
, NumExpanded
))
2882 TemplateTypeParmDecl
*Inst
= TemplateTypeParmDecl::Create(
2883 SemaRef
.Context
, Owner
, D
->getBeginLoc(), D
->getLocation(),
2884 D
->getDepth() - TemplateArgs
.getNumSubstitutedLevels(), D
->getIndex(),
2885 D
->getIdentifier(), D
->wasDeclaredWithTypename(), D
->isParameterPack(),
2886 D
->hasTypeConstraint(), NumExpanded
);
2888 Inst
->setAccess(AS_public
);
2889 Inst
->setImplicit(D
->isImplicit());
2890 if (auto *TC
= D
->getTypeConstraint()) {
2891 if (!D
->isImplicit()) {
2892 // Invented template parameter type constraints will be instantiated
2893 // with the corresponding auto-typed parameter as it might reference
2894 // other parameters.
2895 if (SemaRef
.SubstTypeConstraint(Inst
, TC
, TemplateArgs
,
2896 EvaluateConstraints
))
2900 if (D
->hasDefaultArgument() && !D
->defaultArgumentWasInherited()) {
2901 TypeSourceInfo
*InstantiatedDefaultArg
=
2902 SemaRef
.SubstType(D
->getDefaultArgumentInfo(), TemplateArgs
,
2903 D
->getDefaultArgumentLoc(), D
->getDeclName());
2904 if (InstantiatedDefaultArg
)
2905 Inst
->setDefaultArgument(InstantiatedDefaultArg
);
2908 // Introduce this template parameter's instantiation into the instantiation
2910 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Inst
);
2915 Decl
*TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2916 NonTypeTemplateParmDecl
*D
) {
2917 // Substitute into the type of the non-type template parameter.
2918 TypeLoc TL
= D
->getTypeSourceInfo()->getTypeLoc();
2919 SmallVector
<TypeSourceInfo
*, 4> ExpandedParameterPackTypesAsWritten
;
2920 SmallVector
<QualType
, 4> ExpandedParameterPackTypes
;
2921 bool IsExpandedParameterPack
= false;
2924 bool Invalid
= false;
2926 if (D
->isExpandedParameterPack()) {
2927 // The non-type template parameter pack is an already-expanded pack
2928 // expansion of types. Substitute into each of the expanded types.
2929 ExpandedParameterPackTypes
.reserve(D
->getNumExpansionTypes());
2930 ExpandedParameterPackTypesAsWritten
.reserve(D
->getNumExpansionTypes());
2931 for (unsigned I
= 0, N
= D
->getNumExpansionTypes(); I
!= N
; ++I
) {
2932 TypeSourceInfo
*NewDI
=
2933 SemaRef
.SubstType(D
->getExpansionTypeSourceInfo(I
), TemplateArgs
,
2934 D
->getLocation(), D
->getDeclName());
2939 SemaRef
.CheckNonTypeTemplateParameterType(NewDI
, D
->getLocation());
2943 ExpandedParameterPackTypesAsWritten
.push_back(NewDI
);
2944 ExpandedParameterPackTypes
.push_back(NewT
);
2947 IsExpandedParameterPack
= true;
2948 DI
= D
->getTypeSourceInfo();
2950 } else if (D
->isPackExpansion()) {
2951 // The non-type template parameter pack's type is a pack expansion of types.
2952 // Determine whether we need to expand this parameter pack into separate
2954 PackExpansionTypeLoc Expansion
= TL
.castAs
<PackExpansionTypeLoc
>();
2955 TypeLoc Pattern
= Expansion
.getPatternLoc();
2956 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
2957 SemaRef
.collectUnexpandedParameterPacks(Pattern
, Unexpanded
);
2959 // Determine whether the set of unexpanded parameter packs can and should
2962 bool RetainExpansion
= false;
2963 std::optional
<unsigned> OrigNumExpansions
=
2964 Expansion
.getTypePtr()->getNumExpansions();
2965 std::optional
<unsigned> NumExpansions
= OrigNumExpansions
;
2966 if (SemaRef
.CheckParameterPacksForExpansion(Expansion
.getEllipsisLoc(),
2967 Pattern
.getSourceRange(),
2970 Expand
, RetainExpansion
,
2975 for (unsigned I
= 0; I
!= *NumExpansions
; ++I
) {
2976 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, I
);
2977 TypeSourceInfo
*NewDI
= SemaRef
.SubstType(Pattern
, TemplateArgs
,
2984 SemaRef
.CheckNonTypeTemplateParameterType(NewDI
, D
->getLocation());
2988 ExpandedParameterPackTypesAsWritten
.push_back(NewDI
);
2989 ExpandedParameterPackTypes
.push_back(NewT
);
2992 // Note that we have an expanded parameter pack. The "type" of this
2993 // expanded parameter pack is the original expansion type, but callers
2994 // will end up using the expanded parameter pack types for type-checking.
2995 IsExpandedParameterPack
= true;
2996 DI
= D
->getTypeSourceInfo();
2999 // We cannot fully expand the pack expansion now, so substitute into the
3000 // pattern and create a new pack expansion type.
3001 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, -1);
3002 TypeSourceInfo
*NewPattern
= SemaRef
.SubstType(Pattern
, TemplateArgs
,
3008 SemaRef
.CheckNonTypeTemplateParameterType(NewPattern
, D
->getLocation());
3009 DI
= SemaRef
.CheckPackExpansion(NewPattern
, Expansion
.getEllipsisLoc(),
3017 // Simple case: substitution into a parameter that is not a parameter pack.
3018 DI
= SemaRef
.SubstType(D
->getTypeSourceInfo(), TemplateArgs
,
3019 D
->getLocation(), D
->getDeclName());
3023 // Check that this type is acceptable for a non-type template parameter.
3024 T
= SemaRef
.CheckNonTypeTemplateParameterType(DI
, D
->getLocation());
3026 T
= SemaRef
.Context
.IntTy
;
3031 NonTypeTemplateParmDecl
*Param
;
3032 if (IsExpandedParameterPack
)
3033 Param
= NonTypeTemplateParmDecl::Create(
3034 SemaRef
.Context
, Owner
, D
->getInnerLocStart(), D
->getLocation(),
3035 D
->getDepth() - TemplateArgs
.getNumSubstitutedLevels(),
3036 D
->getPosition(), D
->getIdentifier(), T
, DI
, ExpandedParameterPackTypes
,
3037 ExpandedParameterPackTypesAsWritten
);
3039 Param
= NonTypeTemplateParmDecl::Create(
3040 SemaRef
.Context
, Owner
, D
->getInnerLocStart(), D
->getLocation(),
3041 D
->getDepth() - TemplateArgs
.getNumSubstitutedLevels(),
3042 D
->getPosition(), D
->getIdentifier(), T
, D
->isParameterPack(), DI
);
3044 if (AutoTypeLoc AutoLoc
= DI
->getTypeLoc().getContainedAutoTypeLoc())
3045 if (AutoLoc
.isConstrained())
3046 // Note: We attach the uninstantiated constriant here, so that it can be
3047 // instantiated relative to the top level, like all our other constraints.
3048 if (SemaRef
.AttachTypeConstraint(
3050 IsExpandedParameterPack
3051 ? DI
->getTypeLoc().getAs
<PackExpansionTypeLoc
>()
3053 : SourceLocation()))
3056 Param
->setAccess(AS_public
);
3057 Param
->setImplicit(D
->isImplicit());
3059 Param
->setInvalidDecl();
3061 if (D
->hasDefaultArgument() && !D
->defaultArgumentWasInherited()) {
3062 EnterExpressionEvaluationContext
ConstantEvaluated(
3063 SemaRef
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
3064 ExprResult Value
= SemaRef
.SubstExpr(D
->getDefaultArgument(), TemplateArgs
);
3065 if (!Value
.isInvalid())
3066 Param
->setDefaultArgument(Value
.get());
3069 // Introduce this template parameter's instantiation into the instantiation
3071 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Param
);
3075 static void collectUnexpandedParameterPacks(
3077 TemplateParameterList
*Params
,
3078 SmallVectorImpl
<UnexpandedParameterPack
> &Unexpanded
) {
3079 for (const auto &P
: *Params
) {
3080 if (P
->isTemplateParameterPack())
3082 if (NonTypeTemplateParmDecl
*NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(P
))
3083 S
.collectUnexpandedParameterPacks(NTTP
->getTypeSourceInfo()->getTypeLoc(),
3085 if (TemplateTemplateParmDecl
*TTP
= dyn_cast
<TemplateTemplateParmDecl
>(P
))
3086 collectUnexpandedParameterPacks(S
, TTP
->getTemplateParameters(),
3092 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3093 TemplateTemplateParmDecl
*D
) {
3094 // Instantiate the template parameter list of the template template parameter.
3095 TemplateParameterList
*TempParams
= D
->getTemplateParameters();
3096 TemplateParameterList
*InstParams
;
3097 SmallVector
<TemplateParameterList
*, 8> ExpandedParams
;
3099 bool IsExpandedParameterPack
= false;
3101 if (D
->isExpandedParameterPack()) {
3102 // The template template parameter pack is an already-expanded pack
3103 // expansion of template parameters. Substitute into each of the expanded
3105 ExpandedParams
.reserve(D
->getNumExpansionTemplateParameters());
3106 for (unsigned I
= 0, N
= D
->getNumExpansionTemplateParameters();
3108 LocalInstantiationScope
Scope(SemaRef
);
3109 TemplateParameterList
*Expansion
=
3110 SubstTemplateParams(D
->getExpansionTemplateParameters(I
));
3113 ExpandedParams
.push_back(Expansion
);
3116 IsExpandedParameterPack
= true;
3117 InstParams
= TempParams
;
3118 } else if (D
->isPackExpansion()) {
3119 // The template template parameter pack expands to a pack of template
3120 // template parameters. Determine whether we need to expand this parameter
3121 // pack into separate parameters.
3122 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
3123 collectUnexpandedParameterPacks(SemaRef
, D
->getTemplateParameters(),
3126 // Determine whether the set of unexpanded parameter packs can and should
3129 bool RetainExpansion
= false;
3130 std::optional
<unsigned> NumExpansions
;
3131 if (SemaRef
.CheckParameterPacksForExpansion(D
->getLocation(),
3132 TempParams
->getSourceRange(),
3135 Expand
, RetainExpansion
,
3140 for (unsigned I
= 0; I
!= *NumExpansions
; ++I
) {
3141 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, I
);
3142 LocalInstantiationScope
Scope(SemaRef
);
3143 TemplateParameterList
*Expansion
= SubstTemplateParams(TempParams
);
3146 ExpandedParams
.push_back(Expansion
);
3149 // Note that we have an expanded parameter pack. The "type" of this
3150 // expanded parameter pack is the original expansion type, but callers
3151 // will end up using the expanded parameter pack types for type-checking.
3152 IsExpandedParameterPack
= true;
3153 InstParams
= TempParams
;
3155 // We cannot fully expand the pack expansion now, so just substitute
3156 // into the pattern.
3157 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, -1);
3159 LocalInstantiationScope
Scope(SemaRef
);
3160 InstParams
= SubstTemplateParams(TempParams
);
3165 // Perform the actual substitution of template parameters within a new,
3166 // local instantiation scope.
3167 LocalInstantiationScope
Scope(SemaRef
);
3168 InstParams
= SubstTemplateParams(TempParams
);
3173 // Build the template template parameter.
3174 TemplateTemplateParmDecl
*Param
;
3175 if (IsExpandedParameterPack
)
3176 Param
= TemplateTemplateParmDecl::Create(
3177 SemaRef
.Context
, Owner
, D
->getLocation(),
3178 D
->getDepth() - TemplateArgs
.getNumSubstitutedLevels(),
3179 D
->getPosition(), D
->getIdentifier(), InstParams
, ExpandedParams
);
3181 Param
= TemplateTemplateParmDecl::Create(
3182 SemaRef
.Context
, Owner
, D
->getLocation(),
3183 D
->getDepth() - TemplateArgs
.getNumSubstitutedLevels(),
3184 D
->getPosition(), D
->isParameterPack(), D
->getIdentifier(), InstParams
);
3185 if (D
->hasDefaultArgument() && !D
->defaultArgumentWasInherited()) {
3186 NestedNameSpecifierLoc QualifierLoc
=
3187 D
->getDefaultArgument().getTemplateQualifierLoc();
3189 SemaRef
.SubstNestedNameSpecifierLoc(QualifierLoc
, TemplateArgs
);
3190 TemplateName TName
= SemaRef
.SubstTemplateName(
3191 QualifierLoc
, D
->getDefaultArgument().getArgument().getAsTemplate(),
3192 D
->getDefaultArgument().getTemplateNameLoc(), TemplateArgs
);
3193 if (!TName
.isNull())
3194 Param
->setDefaultArgument(
3196 TemplateArgumentLoc(SemaRef
.Context
, TemplateArgument(TName
),
3197 D
->getDefaultArgument().getTemplateQualifierLoc(),
3198 D
->getDefaultArgument().getTemplateNameLoc()));
3200 Param
->setAccess(AS_public
);
3201 Param
->setImplicit(D
->isImplicit());
3203 // Introduce this template parameter's instantiation into the instantiation
3205 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Param
);
3210 Decl
*TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl
*D
) {
3211 // Using directives are never dependent (and never contain any types or
3212 // expressions), so they require no explicit instantiation work.
3214 UsingDirectiveDecl
*Inst
3215 = UsingDirectiveDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
3216 D
->getNamespaceKeyLocation(),
3217 D
->getQualifierLoc(),
3218 D
->getIdentLocation(),
3219 D
->getNominatedNamespace(),
3220 D
->getCommonAncestor());
3222 // Add the using directive to its declaration context
3223 // only if this is not a function or method.
3224 if (!Owner
->isFunctionOrMethod())
3225 Owner
->addDecl(Inst
);
3230 Decl
*TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl
*D
,
3231 BaseUsingDecl
*Inst
,
3232 LookupResult
*Lookup
) {
3234 bool isFunctionScope
= Owner
->isFunctionOrMethod();
3236 for (auto *Shadow
: D
->shadows()) {
3237 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3238 // reconstruct it in the case where it matters. Hm, can we extract it from
3239 // the DeclSpec when parsing and save it in the UsingDecl itself?
3240 NamedDecl
*OldTarget
= Shadow
->getTargetDecl();
3241 if (auto *CUSD
= dyn_cast
<ConstructorUsingShadowDecl
>(Shadow
))
3242 if (auto *BaseShadow
= CUSD
->getNominatedBaseClassShadowDecl())
3243 OldTarget
= BaseShadow
;
3245 NamedDecl
*InstTarget
= nullptr;
3247 dyn_cast
<UnresolvedUsingIfExistsDecl
>(Shadow
->getTargetDecl())) {
3248 InstTarget
= UnresolvedUsingIfExistsDecl::Create(
3249 SemaRef
.Context
, Owner
, EmptyD
->getLocation(), EmptyD
->getDeclName());
3251 InstTarget
= cast_or_null
<NamedDecl
>(SemaRef
.FindInstantiatedDecl(
3252 Shadow
->getLocation(), OldTarget
, TemplateArgs
));
3257 UsingShadowDecl
*PrevDecl
= nullptr;
3259 SemaRef
.CheckUsingShadowDecl(Inst
, InstTarget
, *Lookup
, PrevDecl
))
3262 if (UsingShadowDecl
*OldPrev
= getPreviousDeclForInstantiation(Shadow
))
3263 PrevDecl
= cast_or_null
<UsingShadowDecl
>(SemaRef
.FindInstantiatedDecl(
3264 Shadow
->getLocation(), OldPrev
, TemplateArgs
));
3266 UsingShadowDecl
*InstShadow
= SemaRef
.BuildUsingShadowDecl(
3267 /*Scope*/ nullptr, Inst
, InstTarget
, PrevDecl
);
3268 SemaRef
.Context
.setInstantiatedFromUsingShadowDecl(InstShadow
, Shadow
);
3270 if (isFunctionScope
)
3271 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(Shadow
, InstShadow
);
3277 Decl
*TemplateDeclInstantiator::VisitUsingDecl(UsingDecl
*D
) {
3279 // The nested name specifier may be dependent, for example
3280 // template <typename T> struct t {
3281 // struct s1 { T f1(); };
3282 // struct s2 : s1 { using s1::f1; };
3284 // template struct t<int>;
3285 // Here, in using s1::f1, s1 refers to t<T>::s1;
3286 // we need to substitute for t<int>::s1.
3287 NestedNameSpecifierLoc QualifierLoc
3288 = SemaRef
.SubstNestedNameSpecifierLoc(D
->getQualifierLoc(),
3293 // For an inheriting constructor declaration, the name of the using
3294 // declaration is the name of a constructor in this class, not in the
3296 DeclarationNameInfo NameInfo
= D
->getNameInfo();
3297 if (NameInfo
.getName().getNameKind() == DeclarationName::CXXConstructorName
)
3298 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(SemaRef
.CurContext
))
3299 NameInfo
.setName(SemaRef
.Context
.DeclarationNames
.getCXXConstructorName(
3300 SemaRef
.Context
.getCanonicalType(SemaRef
.Context
.getRecordType(RD
))));
3302 // We only need to do redeclaration lookups if we're in a class scope (in
3303 // fact, it's not really even possible in non-class scopes).
3304 bool CheckRedeclaration
= Owner
->isRecord();
3305 LookupResult
Prev(SemaRef
, NameInfo
, Sema::LookupUsingDeclName
,
3306 Sema::ForVisibleRedeclaration
);
3308 UsingDecl
*NewUD
= UsingDecl::Create(SemaRef
.Context
, Owner
,
3315 SS
.Adopt(QualifierLoc
);
3316 if (CheckRedeclaration
) {
3317 Prev
.setHideTags(false);
3318 SemaRef
.LookupQualifiedName(Prev
, Owner
);
3320 // Check for invalid redeclarations.
3321 if (SemaRef
.CheckUsingDeclRedeclaration(D
->getUsingLoc(),
3322 D
->hasTypename(), SS
,
3323 D
->getLocation(), Prev
))
3324 NewUD
->setInvalidDecl();
3327 if (!NewUD
->isInvalidDecl() &&
3328 SemaRef
.CheckUsingDeclQualifier(D
->getUsingLoc(), D
->hasTypename(), SS
,
3329 NameInfo
, D
->getLocation(), nullptr, D
))
3330 NewUD
->setInvalidDecl();
3332 SemaRef
.Context
.setInstantiatedFromUsingDecl(NewUD
, D
);
3333 NewUD
->setAccess(D
->getAccess());
3334 Owner
->addDecl(NewUD
);
3336 // Don't process the shadow decls for an invalid decl.
3337 if (NewUD
->isInvalidDecl())
3340 // If the using scope was dependent, or we had dependent bases, we need to
3341 // recheck the inheritance
3342 if (NameInfo
.getName().getNameKind() == DeclarationName::CXXConstructorName
)
3343 SemaRef
.CheckInheritingConstructorUsingDecl(NewUD
);
3345 return VisitBaseUsingDecls(D
, NewUD
, CheckRedeclaration
? &Prev
: nullptr);
3348 Decl
*TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl
*D
) {
3349 // Cannot be a dependent type, but still could be an instantiation
3350 EnumDecl
*EnumD
= cast_or_null
<EnumDecl
>(SemaRef
.FindInstantiatedDecl(
3351 D
->getLocation(), D
->getEnumDecl(), TemplateArgs
));
3353 if (SemaRef
.RequireCompleteEnumDecl(EnumD
, EnumD
->getLocation()))
3356 TypeSourceInfo
*TSI
= SemaRef
.SubstType(D
->getEnumType(), TemplateArgs
,
3357 D
->getLocation(), D
->getDeclName());
3358 UsingEnumDecl
*NewUD
=
3359 UsingEnumDecl::Create(SemaRef
.Context
, Owner
, D
->getUsingLoc(),
3360 D
->getEnumLoc(), D
->getLocation(), TSI
);
3362 SemaRef
.Context
.setInstantiatedFromUsingEnumDecl(NewUD
, D
);
3363 NewUD
->setAccess(D
->getAccess());
3364 Owner
->addDecl(NewUD
);
3366 // Don't process the shadow decls for an invalid decl.
3367 if (NewUD
->isInvalidDecl())
3370 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3371 // cannot be dependent, and will therefore have been checked during template
3374 return VisitBaseUsingDecls(D
, NewUD
, nullptr);
3377 Decl
*TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl
*D
) {
3378 // Ignore these; we handle them in bulk when processing the UsingDecl.
3382 Decl
*TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3383 ConstructorUsingShadowDecl
*D
) {
3384 // Ignore these; we handle them in bulk when processing the UsingDecl.
3388 template <typename T
>
3389 Decl
*TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3390 T
*D
, bool InstantiatingPackElement
) {
3391 // If this is a pack expansion, expand it now.
3392 if (D
->isPackExpansion() && !InstantiatingPackElement
) {
3393 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
3394 SemaRef
.collectUnexpandedParameterPacks(D
->getQualifierLoc(), Unexpanded
);
3395 SemaRef
.collectUnexpandedParameterPacks(D
->getNameInfo(), Unexpanded
);
3397 // Determine whether the set of unexpanded parameter packs can and should
3400 bool RetainExpansion
= false;
3401 std::optional
<unsigned> NumExpansions
;
3402 if (SemaRef
.CheckParameterPacksForExpansion(
3403 D
->getEllipsisLoc(), D
->getSourceRange(), Unexpanded
, TemplateArgs
,
3404 Expand
, RetainExpansion
, NumExpansions
))
3407 // This declaration cannot appear within a function template signature,
3408 // so we can't have a partial argument list for a parameter pack.
3409 assert(!RetainExpansion
&&
3410 "should never need to retain an expansion for UsingPackDecl");
3413 // We cannot fully expand the pack expansion now, so substitute into the
3414 // pattern and create a new pack expansion.
3415 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, -1);
3416 return instantiateUnresolvedUsingDecl(D
, true);
3419 // Within a function, we don't have any normal way to check for conflicts
3420 // between shadow declarations from different using declarations in the
3421 // same pack expansion, but this is always ill-formed because all expansions
3422 // must produce (conflicting) enumerators.
3424 // Sadly we can't just reject this in the template definition because it
3425 // could be valid if the pack is empty or has exactly one expansion.
3426 if (D
->getDeclContext()->isFunctionOrMethod() && *NumExpansions
> 1) {
3427 SemaRef
.Diag(D
->getEllipsisLoc(),
3428 diag::err_using_decl_redeclaration_expansion
);
3432 // Instantiate the slices of this pack and build a UsingPackDecl.
3433 SmallVector
<NamedDecl
*, 8> Expansions
;
3434 for (unsigned I
= 0; I
!= *NumExpansions
; ++I
) {
3435 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, I
);
3436 Decl
*Slice
= instantiateUnresolvedUsingDecl(D
, true);
3439 // Note that we can still get unresolved using declarations here, if we
3440 // had arguments for all packs but the pattern also contained other
3441 // template arguments (this only happens during partial substitution, eg
3442 // into the body of a generic lambda in a function template).
3443 Expansions
.push_back(cast
<NamedDecl
>(Slice
));
3446 auto *NewD
= SemaRef
.BuildUsingPackDecl(D
, Expansions
);
3447 if (isDeclWithinFunction(D
))
3448 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, NewD
);
3452 UnresolvedUsingTypenameDecl
*TD
= dyn_cast
<UnresolvedUsingTypenameDecl
>(D
);
3453 SourceLocation TypenameLoc
= TD
? TD
->getTypenameLoc() : SourceLocation();
3455 NestedNameSpecifierLoc QualifierLoc
3456 = SemaRef
.SubstNestedNameSpecifierLoc(D
->getQualifierLoc(),
3462 SS
.Adopt(QualifierLoc
);
3464 DeclarationNameInfo NameInfo
3465 = SemaRef
.SubstDeclarationNameInfo(D
->getNameInfo(), TemplateArgs
);
3467 // Produce a pack expansion only if we're not instantiating a particular
3468 // slice of a pack expansion.
3469 bool InstantiatingSlice
= D
->getEllipsisLoc().isValid() &&
3470 SemaRef
.ArgumentPackSubstitutionIndex
!= -1;
3471 SourceLocation EllipsisLoc
=
3472 InstantiatingSlice
? SourceLocation() : D
->getEllipsisLoc();
3474 bool IsUsingIfExists
= D
->template hasAttr
<UsingIfExistsAttr
>();
3475 NamedDecl
*UD
= SemaRef
.BuildUsingDeclaration(
3476 /*Scope*/ nullptr, D
->getAccess(), D
->getUsingLoc(),
3477 /*HasTypename*/ TD
, TypenameLoc
, SS
, NameInfo
, EllipsisLoc
,
3478 ParsedAttributesView(),
3479 /*IsInstantiation*/ true, IsUsingIfExists
);
3481 SemaRef
.InstantiateAttrs(TemplateArgs
, D
, UD
);
3482 SemaRef
.Context
.setInstantiatedFromUsingDecl(UD
, D
);
3488 Decl
*TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3489 UnresolvedUsingTypenameDecl
*D
) {
3490 return instantiateUnresolvedUsingDecl(D
);
3493 Decl
*TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3494 UnresolvedUsingValueDecl
*D
) {
3495 return instantiateUnresolvedUsingDecl(D
);
3498 Decl
*TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3499 UnresolvedUsingIfExistsDecl
*D
) {
3500 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3503 Decl
*TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl
*D
) {
3504 SmallVector
<NamedDecl
*, 8> Expansions
;
3505 for (auto *UD
: D
->expansions()) {
3506 if (NamedDecl
*NewUD
=
3507 SemaRef
.FindInstantiatedDecl(D
->getLocation(), UD
, TemplateArgs
))
3508 Expansions
.push_back(NewUD
);
3513 auto *NewD
= SemaRef
.BuildUsingPackDecl(D
, Expansions
);
3514 if (isDeclWithinFunction(D
))
3515 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, NewD
);
3519 Decl
*TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3520 OMPThreadPrivateDecl
*D
) {
3521 SmallVector
<Expr
*, 5> Vars
;
3522 for (auto *I
: D
->varlists()) {
3523 Expr
*Var
= SemaRef
.SubstExpr(I
, TemplateArgs
).get();
3524 assert(isa
<DeclRefExpr
>(Var
) && "threadprivate arg is not a DeclRefExpr");
3525 Vars
.push_back(Var
);
3528 OMPThreadPrivateDecl
*TD
=
3529 SemaRef
.CheckOMPThreadPrivateDecl(D
->getLocation(), Vars
);
3531 TD
->setAccess(AS_public
);
3537 Decl
*TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl
*D
) {
3538 SmallVector
<Expr
*, 5> Vars
;
3539 for (auto *I
: D
->varlists()) {
3540 Expr
*Var
= SemaRef
.SubstExpr(I
, TemplateArgs
).get();
3541 assert(isa
<DeclRefExpr
>(Var
) && "allocate arg is not a DeclRefExpr");
3542 Vars
.push_back(Var
);
3544 SmallVector
<OMPClause
*, 4> Clauses
;
3545 // Copy map clauses from the original mapper.
3546 for (OMPClause
*C
: D
->clauselists()) {
3547 OMPClause
*IC
= nullptr;
3548 if (auto *AC
= dyn_cast
<OMPAllocatorClause
>(C
)) {
3549 ExprResult NewE
= SemaRef
.SubstExpr(AC
->getAllocator(), TemplateArgs
);
3550 if (!NewE
.isUsable())
3552 IC
= SemaRef
.ActOnOpenMPAllocatorClause(
3553 NewE
.get(), AC
->getBeginLoc(), AC
->getLParenLoc(), AC
->getEndLoc());
3554 } else if (auto *AC
= dyn_cast
<OMPAlignClause
>(C
)) {
3555 ExprResult NewE
= SemaRef
.SubstExpr(AC
->getAlignment(), TemplateArgs
);
3556 if (!NewE
.isUsable())
3558 IC
= SemaRef
.ActOnOpenMPAlignClause(NewE
.get(), AC
->getBeginLoc(),
3559 AC
->getLParenLoc(), AC
->getEndLoc());
3560 // If align clause value ends up being invalid, this can end up null.
3564 Clauses
.push_back(IC
);
3567 Sema::DeclGroupPtrTy Res
= SemaRef
.ActOnOpenMPAllocateDirective(
3568 D
->getLocation(), Vars
, Clauses
, Owner
);
3569 if (Res
.get().isNull())
3571 return Res
.get().getSingleDecl();
3574 Decl
*TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl
*D
) {
3576 "Requires directive cannot be instantiated within a dependent context");
3579 Decl
*TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3580 OMPDeclareReductionDecl
*D
) {
3581 // Instantiate type and check if it is allowed.
3582 const bool RequiresInstantiation
=
3583 D
->getType()->isDependentType() ||
3584 D
->getType()->isInstantiationDependentType() ||
3585 D
->getType()->containsUnexpandedParameterPack();
3586 QualType SubstReductionType
;
3587 if (RequiresInstantiation
) {
3588 SubstReductionType
= SemaRef
.ActOnOpenMPDeclareReductionType(
3590 ParsedType::make(SemaRef
.SubstType(
3591 D
->getType(), TemplateArgs
, D
->getLocation(), DeclarationName())));
3593 SubstReductionType
= D
->getType();
3595 if (SubstReductionType
.isNull())
3597 Expr
*Combiner
= D
->getCombiner();
3598 Expr
*Init
= D
->getInitializer();
3599 bool IsCorrect
= true;
3600 // Create instantiated copy.
3601 std::pair
<QualType
, SourceLocation
> ReductionTypes
[] = {
3602 std::make_pair(SubstReductionType
, D
->getLocation())};
3603 auto *PrevDeclInScope
= D
->getPrevDeclInScope();
3604 if (PrevDeclInScope
&& !PrevDeclInScope
->isInvalidDecl()) {
3605 PrevDeclInScope
= cast
<OMPDeclareReductionDecl
>(
3606 SemaRef
.CurrentInstantiationScope
->findInstantiationOf(PrevDeclInScope
)
3609 auto DRD
= SemaRef
.ActOnOpenMPDeclareReductionDirectiveStart(
3610 /*S=*/nullptr, Owner
, D
->getDeclName(), ReductionTypes
, D
->getAccess(),
3612 auto *NewDRD
= cast
<OMPDeclareReductionDecl
>(DRD
.get().getSingleDecl());
3613 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, NewDRD
);
3614 Expr
*SubstCombiner
= nullptr;
3615 Expr
*SubstInitializer
= nullptr;
3616 // Combiners instantiation sequence.
3618 SemaRef
.ActOnOpenMPDeclareReductionCombinerStart(
3619 /*S=*/nullptr, NewDRD
);
3620 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(
3621 cast
<DeclRefExpr
>(D
->getCombinerIn())->getDecl(),
3622 cast
<DeclRefExpr
>(NewDRD
->getCombinerIn())->getDecl());
3623 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(
3624 cast
<DeclRefExpr
>(D
->getCombinerOut())->getDecl(),
3625 cast
<DeclRefExpr
>(NewDRD
->getCombinerOut())->getDecl());
3626 auto *ThisContext
= dyn_cast_or_null
<CXXRecordDecl
>(Owner
);
3627 Sema::CXXThisScopeRAII
ThisScope(SemaRef
, ThisContext
, Qualifiers(),
3629 SubstCombiner
= SemaRef
.SubstExpr(Combiner
, TemplateArgs
).get();
3630 SemaRef
.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD
, SubstCombiner
);
3632 // Initializers instantiation sequence.
3634 VarDecl
*OmpPrivParm
= SemaRef
.ActOnOpenMPDeclareReductionInitializerStart(
3635 /*S=*/nullptr, NewDRD
);
3636 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(
3637 cast
<DeclRefExpr
>(D
->getInitOrig())->getDecl(),
3638 cast
<DeclRefExpr
>(NewDRD
->getInitOrig())->getDecl());
3639 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(
3640 cast
<DeclRefExpr
>(D
->getInitPriv())->getDecl(),
3641 cast
<DeclRefExpr
>(NewDRD
->getInitPriv())->getDecl());
3642 if (D
->getInitializerKind() == OMPDeclareReductionInitKind::Call
) {
3643 SubstInitializer
= SemaRef
.SubstExpr(Init
, TemplateArgs
).get();
3646 cast
<VarDecl
>(cast
<DeclRefExpr
>(D
->getInitPriv())->getDecl());
3647 IsCorrect
= IsCorrect
&& OldPrivParm
->hasInit();
3649 SemaRef
.InstantiateVariableInitializer(OmpPrivParm
, OldPrivParm
,
3652 SemaRef
.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD
, SubstInitializer
,
3655 IsCorrect
= IsCorrect
&& SubstCombiner
&&
3657 (D
->getInitializerKind() == OMPDeclareReductionInitKind::Call
&&
3658 SubstInitializer
) ||
3659 (D
->getInitializerKind() != OMPDeclareReductionInitKind::Call
&&
3660 !SubstInitializer
));
3662 (void)SemaRef
.ActOnOpenMPDeclareReductionDirectiveEnd(
3663 /*S=*/nullptr, DRD
, IsCorrect
&& !D
->isInvalidDecl());
3669 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl
*D
) {
3670 // Instantiate type and check if it is allowed.
3671 const bool RequiresInstantiation
=
3672 D
->getType()->isDependentType() ||
3673 D
->getType()->isInstantiationDependentType() ||
3674 D
->getType()->containsUnexpandedParameterPack();
3675 QualType SubstMapperTy
;
3676 DeclarationName VN
= D
->getVarName();
3677 if (RequiresInstantiation
) {
3678 SubstMapperTy
= SemaRef
.ActOnOpenMPDeclareMapperType(
3680 ParsedType::make(SemaRef
.SubstType(D
->getType(), TemplateArgs
,
3681 D
->getLocation(), VN
)));
3683 SubstMapperTy
= D
->getType();
3685 if (SubstMapperTy
.isNull())
3687 // Create an instantiated copy of mapper.
3688 auto *PrevDeclInScope
= D
->getPrevDeclInScope();
3689 if (PrevDeclInScope
&& !PrevDeclInScope
->isInvalidDecl()) {
3690 PrevDeclInScope
= cast
<OMPDeclareMapperDecl
>(
3691 SemaRef
.CurrentInstantiationScope
->findInstantiationOf(PrevDeclInScope
)
3694 bool IsCorrect
= true;
3695 SmallVector
<OMPClause
*, 6> Clauses
;
3696 // Instantiate the mapper variable.
3697 DeclarationNameInfo DirName
;
3698 SemaRef
.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper
, DirName
,
3700 (*D
->clauselist_begin())->getBeginLoc());
3701 ExprResult MapperVarRef
= SemaRef
.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3702 /*S=*/nullptr, SubstMapperTy
, D
->getLocation(), VN
);
3703 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(
3704 cast
<DeclRefExpr
>(D
->getMapperVarRef())->getDecl(),
3705 cast
<DeclRefExpr
>(MapperVarRef
.get())->getDecl());
3706 auto *ThisContext
= dyn_cast_or_null
<CXXRecordDecl
>(Owner
);
3707 Sema::CXXThisScopeRAII
ThisScope(SemaRef
, ThisContext
, Qualifiers(),
3709 // Instantiate map clauses.
3710 for (OMPClause
*C
: D
->clauselists()) {
3711 auto *OldC
= cast
<OMPMapClause
>(C
);
3712 SmallVector
<Expr
*, 4> NewVars
;
3713 for (Expr
*OE
: OldC
->varlists()) {
3714 Expr
*NE
= SemaRef
.SubstExpr(OE
, TemplateArgs
).get();
3719 NewVars
.push_back(NE
);
3723 NestedNameSpecifierLoc NewQualifierLoc
=
3724 SemaRef
.SubstNestedNameSpecifierLoc(OldC
->getMapperQualifierLoc(),
3727 SS
.Adopt(NewQualifierLoc
);
3728 DeclarationNameInfo NewNameInfo
=
3729 SemaRef
.SubstDeclarationNameInfo(OldC
->getMapperIdInfo(), TemplateArgs
);
3730 OMPVarListLocTy
Locs(OldC
->getBeginLoc(), OldC
->getLParenLoc(),
3732 OMPClause
*NewC
= SemaRef
.ActOnOpenMPMapClause(
3733 OldC
->getIteratorModifier(), OldC
->getMapTypeModifiers(),
3734 OldC
->getMapTypeModifiersLoc(), SS
, NewNameInfo
, OldC
->getMapType(),
3735 OldC
->isImplicitMapType(), OldC
->getMapLoc(), OldC
->getColonLoc(),
3737 Clauses
.push_back(NewC
);
3739 SemaRef
.EndOpenMPDSABlock(nullptr);
3742 Sema::DeclGroupPtrTy DG
= SemaRef
.ActOnOpenMPDeclareMapperDirective(
3743 /*S=*/nullptr, Owner
, D
->getDeclName(), SubstMapperTy
, D
->getLocation(),
3744 VN
, D
->getAccess(), MapperVarRef
.get(), Clauses
, PrevDeclInScope
);
3745 Decl
*NewDMD
= DG
.get().getSingleDecl();
3746 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, NewDMD
);
3750 Decl
*TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3751 OMPCapturedExprDecl
* /*D*/) {
3752 llvm_unreachable("Should not be met in templates");
3755 Decl
*TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl
*D
) {
3756 return VisitFunctionDecl(D
, nullptr);
3760 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl
*D
) {
3761 Decl
*Inst
= VisitFunctionDecl(D
, nullptr);
3762 if (Inst
&& !D
->getDescribedFunctionTemplate())
3763 Owner
->addDecl(Inst
);
3767 Decl
*TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl
*D
) {
3768 return VisitCXXMethodDecl(D
, nullptr);
3771 Decl
*TemplateDeclInstantiator::VisitRecordDecl(RecordDecl
*D
) {
3772 llvm_unreachable("There are only CXXRecordDecls in C++");
3776 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3777 ClassTemplateSpecializationDecl
*D
) {
3778 // As a MS extension, we permit class-scope explicit specialization
3779 // of member class templates.
3780 ClassTemplateDecl
*ClassTemplate
= D
->getSpecializedTemplate();
3781 assert(ClassTemplate
->getDeclContext()->isRecord() &&
3782 D
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&&
3783 "can only instantiate an explicit specialization "
3784 "for a member class template");
3786 // Lookup the already-instantiated declaration in the instantiation
3787 // of the class template.
3788 ClassTemplateDecl
*InstClassTemplate
=
3789 cast_or_null
<ClassTemplateDecl
>(SemaRef
.FindInstantiatedDecl(
3790 D
->getLocation(), ClassTemplate
, TemplateArgs
));
3791 if (!InstClassTemplate
)
3794 // Substitute into the template arguments of the class template explicit
3796 TemplateSpecializationTypeLoc Loc
= D
->getTypeAsWritten()->getTypeLoc().
3797 castAs
<TemplateSpecializationTypeLoc
>();
3798 TemplateArgumentListInfo
InstTemplateArgs(Loc
.getLAngleLoc(),
3799 Loc
.getRAngleLoc());
3800 SmallVector
<TemplateArgumentLoc
, 4> ArgLocs
;
3801 for (unsigned I
= 0; I
!= Loc
.getNumArgs(); ++I
)
3802 ArgLocs
.push_back(Loc
.getArgLoc(I
));
3803 if (SemaRef
.SubstTemplateArguments(ArgLocs
, TemplateArgs
, InstTemplateArgs
))
3806 // Check that the template argument list is well-formed for this
3808 SmallVector
<TemplateArgument
, 4> SugaredConverted
, CanonicalConverted
;
3809 if (SemaRef
.CheckTemplateArgumentList(InstClassTemplate
, D
->getLocation(),
3810 InstTemplateArgs
, false,
3811 SugaredConverted
, CanonicalConverted
,
3812 /*UpdateArgsWithConversions=*/true))
3815 // Figure out where to insert this class template explicit specialization
3816 // in the member template's set of class template explicit specializations.
3817 void *InsertPos
= nullptr;
3818 ClassTemplateSpecializationDecl
*PrevDecl
=
3819 InstClassTemplate
->findSpecialization(CanonicalConverted
, InsertPos
);
3821 // Check whether we've already seen a conflicting instantiation of this
3822 // declaration (for instance, if there was a prior implicit instantiation).
3825 SemaRef
.CheckSpecializationInstantiationRedecl(D
->getLocation(),
3826 D
->getSpecializationKind(),
3828 PrevDecl
->getSpecializationKind(),
3829 PrevDecl
->getPointOfInstantiation(),
3833 // If PrevDecl was a definition and D is also a definition, diagnose.
3834 // This happens in cases like:
3836 // template<typename T, typename U>
3838 // template<typename X> struct Inner;
3839 // template<> struct Inner<T> {};
3840 // template<> struct Inner<U> {};
3843 // Outer<int, int> outer; // error: the explicit specializations of Inner
3844 // // have the same signature.
3845 if (PrevDecl
&& PrevDecl
->getDefinition() &&
3846 D
->isThisDeclarationADefinition()) {
3847 SemaRef
.Diag(D
->getLocation(), diag::err_redefinition
) << PrevDecl
;
3848 SemaRef
.Diag(PrevDecl
->getDefinition()->getLocation(),
3849 diag::note_previous_definition
);
3853 // Create the class template partial specialization declaration.
3854 ClassTemplateSpecializationDecl
*InstD
=
3855 ClassTemplateSpecializationDecl::Create(
3856 SemaRef
.Context
, D
->getTagKind(), Owner
, D
->getBeginLoc(),
3857 D
->getLocation(), InstClassTemplate
, CanonicalConverted
, PrevDecl
);
3859 // Add this partial specialization to the set of class template partial
3862 InstClassTemplate
->AddSpecialization(InstD
, InsertPos
);
3864 // Substitute the nested name specifier, if any.
3865 if (SubstQualifier(D
, InstD
))
3868 // Build the canonical type that describes the converted template
3869 // arguments of the class template explicit specialization.
3870 QualType CanonType
= SemaRef
.Context
.getTemplateSpecializationType(
3871 TemplateName(InstClassTemplate
), CanonicalConverted
,
3872 SemaRef
.Context
.getRecordType(InstD
));
3874 // Build the fully-sugared type for this class template
3875 // specialization as the user wrote in the specialization
3876 // itself. This means that we'll pretty-print the type retrieved
3877 // from the specialization's declaration the way that the user
3878 // actually wrote the specialization, rather than formatting the
3879 // name based on the "canonical" representation used to store the
3880 // template arguments in the specialization.
3881 TypeSourceInfo
*WrittenTy
= SemaRef
.Context
.getTemplateSpecializationTypeInfo(
3882 TemplateName(InstClassTemplate
), D
->getLocation(), InstTemplateArgs
,
3885 InstD
->setAccess(D
->getAccess());
3886 InstD
->setInstantiationOfMemberClass(D
, TSK_ImplicitInstantiation
);
3887 InstD
->setSpecializationKind(D
->getSpecializationKind());
3888 InstD
->setTypeAsWritten(WrittenTy
);
3889 InstD
->setExternLoc(D
->getExternLoc());
3890 InstD
->setTemplateKeywordLoc(D
->getTemplateKeywordLoc());
3892 Owner
->addDecl(InstD
);
3894 // Instantiate the members of the class-scope explicit specialization eagerly.
3895 // We don't have support for lazy instantiation of an explicit specialization
3896 // yet, and MSVC eagerly instantiates in this case.
3897 // FIXME: This is wrong in standard C++.
3898 if (D
->isThisDeclarationADefinition() &&
3899 SemaRef
.InstantiateClass(D
->getLocation(), InstD
, D
, TemplateArgs
,
3900 TSK_ImplicitInstantiation
,
3907 Decl
*TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3908 VarTemplateSpecializationDecl
*D
) {
3910 TemplateArgumentListInfo VarTemplateArgsInfo
;
3911 VarTemplateDecl
*VarTemplate
= D
->getSpecializedTemplate();
3912 assert(VarTemplate
&&
3913 "A template specialization without specialized template?");
3915 VarTemplateDecl
*InstVarTemplate
=
3916 cast_or_null
<VarTemplateDecl
>(SemaRef
.FindInstantiatedDecl(
3917 D
->getLocation(), VarTemplate
, TemplateArgs
));
3918 if (!InstVarTemplate
)
3921 // Substitute the current template arguments.
3922 if (const ASTTemplateArgumentListInfo
*TemplateArgsInfo
=
3923 D
->getTemplateArgsInfo()) {
3924 VarTemplateArgsInfo
.setLAngleLoc(TemplateArgsInfo
->getLAngleLoc());
3925 VarTemplateArgsInfo
.setRAngleLoc(TemplateArgsInfo
->getRAngleLoc());
3927 if (SemaRef
.SubstTemplateArguments(TemplateArgsInfo
->arguments(),
3928 TemplateArgs
, VarTemplateArgsInfo
))
3932 // Check that the template argument list is well-formed for this template.
3933 SmallVector
<TemplateArgument
, 4> SugaredConverted
, CanonicalConverted
;
3934 if (SemaRef
.CheckTemplateArgumentList(InstVarTemplate
, D
->getLocation(),
3935 VarTemplateArgsInfo
, false,
3936 SugaredConverted
, CanonicalConverted
,
3937 /*UpdateArgsWithConversions=*/true))
3940 // Check whether we've already seen a declaration of this specialization.
3941 void *InsertPos
= nullptr;
3942 VarTemplateSpecializationDecl
*PrevDecl
=
3943 InstVarTemplate
->findSpecialization(CanonicalConverted
, InsertPos
);
3945 // Check whether we've already seen a conflicting instantiation of this
3946 // declaration (for instance, if there was a prior implicit instantiation).
3948 if (PrevDecl
&& SemaRef
.CheckSpecializationInstantiationRedecl(
3949 D
->getLocation(), D
->getSpecializationKind(), PrevDecl
,
3950 PrevDecl
->getSpecializationKind(),
3951 PrevDecl
->getPointOfInstantiation(), Ignored
))
3954 return VisitVarTemplateSpecializationDecl(
3955 InstVarTemplate
, D
, VarTemplateArgsInfo
, CanonicalConverted
, PrevDecl
);
3958 Decl
*TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3959 VarTemplateDecl
*VarTemplate
, VarDecl
*D
,
3960 const TemplateArgumentListInfo
&TemplateArgsInfo
,
3961 ArrayRef
<TemplateArgument
> Converted
,
3962 VarTemplateSpecializationDecl
*PrevDecl
) {
3964 // Do substitution on the type of the declaration
3965 TypeSourceInfo
*DI
=
3966 SemaRef
.SubstType(D
->getTypeSourceInfo(), TemplateArgs
,
3967 D
->getTypeSpecStartLoc(), D
->getDeclName());
3971 if (DI
->getType()->isFunctionType()) {
3972 SemaRef
.Diag(D
->getLocation(), diag::err_variable_instantiates_to_function
)
3973 << D
->isStaticDataMember() << DI
->getType();
3977 // Build the instantiated declaration
3978 VarTemplateSpecializationDecl
*Var
= VarTemplateSpecializationDecl::Create(
3979 SemaRef
.Context
, Owner
, D
->getInnerLocStart(), D
->getLocation(),
3980 VarTemplate
, DI
->getType(), DI
, D
->getStorageClass(), Converted
);
3981 Var
->setTemplateArgsInfo(TemplateArgsInfo
);
3983 void *InsertPos
= nullptr;
3984 VarTemplate
->findSpecialization(Converted
, InsertPos
);
3985 VarTemplate
->AddSpecialization(Var
, InsertPos
);
3988 if (SemaRef
.getLangOpts().OpenCL
)
3989 SemaRef
.deduceOpenCLAddressSpace(Var
);
3991 // Substitute the nested name specifier, if any.
3992 if (SubstQualifier(D
, Var
))
3995 SemaRef
.BuildVariableInstantiation(Var
, D
, TemplateArgs
, LateAttrs
, Owner
,
3996 StartingScope
, false, PrevDecl
);
4001 Decl
*TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl
*D
) {
4002 llvm_unreachable("@defs is not supported in Objective-C++");
4005 Decl
*TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl
*D
) {
4006 // FIXME: We need to be able to instantiate FriendTemplateDecls.
4007 unsigned DiagID
= SemaRef
.getDiagnostics().getCustomDiagID(
4008 DiagnosticsEngine::Error
,
4009 "cannot instantiate %0 yet");
4010 SemaRef
.Diag(D
->getLocation(), DiagID
)
4011 << D
->getDeclKindName();
4016 Decl
*TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl
*D
) {
4017 llvm_unreachable("Concept definitions cannot reside inside a template");
4020 Decl
*TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4021 ImplicitConceptSpecializationDecl
*D
) {
4022 llvm_unreachable("Concept specializations cannot reside inside a template");
4026 TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl
*D
) {
4027 return RequiresExprBodyDecl::Create(SemaRef
.Context
, D
->getDeclContext(),
4031 Decl
*TemplateDeclInstantiator::VisitDecl(Decl
*D
) {
4032 llvm_unreachable("Unexpected decl");
4035 Decl
*Sema::SubstDecl(Decl
*D
, DeclContext
*Owner
,
4036 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
4037 TemplateDeclInstantiator
Instantiator(*this, Owner
, TemplateArgs
);
4038 if (D
->isInvalidDecl())
4042 runWithSufficientStackSpace(D
->getLocation(), [&] {
4043 SubstD
= Instantiator
.Visit(D
);
4048 void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK
,
4049 FunctionDecl
*Orig
, QualType
&T
,
4050 TypeSourceInfo
*&TInfo
,
4051 DeclarationNameInfo
&NameInfo
) {
4052 assert(RK
== RewriteKind::RewriteSpaceshipAsEqualEqual
);
4054 // C++2a [class.compare.default]p3:
4055 // the return type is replaced with bool
4056 auto *FPT
= T
->castAs
<FunctionProtoType
>();
4057 T
= SemaRef
.Context
.getFunctionType(
4058 SemaRef
.Context
.BoolTy
, FPT
->getParamTypes(), FPT
->getExtProtoInfo());
4060 // Update the return type in the source info too. The most straightforward
4061 // way is to create new TypeSourceInfo for the new type. Use the location of
4062 // the '= default' as the location of the new type.
4064 // FIXME: Set the correct return type when we initially transform the type,
4065 // rather than delaying it to now.
4066 TypeSourceInfo
*NewTInfo
=
4067 SemaRef
.Context
.getTrivialTypeSourceInfo(T
, Orig
->getEndLoc());
4068 auto OldLoc
= TInfo
->getTypeLoc().getAsAdjusted
<FunctionProtoTypeLoc
>();
4069 assert(OldLoc
&& "type of function is not a function type?");
4070 auto NewLoc
= NewTInfo
->getTypeLoc().castAs
<FunctionProtoTypeLoc
>();
4071 for (unsigned I
= 0, N
= OldLoc
.getNumParams(); I
!= N
; ++I
)
4072 NewLoc
.setParam(I
, OldLoc
.getParam(I
));
4075 // and the declarator-id is replaced with operator==
4077 SemaRef
.Context
.DeclarationNames
.getCXXOperatorName(OO_EqualEqual
));
4080 FunctionDecl
*Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl
*RD
,
4081 FunctionDecl
*Spaceship
) {
4082 if (Spaceship
->isInvalidDecl())
4085 // C++2a [class.compare.default]p3:
4086 // an == operator function is declared implicitly [...] with the same
4087 // access and function-definition and in the same class scope as the
4088 // three-way comparison operator function
4089 MultiLevelTemplateArgumentList NoTemplateArgs
;
4090 NoTemplateArgs
.setKind(TemplateSubstitutionKind::Rewrite
);
4091 NoTemplateArgs
.addOuterRetainedLevels(RD
->getTemplateDepth());
4092 TemplateDeclInstantiator
Instantiator(*this, RD
, NoTemplateArgs
);
4094 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(Spaceship
)) {
4095 R
= Instantiator
.VisitCXXMethodDecl(
4096 MD
, /*TemplateParams=*/nullptr,
4097 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual
);
4099 assert(Spaceship
->getFriendObjectKind() &&
4100 "defaulted spaceship is neither a member nor a friend");
4102 R
= Instantiator
.VisitFunctionDecl(
4103 Spaceship
, /*TemplateParams=*/nullptr,
4104 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual
);
4109 FriendDecl::Create(Context
, RD
, Spaceship
->getLocation(),
4110 cast
<NamedDecl
>(R
), Spaceship
->getBeginLoc());
4111 FD
->setAccess(AS_public
);
4114 return cast_or_null
<FunctionDecl
>(R
);
4117 /// Instantiates a nested template parameter list in the current
4118 /// instantiation context.
4120 /// \param L The parameter list to instantiate
4122 /// \returns NULL if there was an error
4123 TemplateParameterList
*
4124 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList
*L
) {
4125 // Get errors for all the parameters before bailing out.
4126 bool Invalid
= false;
4128 unsigned N
= L
->size();
4129 typedef SmallVector
<NamedDecl
*, 8> ParamVector
;
4132 for (auto &P
: *L
) {
4133 NamedDecl
*D
= cast_or_null
<NamedDecl
>(Visit(P
));
4134 Params
.push_back(D
);
4135 Invalid
= Invalid
|| !D
|| D
->isInvalidDecl();
4138 // Clean up if we had an error.
4142 Expr
*InstRequiresClause
= L
->getRequiresClause();
4144 TemplateParameterList
*InstL
4145 = TemplateParameterList::Create(SemaRef
.Context
, L
->getTemplateLoc(),
4146 L
->getLAngleLoc(), Params
,
4147 L
->getRAngleLoc(), InstRequiresClause
);
4151 TemplateParameterList
*
4152 Sema::SubstTemplateParams(TemplateParameterList
*Params
, DeclContext
*Owner
,
4153 const MultiLevelTemplateArgumentList
&TemplateArgs
,
4154 bool EvaluateConstraints
) {
4155 TemplateDeclInstantiator
Instantiator(*this, Owner
, TemplateArgs
);
4156 Instantiator
.setEvaluateConstraints(EvaluateConstraints
);
4157 return Instantiator
.SubstTemplateParams(Params
);
4160 /// Instantiate the declaration of a class template partial
4163 /// \param ClassTemplate the (instantiated) class template that is partially
4164 // specialized by the instantiation of \p PartialSpec.
4166 /// \param PartialSpec the (uninstantiated) class template partial
4167 /// specialization that we are instantiating.
4169 /// \returns The instantiated partial specialization, if successful; otherwise,
4170 /// NULL to indicate an error.
4171 ClassTemplatePartialSpecializationDecl
*
4172 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
4173 ClassTemplateDecl
*ClassTemplate
,
4174 ClassTemplatePartialSpecializationDecl
*PartialSpec
) {
4175 // Create a local instantiation scope for this class template partial
4176 // specialization, which will contain the instantiations of the template
4178 LocalInstantiationScope
Scope(SemaRef
);
4180 // Substitute into the template parameters of the class template partial
4182 TemplateParameterList
*TempParams
= PartialSpec
->getTemplateParameters();
4183 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
4187 // Substitute into the template arguments of the class template partial
4189 const ASTTemplateArgumentListInfo
*TemplArgInfo
4190 = PartialSpec
->getTemplateArgsAsWritten();
4191 TemplateArgumentListInfo
InstTemplateArgs(TemplArgInfo
->LAngleLoc
,
4192 TemplArgInfo
->RAngleLoc
);
4193 if (SemaRef
.SubstTemplateArguments(TemplArgInfo
->arguments(), TemplateArgs
,
4197 // Check that the template argument list is well-formed for this
4199 SmallVector
<TemplateArgument
, 4> SugaredConverted
, CanonicalConverted
;
4200 if (SemaRef
.CheckTemplateArgumentList(
4201 ClassTemplate
, PartialSpec
->getLocation(), InstTemplateArgs
,
4202 /*PartialTemplateArgs=*/false, SugaredConverted
, CanonicalConverted
))
4205 // Check these arguments are valid for a template partial specialization.
4206 if (SemaRef
.CheckTemplatePartialSpecializationArgs(
4207 PartialSpec
->getLocation(), ClassTemplate
, InstTemplateArgs
.size(),
4208 CanonicalConverted
))
4211 // Figure out where to insert this class template partial specialization
4212 // in the member template's set of class template partial specializations.
4213 void *InsertPos
= nullptr;
4214 ClassTemplateSpecializationDecl
*PrevDecl
=
4215 ClassTemplate
->findPartialSpecialization(CanonicalConverted
, InstParams
,
4218 // Build the canonical type that describes the converted template
4219 // arguments of the class template partial specialization.
4220 QualType CanonType
= SemaRef
.Context
.getTemplateSpecializationType(
4221 TemplateName(ClassTemplate
), CanonicalConverted
);
4223 // Build the fully-sugared type for this class template
4224 // specialization as the user wrote in the specialization
4225 // itself. This means that we'll pretty-print the type retrieved
4226 // from the specialization's declaration the way that the user
4227 // actually wrote the specialization, rather than formatting the
4228 // name based on the "canonical" representation used to store the
4229 // template arguments in the specialization.
4230 TypeSourceInfo
*WrittenTy
4231 = SemaRef
.Context
.getTemplateSpecializationTypeInfo(
4232 TemplateName(ClassTemplate
),
4233 PartialSpec
->getLocation(),
4238 // We've already seen a partial specialization with the same template
4239 // parameters and template arguments. This can happen, for example, when
4240 // substituting the outer template arguments ends up causing two
4241 // class template partial specializations of a member class template
4242 // to have identical forms, e.g.,
4244 // template<typename T, typename U>
4246 // template<typename X, typename Y> struct Inner;
4247 // template<typename Y> struct Inner<T, Y>;
4248 // template<typename Y> struct Inner<U, Y>;
4251 // Outer<int, int> outer; // error: the partial specializations of Inner
4252 // // have the same signature.
4253 SemaRef
.Diag(PartialSpec
->getLocation(), diag::err_partial_spec_redeclared
)
4254 << WrittenTy
->getType();
4255 SemaRef
.Diag(PrevDecl
->getLocation(), diag::note_prev_partial_spec_here
)
4256 << SemaRef
.Context
.getTypeDeclType(PrevDecl
);
4261 // Create the class template partial specialization declaration.
4262 ClassTemplatePartialSpecializationDecl
*InstPartialSpec
=
4263 ClassTemplatePartialSpecializationDecl::Create(
4264 SemaRef
.Context
, PartialSpec
->getTagKind(), Owner
,
4265 PartialSpec
->getBeginLoc(), PartialSpec
->getLocation(), InstParams
,
4266 ClassTemplate
, CanonicalConverted
, InstTemplateArgs
, CanonType
,
4268 // Substitute the nested name specifier, if any.
4269 if (SubstQualifier(PartialSpec
, InstPartialSpec
))
4272 InstPartialSpec
->setInstantiatedFromMember(PartialSpec
);
4273 InstPartialSpec
->setTypeAsWritten(WrittenTy
);
4275 // Check the completed partial specialization.
4276 SemaRef
.CheckTemplatePartialSpecialization(InstPartialSpec
);
4278 // Add this partial specialization to the set of class template partial
4280 ClassTemplate
->AddPartialSpecialization(InstPartialSpec
,
4281 /*InsertPos=*/nullptr);
4282 return InstPartialSpec
;
4285 /// Instantiate the declaration of a variable template partial
4288 /// \param VarTemplate the (instantiated) variable template that is partially
4289 /// specialized by the instantiation of \p PartialSpec.
4291 /// \param PartialSpec the (uninstantiated) variable template partial
4292 /// specialization that we are instantiating.
4294 /// \returns The instantiated partial specialization, if successful; otherwise,
4295 /// NULL to indicate an error.
4296 VarTemplatePartialSpecializationDecl
*
4297 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
4298 VarTemplateDecl
*VarTemplate
,
4299 VarTemplatePartialSpecializationDecl
*PartialSpec
) {
4300 // Create a local instantiation scope for this variable template partial
4301 // specialization, which will contain the instantiations of the template
4303 LocalInstantiationScope
Scope(SemaRef
);
4305 // Substitute into the template parameters of the variable template partial
4307 TemplateParameterList
*TempParams
= PartialSpec
->getTemplateParameters();
4308 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
4312 // Substitute into the template arguments of the variable template partial
4314 const ASTTemplateArgumentListInfo
*TemplArgInfo
4315 = PartialSpec
->getTemplateArgsAsWritten();
4316 TemplateArgumentListInfo
InstTemplateArgs(TemplArgInfo
->LAngleLoc
,
4317 TemplArgInfo
->RAngleLoc
);
4318 if (SemaRef
.SubstTemplateArguments(TemplArgInfo
->arguments(), TemplateArgs
,
4322 // Check that the template argument list is well-formed for this
4324 SmallVector
<TemplateArgument
, 4> SugaredConverted
, CanonicalConverted
;
4325 if (SemaRef
.CheckTemplateArgumentList(
4326 VarTemplate
, PartialSpec
->getLocation(), InstTemplateArgs
,
4327 /*PartialTemplateArgs=*/false, SugaredConverted
, CanonicalConverted
))
4330 // Check these arguments are valid for a template partial specialization.
4331 if (SemaRef
.CheckTemplatePartialSpecializationArgs(
4332 PartialSpec
->getLocation(), VarTemplate
, InstTemplateArgs
.size(),
4333 CanonicalConverted
))
4336 // Figure out where to insert this variable template partial specialization
4337 // in the member template's set of variable template partial specializations.
4338 void *InsertPos
= nullptr;
4339 VarTemplateSpecializationDecl
*PrevDecl
=
4340 VarTemplate
->findPartialSpecialization(CanonicalConverted
, InstParams
,
4343 // Build the canonical type that describes the converted template
4344 // arguments of the variable template partial specialization.
4345 QualType CanonType
= SemaRef
.Context
.getTemplateSpecializationType(
4346 TemplateName(VarTemplate
), CanonicalConverted
);
4348 // Build the fully-sugared type for this variable template
4349 // specialization as the user wrote in the specialization
4350 // itself. This means that we'll pretty-print the type retrieved
4351 // from the specialization's declaration the way that the user
4352 // actually wrote the specialization, rather than formatting the
4353 // name based on the "canonical" representation used to store the
4354 // template arguments in the specialization.
4355 TypeSourceInfo
*WrittenTy
= SemaRef
.Context
.getTemplateSpecializationTypeInfo(
4356 TemplateName(VarTemplate
), PartialSpec
->getLocation(), InstTemplateArgs
,
4360 // We've already seen a partial specialization with the same template
4361 // parameters and template arguments. This can happen, for example, when
4362 // substituting the outer template arguments ends up causing two
4363 // variable template partial specializations of a member variable template
4364 // to have identical forms, e.g.,
4366 // template<typename T, typename U>
4368 // template<typename X, typename Y> pair<X,Y> p;
4369 // template<typename Y> pair<T, Y> p;
4370 // template<typename Y> pair<U, Y> p;
4373 // Outer<int, int> outer; // error: the partial specializations of Inner
4374 // // have the same signature.
4375 SemaRef
.Diag(PartialSpec
->getLocation(),
4376 diag::err_var_partial_spec_redeclared
)
4377 << WrittenTy
->getType();
4378 SemaRef
.Diag(PrevDecl
->getLocation(),
4379 diag::note_var_prev_partial_spec_here
);
4383 // Do substitution on the type of the declaration
4384 TypeSourceInfo
*DI
= SemaRef
.SubstType(
4385 PartialSpec
->getTypeSourceInfo(), TemplateArgs
,
4386 PartialSpec
->getTypeSpecStartLoc(), PartialSpec
->getDeclName());
4390 if (DI
->getType()->isFunctionType()) {
4391 SemaRef
.Diag(PartialSpec
->getLocation(),
4392 diag::err_variable_instantiates_to_function
)
4393 << PartialSpec
->isStaticDataMember() << DI
->getType();
4397 // Create the variable template partial specialization declaration.
4398 VarTemplatePartialSpecializationDecl
*InstPartialSpec
=
4399 VarTemplatePartialSpecializationDecl::Create(
4400 SemaRef
.Context
, Owner
, PartialSpec
->getInnerLocStart(),
4401 PartialSpec
->getLocation(), InstParams
, VarTemplate
, DI
->getType(),
4402 DI
, PartialSpec
->getStorageClass(), CanonicalConverted
,
4405 // Substitute the nested name specifier, if any.
4406 if (SubstQualifier(PartialSpec
, InstPartialSpec
))
4409 InstPartialSpec
->setInstantiatedFromMember(PartialSpec
);
4410 InstPartialSpec
->setTypeAsWritten(WrittenTy
);
4412 // Check the completed partial specialization.
4413 SemaRef
.CheckTemplatePartialSpecialization(InstPartialSpec
);
4415 // Add this partial specialization to the set of variable template partial
4416 // specializations. The instantiation of the initializer is not necessary.
4417 VarTemplate
->AddPartialSpecialization(InstPartialSpec
, /*InsertPos=*/nullptr);
4419 SemaRef
.BuildVariableInstantiation(InstPartialSpec
, PartialSpec
, TemplateArgs
,
4420 LateAttrs
, Owner
, StartingScope
);
4422 return InstPartialSpec
;
4426 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl
*D
,
4427 SmallVectorImpl
<ParmVarDecl
*> &Params
) {
4428 TypeSourceInfo
*OldTInfo
= D
->getTypeSourceInfo();
4429 assert(OldTInfo
&& "substituting function without type source info");
4430 assert(Params
.empty() && "parameter vector is non-empty at start");
4432 CXXRecordDecl
*ThisContext
= nullptr;
4433 Qualifiers ThisTypeQuals
;
4434 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(D
)) {
4435 ThisContext
= cast
<CXXRecordDecl
>(Owner
);
4436 ThisTypeQuals
= Method
->getFunctionObjectParameterType().getQualifiers();
4439 TypeSourceInfo
*NewTInfo
= SemaRef
.SubstFunctionDeclType(
4440 OldTInfo
, TemplateArgs
, D
->getTypeSpecStartLoc(), D
->getDeclName(),
4441 ThisContext
, ThisTypeQuals
, EvaluateConstraints
);
4445 TypeLoc OldTL
= OldTInfo
->getTypeLoc().IgnoreParens();
4446 if (FunctionProtoTypeLoc OldProtoLoc
= OldTL
.getAs
<FunctionProtoTypeLoc
>()) {
4447 if (NewTInfo
!= OldTInfo
) {
4448 // Get parameters from the new type info.
4449 TypeLoc NewTL
= NewTInfo
->getTypeLoc().IgnoreParens();
4450 FunctionProtoTypeLoc NewProtoLoc
= NewTL
.castAs
<FunctionProtoTypeLoc
>();
4451 unsigned NewIdx
= 0;
4452 for (unsigned OldIdx
= 0, NumOldParams
= OldProtoLoc
.getNumParams();
4453 OldIdx
!= NumOldParams
; ++OldIdx
) {
4454 ParmVarDecl
*OldParam
= OldProtoLoc
.getParam(OldIdx
);
4458 LocalInstantiationScope
*Scope
= SemaRef
.CurrentInstantiationScope
;
4460 std::optional
<unsigned> NumArgumentsInExpansion
;
4461 if (OldParam
->isParameterPack())
4462 NumArgumentsInExpansion
=
4463 SemaRef
.getNumArgumentsInExpansion(OldParam
->getType(),
4465 if (!NumArgumentsInExpansion
) {
4466 // Simple case: normal parameter, or a parameter pack that's
4467 // instantiated to a (still-dependent) parameter pack.
4468 ParmVarDecl
*NewParam
= NewProtoLoc
.getParam(NewIdx
++);
4469 Params
.push_back(NewParam
);
4470 Scope
->InstantiatedLocal(OldParam
, NewParam
);
4472 // Parameter pack expansion: make the instantiation an argument pack.
4473 Scope
->MakeInstantiatedLocalArgPack(OldParam
);
4474 for (unsigned I
= 0; I
!= *NumArgumentsInExpansion
; ++I
) {
4475 ParmVarDecl
*NewParam
= NewProtoLoc
.getParam(NewIdx
++);
4476 Params
.push_back(NewParam
);
4477 Scope
->InstantiatedLocalPackArg(OldParam
, NewParam
);
4482 // The function type itself was not dependent and therefore no
4483 // substitution occurred. However, we still need to instantiate
4484 // the function parameters themselves.
4485 const FunctionProtoType
*OldProto
=
4486 cast
<FunctionProtoType
>(OldProtoLoc
.getType());
4487 for (unsigned i
= 0, i_end
= OldProtoLoc
.getNumParams(); i
!= i_end
;
4489 ParmVarDecl
*OldParam
= OldProtoLoc
.getParam(i
);
4491 Params
.push_back(SemaRef
.BuildParmVarDeclForTypedef(
4492 D
, D
->getLocation(), OldProto
->getParamType(i
)));
4497 cast_or_null
<ParmVarDecl
>(VisitParmVarDecl(OldParam
));
4500 Params
.push_back(Parm
);
4504 // If the type of this function, after ignoring parentheses, is not
4505 // *directly* a function type, then we're instantiating a function that
4506 // was declared via a typedef or with attributes, e.g.,
4508 // typedef int functype(int, int);
4510 // int __cdecl meth(int, int);
4512 // In this case, we'll just go instantiate the ParmVarDecls that we
4513 // synthesized in the method declaration.
4514 SmallVector
<QualType
, 4> ParamTypes
;
4515 Sema::ExtParameterInfoBuilder ExtParamInfos
;
4516 if (SemaRef
.SubstParmTypes(D
->getLocation(), D
->parameters(), nullptr,
4517 TemplateArgs
, ParamTypes
, &Params
,
4525 /// Introduce the instantiated local variables into the local
4526 /// instantiation scope.
4527 void Sema::addInstantiatedLocalVarsToScope(FunctionDecl
*Function
,
4528 const FunctionDecl
*PatternDecl
,
4529 LocalInstantiationScope
&Scope
) {
4530 LambdaScopeInfo
*LSI
= cast
<LambdaScopeInfo
>(getFunctionScopes().back());
4532 for (auto *decl
: PatternDecl
->decls()) {
4533 if (!isa
<VarDecl
>(decl
) || isa
<ParmVarDecl
>(decl
))
4536 VarDecl
*VD
= cast
<VarDecl
>(decl
);
4537 IdentifierInfo
*II
= VD
->getIdentifier();
4539 auto it
= llvm::find_if(Function
->decls(), [&](Decl
*inst
) {
4540 VarDecl
*InstVD
= dyn_cast
<VarDecl
>(inst
);
4541 return InstVD
&& InstVD
->isLocalVarDecl() &&
4542 InstVD
->getIdentifier() == II
;
4545 if (it
== Function
->decls().end())
4548 Scope
.InstantiatedLocal(VD
, *it
);
4549 LSI
->addCapture(cast
<VarDecl
>(*it
), /*isBlock=*/false, /*isByref=*/false,
4550 /*isNested=*/false, VD
->getLocation(), SourceLocation(),
4551 VD
->getType(), /*Invalid=*/false);
4555 /// Introduce the instantiated function parameters into the local
4556 /// instantiation scope, and set the parameter names to those used
4557 /// in the template.
4558 bool Sema::addInstantiatedParametersToScope(
4559 FunctionDecl
*Function
, const FunctionDecl
*PatternDecl
,
4560 LocalInstantiationScope
&Scope
,
4561 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
4562 unsigned FParamIdx
= 0;
4563 for (unsigned I
= 0, N
= PatternDecl
->getNumParams(); I
!= N
; ++I
) {
4564 const ParmVarDecl
*PatternParam
= PatternDecl
->getParamDecl(I
);
4565 if (!PatternParam
->isParameterPack()) {
4566 // Simple case: not a parameter pack.
4567 assert(FParamIdx
< Function
->getNumParams());
4568 ParmVarDecl
*FunctionParam
= Function
->getParamDecl(FParamIdx
);
4569 FunctionParam
->setDeclName(PatternParam
->getDeclName());
4570 // If the parameter's type is not dependent, update it to match the type
4571 // in the pattern. They can differ in top-level cv-qualifiers, and we want
4572 // the pattern's type here. If the type is dependent, they can't differ,
4573 // per core issue 1668. Substitute into the type from the pattern, in case
4574 // it's instantiation-dependent.
4575 // FIXME: Updating the type to work around this is at best fragile.
4576 if (!PatternDecl
->getType()->isDependentType()) {
4577 QualType T
= SubstType(PatternParam
->getType(), TemplateArgs
,
4578 FunctionParam
->getLocation(),
4579 FunctionParam
->getDeclName());
4582 FunctionParam
->setType(T
);
4585 Scope
.InstantiatedLocal(PatternParam
, FunctionParam
);
4590 // Expand the parameter pack.
4591 Scope
.MakeInstantiatedLocalArgPack(PatternParam
);
4592 std::optional
<unsigned> NumArgumentsInExpansion
=
4593 getNumArgumentsInExpansion(PatternParam
->getType(), TemplateArgs
);
4594 if (NumArgumentsInExpansion
) {
4595 QualType PatternType
=
4596 PatternParam
->getType()->castAs
<PackExpansionType
>()->getPattern();
4597 for (unsigned Arg
= 0; Arg
< *NumArgumentsInExpansion
; ++Arg
) {
4598 ParmVarDecl
*FunctionParam
= Function
->getParamDecl(FParamIdx
);
4599 FunctionParam
->setDeclName(PatternParam
->getDeclName());
4600 if (!PatternDecl
->getType()->isDependentType()) {
4601 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(*this, Arg
);
4603 SubstType(PatternType
, TemplateArgs
, FunctionParam
->getLocation(),
4604 FunctionParam
->getDeclName());
4607 FunctionParam
->setType(T
);
4610 Scope
.InstantiatedLocalPackArg(PatternParam
, FunctionParam
);
4619 bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc
, FunctionDecl
*FD
,
4620 ParmVarDecl
*Param
) {
4621 assert(Param
->hasUninstantiatedDefaultArg());
4623 // Instantiate the expression.
4625 // FIXME: Pass in a correct Pattern argument, otherwise
4626 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4628 // template<typename T>
4630 // static int FooImpl();
4632 // template<typename Tp>
4633 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4634 // // template argument list [[T], [Tp]], should be [[Tp]].
4635 // friend A<Tp> Foo(int a);
4638 // template<typename T>
4639 // A<T> Foo(int a = A<T>::FooImpl());
4640 MultiLevelTemplateArgumentList TemplateArgs
= getTemplateInstantiationArgs(
4641 FD
, FD
->getLexicalDeclContext(), /*Final=*/false, nullptr,
4642 /*RelativeToPrimary=*/true);
4644 if (SubstDefaultArgument(CallLoc
, Param
, TemplateArgs
, /*ForCallExpr*/ true))
4647 if (ASTMutationListener
*L
= getASTMutationListener())
4648 L
->DefaultArgumentInstantiated(Param
);
4653 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation
,
4654 FunctionDecl
*Decl
) {
4655 const FunctionProtoType
*Proto
= Decl
->getType()->castAs
<FunctionProtoType
>();
4656 if (Proto
->getExceptionSpecType() != EST_Uninstantiated
)
4659 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, Decl
,
4660 InstantiatingTemplate::ExceptionSpecification());
4661 if (Inst
.isInvalid()) {
4662 // We hit the instantiation depth limit. Clear the exception specification
4663 // so that our callers don't have to cope with EST_Uninstantiated.
4664 UpdateExceptionSpec(Decl
, EST_None
);
4667 if (Inst
.isAlreadyInstantiating()) {
4668 // This exception specification indirectly depends on itself. Reject.
4669 // FIXME: Corresponding rule in the standard?
4670 Diag(PointOfInstantiation
, diag::err_exception_spec_cycle
) << Decl
;
4671 UpdateExceptionSpec(Decl
, EST_None
);
4675 // Enter the scope of this instantiation. We don't use
4676 // PushDeclContext because we don't have a scope.
4677 Sema::ContextRAII
savedContext(*this, Decl
);
4678 LocalInstantiationScope
Scope(*this);
4680 MultiLevelTemplateArgumentList TemplateArgs
= getTemplateInstantiationArgs(
4681 Decl
, Decl
->getLexicalDeclContext(), /*Final=*/false, nullptr,
4682 /*RelativeToPrimary*/ true);
4684 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4685 // here, because for a non-defining friend declaration in a class template,
4686 // we don't store enough information to map back to the friend declaration in
4688 FunctionDecl
*Template
= Proto
->getExceptionSpecTemplate();
4689 if (addInstantiatedParametersToScope(Decl
, Template
, Scope
, TemplateArgs
)) {
4690 UpdateExceptionSpec(Decl
, EST_None
);
4694 SubstExceptionSpec(Decl
, Template
->getType()->castAs
<FunctionProtoType
>(),
4698 /// Initializes the common fields of an instantiation function
4699 /// declaration (New) from the corresponding fields of its template (Tmpl).
4701 /// \returns true if there was an error
4703 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl
*New
,
4704 FunctionDecl
*Tmpl
) {
4705 New
->setImplicit(Tmpl
->isImplicit());
4707 // Forward the mangling number from the template to the instantiated decl.
4708 SemaRef
.Context
.setManglingNumber(New
,
4709 SemaRef
.Context
.getManglingNumber(Tmpl
));
4711 // If we are performing substituting explicitly-specified template arguments
4712 // or deduced template arguments into a function template and we reach this
4713 // point, we are now past the point where SFINAE applies and have committed
4714 // to keeping the new function template specialization. We therefore
4715 // convert the active template instantiation for the function template
4716 // into a template instantiation for this specific function template
4717 // specialization, which is not a SFINAE context, so that we diagnose any
4718 // further errors in the declaration itself.
4720 // FIXME: This is a hack.
4721 typedef Sema::CodeSynthesisContext ActiveInstType
;
4722 ActiveInstType
&ActiveInst
= SemaRef
.CodeSynthesisContexts
.back();
4723 if (ActiveInst
.Kind
== ActiveInstType::ExplicitTemplateArgumentSubstitution
||
4724 ActiveInst
.Kind
== ActiveInstType::DeducedTemplateArgumentSubstitution
) {
4725 if (isa
<FunctionTemplateDecl
>(ActiveInst
.Entity
)) {
4726 SemaRef
.InstantiatingSpecializations
.erase(
4727 {ActiveInst
.Entity
->getCanonicalDecl(), ActiveInst
.Kind
});
4728 atTemplateEnd(SemaRef
.TemplateInstCallbacks
, SemaRef
, ActiveInst
);
4729 ActiveInst
.Kind
= ActiveInstType::TemplateInstantiation
;
4730 ActiveInst
.Entity
= New
;
4731 atTemplateBegin(SemaRef
.TemplateInstCallbacks
, SemaRef
, ActiveInst
);
4735 const FunctionProtoType
*Proto
= Tmpl
->getType()->getAs
<FunctionProtoType
>();
4736 assert(Proto
&& "Function template without prototype?");
4738 if (Proto
->hasExceptionSpec() || Proto
->getNoReturnAttr()) {
4739 FunctionProtoType::ExtProtoInfo EPI
= Proto
->getExtProtoInfo();
4741 // DR1330: In C++11, defer instantiation of a non-trivial
4742 // exception specification.
4743 // DR1484: Local classes and their members are instantiated along with the
4744 // containing function.
4745 if (SemaRef
.getLangOpts().CPlusPlus11
&&
4746 EPI
.ExceptionSpec
.Type
!= EST_None
&&
4747 EPI
.ExceptionSpec
.Type
!= EST_DynamicNone
&&
4748 EPI
.ExceptionSpec
.Type
!= EST_BasicNoexcept
&&
4749 !Tmpl
->isInLocalScopeForInstantiation()) {
4750 FunctionDecl
*ExceptionSpecTemplate
= Tmpl
;
4751 if (EPI
.ExceptionSpec
.Type
== EST_Uninstantiated
)
4752 ExceptionSpecTemplate
= EPI
.ExceptionSpec
.SourceTemplate
;
4753 ExceptionSpecificationType NewEST
= EST_Uninstantiated
;
4754 if (EPI
.ExceptionSpec
.Type
== EST_Unevaluated
)
4755 NewEST
= EST_Unevaluated
;
4757 // Mark the function has having an uninstantiated exception specification.
4758 const FunctionProtoType
*NewProto
4759 = New
->getType()->getAs
<FunctionProtoType
>();
4760 assert(NewProto
&& "Template instantiation without function prototype?");
4761 EPI
= NewProto
->getExtProtoInfo();
4762 EPI
.ExceptionSpec
.Type
= NewEST
;
4763 EPI
.ExceptionSpec
.SourceDecl
= New
;
4764 EPI
.ExceptionSpec
.SourceTemplate
= ExceptionSpecTemplate
;
4765 New
->setType(SemaRef
.Context
.getFunctionType(
4766 NewProto
->getReturnType(), NewProto
->getParamTypes(), EPI
));
4768 Sema::ContextRAII
SwitchContext(SemaRef
, New
);
4769 SemaRef
.SubstExceptionSpec(New
, Proto
, TemplateArgs
);
4773 // Get the definition. Leaves the variable unchanged if undefined.
4774 const FunctionDecl
*Definition
= Tmpl
;
4775 Tmpl
->isDefined(Definition
);
4777 SemaRef
.InstantiateAttrs(TemplateArgs
, Definition
, New
,
4778 LateAttrs
, StartingScope
);
4783 /// Initializes common fields of an instantiated method
4784 /// declaration (New) from the corresponding fields of its template
4787 /// \returns true if there was an error
4789 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl
*New
,
4790 CXXMethodDecl
*Tmpl
) {
4791 if (InitFunctionInstantiation(New
, Tmpl
))
4794 if (isa
<CXXDestructorDecl
>(New
) && SemaRef
.getLangOpts().CPlusPlus11
)
4795 SemaRef
.AdjustDestructorExceptionSpec(cast
<CXXDestructorDecl
>(New
));
4797 New
->setAccess(Tmpl
->getAccess());
4798 if (Tmpl
->isVirtualAsWritten())
4799 New
->setVirtualAsWritten(true);
4801 // FIXME: New needs a pointer to Tmpl
4805 bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl
*New
,
4806 FunctionDecl
*Tmpl
) {
4807 // Transfer across any unqualified lookups.
4808 if (auto *DFI
= Tmpl
->getDefaultedFunctionInfo()) {
4809 SmallVector
<DeclAccessPair
, 32> Lookups
;
4810 Lookups
.reserve(DFI
->getUnqualifiedLookups().size());
4811 bool AnyChanged
= false;
4812 for (DeclAccessPair DA
: DFI
->getUnqualifiedLookups()) {
4813 NamedDecl
*D
= SemaRef
.FindInstantiatedDecl(New
->getLocation(),
4814 DA
.getDecl(), TemplateArgs
);
4817 AnyChanged
|= (D
!= DA
.getDecl());
4818 Lookups
.push_back(DeclAccessPair::make(D
, DA
.getAccess()));
4821 // It's unlikely that substitution will change any declarations. Don't
4822 // store an unnecessary copy in that case.
4823 New
->setDefaultedFunctionInfo(
4824 AnyChanged
? FunctionDecl::DefaultedFunctionInfo::Create(
4825 SemaRef
.Context
, Lookups
)
4829 SemaRef
.SetDeclDefaulted(New
, Tmpl
->getLocation());
4833 /// Instantiate (or find existing instantiation of) a function template with a
4834 /// given set of template arguments.
4836 /// Usually this should not be used, and template argument deduction should be
4837 /// used in its place.
4839 Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl
*FTD
,
4840 const TemplateArgumentList
*Args
,
4841 SourceLocation Loc
) {
4842 FunctionDecl
*FD
= FTD
->getTemplatedDecl();
4844 sema::TemplateDeductionInfo
Info(Loc
);
4845 InstantiatingTemplate
Inst(
4846 *this, Loc
, FTD
, Args
->asArray(),
4847 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
, Info
);
4848 if (Inst
.isInvalid())
4851 ContextRAII
SavedContext(*this, FD
);
4852 MultiLevelTemplateArgumentList
MArgs(FTD
, Args
->asArray(),
4855 return cast_or_null
<FunctionDecl
>(SubstDecl(FD
, FD
->getParent(), MArgs
));
4858 /// Instantiate the definition of the given function from its
4861 /// \param PointOfInstantiation the point at which the instantiation was
4862 /// required. Note that this is not precisely a "point of instantiation"
4863 /// for the function, but it's close.
4865 /// \param Function the already-instantiated declaration of a
4866 /// function template specialization or member function of a class template
4869 /// \param Recursive if true, recursively instantiates any functions that
4870 /// are required by this instantiation.
4872 /// \param DefinitionRequired if true, then we are performing an explicit
4873 /// instantiation where the body of the function is required. Complain if
4874 /// there is no such body.
4875 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation
,
4876 FunctionDecl
*Function
,
4878 bool DefinitionRequired
,
4880 if (Function
->isInvalidDecl() || isa
<CXXDeductionGuideDecl
>(Function
))
4883 // Never instantiate an explicit specialization except if it is a class scope
4884 // explicit specialization.
4885 TemplateSpecializationKind TSK
=
4886 Function
->getTemplateSpecializationKindForInstantiation();
4887 if (TSK
== TSK_ExplicitSpecialization
)
4890 // Never implicitly instantiate a builtin; we don't actually need a function
4892 if (Function
->getBuiltinID() && TSK
== TSK_ImplicitInstantiation
&&
4893 !DefinitionRequired
)
4896 // Don't instantiate a definition if we already have one.
4897 const FunctionDecl
*ExistingDefn
= nullptr;
4898 if (Function
->isDefined(ExistingDefn
,
4899 /*CheckForPendingFriendDefinition=*/true)) {
4900 if (ExistingDefn
->isThisDeclarationADefinition())
4903 // If we're asked to instantiate a function whose body comes from an
4904 // instantiated friend declaration, attach the instantiated body to the
4905 // corresponding declaration of the function.
4906 assert(ExistingDefn
->isThisDeclarationInstantiatedFromAFriendDefinition());
4907 Function
= const_cast<FunctionDecl
*>(ExistingDefn
);
4910 // Find the function body that we'll be substituting.
4911 const FunctionDecl
*PatternDecl
= Function
->getTemplateInstantiationPattern();
4912 assert(PatternDecl
&& "instantiating a non-template");
4914 const FunctionDecl
*PatternDef
= PatternDecl
->getDefinition();
4915 Stmt
*Pattern
= nullptr;
4917 Pattern
= PatternDef
->getBody(PatternDef
);
4918 PatternDecl
= PatternDef
;
4919 if (PatternDef
->willHaveBody())
4920 PatternDef
= nullptr;
4923 // FIXME: We need to track the instantiation stack in order to know which
4924 // definitions should be visible within this instantiation.
4925 if (DiagnoseUninstantiableTemplate(PointOfInstantiation
, Function
,
4926 Function
->getInstantiatedFromMemberFunction(),
4927 PatternDecl
, PatternDef
, TSK
,
4928 /*Complain*/DefinitionRequired
)) {
4929 if (DefinitionRequired
)
4930 Function
->setInvalidDecl();
4931 else if (TSK
== TSK_ExplicitInstantiationDefinition
||
4932 (Function
->isConstexpr() && !Recursive
)) {
4933 // Try again at the end of the translation unit (at which point a
4934 // definition will be required).
4936 Function
->setInstantiationIsPending(true);
4937 PendingInstantiations
.push_back(
4938 std::make_pair(Function
, PointOfInstantiation
));
4939 } else if (TSK
== TSK_ImplicitInstantiation
) {
4940 if (AtEndOfTU
&& !getDiagnostics().hasErrorOccurred() &&
4941 !getSourceManager().isInSystemHeader(PatternDecl
->getBeginLoc())) {
4942 Diag(PointOfInstantiation
, diag::warn_func_template_missing
)
4944 Diag(PatternDecl
->getLocation(), diag::note_forward_template_decl
);
4945 if (getLangOpts().CPlusPlus11
)
4946 Diag(PointOfInstantiation
, diag::note_inst_declaration_hint
)
4954 // Postpone late parsed template instantiations.
4955 if (PatternDecl
->isLateTemplateParsed() &&
4956 !LateTemplateParser
) {
4957 Function
->setInstantiationIsPending(true);
4958 LateParsedInstantiations
.push_back(
4959 std::make_pair(Function
, PointOfInstantiation
));
4963 llvm::TimeTraceScope
TimeScope("InstantiateFunction", [&]() {
4965 llvm::raw_string_ostream
OS(Name
);
4966 Function
->getNameForDiagnostic(OS
, getPrintingPolicy(),
4967 /*Qualified=*/true);
4971 // If we're performing recursive template instantiation, create our own
4972 // queue of pending implicit instantiations that we will instantiate later,
4973 // while we're still within our own instantiation context.
4974 // This has to happen before LateTemplateParser below is called, so that
4975 // it marks vtables used in late parsed templates as used.
4976 GlobalEagerInstantiationScope
GlobalInstantiations(*this,
4977 /*Enabled=*/Recursive
);
4978 LocalEagerInstantiationScope
LocalInstantiations(*this);
4980 // Call the LateTemplateParser callback if there is a need to late parse
4981 // a templated function definition.
4982 if (!Pattern
&& PatternDecl
->isLateTemplateParsed() &&
4983 LateTemplateParser
) {
4984 // FIXME: Optimize to allow individual templates to be deserialized.
4985 if (PatternDecl
->isFromASTFile())
4986 ExternalSource
->ReadLateParsedTemplates(LateParsedTemplateMap
);
4988 auto LPTIter
= LateParsedTemplateMap
.find(PatternDecl
);
4989 assert(LPTIter
!= LateParsedTemplateMap
.end() &&
4990 "missing LateParsedTemplate");
4991 LateTemplateParser(OpaqueParser
, *LPTIter
->second
);
4992 Pattern
= PatternDecl
->getBody(PatternDecl
);
4993 updateAttrsForLateParsedTemplate(PatternDecl
, Function
);
4996 // Note, we should never try to instantiate a deleted function template.
4997 assert((Pattern
|| PatternDecl
->isDefaulted() ||
4998 PatternDecl
->hasSkippedBody()) &&
4999 "unexpected kind of function template definition");
5001 // C++1y [temp.explicit]p10:
5002 // Except for inline functions, declarations with types deduced from their
5003 // initializer or return value, and class template specializations, other
5004 // explicit instantiation declarations have the effect of suppressing the
5005 // implicit instantiation of the entity to which they refer.
5006 if (TSK
== TSK_ExplicitInstantiationDeclaration
&&
5007 !PatternDecl
->isInlined() &&
5008 !PatternDecl
->getReturnType()->getContainedAutoType())
5011 if (PatternDecl
->isInlined()) {
5012 // Function, and all later redeclarations of it (from imported modules,
5013 // for instance), are now implicitly inline.
5014 for (auto *D
= Function
->getMostRecentDecl(); /**/;
5015 D
= D
->getPreviousDecl()) {
5016 D
->setImplicitlyInline();
5022 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, Function
);
5023 if (Inst
.isInvalid() || Inst
.isAlreadyInstantiating())
5025 PrettyDeclStackTraceEntry
CrashInfo(Context
, Function
, SourceLocation(),
5026 "instantiating function definition");
5028 // The instantiation is visible here, even if it was first declared in an
5029 // unimported module.
5030 Function
->setVisibleDespiteOwningModule();
5032 // Copy the source locations from the pattern.
5033 Function
->setLocation(PatternDecl
->getLocation());
5034 Function
->setInnerLocStart(PatternDecl
->getInnerLocStart());
5035 Function
->setRangeEnd(PatternDecl
->getEndLoc());
5037 EnterExpressionEvaluationContext
EvalContext(
5038 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated
);
5040 // Introduce a new scope where local variable instantiations will be
5041 // recorded, unless we're actually a member function within a local
5042 // class, in which case we need to merge our results with the parent
5043 // scope (of the enclosing function). The exception is instantiating
5044 // a function template specialization, since the template to be
5045 // instantiated already has references to locals properly substituted.
5046 bool MergeWithParentScope
= false;
5047 if (CXXRecordDecl
*Rec
= dyn_cast
<CXXRecordDecl
>(Function
->getDeclContext()))
5048 MergeWithParentScope
=
5049 Rec
->isLocalClass() && !Function
->isFunctionTemplateSpecialization();
5051 LocalInstantiationScope
Scope(*this, MergeWithParentScope
);
5052 auto RebuildTypeSourceInfoForDefaultSpecialMembers
= [&]() {
5053 // Special members might get their TypeSourceInfo set up w.r.t the
5054 // PatternDecl context, in which case parameters could still be pointing
5055 // back to the original class, make sure arguments are bound to the
5056 // instantiated record instead.
5057 assert(PatternDecl
->isDefaulted() &&
5058 "Special member needs to be defaulted");
5059 auto PatternSM
= getDefaultedFunctionKind(PatternDecl
).asSpecialMember();
5060 if (!(PatternSM
== Sema::CXXCopyConstructor
||
5061 PatternSM
== Sema::CXXCopyAssignment
||
5062 PatternSM
== Sema::CXXMoveConstructor
||
5063 PatternSM
== Sema::CXXMoveAssignment
))
5066 auto *NewRec
= dyn_cast
<CXXRecordDecl
>(Function
->getDeclContext());
5067 const auto *PatternRec
=
5068 dyn_cast
<CXXRecordDecl
>(PatternDecl
->getDeclContext());
5069 if (!NewRec
|| !PatternRec
)
5071 if (!PatternRec
->isLambda())
5074 struct SpecialMemberTypeInfoRebuilder
5075 : TreeTransform
<SpecialMemberTypeInfoRebuilder
> {
5076 using Base
= TreeTransform
<SpecialMemberTypeInfoRebuilder
>;
5077 const CXXRecordDecl
*OldDecl
;
5078 CXXRecordDecl
*NewDecl
;
5080 SpecialMemberTypeInfoRebuilder(Sema
&SemaRef
, const CXXRecordDecl
*O
,
5082 : TreeTransform(SemaRef
), OldDecl(O
), NewDecl(N
) {}
5084 bool TransformExceptionSpec(SourceLocation Loc
,
5085 FunctionProtoType::ExceptionSpecInfo
&ESI
,
5086 SmallVectorImpl
<QualType
> &Exceptions
,
5091 QualType
TransformRecordType(TypeLocBuilder
&TLB
, RecordTypeLoc TL
) {
5092 const RecordType
*T
= TL
.getTypePtr();
5093 RecordDecl
*Record
= cast_or_null
<RecordDecl
>(
5094 getDerived().TransformDecl(TL
.getNameLoc(), T
->getDecl()));
5095 if (Record
!= OldDecl
)
5096 return Base::TransformRecordType(TLB
, TL
);
5098 QualType Result
= getDerived().RebuildRecordType(NewDecl
);
5099 if (Result
.isNull())
5102 RecordTypeLoc NewTL
= TLB
.push
<RecordTypeLoc
>(Result
);
5103 NewTL
.setNameLoc(TL
.getNameLoc());
5106 } IR
{*this, PatternRec
, NewRec
};
5108 TypeSourceInfo
*NewSI
= IR
.TransformType(Function
->getTypeSourceInfo());
5109 assert(NewSI
&& "Type Transform failed?");
5110 Function
->setType(NewSI
->getType());
5111 Function
->setTypeSourceInfo(NewSI
);
5113 ParmVarDecl
*Parm
= Function
->getParamDecl(0);
5114 TypeSourceInfo
*NewParmSI
= IR
.TransformType(Parm
->getTypeSourceInfo());
5115 Parm
->setType(NewParmSI
->getType());
5116 Parm
->setTypeSourceInfo(NewParmSI
);
5119 if (PatternDecl
->isDefaulted()) {
5120 RebuildTypeSourceInfoForDefaultSpecialMembers();
5121 SetDeclDefaulted(Function
, PatternDecl
->getLocation());
5123 MultiLevelTemplateArgumentList TemplateArgs
= getTemplateInstantiationArgs(
5124 Function
, Function
->getLexicalDeclContext(), /*Final=*/false, nullptr,
5125 false, PatternDecl
);
5127 // Substitute into the qualifier; we can get a substitution failure here
5128 // through evil use of alias templates.
5129 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5130 // of the) lexical context of the pattern?
5131 SubstQualifier(*this, PatternDecl
, Function
, TemplateArgs
);
5133 ActOnStartOfFunctionDef(nullptr, Function
);
5135 // Enter the scope of this instantiation. We don't use
5136 // PushDeclContext because we don't have a scope.
5137 Sema::ContextRAII
savedContext(*this, Function
);
5139 FPFeaturesStateRAII
SavedFPFeatures(*this);
5140 CurFPFeatures
= FPOptions(getLangOpts());
5141 FpPragmaStack
.CurrentValue
= FPOptionsOverride();
5143 if (addInstantiatedParametersToScope(Function
, PatternDecl
, Scope
,
5148 if (PatternDecl
->hasSkippedBody()) {
5149 ActOnSkippedFunctionBody(Function
);
5152 if (CXXConstructorDecl
*Ctor
= dyn_cast
<CXXConstructorDecl
>(Function
)) {
5153 // If this is a constructor, instantiate the member initializers.
5154 InstantiateMemInitializers(Ctor
, cast
<CXXConstructorDecl
>(PatternDecl
),
5157 // If this is an MS ABI dllexport default constructor, instantiate any
5158 // default arguments.
5159 if (Context
.getTargetInfo().getCXXABI().isMicrosoft() &&
5160 Ctor
->isDefaultConstructor()) {
5161 InstantiateDefaultCtorDefaultArgs(Ctor
);
5165 // Instantiate the function body.
5166 Body
= SubstStmt(Pattern
, TemplateArgs
);
5168 if (Body
.isInvalid())
5169 Function
->setInvalidDecl();
5171 // FIXME: finishing the function body while in an expression evaluation
5172 // context seems wrong. Investigate more.
5173 ActOnFinishFunctionBody(Function
, Body
.get(), /*IsInstantiation=*/true);
5175 PerformDependentDiagnostics(PatternDecl
, TemplateArgs
);
5177 if (auto *Listener
= getASTMutationListener())
5178 Listener
->FunctionDefinitionInstantiated(Function
);
5183 DeclGroupRef
DG(Function
);
5184 Consumer
.HandleTopLevelDecl(DG
);
5186 // This class may have local implicit instantiations that need to be
5187 // instantiation within this scope.
5188 LocalInstantiations
.perform();
5190 GlobalInstantiations
.perform();
5193 VarTemplateSpecializationDecl
*Sema::BuildVarTemplateInstantiation(
5194 VarTemplateDecl
*VarTemplate
, VarDecl
*FromVar
,
5195 const TemplateArgumentList
&TemplateArgList
,
5196 const TemplateArgumentListInfo
&TemplateArgsInfo
,
5197 SmallVectorImpl
<TemplateArgument
> &Converted
,
5198 SourceLocation PointOfInstantiation
, LateInstantiatedAttrVec
*LateAttrs
,
5199 LocalInstantiationScope
*StartingScope
) {
5200 if (FromVar
->isInvalidDecl())
5203 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, FromVar
);
5204 if (Inst
.isInvalid())
5207 // Instantiate the first declaration of the variable template: for a partial
5208 // specialization of a static data member template, the first declaration may
5209 // or may not be the declaration in the class; if it's in the class, we want
5210 // to instantiate a member in the class (a declaration), and if it's outside,
5211 // we want to instantiate a definition.
5213 // If we're instantiating an explicitly-specialized member template or member
5214 // partial specialization, don't do this. The member specialization completely
5215 // replaces the original declaration in this case.
5216 bool IsMemberSpec
= false;
5217 MultiLevelTemplateArgumentList MultiLevelList
;
5218 if (auto *PartialSpec
=
5219 dyn_cast
<VarTemplatePartialSpecializationDecl
>(FromVar
)) {
5220 IsMemberSpec
= PartialSpec
->isMemberSpecialization();
5221 MultiLevelList
.addOuterTemplateArguments(
5222 PartialSpec
, TemplateArgList
.asArray(), /*Final=*/false);
5224 assert(VarTemplate
== FromVar
->getDescribedVarTemplate());
5225 IsMemberSpec
= VarTemplate
->isMemberSpecialization();
5226 MultiLevelList
.addOuterTemplateArguments(
5227 VarTemplate
, TemplateArgList
.asArray(), /*Final=*/false);
5230 FromVar
= FromVar
->getFirstDecl();
5232 TemplateDeclInstantiator
Instantiator(*this, FromVar
->getDeclContext(),
5235 // TODO: Set LateAttrs and StartingScope ...
5237 return cast_or_null
<VarTemplateSpecializationDecl
>(
5238 Instantiator
.VisitVarTemplateSpecializationDecl(
5239 VarTemplate
, FromVar
, TemplateArgsInfo
, Converted
));
5242 /// Instantiates a variable template specialization by completing it
5243 /// with appropriate type information and initializer.
5244 VarTemplateSpecializationDecl
*Sema::CompleteVarTemplateSpecializationDecl(
5245 VarTemplateSpecializationDecl
*VarSpec
, VarDecl
*PatternDecl
,
5246 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
5247 assert(PatternDecl
->isThisDeclarationADefinition() &&
5248 "don't have a definition to instantiate from");
5250 // Do substitution on the type of the declaration
5251 TypeSourceInfo
*DI
=
5252 SubstType(PatternDecl
->getTypeSourceInfo(), TemplateArgs
,
5253 PatternDecl
->getTypeSpecStartLoc(), PatternDecl
->getDeclName());
5257 // Update the type of this variable template specialization.
5258 VarSpec
->setType(DI
->getType());
5260 // Convert the declaration into a definition now.
5261 VarSpec
->setCompleteDefinition();
5263 // Instantiate the initializer.
5264 InstantiateVariableInitializer(VarSpec
, PatternDecl
, TemplateArgs
);
5266 if (getLangOpts().OpenCL
)
5267 deduceOpenCLAddressSpace(VarSpec
);
5272 /// BuildVariableInstantiation - Used after a new variable has been created.
5273 /// Sets basic variable data and decides whether to postpone the
5274 /// variable instantiation.
5275 void Sema::BuildVariableInstantiation(
5276 VarDecl
*NewVar
, VarDecl
*OldVar
,
5277 const MultiLevelTemplateArgumentList
&TemplateArgs
,
5278 LateInstantiatedAttrVec
*LateAttrs
, DeclContext
*Owner
,
5279 LocalInstantiationScope
*StartingScope
,
5280 bool InstantiatingVarTemplate
,
5281 VarTemplateSpecializationDecl
*PrevDeclForVarTemplateSpecialization
) {
5282 // Instantiating a partial specialization to produce a partial
5284 bool InstantiatingVarTemplatePartialSpec
=
5285 isa
<VarTemplatePartialSpecializationDecl
>(OldVar
) &&
5286 isa
<VarTemplatePartialSpecializationDecl
>(NewVar
);
5287 // Instantiating from a variable template (or partial specialization) to
5288 // produce a variable template specialization.
5289 bool InstantiatingSpecFromTemplate
=
5290 isa
<VarTemplateSpecializationDecl
>(NewVar
) &&
5291 (OldVar
->getDescribedVarTemplate() ||
5292 isa
<VarTemplatePartialSpecializationDecl
>(OldVar
));
5294 // If we are instantiating a local extern declaration, the
5295 // instantiation belongs lexically to the containing function.
5296 // If we are instantiating a static data member defined
5297 // out-of-line, the instantiation will have the same lexical
5298 // context (which will be a namespace scope) as the template.
5299 if (OldVar
->isLocalExternDecl()) {
5300 NewVar
->setLocalExternDecl();
5301 NewVar
->setLexicalDeclContext(Owner
);
5302 } else if (OldVar
->isOutOfLine())
5303 NewVar
->setLexicalDeclContext(OldVar
->getLexicalDeclContext());
5304 NewVar
->setTSCSpec(OldVar
->getTSCSpec());
5305 NewVar
->setInitStyle(OldVar
->getInitStyle());
5306 NewVar
->setCXXForRangeDecl(OldVar
->isCXXForRangeDecl());
5307 NewVar
->setObjCForDecl(OldVar
->isObjCForDecl());
5308 NewVar
->setConstexpr(OldVar
->isConstexpr());
5309 NewVar
->setInitCapture(OldVar
->isInitCapture());
5310 NewVar
->setPreviousDeclInSameBlockScope(
5311 OldVar
->isPreviousDeclInSameBlockScope());
5312 NewVar
->setAccess(OldVar
->getAccess());
5314 if (!OldVar
->isStaticDataMember()) {
5315 if (OldVar
->isUsed(false))
5316 NewVar
->setIsUsed();
5317 NewVar
->setReferenced(OldVar
->isReferenced());
5320 InstantiateAttrs(TemplateArgs
, OldVar
, NewVar
, LateAttrs
, StartingScope
);
5322 LookupResult
Previous(
5323 *this, NewVar
->getDeclName(), NewVar
->getLocation(),
5324 NewVar
->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
5325 : Sema::LookupOrdinaryName
,
5326 NewVar
->isLocalExternDecl() ? Sema::ForExternalRedeclaration
5327 : forRedeclarationInCurContext());
5329 if (NewVar
->isLocalExternDecl() && OldVar
->getPreviousDecl() &&
5330 (!OldVar
->getPreviousDecl()->getDeclContext()->isDependentContext() ||
5331 OldVar
->getPreviousDecl()->getDeclContext()==OldVar
->getDeclContext())) {
5332 // We have a previous declaration. Use that one, so we merge with the
5334 if (NamedDecl
*NewPrev
= FindInstantiatedDecl(
5335 NewVar
->getLocation(), OldVar
->getPreviousDecl(), TemplateArgs
))
5336 Previous
.addDecl(NewPrev
);
5337 } else if (!isa
<VarTemplateSpecializationDecl
>(NewVar
) &&
5338 OldVar
->hasLinkage()) {
5339 LookupQualifiedName(Previous
, NewVar
->getDeclContext(), false);
5340 } else if (PrevDeclForVarTemplateSpecialization
) {
5341 Previous
.addDecl(PrevDeclForVarTemplateSpecialization
);
5343 CheckVariableDeclaration(NewVar
, Previous
);
5345 if (!InstantiatingVarTemplate
) {
5346 NewVar
->getLexicalDeclContext()->addHiddenDecl(NewVar
);
5347 if (!NewVar
->isLocalExternDecl() || !NewVar
->getPreviousDecl())
5348 NewVar
->getDeclContext()->makeDeclVisibleInContext(NewVar
);
5351 if (!OldVar
->isOutOfLine()) {
5352 if (NewVar
->getDeclContext()->isFunctionOrMethod())
5353 CurrentInstantiationScope
->InstantiatedLocal(OldVar
, NewVar
);
5356 // Link instantiations of static data members back to the template from
5357 // which they were instantiated.
5359 // Don't do this when instantiating a template (we link the template itself
5360 // back in that case) nor when instantiating a static data member template
5361 // (that's not a member specialization).
5362 if (NewVar
->isStaticDataMember() && !InstantiatingVarTemplate
&&
5363 !InstantiatingSpecFromTemplate
)
5364 NewVar
->setInstantiationOfStaticDataMember(OldVar
,
5365 TSK_ImplicitInstantiation
);
5367 // If the pattern is an (in-class) explicit specialization, then the result
5368 // is also an explicit specialization.
5369 if (VarTemplateSpecializationDecl
*OldVTSD
=
5370 dyn_cast
<VarTemplateSpecializationDecl
>(OldVar
)) {
5371 if (OldVTSD
->getSpecializationKind() == TSK_ExplicitSpecialization
&&
5372 !isa
<VarTemplatePartialSpecializationDecl
>(OldVTSD
))
5373 cast
<VarTemplateSpecializationDecl
>(NewVar
)->setSpecializationKind(
5374 TSK_ExplicitSpecialization
);
5377 // Forward the mangling number from the template to the instantiated decl.
5378 Context
.setManglingNumber(NewVar
, Context
.getManglingNumber(OldVar
));
5379 Context
.setStaticLocalNumber(NewVar
, Context
.getStaticLocalNumber(OldVar
));
5381 // Figure out whether to eagerly instantiate the initializer.
5382 if (InstantiatingVarTemplate
|| InstantiatingVarTemplatePartialSpec
) {
5383 // We're producing a template. Don't instantiate the initializer yet.
5384 } else if (NewVar
->getType()->isUndeducedType()) {
5385 // We need the type to complete the declaration of the variable.
5386 InstantiateVariableInitializer(NewVar
, OldVar
, TemplateArgs
);
5387 } else if (InstantiatingSpecFromTemplate
||
5388 (OldVar
->isInline() && OldVar
->isThisDeclarationADefinition() &&
5389 !NewVar
->isThisDeclarationADefinition())) {
5390 // Delay instantiation of the initializer for variable template
5391 // specializations or inline static data members until a definition of the
5392 // variable is needed.
5394 InstantiateVariableInitializer(NewVar
, OldVar
, TemplateArgs
);
5397 // Diagnose unused local variables with dependent types, where the diagnostic
5398 // will have been deferred.
5399 if (!NewVar
->isInvalidDecl() &&
5400 NewVar
->getDeclContext()->isFunctionOrMethod() &&
5401 OldVar
->getType()->isDependentType())
5402 DiagnoseUnusedDecl(NewVar
);
5405 /// Instantiate the initializer of a variable.
5406 void Sema::InstantiateVariableInitializer(
5407 VarDecl
*Var
, VarDecl
*OldVar
,
5408 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
5409 if (ASTMutationListener
*L
= getASTContext().getASTMutationListener())
5410 L
->VariableDefinitionInstantiated(Var
);
5412 // We propagate the 'inline' flag with the initializer, because it
5413 // would otherwise imply that the variable is a definition for a
5414 // non-static data member.
5415 if (OldVar
->isInlineSpecified())
5416 Var
->setInlineSpecified();
5417 else if (OldVar
->isInline())
5418 Var
->setImplicitlyInline();
5420 if (OldVar
->getInit()) {
5421 EnterExpressionEvaluationContext
Evaluated(
5422 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated
, Var
);
5424 // Instantiate the initializer.
5428 ContextRAII
SwitchContext(*this, Var
->getDeclContext());
5429 Init
= SubstInitializer(OldVar
->getInit(), TemplateArgs
,
5430 OldVar
->getInitStyle() == VarDecl::CallInit
);
5433 if (!Init
.isInvalid()) {
5434 Expr
*InitExpr
= Init
.get();
5436 if (Var
->hasAttr
<DLLImportAttr
>() &&
5438 !InitExpr
->isConstantInitializer(getASTContext(), false))) {
5439 // Do not dynamically initialize dllimport variables.
5440 } else if (InitExpr
) {
5441 bool DirectInit
= OldVar
->isDirectInit();
5442 AddInitializerToDecl(Var
, InitExpr
, DirectInit
);
5444 ActOnUninitializedDecl(Var
);
5446 // FIXME: Not too happy about invalidating the declaration
5447 // because of a bogus initializer.
5448 Var
->setInvalidDecl();
5451 // `inline` variables are a definition and declaration all in one; we won't
5452 // pick up an initializer from anywhere else.
5453 if (Var
->isStaticDataMember() && !Var
->isInline()) {
5454 if (!Var
->isOutOfLine())
5457 // If the declaration inside the class had an initializer, don't add
5458 // another one to the out-of-line definition.
5459 if (OldVar
->getFirstDecl()->hasInit())
5463 // We'll add an initializer to a for-range declaration later.
5464 if (Var
->isCXXForRangeDecl() || Var
->isObjCForDecl())
5467 ActOnUninitializedDecl(Var
);
5470 if (getLangOpts().CUDA
)
5471 checkAllowedCUDAInitializer(Var
);
5474 /// Instantiate the definition of the given variable from its
5477 /// \param PointOfInstantiation the point at which the instantiation was
5478 /// required. Note that this is not precisely a "point of instantiation"
5479 /// for the variable, but it's close.
5481 /// \param Var the already-instantiated declaration of a templated variable.
5483 /// \param Recursive if true, recursively instantiates any functions that
5484 /// are required by this instantiation.
5486 /// \param DefinitionRequired if true, then we are performing an explicit
5487 /// instantiation where a definition of the variable is required. Complain
5488 /// if there is no such definition.
5489 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation
,
5490 VarDecl
*Var
, bool Recursive
,
5491 bool DefinitionRequired
, bool AtEndOfTU
) {
5492 if (Var
->isInvalidDecl())
5495 // Never instantiate an explicitly-specialized entity.
5496 TemplateSpecializationKind TSK
=
5497 Var
->getTemplateSpecializationKindForInstantiation();
5498 if (TSK
== TSK_ExplicitSpecialization
)
5501 // Find the pattern and the arguments to substitute into it.
5502 VarDecl
*PatternDecl
= Var
->getTemplateInstantiationPattern();
5503 assert(PatternDecl
&& "no pattern for templated variable");
5504 MultiLevelTemplateArgumentList TemplateArgs
=
5505 getTemplateInstantiationArgs(Var
);
5507 VarTemplateSpecializationDecl
*VarSpec
=
5508 dyn_cast
<VarTemplateSpecializationDecl
>(Var
);
5510 // If this is a static data member template, there might be an
5511 // uninstantiated initializer on the declaration. If so, instantiate
5514 // FIXME: This largely duplicates what we would do below. The difference
5515 // is that along this path we may instantiate an initializer from an
5516 // in-class declaration of the template and instantiate the definition
5517 // from a separate out-of-class definition.
5518 if (PatternDecl
->isStaticDataMember() &&
5519 (PatternDecl
= PatternDecl
->getFirstDecl())->hasInit() &&
5521 // FIXME: Factor out the duplicated instantiation context setup/tear down
5523 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, Var
);
5524 if (Inst
.isInvalid() || Inst
.isAlreadyInstantiating())
5526 PrettyDeclStackTraceEntry
CrashInfo(Context
, Var
, SourceLocation(),
5527 "instantiating variable initializer");
5529 // The instantiation is visible here, even if it was first declared in an
5530 // unimported module.
5531 Var
->setVisibleDespiteOwningModule();
5533 // If we're performing recursive template instantiation, create our own
5534 // queue of pending implicit instantiations that we will instantiate
5535 // later, while we're still within our own instantiation context.
5536 GlobalEagerInstantiationScope
GlobalInstantiations(*this,
5537 /*Enabled=*/Recursive
);
5538 LocalInstantiationScope
Local(*this);
5539 LocalEagerInstantiationScope
LocalInstantiations(*this);
5541 // Enter the scope of this instantiation. We don't use
5542 // PushDeclContext because we don't have a scope.
5543 ContextRAII
PreviousContext(*this, Var
->getDeclContext());
5544 InstantiateVariableInitializer(Var
, PatternDecl
, TemplateArgs
);
5545 PreviousContext
.pop();
5547 // This variable may have local implicit instantiations that need to be
5548 // instantiated within this scope.
5549 LocalInstantiations
.perform();
5551 GlobalInstantiations
.perform();
5554 assert(Var
->isStaticDataMember() && PatternDecl
->isStaticDataMember() &&
5555 "not a static data member?");
5558 VarDecl
*Def
= PatternDecl
->getDefinition(getASTContext());
5560 // If we don't have a definition of the variable template, we won't perform
5561 // any instantiation. Rather, we rely on the user to instantiate this
5562 // definition (or provide a specialization for it) in another translation
5564 if (!Def
&& !DefinitionRequired
) {
5565 if (TSK
== TSK_ExplicitInstantiationDefinition
) {
5566 PendingInstantiations
.push_back(
5567 std::make_pair(Var
, PointOfInstantiation
));
5568 } else if (TSK
== TSK_ImplicitInstantiation
) {
5569 // Warn about missing definition at the end of translation unit.
5570 if (AtEndOfTU
&& !getDiagnostics().hasErrorOccurred() &&
5571 !getSourceManager().isInSystemHeader(PatternDecl
->getBeginLoc())) {
5572 Diag(PointOfInstantiation
, diag::warn_var_template_missing
)
5574 Diag(PatternDecl
->getLocation(), diag::note_forward_template_decl
);
5575 if (getLangOpts().CPlusPlus11
)
5576 Diag(PointOfInstantiation
, diag::note_inst_declaration_hint
) << Var
;
5582 // FIXME: We need to track the instantiation stack in order to know which
5583 // definitions should be visible within this instantiation.
5584 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
5585 if (DiagnoseUninstantiableTemplate(PointOfInstantiation
, Var
,
5586 /*InstantiatedFromMember*/false,
5587 PatternDecl
, Def
, TSK
,
5588 /*Complain*/DefinitionRequired
))
5591 // C++11 [temp.explicit]p10:
5592 // Except for inline functions, const variables of literal types, variables
5593 // of reference types, [...] explicit instantiation declarations
5594 // have the effect of suppressing the implicit instantiation of the entity
5595 // to which they refer.
5597 // FIXME: That's not exactly the same as "might be usable in constant
5598 // expressions", which only allows constexpr variables and const integral
5599 // types, not arbitrary const literal types.
5600 if (TSK
== TSK_ExplicitInstantiationDeclaration
&&
5601 !Var
->mightBeUsableInConstantExpressions(getASTContext()))
5604 // Make sure to pass the instantiated variable to the consumer at the end.
5605 struct PassToConsumerRAII
{
5606 ASTConsumer
&Consumer
;
5609 PassToConsumerRAII(ASTConsumer
&Consumer
, VarDecl
*Var
)
5610 : Consumer(Consumer
), Var(Var
) { }
5612 ~PassToConsumerRAII() {
5613 Consumer
.HandleCXXStaticMemberVarInstantiation(Var
);
5615 } PassToConsumerRAII(Consumer
, Var
);
5617 // If we already have a definition, we're done.
5618 if (VarDecl
*Def
= Var
->getDefinition()) {
5619 // We may be explicitly instantiating something we've already implicitly
5621 Def
->setTemplateSpecializationKind(Var
->getTemplateSpecializationKind(),
5622 PointOfInstantiation
);
5626 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, Var
);
5627 if (Inst
.isInvalid() || Inst
.isAlreadyInstantiating())
5629 PrettyDeclStackTraceEntry
CrashInfo(Context
, Var
, SourceLocation(),
5630 "instantiating variable definition");
5632 // If we're performing recursive template instantiation, create our own
5633 // queue of pending implicit instantiations that we will instantiate later,
5634 // while we're still within our own instantiation context.
5635 GlobalEagerInstantiationScope
GlobalInstantiations(*this,
5636 /*Enabled=*/Recursive
);
5638 // Enter the scope of this instantiation. We don't use
5639 // PushDeclContext because we don't have a scope.
5640 ContextRAII
PreviousContext(*this, Var
->getDeclContext());
5641 LocalInstantiationScope
Local(*this);
5643 LocalEagerInstantiationScope
LocalInstantiations(*this);
5645 VarDecl
*OldVar
= Var
;
5646 if (Def
->isStaticDataMember() && !Def
->isOutOfLine()) {
5647 // We're instantiating an inline static data member whose definition was
5648 // provided inside the class.
5649 InstantiateVariableInitializer(Var
, Def
, TemplateArgs
);
5650 } else if (!VarSpec
) {
5651 Var
= cast_or_null
<VarDecl
>(SubstDecl(Def
, Var
->getDeclContext(),
5653 } else if (Var
->isStaticDataMember() &&
5654 Var
->getLexicalDeclContext()->isRecord()) {
5655 // We need to instantiate the definition of a static data member template,
5656 // and all we have is the in-class declaration of it. Instantiate a separate
5657 // declaration of the definition.
5658 TemplateDeclInstantiator
Instantiator(*this, Var
->getDeclContext(),
5661 TemplateArgumentListInfo TemplateArgInfo
;
5662 if (const ASTTemplateArgumentListInfo
*ArgInfo
=
5663 VarSpec
->getTemplateArgsInfo()) {
5664 TemplateArgInfo
.setLAngleLoc(ArgInfo
->getLAngleLoc());
5665 TemplateArgInfo
.setRAngleLoc(ArgInfo
->getRAngleLoc());
5666 for (const TemplateArgumentLoc
&Arg
: ArgInfo
->arguments())
5667 TemplateArgInfo
.addArgument(Arg
);
5670 Var
= cast_or_null
<VarDecl
>(Instantiator
.VisitVarTemplateSpecializationDecl(
5671 VarSpec
->getSpecializedTemplate(), Def
, TemplateArgInfo
,
5672 VarSpec
->getTemplateArgs().asArray(), VarSpec
));
5674 llvm::PointerUnion
<VarTemplateDecl
*,
5675 VarTemplatePartialSpecializationDecl
*> PatternPtr
=
5676 VarSpec
->getSpecializedTemplateOrPartial();
5677 if (VarTemplatePartialSpecializationDecl
*Partial
=
5678 PatternPtr
.dyn_cast
<VarTemplatePartialSpecializationDecl
*>())
5679 cast
<VarTemplateSpecializationDecl
>(Var
)->setInstantiationOf(
5680 Partial
, &VarSpec
->getTemplateInstantiationArgs());
5682 // Attach the initializer.
5683 InstantiateVariableInitializer(Var
, Def
, TemplateArgs
);
5686 // Complete the existing variable's definition with an appropriately
5687 // substituted type and initializer.
5688 Var
= CompleteVarTemplateSpecializationDecl(VarSpec
, Def
, TemplateArgs
);
5690 PreviousContext
.pop();
5693 PassToConsumerRAII
.Var
= Var
;
5694 Var
->setTemplateSpecializationKind(OldVar
->getTemplateSpecializationKind(),
5695 OldVar
->getPointOfInstantiation());
5698 // This variable may have local implicit instantiations that need to be
5699 // instantiated within this scope.
5700 LocalInstantiations
.perform();
5702 GlobalInstantiations
.perform();
5706 Sema::InstantiateMemInitializers(CXXConstructorDecl
*New
,
5707 const CXXConstructorDecl
*Tmpl
,
5708 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
5710 SmallVector
<CXXCtorInitializer
*, 4> NewInits
;
5711 bool AnyErrors
= Tmpl
->isInvalidDecl();
5713 // Instantiate all the initializers.
5714 for (const auto *Init
: Tmpl
->inits()) {
5715 // Only instantiate written initializers, let Sema re-construct implicit
5717 if (!Init
->isWritten())
5720 SourceLocation EllipsisLoc
;
5722 if (Init
->isPackExpansion()) {
5723 // This is a pack expansion. We should expand it now.
5724 TypeLoc BaseTL
= Init
->getTypeSourceInfo()->getTypeLoc();
5725 SmallVector
<UnexpandedParameterPack
, 4> Unexpanded
;
5726 collectUnexpandedParameterPacks(BaseTL
, Unexpanded
);
5727 collectUnexpandedParameterPacks(Init
->getInit(), Unexpanded
);
5728 bool ShouldExpand
= false;
5729 bool RetainExpansion
= false;
5730 std::optional
<unsigned> NumExpansions
;
5731 if (CheckParameterPacksForExpansion(Init
->getEllipsisLoc(),
5732 BaseTL
.getSourceRange(),
5734 TemplateArgs
, ShouldExpand
,
5738 New
->setInvalidDecl();
5741 assert(ShouldExpand
&& "Partial instantiation of base initializer?");
5743 // Loop over all of the arguments in the argument pack(s),
5744 for (unsigned I
= 0; I
!= *NumExpansions
; ++I
) {
5745 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(*this, I
);
5747 // Instantiate the initializer.
5748 ExprResult TempInit
= SubstInitializer(Init
->getInit(), TemplateArgs
,
5749 /*CXXDirectInit=*/true);
5750 if (TempInit
.isInvalid()) {
5755 // Instantiate the base type.
5756 TypeSourceInfo
*BaseTInfo
= SubstType(Init
->getTypeSourceInfo(),
5758 Init
->getSourceLocation(),
5759 New
->getDeclName());
5765 // Build the initializer.
5766 MemInitResult NewInit
= BuildBaseInitializer(BaseTInfo
->getType(),
5767 BaseTInfo
, TempInit
.get(),
5770 if (NewInit
.isInvalid()) {
5775 NewInits
.push_back(NewInit
.get());
5781 // Instantiate the initializer.
5782 ExprResult TempInit
= SubstInitializer(Init
->getInit(), TemplateArgs
,
5783 /*CXXDirectInit=*/true);
5784 if (TempInit
.isInvalid()) {
5789 MemInitResult NewInit
;
5790 if (Init
->isDelegatingInitializer() || Init
->isBaseInitializer()) {
5791 TypeSourceInfo
*TInfo
= SubstType(Init
->getTypeSourceInfo(),
5793 Init
->getSourceLocation(),
5794 New
->getDeclName());
5797 New
->setInvalidDecl();
5801 if (Init
->isBaseInitializer())
5802 NewInit
= BuildBaseInitializer(TInfo
->getType(), TInfo
, TempInit
.get(),
5803 New
->getParent(), EllipsisLoc
);
5805 NewInit
= BuildDelegatingInitializer(TInfo
, TempInit
.get(),
5806 cast
<CXXRecordDecl
>(CurContext
->getParent()));
5807 } else if (Init
->isMemberInitializer()) {
5808 FieldDecl
*Member
= cast_or_null
<FieldDecl
>(FindInstantiatedDecl(
5809 Init
->getMemberLocation(),
5814 New
->setInvalidDecl();
5818 NewInit
= BuildMemberInitializer(Member
, TempInit
.get(),
5819 Init
->getSourceLocation());
5820 } else if (Init
->isIndirectMemberInitializer()) {
5821 IndirectFieldDecl
*IndirectMember
=
5822 cast_or_null
<IndirectFieldDecl
>(FindInstantiatedDecl(
5823 Init
->getMemberLocation(),
5824 Init
->getIndirectMember(), TemplateArgs
));
5826 if (!IndirectMember
) {
5828 New
->setInvalidDecl();
5832 NewInit
= BuildMemberInitializer(IndirectMember
, TempInit
.get(),
5833 Init
->getSourceLocation());
5836 if (NewInit
.isInvalid()) {
5838 New
->setInvalidDecl();
5840 NewInits
.push_back(NewInit
.get());
5844 // Assign all the initializers to the new constructor.
5845 ActOnMemInitializers(New
,
5846 /*FIXME: ColonLoc */
5852 // TODO: this could be templated if the various decl types used the
5853 // same method name.
5854 static bool isInstantiationOf(ClassTemplateDecl
*Pattern
,
5855 ClassTemplateDecl
*Instance
) {
5856 Pattern
= Pattern
->getCanonicalDecl();
5859 Instance
= Instance
->getCanonicalDecl();
5860 if (Pattern
== Instance
) return true;
5861 Instance
= Instance
->getInstantiatedFromMemberTemplate();
5867 static bool isInstantiationOf(FunctionTemplateDecl
*Pattern
,
5868 FunctionTemplateDecl
*Instance
) {
5869 Pattern
= Pattern
->getCanonicalDecl();
5872 Instance
= Instance
->getCanonicalDecl();
5873 if (Pattern
== Instance
) return true;
5874 Instance
= Instance
->getInstantiatedFromMemberTemplate();
5881 isInstantiationOf(ClassTemplatePartialSpecializationDecl
*Pattern
,
5882 ClassTemplatePartialSpecializationDecl
*Instance
) {
5884 = cast
<ClassTemplatePartialSpecializationDecl
>(Pattern
->getCanonicalDecl());
5886 Instance
= cast
<ClassTemplatePartialSpecializationDecl
>(
5887 Instance
->getCanonicalDecl());
5888 if (Pattern
== Instance
)
5890 Instance
= Instance
->getInstantiatedFromMember();
5896 static bool isInstantiationOf(CXXRecordDecl
*Pattern
,
5897 CXXRecordDecl
*Instance
) {
5898 Pattern
= Pattern
->getCanonicalDecl();
5901 Instance
= Instance
->getCanonicalDecl();
5902 if (Pattern
== Instance
) return true;
5903 Instance
= Instance
->getInstantiatedFromMemberClass();
5909 static bool isInstantiationOf(FunctionDecl
*Pattern
,
5910 FunctionDecl
*Instance
) {
5911 Pattern
= Pattern
->getCanonicalDecl();
5914 Instance
= Instance
->getCanonicalDecl();
5915 if (Pattern
== Instance
) return true;
5916 Instance
= Instance
->getInstantiatedFromMemberFunction();
5922 static bool isInstantiationOf(EnumDecl
*Pattern
,
5923 EnumDecl
*Instance
) {
5924 Pattern
= Pattern
->getCanonicalDecl();
5927 Instance
= Instance
->getCanonicalDecl();
5928 if (Pattern
== Instance
) return true;
5929 Instance
= Instance
->getInstantiatedFromMemberEnum();
5935 static bool isInstantiationOf(UsingShadowDecl
*Pattern
,
5936 UsingShadowDecl
*Instance
,
5938 return declaresSameEntity(C
.getInstantiatedFromUsingShadowDecl(Instance
),
5942 static bool isInstantiationOf(UsingDecl
*Pattern
, UsingDecl
*Instance
,
5944 return declaresSameEntity(C
.getInstantiatedFromUsingDecl(Instance
), Pattern
);
5947 template<typename T
>
5948 static bool isInstantiationOfUnresolvedUsingDecl(T
*Pattern
, Decl
*Other
,
5950 // An unresolved using declaration can instantiate to an unresolved using
5951 // declaration, or to a using declaration or a using declaration pack.
5953 // Multiple declarations can claim to be instantiated from an unresolved
5954 // using declaration if it's a pack expansion. We want the UsingPackDecl
5955 // in that case, not the individual UsingDecls within the pack.
5956 bool OtherIsPackExpansion
;
5957 NamedDecl
*OtherFrom
;
5958 if (auto *OtherUUD
= dyn_cast
<T
>(Other
)) {
5959 OtherIsPackExpansion
= OtherUUD
->isPackExpansion();
5960 OtherFrom
= Ctx
.getInstantiatedFromUsingDecl(OtherUUD
);
5961 } else if (auto *OtherUPD
= dyn_cast
<UsingPackDecl
>(Other
)) {
5962 OtherIsPackExpansion
= true;
5963 OtherFrom
= OtherUPD
->getInstantiatedFromUsingDecl();
5964 } else if (auto *OtherUD
= dyn_cast
<UsingDecl
>(Other
)) {
5965 OtherIsPackExpansion
= false;
5966 OtherFrom
= Ctx
.getInstantiatedFromUsingDecl(OtherUD
);
5970 return Pattern
->isPackExpansion() == OtherIsPackExpansion
&&
5971 declaresSameEntity(OtherFrom
, Pattern
);
5974 static bool isInstantiationOfStaticDataMember(VarDecl
*Pattern
,
5975 VarDecl
*Instance
) {
5976 assert(Instance
->isStaticDataMember());
5978 Pattern
= Pattern
->getCanonicalDecl();
5981 Instance
= Instance
->getCanonicalDecl();
5982 if (Pattern
== Instance
) return true;
5983 Instance
= Instance
->getInstantiatedFromStaticDataMember();
5989 // Other is the prospective instantiation
5990 // D is the prospective pattern
5991 static bool isInstantiationOf(ASTContext
&Ctx
, NamedDecl
*D
, Decl
*Other
) {
5992 if (auto *UUD
= dyn_cast
<UnresolvedUsingTypenameDecl
>(D
))
5993 return isInstantiationOfUnresolvedUsingDecl(UUD
, Other
, Ctx
);
5995 if (auto *UUD
= dyn_cast
<UnresolvedUsingValueDecl
>(D
))
5996 return isInstantiationOfUnresolvedUsingDecl(UUD
, Other
, Ctx
);
5998 if (D
->getKind() != Other
->getKind())
6001 if (auto *Record
= dyn_cast
<CXXRecordDecl
>(Other
))
6002 return isInstantiationOf(cast
<CXXRecordDecl
>(D
), Record
);
6004 if (auto *Function
= dyn_cast
<FunctionDecl
>(Other
))
6005 return isInstantiationOf(cast
<FunctionDecl
>(D
), Function
);
6007 if (auto *Enum
= dyn_cast
<EnumDecl
>(Other
))
6008 return isInstantiationOf(cast
<EnumDecl
>(D
), Enum
);
6010 if (auto *Var
= dyn_cast
<VarDecl
>(Other
))
6011 if (Var
->isStaticDataMember())
6012 return isInstantiationOfStaticDataMember(cast
<VarDecl
>(D
), Var
);
6014 if (auto *Temp
= dyn_cast
<ClassTemplateDecl
>(Other
))
6015 return isInstantiationOf(cast
<ClassTemplateDecl
>(D
), Temp
);
6017 if (auto *Temp
= dyn_cast
<FunctionTemplateDecl
>(Other
))
6018 return isInstantiationOf(cast
<FunctionTemplateDecl
>(D
), Temp
);
6020 if (auto *PartialSpec
=
6021 dyn_cast
<ClassTemplatePartialSpecializationDecl
>(Other
))
6022 return isInstantiationOf(cast
<ClassTemplatePartialSpecializationDecl
>(D
),
6025 if (auto *Field
= dyn_cast
<FieldDecl
>(Other
)) {
6026 if (!Field
->getDeclName()) {
6027 // This is an unnamed field.
6028 return declaresSameEntity(Ctx
.getInstantiatedFromUnnamedFieldDecl(Field
),
6029 cast
<FieldDecl
>(D
));
6033 if (auto *Using
= dyn_cast
<UsingDecl
>(Other
))
6034 return isInstantiationOf(cast
<UsingDecl
>(D
), Using
, Ctx
);
6036 if (auto *Shadow
= dyn_cast
<UsingShadowDecl
>(Other
))
6037 return isInstantiationOf(cast
<UsingShadowDecl
>(D
), Shadow
, Ctx
);
6039 return D
->getDeclName() &&
6040 D
->getDeclName() == cast
<NamedDecl
>(Other
)->getDeclName();
6043 template<typename ForwardIterator
>
6044 static NamedDecl
*findInstantiationOf(ASTContext
&Ctx
,
6046 ForwardIterator first
,
6047 ForwardIterator last
) {
6048 for (; first
!= last
; ++first
)
6049 if (isInstantiationOf(Ctx
, D
, *first
))
6050 return cast
<NamedDecl
>(*first
);
6055 /// Finds the instantiation of the given declaration context
6056 /// within the current instantiation.
6058 /// \returns NULL if there was an error
6059 DeclContext
*Sema::FindInstantiatedContext(SourceLocation Loc
, DeclContext
* DC
,
6060 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
6061 if (NamedDecl
*D
= dyn_cast
<NamedDecl
>(DC
)) {
6062 Decl
* ID
= FindInstantiatedDecl(Loc
, D
, TemplateArgs
, true);
6063 return cast_or_null
<DeclContext
>(ID
);
6067 /// Determine whether the given context is dependent on template parameters at
6068 /// level \p Level or below.
6070 /// Sometimes we only substitute an inner set of template arguments and leave
6071 /// the outer templates alone. In such cases, contexts dependent only on the
6072 /// outer levels are not effectively dependent.
6073 static bool isDependentContextAtLevel(DeclContext
*DC
, unsigned Level
) {
6074 if (!DC
->isDependentContext())
6078 return cast
<Decl
>(DC
)->getTemplateDepth() > Level
;
6081 /// Find the instantiation of the given declaration within the
6082 /// current instantiation.
6084 /// This routine is intended to be used when \p D is a declaration
6085 /// referenced from within a template, that needs to mapped into the
6086 /// corresponding declaration within an instantiation. For example,
6090 /// template<typename T>
6093 /// KnownValue = sizeof(T)
6096 /// bool getKind() const { return KnownValue; }
6099 /// template struct X<int>;
6102 /// In the instantiation of X<int>::getKind(), we need to map the \p
6103 /// EnumConstantDecl for \p KnownValue (which refers to
6104 /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
6105 /// \p FindInstantiatedDecl performs this mapping from within the instantiation
6107 NamedDecl
*Sema::FindInstantiatedDecl(SourceLocation Loc
, NamedDecl
*D
,
6108 const MultiLevelTemplateArgumentList
&TemplateArgs
,
6109 bool FindingInstantiatedContext
) {
6110 DeclContext
*ParentDC
= D
->getDeclContext();
6111 // Determine whether our parent context depends on any of the template
6112 // arguments we're currently substituting.
6113 bool ParentDependsOnArgs
= isDependentContextAtLevel(
6114 ParentDC
, TemplateArgs
.getNumRetainedOuterLevels());
6115 // FIXME: Parameters of pointer to functions (y below) that are themselves
6116 // parameters (p below) can have their ParentDC set to the translation-unit
6117 // - thus we can not consistently check if the ParentDC of such a parameter
6118 // is Dependent or/and a FunctionOrMethod.
6119 // For e.g. this code, during Template argument deduction tries to
6120 // find an instantiated decl for (T y) when the ParentDC for y is
6121 // the translation unit.
6122 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6123 // float baz(float(*)()) { return 0.0; }
6125 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6126 // it gets here, always has a FunctionOrMethod as its ParentDC??
6128 // - as long as we have a ParmVarDecl whose parent is non-dependent and
6129 // whose type is not instantiation dependent, do nothing to the decl
6130 // - otherwise find its instantiated decl.
6131 if (isa
<ParmVarDecl
>(D
) && !ParentDependsOnArgs
&&
6132 !cast
<ParmVarDecl
>(D
)->getType()->isInstantiationDependentType())
6134 if (isa
<ParmVarDecl
>(D
) || isa
<NonTypeTemplateParmDecl
>(D
) ||
6135 isa
<TemplateTypeParmDecl
>(D
) || isa
<TemplateTemplateParmDecl
>(D
) ||
6136 (ParentDependsOnArgs
&& (ParentDC
->isFunctionOrMethod() ||
6137 isa
<OMPDeclareReductionDecl
>(ParentDC
) ||
6138 isa
<OMPDeclareMapperDecl
>(ParentDC
))) ||
6139 (isa
<CXXRecordDecl
>(D
) && cast
<CXXRecordDecl
>(D
)->isLambda() &&
6140 cast
<CXXRecordDecl
>(D
)->getTemplateDepth() >
6141 TemplateArgs
.getNumRetainedOuterLevels())) {
6142 // D is a local of some kind. Look into the map of local
6143 // declarations to their instantiations.
6144 if (CurrentInstantiationScope
) {
6145 if (auto Found
= CurrentInstantiationScope
->findInstantiationOf(D
)) {
6146 if (Decl
*FD
= Found
->dyn_cast
<Decl
*>())
6147 return cast
<NamedDecl
>(FD
);
6149 int PackIdx
= ArgumentPackSubstitutionIndex
;
6150 assert(PackIdx
!= -1 &&
6151 "found declaration pack but not pack expanding");
6152 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack
;
6153 return cast
<NamedDecl
>((*Found
->get
<DeclArgumentPack
*>())[PackIdx
]);
6157 // If we're performing a partial substitution during template argument
6158 // deduction, we may not have values for template parameters yet. They
6159 // just map to themselves.
6160 if (isa
<NonTypeTemplateParmDecl
>(D
) || isa
<TemplateTypeParmDecl
>(D
) ||
6161 isa
<TemplateTemplateParmDecl
>(D
))
6164 if (D
->isInvalidDecl())
6167 // Normally this function only searches for already instantiated declaration
6168 // however we have to make an exclusion for local types used before
6169 // definition as in the code:
6171 // template<typename T> void f1() {
6172 // void g1(struct x1);
6176 // In this case instantiation of the type of 'g1' requires definition of
6177 // 'x1', which is defined later. Error recovery may produce an enum used
6178 // before definition. In these cases we need to instantiate relevant
6179 // declarations here.
6180 bool NeedInstantiate
= false;
6181 if (CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(D
))
6182 NeedInstantiate
= RD
->isLocalClass();
6183 else if (isa
<TypedefNameDecl
>(D
) &&
6184 isa
<CXXDeductionGuideDecl
>(D
->getDeclContext()))
6185 NeedInstantiate
= true;
6187 NeedInstantiate
= isa
<EnumDecl
>(D
);
6188 if (NeedInstantiate
) {
6189 Decl
*Inst
= SubstDecl(D
, CurContext
, TemplateArgs
);
6190 CurrentInstantiationScope
->InstantiatedLocal(D
, Inst
);
6191 return cast
<TypeDecl
>(Inst
);
6194 // If we didn't find the decl, then we must have a label decl that hasn't
6195 // been found yet. Lazily instantiate it and return it now.
6196 assert(isa
<LabelDecl
>(D
));
6198 Decl
*Inst
= SubstDecl(D
, CurContext
, TemplateArgs
);
6199 assert(Inst
&& "Failed to instantiate label??");
6201 CurrentInstantiationScope
->InstantiatedLocal(D
, Inst
);
6202 return cast
<LabelDecl
>(Inst
);
6205 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(D
)) {
6206 if (!Record
->isDependentContext())
6209 // Determine whether this record is the "templated" declaration describing
6210 // a class template or class template partial specialization.
6211 ClassTemplateDecl
*ClassTemplate
= Record
->getDescribedClassTemplate();
6213 ClassTemplate
= ClassTemplate
->getCanonicalDecl();
6214 else if (ClassTemplatePartialSpecializationDecl
*PartialSpec
6215 = dyn_cast
<ClassTemplatePartialSpecializationDecl
>(Record
))
6216 ClassTemplate
= PartialSpec
->getSpecializedTemplate()->getCanonicalDecl();
6218 // Walk the current context to find either the record or an instantiation of
6220 DeclContext
*DC
= CurContext
;
6221 while (!DC
->isFileContext()) {
6222 // If we're performing substitution while we're inside the template
6223 // definition, we'll find our own context. We're done.
6224 if (DC
->Equals(Record
))
6227 if (CXXRecordDecl
*InstRecord
= dyn_cast
<CXXRecordDecl
>(DC
)) {
6228 // Check whether we're in the process of instantiating a class template
6229 // specialization of the template we're mapping.
6230 if (ClassTemplateSpecializationDecl
*InstSpec
6231 = dyn_cast
<ClassTemplateSpecializationDecl
>(InstRecord
)){
6232 ClassTemplateDecl
*SpecTemplate
= InstSpec
->getSpecializedTemplate();
6233 if (ClassTemplate
&& isInstantiationOf(ClassTemplate
, SpecTemplate
))
6237 // Check whether we're in the process of instantiating a member class.
6238 if (isInstantiationOf(Record
, InstRecord
))
6242 // Move to the outer template scope.
6243 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(DC
)) {
6244 if (FD
->getFriendObjectKind() &&
6245 FD
->getNonTransparentDeclContext()->isFileContext()) {
6246 DC
= FD
->getLexicalDeclContext();
6249 // An implicit deduction guide acts as if it's within the class template
6250 // specialization described by its name and first N template params.
6251 auto *Guide
= dyn_cast
<CXXDeductionGuideDecl
>(FD
);
6252 if (Guide
&& Guide
->isImplicit()) {
6253 TemplateDecl
*TD
= Guide
->getDeducedTemplate();
6254 // Convert the arguments to an "as-written" list.
6255 TemplateArgumentListInfo
Args(Loc
, Loc
);
6256 for (TemplateArgument Arg
: TemplateArgs
.getInnermost().take_front(
6257 TD
->getTemplateParameters()->size())) {
6258 ArrayRef
<TemplateArgument
> Unpacked(Arg
);
6259 if (Arg
.getKind() == TemplateArgument::Pack
)
6260 Unpacked
= Arg
.pack_elements();
6261 for (TemplateArgument UnpackedArg
: Unpacked
)
6263 getTrivialTemplateArgumentLoc(UnpackedArg
, QualType(), Loc
));
6265 QualType T
= CheckTemplateIdType(TemplateName(TD
), Loc
, Args
);
6268 auto *SubstRecord
= T
->getAsCXXRecordDecl();
6269 assert(SubstRecord
&& "class template id not a class type?");
6270 // Check that this template-id names the primary template and not a
6271 // partial or explicit specialization. (In the latter cases, it's
6272 // meaningless to attempt to find an instantiation of D within the
6274 // FIXME: The standard doesn't say what should happen here.
6275 if (FindingInstantiatedContext
&&
6276 usesPartialOrExplicitSpecialization(
6277 Loc
, cast
<ClassTemplateSpecializationDecl
>(SubstRecord
))) {
6278 Diag(Loc
, diag::err_specialization_not_primary_template
)
6279 << T
<< (SubstRecord
->getTemplateSpecializationKind() ==
6280 TSK_ExplicitSpecialization
);
6288 DC
= DC
->getParent();
6291 // Fall through to deal with other dependent record types (e.g.,
6292 // anonymous unions in class templates).
6295 if (!ParentDependsOnArgs
)
6298 ParentDC
= FindInstantiatedContext(Loc
, ParentDC
, TemplateArgs
);
6302 if (ParentDC
!= D
->getDeclContext()) {
6303 // We performed some kind of instantiation in the parent context,
6304 // so now we need to look into the instantiated parent context to
6305 // find the instantiation of the declaration D.
6307 // If our context used to be dependent, we may need to instantiate
6308 // it before performing lookup into that context.
6309 bool IsBeingInstantiated
= false;
6310 if (CXXRecordDecl
*Spec
= dyn_cast
<CXXRecordDecl
>(ParentDC
)) {
6311 if (!Spec
->isDependentContext()) {
6312 QualType T
= Context
.getTypeDeclType(Spec
);
6313 const RecordType
*Tag
= T
->getAs
<RecordType
>();
6314 assert(Tag
&& "type of non-dependent record is not a RecordType");
6315 if (Tag
->isBeingDefined())
6316 IsBeingInstantiated
= true;
6317 if (!Tag
->isBeingDefined() &&
6318 RequireCompleteType(Loc
, T
, diag::err_incomplete_type
))
6321 ParentDC
= Tag
->getDecl();
6325 NamedDecl
*Result
= nullptr;
6326 // FIXME: If the name is a dependent name, this lookup won't necessarily
6327 // find it. Does that ever matter?
6328 if (auto Name
= D
->getDeclName()) {
6329 DeclarationNameInfo
NameInfo(Name
, D
->getLocation());
6330 DeclarationNameInfo NewNameInfo
=
6331 SubstDeclarationNameInfo(NameInfo
, TemplateArgs
);
6332 Name
= NewNameInfo
.getName();
6335 DeclContext::lookup_result Found
= ParentDC
->lookup(Name
);
6337 Result
= findInstantiationOf(Context
, D
, Found
.begin(), Found
.end());
6339 // Since we don't have a name for the entity we're looking for,
6340 // our only option is to walk through all of the declarations to
6341 // find that name. This will occur in a few cases:
6343 // - anonymous struct/union within a template
6344 // - unnamed class/struct/union/enum within a template
6346 // FIXME: Find a better way to find these instantiations!
6347 Result
= findInstantiationOf(Context
, D
,
6348 ParentDC
->decls_begin(),
6349 ParentDC
->decls_end());
6353 if (isa
<UsingShadowDecl
>(D
)) {
6354 // UsingShadowDecls can instantiate to nothing because of using hiding.
6355 } else if (hasUncompilableErrorOccurred()) {
6356 // We've already complained about some ill-formed code, so most likely
6357 // this declaration failed to instantiate. There's no point in
6358 // complaining further, since this is normal in invalid code.
6359 // FIXME: Use more fine-grained 'invalid' tracking for this.
6360 } else if (IsBeingInstantiated
) {
6361 // The class in which this member exists is currently being
6362 // instantiated, and we haven't gotten around to instantiating this
6363 // member yet. This can happen when the code uses forward declarations
6364 // of member classes, and introduces ordering dependencies via
6365 // template instantiation.
6366 Diag(Loc
, diag::err_member_not_yet_instantiated
)
6368 << Context
.getTypeDeclType(cast
<CXXRecordDecl
>(ParentDC
));
6369 Diag(D
->getLocation(), diag::note_non_instantiated_member_here
);
6370 } else if (EnumConstantDecl
*ED
= dyn_cast
<EnumConstantDecl
>(D
)) {
6371 // This enumeration constant was found when the template was defined,
6372 // but can't be found in the instantiation. This can happen if an
6373 // unscoped enumeration member is explicitly specialized.
6374 EnumDecl
*Enum
= cast
<EnumDecl
>(ED
->getLexicalDeclContext());
6375 EnumDecl
*Spec
= cast
<EnumDecl
>(FindInstantiatedDecl(Loc
, Enum
,
6377 assert(Spec
->getTemplateSpecializationKind() ==
6378 TSK_ExplicitSpecialization
);
6379 Diag(Loc
, diag::err_enumerator_does_not_exist
)
6381 << Context
.getTypeDeclType(cast
<TypeDecl
>(Spec
->getDeclContext()));
6382 Diag(Spec
->getLocation(), diag::note_enum_specialized_here
)
6383 << Context
.getTypeDeclType(Spec
);
6385 // We should have found something, but didn't.
6386 llvm_unreachable("Unable to find instantiation of declaration!");
6396 /// Performs template instantiation for all implicit template
6397 /// instantiations we have seen until this point.
6398 void Sema::PerformPendingInstantiations(bool LocalOnly
) {
6399 std::deque
<PendingImplicitInstantiation
> delayedPCHInstantiations
;
6400 while (!PendingLocalImplicitInstantiations
.empty() ||
6401 (!LocalOnly
&& !PendingInstantiations
.empty())) {
6402 PendingImplicitInstantiation Inst
;
6404 if (PendingLocalImplicitInstantiations
.empty()) {
6405 Inst
= PendingInstantiations
.front();
6406 PendingInstantiations
.pop_front();
6408 Inst
= PendingLocalImplicitInstantiations
.front();
6409 PendingLocalImplicitInstantiations
.pop_front();
6412 // Instantiate function definitions
6413 if (FunctionDecl
*Function
= dyn_cast
<FunctionDecl
>(Inst
.first
)) {
6414 bool DefinitionRequired
= Function
->getTemplateSpecializationKind() ==
6415 TSK_ExplicitInstantiationDefinition
;
6416 if (Function
->isMultiVersion()) {
6417 getASTContext().forEachMultiversionedFunctionVersion(
6418 Function
, [this, Inst
, DefinitionRequired
](FunctionDecl
*CurFD
) {
6419 InstantiateFunctionDefinition(/*FIXME:*/ Inst
.second
, CurFD
, true,
6420 DefinitionRequired
, true);
6421 if (CurFD
->isDefined())
6422 CurFD
->setInstantiationIsPending(false);
6425 InstantiateFunctionDefinition(/*FIXME:*/ Inst
.second
, Function
, true,
6426 DefinitionRequired
, true);
6427 if (Function
->isDefined())
6428 Function
->setInstantiationIsPending(false);
6430 // Definition of a PCH-ed template declaration may be available only in the TU.
6431 if (!LocalOnly
&& LangOpts
.PCHInstantiateTemplates
&&
6432 TUKind
== TU_Prefix
&& Function
->instantiationIsPending())
6433 delayedPCHInstantiations
.push_back(Inst
);
6437 // Instantiate variable definitions
6438 VarDecl
*Var
= cast
<VarDecl
>(Inst
.first
);
6440 assert((Var
->isStaticDataMember() ||
6441 isa
<VarTemplateSpecializationDecl
>(Var
)) &&
6442 "Not a static data member, nor a variable template"
6443 " specialization?");
6445 // Don't try to instantiate declarations if the most recent redeclaration
6447 if (Var
->getMostRecentDecl()->isInvalidDecl())
6450 // Check if the most recent declaration has changed the specialization kind
6451 // and removed the need for implicit instantiation.
6452 switch (Var
->getMostRecentDecl()
6453 ->getTemplateSpecializationKindForInstantiation()) {
6454 case TSK_Undeclared
:
6455 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
6456 case TSK_ExplicitInstantiationDeclaration
:
6457 case TSK_ExplicitSpecialization
:
6458 continue; // No longer need to instantiate this type.
6459 case TSK_ExplicitInstantiationDefinition
:
6460 // We only need an instantiation if the pending instantiation *is* the
6461 // explicit instantiation.
6462 if (Var
!= Var
->getMostRecentDecl())
6465 case TSK_ImplicitInstantiation
:
6469 PrettyDeclStackTraceEntry
CrashInfo(Context
, Var
, SourceLocation(),
6470 "instantiating variable definition");
6471 bool DefinitionRequired
= Var
->getTemplateSpecializationKind() ==
6472 TSK_ExplicitInstantiationDefinition
;
6474 // Instantiate static data member definitions or variable template
6476 InstantiateVariableDefinition(/*FIXME:*/ Inst
.second
, Var
, true,
6477 DefinitionRequired
, true);
6480 if (!LocalOnly
&& LangOpts
.PCHInstantiateTemplates
)
6481 PendingInstantiations
.swap(delayedPCHInstantiations
);
6484 void Sema::PerformDependentDiagnostics(const DeclContext
*Pattern
,
6485 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
6486 for (auto *DD
: Pattern
->ddiags()) {
6487 switch (DD
->getKind()) {
6488 case DependentDiagnostic::Access
:
6489 HandleDependentAccessCheck(*DD
, TemplateArgs
);