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 static void instantiateDependentHLSLParamModifierAttr(
667 Sema
&S
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
668 const HLSLParamModifierAttr
*Attr
, Decl
*New
) {
669 ParmVarDecl
*P
= cast
<ParmVarDecl
>(New
);
670 P
->addAttr(Attr
->clone(S
.getASTContext()));
671 P
->setType(S
.getASTContext().getLValueReferenceType(P
->getType()));
674 void Sema::InstantiateAttrsForDecl(
675 const MultiLevelTemplateArgumentList
&TemplateArgs
, const Decl
*Tmpl
,
676 Decl
*New
, LateInstantiatedAttrVec
*LateAttrs
,
677 LocalInstantiationScope
*OuterMostScope
) {
678 if (NamedDecl
*ND
= dyn_cast
<NamedDecl
>(New
)) {
679 // FIXME: This function is called multiple times for the same template
680 // specialization. We should only instantiate attributes that were added
681 // since the previous instantiation.
682 for (const auto *TmplAttr
: Tmpl
->attrs()) {
683 if (!isRelevantAttr(*this, New
, TmplAttr
))
686 // FIXME: If any of the special case versions from InstantiateAttrs become
687 // applicable to template declaration, we'll need to add them here.
688 CXXThisScopeRAII
ThisScope(
689 *this, dyn_cast_or_null
<CXXRecordDecl
>(ND
->getDeclContext()),
690 Qualifiers(), ND
->isCXXInstanceMember());
692 Attr
*NewAttr
= sema::instantiateTemplateAttributeForDecl(
693 TmplAttr
, Context
, *this, TemplateArgs
);
694 if (NewAttr
&& isRelevantAttr(*this, New
, NewAttr
))
695 New
->addAttr(NewAttr
);
700 static Sema::RetainOwnershipKind
701 attrToRetainOwnershipKind(const Attr
*A
) {
702 switch (A
->getKind()) {
703 case clang::attr::CFConsumed
:
704 return Sema::RetainOwnershipKind::CF
;
705 case clang::attr::OSConsumed
:
706 return Sema::RetainOwnershipKind::OS
;
707 case clang::attr::NSConsumed
:
708 return Sema::RetainOwnershipKind::NS
;
710 llvm_unreachable("Wrong argument supplied");
714 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList
&TemplateArgs
,
715 const Decl
*Tmpl
, Decl
*New
,
716 LateInstantiatedAttrVec
*LateAttrs
,
717 LocalInstantiationScope
*OuterMostScope
) {
718 for (const auto *TmplAttr
: Tmpl
->attrs()) {
719 if (!isRelevantAttr(*this, New
, TmplAttr
))
722 // FIXME: This should be generalized to more than just the AlignedAttr.
723 const AlignedAttr
*Aligned
= dyn_cast
<AlignedAttr
>(TmplAttr
);
724 if (Aligned
&& Aligned
->isAlignmentDependent()) {
725 instantiateDependentAlignedAttr(*this, TemplateArgs
, Aligned
, New
);
729 if (const auto *AssumeAligned
= dyn_cast
<AssumeAlignedAttr
>(TmplAttr
)) {
730 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs
, AssumeAligned
, New
);
734 if (const auto *AlignValue
= dyn_cast
<AlignValueAttr
>(TmplAttr
)) {
735 instantiateDependentAlignValueAttr(*this, TemplateArgs
, AlignValue
, New
);
739 if (const auto *AllocAlign
= dyn_cast
<AllocAlignAttr
>(TmplAttr
)) {
740 instantiateDependentAllocAlignAttr(*this, TemplateArgs
, AllocAlign
, New
);
744 if (const auto *Annotate
= dyn_cast
<AnnotateAttr
>(TmplAttr
)) {
745 instantiateDependentAnnotationAttr(*this, TemplateArgs
, Annotate
, New
);
749 if (const auto *EnableIf
= dyn_cast
<EnableIfAttr
>(TmplAttr
)) {
750 instantiateDependentEnableIfAttr(*this, TemplateArgs
, EnableIf
, Tmpl
,
751 cast
<FunctionDecl
>(New
));
755 if (const auto *DiagnoseIf
= dyn_cast
<DiagnoseIfAttr
>(TmplAttr
)) {
756 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs
, DiagnoseIf
, Tmpl
,
757 cast
<FunctionDecl
>(New
));
761 if (const auto *CUDALaunchBounds
=
762 dyn_cast
<CUDALaunchBoundsAttr
>(TmplAttr
)) {
763 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs
,
764 *CUDALaunchBounds
, New
);
768 if (const auto *Mode
= dyn_cast
<ModeAttr
>(TmplAttr
)) {
769 instantiateDependentModeAttr(*this, TemplateArgs
, *Mode
, New
);
773 if (const auto *OMPAttr
= dyn_cast
<OMPDeclareSimdDeclAttr
>(TmplAttr
)) {
774 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs
, *OMPAttr
, New
);
778 if (const auto *OMPAttr
= dyn_cast
<OMPDeclareVariantAttr
>(TmplAttr
)) {
779 instantiateOMPDeclareVariantAttr(*this, TemplateArgs
, *OMPAttr
, New
);
783 if (const auto *AMDGPUFlatWorkGroupSize
=
784 dyn_cast
<AMDGPUFlatWorkGroupSizeAttr
>(TmplAttr
)) {
785 instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
786 *this, TemplateArgs
, *AMDGPUFlatWorkGroupSize
, New
);
789 if (const auto *AMDGPUFlatWorkGroupSize
=
790 dyn_cast
<AMDGPUWavesPerEUAttr
>(TmplAttr
)) {
791 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs
,
792 *AMDGPUFlatWorkGroupSize
, New
);
795 if (const auto *ParamAttr
= dyn_cast
<HLSLParamModifierAttr
>(TmplAttr
)) {
796 instantiateDependentHLSLParamModifierAttr(*this, TemplateArgs
, ParamAttr
,
801 // Existing DLL attribute on the instantiation takes precedence.
802 if (TmplAttr
->getKind() == attr::DLLExport
||
803 TmplAttr
->getKind() == attr::DLLImport
) {
804 if (New
->hasAttr
<DLLExportAttr
>() || New
->hasAttr
<DLLImportAttr
>()) {
809 if (const auto *ABIAttr
= dyn_cast
<ParameterABIAttr
>(TmplAttr
)) {
810 AddParameterABIAttr(New
, *ABIAttr
, ABIAttr
->getABI());
814 if (isa
<NSConsumedAttr
>(TmplAttr
) || isa
<OSConsumedAttr
>(TmplAttr
) ||
815 isa
<CFConsumedAttr
>(TmplAttr
)) {
816 AddXConsumedAttr(New
, *TmplAttr
, attrToRetainOwnershipKind(TmplAttr
),
817 /*template instantiation=*/true);
821 if (auto *A
= dyn_cast
<PointerAttr
>(TmplAttr
)) {
822 if (!New
->hasAttr
<PointerAttr
>())
823 New
->addAttr(A
->clone(Context
));
827 if (auto *A
= dyn_cast
<OwnerAttr
>(TmplAttr
)) {
828 if (!New
->hasAttr
<OwnerAttr
>())
829 New
->addAttr(A
->clone(Context
));
833 if (auto *A
= dyn_cast
<SYCLKernelAttr
>(TmplAttr
)) {
834 instantiateDependentSYCLKernelAttr(*this, TemplateArgs
, *A
, New
);
838 assert(!TmplAttr
->isPackExpansion());
839 if (TmplAttr
->isLateParsed() && LateAttrs
) {
840 // Late parsed attributes must be instantiated and attached after the
841 // enclosing class has been instantiated. See Sema::InstantiateClass.
842 LocalInstantiationScope
*Saved
= nullptr;
843 if (CurrentInstantiationScope
)
844 Saved
= CurrentInstantiationScope
->cloneScopes(OuterMostScope
);
845 LateAttrs
->push_back(LateInstantiatedAttribute(TmplAttr
, Saved
, New
));
847 // Allow 'this' within late-parsed attributes.
848 auto *ND
= cast
<NamedDecl
>(New
);
849 auto *ThisContext
= dyn_cast_or_null
<CXXRecordDecl
>(ND
->getDeclContext());
850 CXXThisScopeRAII
ThisScope(*this, ThisContext
, Qualifiers(),
851 ND
->isCXXInstanceMember());
853 Attr
*NewAttr
= sema::instantiateTemplateAttribute(TmplAttr
, Context
,
854 *this, TemplateArgs
);
855 if (NewAttr
&& isRelevantAttr(*this, New
, TmplAttr
))
856 New
->addAttr(NewAttr
);
861 /// Update instantiation attributes after template was late parsed.
863 /// Some attributes are evaluated based on the body of template. If it is
864 /// late parsed, such attributes cannot be evaluated when declaration is
865 /// instantiated. This function is used to update instantiation attributes when
866 /// template definition is ready.
867 void Sema::updateAttrsForLateParsedTemplate(const Decl
*Pattern
, Decl
*Inst
) {
868 for (const auto *Attr
: Pattern
->attrs()) {
869 if (auto *A
= dyn_cast
<StrictFPAttr
>(Attr
)) {
870 if (!Inst
->hasAttr
<StrictFPAttr
>())
871 Inst
->addAttr(A
->clone(getASTContext()));
877 /// In the MS ABI, we need to instantiate default arguments of dllexported
878 /// default constructors along with the constructor definition. This allows IR
879 /// gen to emit a constructor closure which calls the default constructor with
880 /// its default arguments.
881 void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl
*Ctor
) {
882 assert(Context
.getTargetInfo().getCXXABI().isMicrosoft() &&
883 Ctor
->isDefaultConstructor());
884 unsigned NumParams
= Ctor
->getNumParams();
887 DLLExportAttr
*Attr
= Ctor
->getAttr
<DLLExportAttr
>();
890 for (unsigned I
= 0; I
!= NumParams
; ++I
) {
891 (void)CheckCXXDefaultArgExpr(Attr
->getLocation(), Ctor
,
892 Ctor
->getParamDecl(I
));
893 CleanupVarDeclMarking();
897 /// Get the previous declaration of a declaration for the purposes of template
898 /// instantiation. If this finds a previous declaration, then the previous
899 /// declaration of the instantiation of D should be an instantiation of the
900 /// result of this function.
901 template<typename DeclT
>
902 static DeclT
*getPreviousDeclForInstantiation(DeclT
*D
) {
903 DeclT
*Result
= D
->getPreviousDecl();
905 // If the declaration is within a class, and the previous declaration was
906 // merged from a different definition of that class, then we don't have a
907 // previous declaration for the purpose of template instantiation.
908 if (Result
&& isa
<CXXRecordDecl
>(D
->getDeclContext()) &&
909 D
->getLexicalDeclContext() != Result
->getLexicalDeclContext())
916 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl
*D
) {
917 llvm_unreachable("Translation units cannot be instantiated");
920 Decl
*TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl
*Decl
) {
921 llvm_unreachable("HLSL buffer declarations cannot be instantiated");
925 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl
*D
) {
926 llvm_unreachable("pragma comment cannot be instantiated");
929 Decl
*TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
930 PragmaDetectMismatchDecl
*D
) {
931 llvm_unreachable("pragma comment cannot be instantiated");
935 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl
*D
) {
936 llvm_unreachable("extern \"C\" context cannot be instantiated");
939 Decl
*TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl
*D
) {
940 llvm_unreachable("GUID declaration cannot be instantiated");
943 Decl
*TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
944 UnnamedGlobalConstantDecl
*D
) {
945 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
948 Decl
*TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
949 TemplateParamObjectDecl
*D
) {
950 llvm_unreachable("template parameter objects cannot be instantiated");
954 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl
*D
) {
955 LabelDecl
*Inst
= LabelDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
957 Owner
->addDecl(Inst
);
962 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl
*D
) {
963 llvm_unreachable("Namespaces cannot be instantiated");
967 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl
*D
) {
968 NamespaceAliasDecl
*Inst
969 = NamespaceAliasDecl::Create(SemaRef
.Context
, Owner
,
970 D
->getNamespaceLoc(),
973 D
->getQualifierLoc(),
974 D
->getTargetNameLoc(),
976 Owner
->addDecl(Inst
);
980 Decl
*TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl
*D
,
982 bool Invalid
= false;
983 TypeSourceInfo
*DI
= D
->getTypeSourceInfo();
984 if (DI
->getType()->isInstantiationDependentType() ||
985 DI
->getType()->isVariablyModifiedType()) {
986 DI
= SemaRef
.SubstType(DI
, TemplateArgs
,
987 D
->getLocation(), D
->getDeclName());
990 DI
= SemaRef
.Context
.getTrivialTypeSourceInfo(SemaRef
.Context
.IntTy
);
993 SemaRef
.MarkDeclarationsReferencedInType(D
->getLocation(), DI
->getType());
996 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
997 // libstdc++ relies upon this bug in its implementation of common_type. If we
998 // happen to be processing that implementation, fake up the g++ ?:
999 // semantics. See LWG issue 2141 for more information on the bug. The bugs
1000 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
1001 const DecltypeType
*DT
= DI
->getType()->getAs
<DecltypeType
>();
1002 CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(D
->getDeclContext());
1003 if (DT
&& RD
&& isa
<ConditionalOperator
>(DT
->getUnderlyingExpr()) &&
1004 DT
->isReferenceType() &&
1005 RD
->getEnclosingNamespaceContext() == SemaRef
.getStdNamespace() &&
1006 RD
->getIdentifier() && RD
->getIdentifier()->isStr("common_type") &&
1007 D
->getIdentifier() && D
->getIdentifier()->isStr("type") &&
1008 SemaRef
.getSourceManager().isInSystemHeader(D
->getBeginLoc()))
1009 // Fold it to the (non-reference) type which g++ would have produced.
1010 DI
= SemaRef
.Context
.getTrivialTypeSourceInfo(
1011 DI
->getType().getNonReferenceType());
1013 // Create the new typedef
1014 TypedefNameDecl
*Typedef
;
1016 Typedef
= TypeAliasDecl::Create(SemaRef
.Context
, Owner
, D
->getBeginLoc(),
1017 D
->getLocation(), D
->getIdentifier(), DI
);
1019 Typedef
= TypedefDecl::Create(SemaRef
.Context
, Owner
, D
->getBeginLoc(),
1020 D
->getLocation(), D
->getIdentifier(), DI
);
1022 Typedef
->setInvalidDecl();
1024 // If the old typedef was the name for linkage purposes of an anonymous
1025 // tag decl, re-establish that relationship for the new typedef.
1026 if (const TagType
*oldTagType
= D
->getUnderlyingType()->getAs
<TagType
>()) {
1027 TagDecl
*oldTag
= oldTagType
->getDecl();
1028 if (oldTag
->getTypedefNameForAnonDecl() == D
&& !Invalid
) {
1029 TagDecl
*newTag
= DI
->getType()->castAs
<TagType
>()->getDecl();
1030 assert(!newTag
->hasNameForLinkage());
1031 newTag
->setTypedefNameForAnonDecl(Typedef
);
1035 if (TypedefNameDecl
*Prev
= getPreviousDeclForInstantiation(D
)) {
1036 NamedDecl
*InstPrev
= SemaRef
.FindInstantiatedDecl(D
->getLocation(), Prev
,
1041 TypedefNameDecl
*InstPrevTypedef
= cast
<TypedefNameDecl
>(InstPrev
);
1043 // If the typedef types are not identical, reject them.
1044 SemaRef
.isIncompatibleTypedef(InstPrevTypedef
, Typedef
);
1046 Typedef
->setPreviousDecl(InstPrevTypedef
);
1049 SemaRef
.InstantiateAttrs(TemplateArgs
, D
, Typedef
);
1051 if (D
->getUnderlyingType()->getAs
<DependentNameType
>())
1052 SemaRef
.inferGslPointerAttribute(Typedef
);
1054 Typedef
->setAccess(D
->getAccess());
1055 Typedef
->setReferenced(D
->isReferenced());
1060 Decl
*TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl
*D
) {
1061 Decl
*Typedef
= InstantiateTypedefNameDecl(D
, /*IsTypeAlias=*/false);
1063 Owner
->addDecl(Typedef
);
1067 Decl
*TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl
*D
) {
1068 Decl
*Typedef
= InstantiateTypedefNameDecl(D
, /*IsTypeAlias=*/true);
1070 Owner
->addDecl(Typedef
);
1075 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl
*D
) {
1076 // Create a local instantiation scope for this type alias template, which
1077 // will contain the instantiations of the template parameters.
1078 LocalInstantiationScope
Scope(SemaRef
);
1080 TemplateParameterList
*TempParams
= D
->getTemplateParameters();
1081 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
1085 TypeAliasDecl
*Pattern
= D
->getTemplatedDecl();
1087 TypeAliasTemplateDecl
*PrevAliasTemplate
= nullptr;
1088 if (getPreviousDeclForInstantiation
<TypedefNameDecl
>(Pattern
)) {
1089 DeclContext::lookup_result Found
= Owner
->lookup(Pattern
->getDeclName());
1090 if (!Found
.empty()) {
1091 PrevAliasTemplate
= dyn_cast
<TypeAliasTemplateDecl
>(Found
.front());
1095 TypeAliasDecl
*AliasInst
= cast_or_null
<TypeAliasDecl
>(
1096 InstantiateTypedefNameDecl(Pattern
, /*IsTypeAlias=*/true));
1100 TypeAliasTemplateDecl
*Inst
1101 = TypeAliasTemplateDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
1102 D
->getDeclName(), InstParams
, AliasInst
);
1103 AliasInst
->setDescribedAliasTemplate(Inst
);
1104 if (PrevAliasTemplate
)
1105 Inst
->setPreviousDecl(PrevAliasTemplate
);
1107 Inst
->setAccess(D
->getAccess());
1109 if (!PrevAliasTemplate
)
1110 Inst
->setInstantiatedFromMemberTemplate(D
);
1112 Owner
->addDecl(Inst
);
1117 Decl
*TemplateDeclInstantiator::VisitBindingDecl(BindingDecl
*D
) {
1118 auto *NewBD
= BindingDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
1119 D
->getIdentifier());
1120 NewBD
->setReferenced(D
->isReferenced());
1121 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, NewBD
);
1125 Decl
*TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl
*D
) {
1126 // Transform the bindings first.
1127 SmallVector
<BindingDecl
*, 16> NewBindings
;
1128 for (auto *OldBD
: D
->bindings())
1129 NewBindings
.push_back(cast
<BindingDecl
>(VisitBindingDecl(OldBD
)));
1130 ArrayRef
<BindingDecl
*> NewBindingArray
= NewBindings
;
1132 auto *NewDD
= cast_or_null
<DecompositionDecl
>(
1133 VisitVarDecl(D
, /*InstantiatingVarTemplate=*/false, &NewBindingArray
));
1135 if (!NewDD
|| NewDD
->isInvalidDecl())
1136 for (auto *NewBD
: NewBindings
)
1137 NewBD
->setInvalidDecl();
1142 Decl
*TemplateDeclInstantiator::VisitVarDecl(VarDecl
*D
) {
1143 return VisitVarDecl(D
, /*InstantiatingVarTemplate=*/false);
1146 Decl
*TemplateDeclInstantiator::VisitVarDecl(VarDecl
*D
,
1147 bool InstantiatingVarTemplate
,
1148 ArrayRef
<BindingDecl
*> *Bindings
) {
1150 // Do substitution on the type of the declaration
1151 TypeSourceInfo
*DI
= SemaRef
.SubstType(
1152 D
->getTypeSourceInfo(), TemplateArgs
, D
->getTypeSpecStartLoc(),
1153 D
->getDeclName(), /*AllowDeducedTST*/true);
1157 if (DI
->getType()->isFunctionType()) {
1158 SemaRef
.Diag(D
->getLocation(), diag::err_variable_instantiates_to_function
)
1159 << D
->isStaticDataMember() << DI
->getType();
1163 DeclContext
*DC
= Owner
;
1164 if (D
->isLocalExternDecl())
1165 SemaRef
.adjustContextForLocalExternDecl(DC
);
1167 // Build the instantiated declaration.
1170 Var
= DecompositionDecl::Create(SemaRef
.Context
, DC
, D
->getInnerLocStart(),
1171 D
->getLocation(), DI
->getType(), DI
,
1172 D
->getStorageClass(), *Bindings
);
1174 Var
= VarDecl::Create(SemaRef
.Context
, DC
, D
->getInnerLocStart(),
1175 D
->getLocation(), D
->getIdentifier(), DI
->getType(),
1176 DI
, D
->getStorageClass());
1178 // In ARC, infer 'retaining' for variables of retainable type.
1179 if (SemaRef
.getLangOpts().ObjCAutoRefCount
&&
1180 SemaRef
.inferObjCARCLifetime(Var
))
1181 Var
->setInvalidDecl();
1183 if (SemaRef
.getLangOpts().OpenCL
)
1184 SemaRef
.deduceOpenCLAddressSpace(Var
);
1186 // Substitute the nested name specifier, if any.
1187 if (SubstQualifier(D
, Var
))
1190 SemaRef
.BuildVariableInstantiation(Var
, D
, TemplateArgs
, LateAttrs
, Owner
,
1191 StartingScope
, InstantiatingVarTemplate
);
1192 if (D
->isNRVOVariable() && !Var
->isInvalidDecl()) {
1194 if (auto *F
= dyn_cast
<FunctionDecl
>(DC
))
1195 RT
= F
->getReturnType();
1196 else if (isa
<BlockDecl
>(DC
))
1197 RT
= cast
<FunctionType
>(SemaRef
.getCurBlock()->FunctionType
)
1200 llvm_unreachable("Unknown context type");
1202 // This is the last chance we have of checking copy elision eligibility
1203 // for functions in dependent contexts. The sema actions for building
1204 // the return statement during template instantiation will have no effect
1205 // regarding copy elision, since NRVO propagation runs on the scope exit
1206 // actions, and these are not run on instantiation.
1207 // This might run through some VarDecls which were returned from non-taken
1208 // 'if constexpr' branches, and these will end up being constructed on the
1209 // return slot even if they will never be returned, as a sort of accidental
1210 // 'optimization'. Notably, functions with 'auto' return types won't have it
1211 // deduced by this point. Coupled with the limitation described
1212 // previously, this makes it very hard to support copy elision for these.
1213 Sema::NamedReturnInfo Info
= SemaRef
.getNamedReturnInfo(Var
);
1214 bool NRVO
= SemaRef
.getCopyElisionCandidate(Info
, RT
) != nullptr;
1215 Var
->setNRVOVariable(NRVO
);
1218 Var
->setImplicit(D
->isImplicit());
1220 if (Var
->isStaticLocal())
1221 SemaRef
.CheckStaticLocalForDllExport(Var
);
1223 if (Var
->getTLSKind())
1224 SemaRef
.CheckThreadLocalForLargeAlignment(Var
);
1229 Decl
*TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl
*D
) {
1231 = AccessSpecDecl::Create(SemaRef
.Context
, D
->getAccess(), Owner
,
1232 D
->getAccessSpecifierLoc(), D
->getColonLoc());
1233 Owner
->addHiddenDecl(AD
);
1237 Decl
*TemplateDeclInstantiator::VisitFieldDecl(FieldDecl
*D
) {
1238 bool Invalid
= false;
1239 TypeSourceInfo
*DI
= D
->getTypeSourceInfo();
1240 if (DI
->getType()->isInstantiationDependentType() ||
1241 DI
->getType()->isVariablyModifiedType()) {
1242 DI
= SemaRef
.SubstType(DI
, TemplateArgs
,
1243 D
->getLocation(), D
->getDeclName());
1245 DI
= D
->getTypeSourceInfo();
1247 } else if (DI
->getType()->isFunctionType()) {
1248 // C++ [temp.arg.type]p3:
1249 // If a declaration acquires a function type through a type
1250 // dependent on a template-parameter and this causes a
1251 // declaration that does not use the syntactic form of a
1252 // function declarator to have function type, the program is
1254 SemaRef
.Diag(D
->getLocation(), diag::err_field_instantiates_to_function
)
1259 SemaRef
.MarkDeclarationsReferencedInType(D
->getLocation(), DI
->getType());
1262 Expr
*BitWidth
= D
->getBitWidth();
1265 else if (BitWidth
) {
1266 // The bit-width expression is a constant expression.
1267 EnterExpressionEvaluationContext
Unevaluated(
1268 SemaRef
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
1270 ExprResult InstantiatedBitWidth
1271 = SemaRef
.SubstExpr(BitWidth
, TemplateArgs
);
1272 if (InstantiatedBitWidth
.isInvalid()) {
1276 BitWidth
= InstantiatedBitWidth
.getAs
<Expr
>();
1279 FieldDecl
*Field
= SemaRef
.CheckFieldDecl(D
->getDeclName(),
1281 cast
<RecordDecl
>(Owner
),
1285 D
->getInClassInitStyle(),
1286 D
->getInnerLocStart(),
1290 cast
<Decl
>(Owner
)->setInvalidDecl();
1294 SemaRef
.InstantiateAttrs(TemplateArgs
, D
, Field
, LateAttrs
, StartingScope
);
1296 if (Field
->hasAttrs())
1297 SemaRef
.CheckAlignasUnderalignment(Field
);
1300 Field
->setInvalidDecl();
1302 if (!Field
->getDeclName()) {
1303 // Keep track of where this decl came from.
1304 SemaRef
.Context
.setInstantiatedFromUnnamedFieldDecl(Field
, D
);
1306 if (CXXRecordDecl
*Parent
= dyn_cast
<CXXRecordDecl
>(Field
->getDeclContext())) {
1307 if (Parent
->isAnonymousStructOrUnion() &&
1308 Parent
->getRedeclContext()->isFunctionOrMethod())
1309 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Field
);
1312 Field
->setImplicit(D
->isImplicit());
1313 Field
->setAccess(D
->getAccess());
1314 Owner
->addDecl(Field
);
1319 Decl
*TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl
*D
) {
1320 bool Invalid
= false;
1321 TypeSourceInfo
*DI
= D
->getTypeSourceInfo();
1323 if (DI
->getType()->isVariablyModifiedType()) {
1324 SemaRef
.Diag(D
->getLocation(), diag::err_property_is_variably_modified
)
1327 } else if (DI
->getType()->isInstantiationDependentType()) {
1328 DI
= SemaRef
.SubstType(DI
, TemplateArgs
,
1329 D
->getLocation(), D
->getDeclName());
1331 DI
= D
->getTypeSourceInfo();
1333 } else if (DI
->getType()->isFunctionType()) {
1334 // C++ [temp.arg.type]p3:
1335 // If a declaration acquires a function type through a type
1336 // dependent on a template-parameter and this causes a
1337 // declaration that does not use the syntactic form of a
1338 // function declarator to have function type, the program is
1340 SemaRef
.Diag(D
->getLocation(), diag::err_field_instantiates_to_function
)
1345 SemaRef
.MarkDeclarationsReferencedInType(D
->getLocation(), DI
->getType());
1348 MSPropertyDecl
*Property
= MSPropertyDecl::Create(
1349 SemaRef
.Context
, Owner
, D
->getLocation(), D
->getDeclName(), DI
->getType(),
1350 DI
, D
->getBeginLoc(), D
->getGetterId(), D
->getSetterId());
1352 SemaRef
.InstantiateAttrs(TemplateArgs
, D
, Property
, LateAttrs
,
1356 Property
->setInvalidDecl();
1358 Property
->setAccess(D
->getAccess());
1359 Owner
->addDecl(Property
);
1364 Decl
*TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl
*D
) {
1365 NamedDecl
**NamedChain
=
1366 new (SemaRef
.Context
)NamedDecl
*[D
->getChainingSize()];
1369 for (auto *PI
: D
->chain()) {
1370 NamedDecl
*Next
= SemaRef
.FindInstantiatedDecl(D
->getLocation(), PI
,
1375 NamedChain
[i
++] = Next
;
1378 QualType T
= cast
<FieldDecl
>(NamedChain
[i
-1])->getType();
1379 IndirectFieldDecl
*IndirectField
= IndirectFieldDecl::Create(
1380 SemaRef
.Context
, Owner
, D
->getLocation(), D
->getIdentifier(), T
,
1381 {NamedChain
, D
->getChainingSize()});
1383 for (const auto *Attr
: D
->attrs())
1384 IndirectField
->addAttr(Attr
->clone(SemaRef
.Context
));
1386 IndirectField
->setImplicit(D
->isImplicit());
1387 IndirectField
->setAccess(D
->getAccess());
1388 Owner
->addDecl(IndirectField
);
1389 return IndirectField
;
1392 Decl
*TemplateDeclInstantiator::VisitFriendDecl(FriendDecl
*D
) {
1393 // Handle friend type expressions by simply substituting template
1394 // parameters into the pattern type and checking the result.
1395 if (TypeSourceInfo
*Ty
= D
->getFriendType()) {
1396 TypeSourceInfo
*InstTy
;
1397 // If this is an unsupported friend, don't bother substituting template
1398 // arguments into it. The actual type referred to won't be used by any
1399 // parts of Clang, and may not be valid for instantiating. Just use the
1400 // same info for the instantiated friend.
1401 if (D
->isUnsupportedFriend()) {
1404 InstTy
= SemaRef
.SubstType(Ty
, TemplateArgs
,
1405 D
->getLocation(), DeclarationName());
1410 FriendDecl
*FD
= SemaRef
.CheckFriendTypeDecl(D
->getBeginLoc(),
1411 D
->getFriendLoc(), InstTy
);
1415 FD
->setAccess(AS_public
);
1416 FD
->setUnsupportedFriend(D
->isUnsupportedFriend());
1421 NamedDecl
*ND
= D
->getFriendDecl();
1422 assert(ND
&& "friend decl must be a decl or a type!");
1424 // All of the Visit implementations for the various potential friend
1425 // declarations have to be carefully written to work for friend
1426 // objects, with the most important detail being that the target
1427 // decl should almost certainly not be placed in Owner.
1428 Decl
*NewND
= Visit(ND
);
1429 if (!NewND
) return nullptr;
1432 FriendDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
1433 cast
<NamedDecl
>(NewND
), D
->getFriendLoc());
1434 FD
->setAccess(AS_public
);
1435 FD
->setUnsupportedFriend(D
->isUnsupportedFriend());
1440 Decl
*TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl
*D
) {
1441 Expr
*AssertExpr
= D
->getAssertExpr();
1443 // The expression in a static assertion is a constant expression.
1444 EnterExpressionEvaluationContext
Unevaluated(
1445 SemaRef
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
1447 ExprResult InstantiatedAssertExpr
1448 = SemaRef
.SubstExpr(AssertExpr
, TemplateArgs
);
1449 if (InstantiatedAssertExpr
.isInvalid())
1452 ExprResult InstantiatedMessageExpr
=
1453 SemaRef
.SubstExpr(D
->getMessage(), TemplateArgs
);
1454 if (InstantiatedMessageExpr
.isInvalid())
1457 return SemaRef
.BuildStaticAssertDeclaration(
1458 D
->getLocation(), InstantiatedAssertExpr
.get(),
1459 InstantiatedMessageExpr
.get(), D
->getRParenLoc(), D
->isFailed());
1462 Decl
*TemplateDeclInstantiator::VisitEnumDecl(EnumDecl
*D
) {
1463 EnumDecl
*PrevDecl
= nullptr;
1464 if (EnumDecl
*PatternPrev
= getPreviousDeclForInstantiation(D
)) {
1465 NamedDecl
*Prev
= SemaRef
.FindInstantiatedDecl(D
->getLocation(),
1468 if (!Prev
) return nullptr;
1469 PrevDecl
= cast
<EnumDecl
>(Prev
);
1473 EnumDecl::Create(SemaRef
.Context
, Owner
, D
->getBeginLoc(),
1474 D
->getLocation(), D
->getIdentifier(), PrevDecl
,
1475 D
->isScoped(), D
->isScopedUsingClassTag(), D
->isFixed());
1477 if (TypeSourceInfo
*TI
= D
->getIntegerTypeSourceInfo()) {
1478 // If we have type source information for the underlying type, it means it
1479 // has been explicitly set by the user. Perform substitution on it before
1481 SourceLocation UnderlyingLoc
= TI
->getTypeLoc().getBeginLoc();
1482 TypeSourceInfo
*NewTI
= SemaRef
.SubstType(TI
, TemplateArgs
, UnderlyingLoc
,
1484 if (!NewTI
|| SemaRef
.CheckEnumUnderlyingType(NewTI
))
1485 Enum
->setIntegerType(SemaRef
.Context
.IntTy
);
1487 Enum
->setIntegerTypeSourceInfo(NewTI
);
1489 assert(!D
->getIntegerType()->isDependentType()
1490 && "Dependent type without type source info");
1491 Enum
->setIntegerType(D
->getIntegerType());
1495 SemaRef
.InstantiateAttrs(TemplateArgs
, D
, Enum
);
1497 Enum
->setInstantiationOfMemberEnum(D
, TSK_ImplicitInstantiation
);
1498 Enum
->setAccess(D
->getAccess());
1499 // Forward the mangling number from the template to the instantiated decl.
1500 SemaRef
.Context
.setManglingNumber(Enum
, SemaRef
.Context
.getManglingNumber(D
));
1501 // See if the old tag was defined along with a declarator.
1502 // If it did, mark the new tag as being associated with that declarator.
1503 if (DeclaratorDecl
*DD
= SemaRef
.Context
.getDeclaratorForUnnamedTagDecl(D
))
1504 SemaRef
.Context
.addDeclaratorForUnnamedTagDecl(Enum
, DD
);
1505 // See if the old tag was defined along with a typedef.
1506 // If it did, mark the new tag as being associated with that typedef.
1507 if (TypedefNameDecl
*TND
= SemaRef
.Context
.getTypedefNameForUnnamedTagDecl(D
))
1508 SemaRef
.Context
.addTypedefNameForUnnamedTagDecl(Enum
, TND
);
1509 if (SubstQualifier(D
, Enum
)) return nullptr;
1510 Owner
->addDecl(Enum
);
1512 EnumDecl
*Def
= D
->getDefinition();
1513 if (Def
&& Def
!= D
) {
1514 // If this is an out-of-line definition of an enum member template, check
1515 // that the underlying types match in the instantiation of both
1517 if (TypeSourceInfo
*TI
= Def
->getIntegerTypeSourceInfo()) {
1518 SourceLocation UnderlyingLoc
= TI
->getTypeLoc().getBeginLoc();
1519 QualType DefnUnderlying
=
1520 SemaRef
.SubstType(TI
->getType(), TemplateArgs
,
1521 UnderlyingLoc
, DeclarationName());
1522 SemaRef
.CheckEnumRedeclaration(Def
->getLocation(), Def
->isScoped(),
1523 DefnUnderlying
, /*IsFixed=*/true, Enum
);
1527 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1528 // specialization causes the implicit instantiation of the declarations, but
1529 // not the definitions of scoped member enumerations.
1531 // DR1484 clarifies that enumeration definitions inside of a template
1532 // declaration aren't considered entities that can be separately instantiated
1533 // from the rest of the entity they are declared inside of.
1534 if (isDeclWithinFunction(D
) ? D
== Def
: Def
&& !Enum
->isScoped()) {
1535 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Enum
);
1536 InstantiateEnumDefinition(Enum
, Def
);
1542 void TemplateDeclInstantiator::InstantiateEnumDefinition(
1543 EnumDecl
*Enum
, EnumDecl
*Pattern
) {
1544 Enum
->startDefinition();
1546 // Update the location to refer to the definition.
1547 Enum
->setLocation(Pattern
->getLocation());
1549 SmallVector
<Decl
*, 4> Enumerators
;
1551 EnumConstantDecl
*LastEnumConst
= nullptr;
1552 for (auto *EC
: Pattern
->enumerators()) {
1553 // The specified value for the enumerator.
1554 ExprResult
Value((Expr
*)nullptr);
1555 if (Expr
*UninstValue
= EC
->getInitExpr()) {
1556 // The enumerator's value expression is a constant expression.
1557 EnterExpressionEvaluationContext
Unevaluated(
1558 SemaRef
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
1560 Value
= SemaRef
.SubstExpr(UninstValue
, TemplateArgs
);
1563 // Drop the initial value and continue.
1564 bool isInvalid
= false;
1565 if (Value
.isInvalid()) {
1570 EnumConstantDecl
*EnumConst
1571 = SemaRef
.CheckEnumConstant(Enum
, LastEnumConst
,
1572 EC
->getLocation(), EC
->getIdentifier(),
1577 EnumConst
->setInvalidDecl();
1578 Enum
->setInvalidDecl();
1582 SemaRef
.InstantiateAttrs(TemplateArgs
, EC
, EnumConst
);
1584 EnumConst
->setAccess(Enum
->getAccess());
1585 Enum
->addDecl(EnumConst
);
1586 Enumerators
.push_back(EnumConst
);
1587 LastEnumConst
= EnumConst
;
1589 if (Pattern
->getDeclContext()->isFunctionOrMethod() &&
1590 !Enum
->isScoped()) {
1591 // If the enumeration is within a function or method, record the enum
1592 // constant as a local.
1593 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(EC
, EnumConst
);
1598 SemaRef
.ActOnEnumBody(Enum
->getLocation(), Enum
->getBraceRange(), Enum
,
1599 Enumerators
, nullptr, ParsedAttributesView());
1602 Decl
*TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl
*D
) {
1603 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1607 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl
*D
) {
1608 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1611 Decl
*TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl
*D
) {
1612 bool isFriend
= (D
->getFriendObjectKind() != Decl::FOK_None
);
1614 // Create a local instantiation scope for this class template, which
1615 // will contain the instantiations of the template parameters.
1616 LocalInstantiationScope
Scope(SemaRef
);
1617 TemplateParameterList
*TempParams
= D
->getTemplateParameters();
1618 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
1622 CXXRecordDecl
*Pattern
= D
->getTemplatedDecl();
1624 // Instantiate the qualifier. We have to do this first in case
1625 // we're a friend declaration, because if we are then we need to put
1626 // the new declaration in the appropriate context.
1627 NestedNameSpecifierLoc QualifierLoc
= Pattern
->getQualifierLoc();
1629 QualifierLoc
= SemaRef
.SubstNestedNameSpecifierLoc(QualifierLoc
,
1635 CXXRecordDecl
*PrevDecl
= nullptr;
1636 ClassTemplateDecl
*PrevClassTemplate
= nullptr;
1638 if (!isFriend
&& getPreviousDeclForInstantiation(Pattern
)) {
1639 DeclContext::lookup_result Found
= Owner
->lookup(Pattern
->getDeclName());
1640 if (!Found
.empty()) {
1641 PrevClassTemplate
= dyn_cast
<ClassTemplateDecl
>(Found
.front());
1642 if (PrevClassTemplate
)
1643 PrevDecl
= PrevClassTemplate
->getTemplatedDecl();
1647 // If this isn't a friend, then it's a member template, in which
1648 // case we just want to build the instantiation in the
1649 // specialization. If it is a friend, we want to build it in
1650 // the appropriate context.
1651 DeclContext
*DC
= Owner
;
1655 SS
.Adopt(QualifierLoc
);
1656 DC
= SemaRef
.computeDeclContext(SS
);
1657 if (!DC
) return nullptr;
1659 DC
= SemaRef
.FindInstantiatedContext(Pattern
->getLocation(),
1660 Pattern
->getDeclContext(),
1664 // Look for a previous declaration of the template in the owning
1666 LookupResult
R(SemaRef
, Pattern
->getDeclName(), Pattern
->getLocation(),
1667 Sema::LookupOrdinaryName
,
1668 SemaRef
.forRedeclarationInCurContext());
1669 SemaRef
.LookupQualifiedName(R
, DC
);
1671 if (R
.isSingleResult()) {
1672 PrevClassTemplate
= R
.getAsSingle
<ClassTemplateDecl
>();
1673 if (PrevClassTemplate
)
1674 PrevDecl
= PrevClassTemplate
->getTemplatedDecl();
1677 if (!PrevClassTemplate
&& QualifierLoc
) {
1678 SemaRef
.Diag(Pattern
->getLocation(), diag::err_not_tag_in_scope
)
1679 << llvm::to_underlying(D
->getTemplatedDecl()->getTagKind())
1680 << Pattern
->getDeclName() << DC
<< QualifierLoc
.getSourceRange();
1685 CXXRecordDecl
*RecordInst
= CXXRecordDecl::Create(
1686 SemaRef
.Context
, Pattern
->getTagKind(), DC
, Pattern
->getBeginLoc(),
1687 Pattern
->getLocation(), Pattern
->getIdentifier(), PrevDecl
,
1688 /*DelayTypeCreation=*/true);
1690 RecordInst
->setQualifierInfo(QualifierLoc
);
1692 SemaRef
.InstantiateAttrsForDecl(TemplateArgs
, Pattern
, RecordInst
, LateAttrs
,
1695 ClassTemplateDecl
*Inst
1696 = ClassTemplateDecl::Create(SemaRef
.Context
, DC
, D
->getLocation(),
1697 D
->getIdentifier(), InstParams
, RecordInst
);
1698 RecordInst
->setDescribedClassTemplate(Inst
);
1701 assert(!Owner
->isDependentContext());
1702 Inst
->setLexicalDeclContext(Owner
);
1703 RecordInst
->setLexicalDeclContext(Owner
);
1705 if (PrevClassTemplate
) {
1706 Inst
->setCommonPtr(PrevClassTemplate
->getCommonPtr());
1707 RecordInst
->setTypeForDecl(
1708 PrevClassTemplate
->getTemplatedDecl()->getTypeForDecl());
1709 const ClassTemplateDecl
*MostRecentPrevCT
=
1710 PrevClassTemplate
->getMostRecentDecl();
1711 TemplateParameterList
*PrevParams
=
1712 MostRecentPrevCT
->getTemplateParameters();
1714 // Make sure the parameter lists match.
1715 if (!SemaRef
.TemplateParameterListsAreEqual(
1716 RecordInst
, InstParams
, MostRecentPrevCT
->getTemplatedDecl(),
1717 PrevParams
, true, Sema::TPL_TemplateMatch
))
1720 // Do some additional validation, then merge default arguments
1721 // from the existing declarations.
1722 if (SemaRef
.CheckTemplateParameterList(InstParams
, PrevParams
,
1723 Sema::TPC_ClassTemplate
))
1726 Inst
->setAccess(PrevClassTemplate
->getAccess());
1728 Inst
->setAccess(D
->getAccess());
1731 Inst
->setObjectOfFriendDecl();
1732 // TODO: do we want to track the instantiation progeny of this
1733 // friend target decl?
1735 Inst
->setAccess(D
->getAccess());
1736 if (!PrevClassTemplate
)
1737 Inst
->setInstantiatedFromMemberTemplate(D
);
1740 Inst
->setPreviousDecl(PrevClassTemplate
);
1742 // Trigger creation of the type for the instantiation.
1743 SemaRef
.Context
.getInjectedClassNameType(
1744 RecordInst
, Inst
->getInjectedClassNameSpecialization());
1746 // Finish handling of friends.
1748 DC
->makeDeclVisibleInContext(Inst
);
1752 if (D
->isOutOfLine()) {
1753 Inst
->setLexicalDeclContext(D
->getLexicalDeclContext());
1754 RecordInst
->setLexicalDeclContext(D
->getLexicalDeclContext());
1757 Owner
->addDecl(Inst
);
1759 if (!PrevClassTemplate
) {
1760 // Queue up any out-of-line partial specializations of this member
1761 // class template; the client will force their instantiation once
1762 // the enclosing class has been instantiated.
1763 SmallVector
<ClassTemplatePartialSpecializationDecl
*, 4> PartialSpecs
;
1764 D
->getPartialSpecializations(PartialSpecs
);
1765 for (unsigned I
= 0, N
= PartialSpecs
.size(); I
!= N
; ++I
)
1766 if (PartialSpecs
[I
]->getFirstDecl()->isOutOfLine())
1767 OutOfLinePartialSpecs
.push_back(std::make_pair(Inst
, PartialSpecs
[I
]));
1774 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1775 ClassTemplatePartialSpecializationDecl
*D
) {
1776 ClassTemplateDecl
*ClassTemplate
= D
->getSpecializedTemplate();
1778 // Lookup the already-instantiated declaration in the instantiation
1779 // of the class template and return that.
1780 DeclContext::lookup_result Found
1781 = Owner
->lookup(ClassTemplate
->getDeclName());
1785 ClassTemplateDecl
*InstClassTemplate
1786 = dyn_cast
<ClassTemplateDecl
>(Found
.front());
1787 if (!InstClassTemplate
)
1790 if (ClassTemplatePartialSpecializationDecl
*Result
1791 = InstClassTemplate
->findPartialSpecInstantiatedFromMember(D
))
1794 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate
, D
);
1797 Decl
*TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl
*D
) {
1798 assert(D
->getTemplatedDecl()->isStaticDataMember() &&
1799 "Only static data member templates are allowed.");
1801 // Create a local instantiation scope for this variable template, which
1802 // will contain the instantiations of the template parameters.
1803 LocalInstantiationScope
Scope(SemaRef
);
1804 TemplateParameterList
*TempParams
= D
->getTemplateParameters();
1805 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
1809 VarDecl
*Pattern
= D
->getTemplatedDecl();
1810 VarTemplateDecl
*PrevVarTemplate
= nullptr;
1812 if (getPreviousDeclForInstantiation(Pattern
)) {
1813 DeclContext::lookup_result Found
= Owner
->lookup(Pattern
->getDeclName());
1815 PrevVarTemplate
= dyn_cast
<VarTemplateDecl
>(Found
.front());
1819 cast_or_null
<VarDecl
>(VisitVarDecl(Pattern
,
1820 /*InstantiatingVarTemplate=*/true));
1821 if (!VarInst
) return nullptr;
1823 DeclContext
*DC
= Owner
;
1825 VarTemplateDecl
*Inst
= VarTemplateDecl::Create(
1826 SemaRef
.Context
, DC
, D
->getLocation(), D
->getIdentifier(), InstParams
,
1828 VarInst
->setDescribedVarTemplate(Inst
);
1829 Inst
->setPreviousDecl(PrevVarTemplate
);
1831 Inst
->setAccess(D
->getAccess());
1832 if (!PrevVarTemplate
)
1833 Inst
->setInstantiatedFromMemberTemplate(D
);
1835 if (D
->isOutOfLine()) {
1836 Inst
->setLexicalDeclContext(D
->getLexicalDeclContext());
1837 VarInst
->setLexicalDeclContext(D
->getLexicalDeclContext());
1840 Owner
->addDecl(Inst
);
1842 if (!PrevVarTemplate
) {
1843 // Queue up any out-of-line partial specializations of this member
1844 // variable template; the client will force their instantiation once
1845 // the enclosing class has been instantiated.
1846 SmallVector
<VarTemplatePartialSpecializationDecl
*, 4> PartialSpecs
;
1847 D
->getPartialSpecializations(PartialSpecs
);
1848 for (unsigned I
= 0, N
= PartialSpecs
.size(); I
!= N
; ++I
)
1849 if (PartialSpecs
[I
]->getFirstDecl()->isOutOfLine())
1850 OutOfLineVarPartialSpecs
.push_back(
1851 std::make_pair(Inst
, PartialSpecs
[I
]));
1857 Decl
*TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1858 VarTemplatePartialSpecializationDecl
*D
) {
1859 assert(D
->isStaticDataMember() &&
1860 "Only static data member templates are allowed.");
1862 VarTemplateDecl
*VarTemplate
= D
->getSpecializedTemplate();
1864 // Lookup the already-instantiated declaration and return that.
1865 DeclContext::lookup_result Found
= Owner
->lookup(VarTemplate
->getDeclName());
1866 assert(!Found
.empty() && "Instantiation found nothing?");
1868 VarTemplateDecl
*InstVarTemplate
= dyn_cast
<VarTemplateDecl
>(Found
.front());
1869 assert(InstVarTemplate
&& "Instantiation did not find a variable template?");
1871 if (VarTemplatePartialSpecializationDecl
*Result
=
1872 InstVarTemplate
->findPartialSpecInstantiatedFromMember(D
))
1875 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate
, D
);
1879 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl
*D
) {
1880 // Create a local instantiation scope for this function template, which
1881 // will contain the instantiations of the template parameters and then get
1882 // merged with the local instantiation scope for the function template
1884 LocalInstantiationScope
Scope(SemaRef
);
1885 Sema::ConstraintEvalRAII
<TemplateDeclInstantiator
> RAII(*this);
1887 TemplateParameterList
*TempParams
= D
->getTemplateParameters();
1888 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
1892 FunctionDecl
*Instantiated
= nullptr;
1893 if (CXXMethodDecl
*DMethod
= dyn_cast
<CXXMethodDecl
>(D
->getTemplatedDecl()))
1894 Instantiated
= cast_or_null
<FunctionDecl
>(VisitCXXMethodDecl(DMethod
,
1897 Instantiated
= cast_or_null
<FunctionDecl
>(VisitFunctionDecl(
1898 D
->getTemplatedDecl(),
1904 // Link the instantiated function template declaration to the function
1905 // template from which it was instantiated.
1906 FunctionTemplateDecl
*InstTemplate
1907 = Instantiated
->getDescribedFunctionTemplate();
1908 InstTemplate
->setAccess(D
->getAccess());
1909 assert(InstTemplate
&&
1910 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1912 bool isFriend
= (InstTemplate
->getFriendObjectKind() != Decl::FOK_None
);
1914 // Link the instantiation back to the pattern *unless* this is a
1915 // non-definition friend declaration.
1916 if (!InstTemplate
->getInstantiatedFromMemberTemplate() &&
1917 !(isFriend
&& !D
->getTemplatedDecl()->isThisDeclarationADefinition()))
1918 InstTemplate
->setInstantiatedFromMemberTemplate(D
);
1920 // Make declarations visible in the appropriate context.
1922 Owner
->addDecl(InstTemplate
);
1923 } else if (InstTemplate
->getDeclContext()->isRecord() &&
1924 !getPreviousDeclForInstantiation(D
)) {
1925 SemaRef
.CheckFriendAccess(InstTemplate
);
1928 return InstTemplate
;
1931 Decl
*TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl
*D
) {
1932 CXXRecordDecl
*PrevDecl
= nullptr;
1933 if (CXXRecordDecl
*PatternPrev
= getPreviousDeclForInstantiation(D
)) {
1934 NamedDecl
*Prev
= SemaRef
.FindInstantiatedDecl(D
->getLocation(),
1937 if (!Prev
) return nullptr;
1938 PrevDecl
= cast
<CXXRecordDecl
>(Prev
);
1941 CXXRecordDecl
*Record
= nullptr;
1942 bool IsInjectedClassName
= D
->isInjectedClassName();
1944 Record
= CXXRecordDecl::CreateLambda(
1945 SemaRef
.Context
, Owner
, D
->getLambdaTypeInfo(), D
->getLocation(),
1946 D
->getLambdaDependencyKind(), D
->isGenericLambda(),
1947 D
->getLambdaCaptureDefault());
1949 Record
= CXXRecordDecl::Create(SemaRef
.Context
, D
->getTagKind(), Owner
,
1950 D
->getBeginLoc(), D
->getLocation(),
1951 D
->getIdentifier(), PrevDecl
,
1952 /*DelayTypeCreation=*/IsInjectedClassName
);
1953 // Link the type of the injected-class-name to that of the outer class.
1954 if (IsInjectedClassName
)
1955 (void)SemaRef
.Context
.getTypeDeclType(Record
, cast
<CXXRecordDecl
>(Owner
));
1957 // Substitute the nested name specifier, if any.
1958 if (SubstQualifier(D
, Record
))
1961 SemaRef
.InstantiateAttrsForDecl(TemplateArgs
, D
, Record
, LateAttrs
,
1964 Record
->setImplicit(D
->isImplicit());
1965 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1966 // the tag decls introduced by friend class declarations don't have an access
1967 // specifier. Remove once this area of the code gets sorted out.
1968 if (D
->getAccess() != AS_none
)
1969 Record
->setAccess(D
->getAccess());
1970 if (!IsInjectedClassName
)
1971 Record
->setInstantiationOfMemberClass(D
, TSK_ImplicitInstantiation
);
1973 // If the original function was part of a friend declaration,
1974 // inherit its namespace state.
1975 if (D
->getFriendObjectKind())
1976 Record
->setObjectOfFriendDecl();
1978 // Make sure that anonymous structs and unions are recorded.
1979 if (D
->isAnonymousStructOrUnion())
1980 Record
->setAnonymousStructOrUnion(true);
1982 if (D
->isLocalClass())
1983 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Record
);
1985 // Forward the mangling number from the template to the instantiated decl.
1986 SemaRef
.Context
.setManglingNumber(Record
,
1987 SemaRef
.Context
.getManglingNumber(D
));
1989 // See if the old tag was defined along with a declarator.
1990 // If it did, mark the new tag as being associated with that declarator.
1991 if (DeclaratorDecl
*DD
= SemaRef
.Context
.getDeclaratorForUnnamedTagDecl(D
))
1992 SemaRef
.Context
.addDeclaratorForUnnamedTagDecl(Record
, DD
);
1994 // See if the old tag was defined along with a typedef.
1995 // If it did, mark the new tag as being associated with that typedef.
1996 if (TypedefNameDecl
*TND
= SemaRef
.Context
.getTypedefNameForUnnamedTagDecl(D
))
1997 SemaRef
.Context
.addTypedefNameForUnnamedTagDecl(Record
, TND
);
1999 Owner
->addDecl(Record
);
2001 // DR1484 clarifies that the members of a local class are instantiated as part
2002 // of the instantiation of their enclosing entity.
2003 if (D
->isCompleteDefinition() && D
->isLocalClass()) {
2004 Sema::LocalEagerInstantiationScope
LocalInstantiations(SemaRef
);
2006 SemaRef
.InstantiateClass(D
->getLocation(), Record
, D
, TemplateArgs
,
2007 TSK_ImplicitInstantiation
,
2010 // For nested local classes, we will instantiate the members when we
2011 // reach the end of the outermost (non-nested) local class.
2012 if (!D
->isCXXClassMember())
2013 SemaRef
.InstantiateClassMembers(D
->getLocation(), Record
, TemplateArgs
,
2014 TSK_ImplicitInstantiation
);
2016 // This class may have local implicit instantiations that need to be
2017 // performed within this scope.
2018 LocalInstantiations
.perform();
2021 SemaRef
.DiagnoseUnusedNestedTypedefs(Record
);
2023 if (IsInjectedClassName
)
2024 assert(Record
->isInjectedClassName() && "Broken injected-class-name");
2029 /// Adjust the given function type for an instantiation of the
2030 /// given declaration, to cope with modifications to the function's type that
2031 /// aren't reflected in the type-source information.
2033 /// \param D The declaration we're instantiating.
2034 /// \param TInfo The already-instantiated type.
2035 static QualType
adjustFunctionTypeForInstantiation(ASTContext
&Context
,
2037 TypeSourceInfo
*TInfo
) {
2038 const FunctionProtoType
*OrigFunc
2039 = D
->getType()->castAs
<FunctionProtoType
>();
2040 const FunctionProtoType
*NewFunc
2041 = TInfo
->getType()->castAs
<FunctionProtoType
>();
2042 if (OrigFunc
->getExtInfo() == NewFunc
->getExtInfo())
2043 return TInfo
->getType();
2045 FunctionProtoType::ExtProtoInfo NewEPI
= NewFunc
->getExtProtoInfo();
2046 NewEPI
.ExtInfo
= OrigFunc
->getExtInfo();
2047 return Context
.getFunctionType(NewFunc
->getReturnType(),
2048 NewFunc
->getParamTypes(), NewEPI
);
2051 /// Normal class members are of more specific types and therefore
2052 /// don't make it here. This function serves three purposes:
2053 /// 1) instantiating function templates
2054 /// 2) substituting friend and local function declarations
2055 /// 3) substituting deduction guide declarations for nested class templates
2056 Decl
*TemplateDeclInstantiator::VisitFunctionDecl(
2057 FunctionDecl
*D
, TemplateParameterList
*TemplateParams
,
2058 RewriteKind FunctionRewriteKind
) {
2059 // Check whether there is already a function template specialization for
2060 // this declaration.
2061 FunctionTemplateDecl
*FunctionTemplate
= D
->getDescribedFunctionTemplate();
2062 if (FunctionTemplate
&& !TemplateParams
) {
2063 ArrayRef
<TemplateArgument
> Innermost
= TemplateArgs
.getInnermost();
2065 void *InsertPos
= nullptr;
2066 FunctionDecl
*SpecFunc
2067 = FunctionTemplate
->findSpecialization(Innermost
, InsertPos
);
2069 // If we already have a function template specialization, return it.
2075 if (FunctionTemplate
)
2076 isFriend
= (FunctionTemplate
->getFriendObjectKind() != Decl::FOK_None
);
2078 isFriend
= (D
->getFriendObjectKind() != Decl::FOK_None
);
2080 bool MergeWithParentScope
= (TemplateParams
!= nullptr) ||
2081 Owner
->isFunctionOrMethod() ||
2082 !(isa
<Decl
>(Owner
) &&
2083 cast
<Decl
>(Owner
)->isDefinedOutsideFunctionOrMethod());
2084 LocalInstantiationScope
Scope(SemaRef
, MergeWithParentScope
);
2086 ExplicitSpecifier InstantiatedExplicitSpecifier
;
2087 if (auto *DGuide
= dyn_cast
<CXXDeductionGuideDecl
>(D
)) {
2088 InstantiatedExplicitSpecifier
= SemaRef
.instantiateExplicitSpecifier(
2089 TemplateArgs
, DGuide
->getExplicitSpecifier());
2090 if (InstantiatedExplicitSpecifier
.isInvalid())
2094 SmallVector
<ParmVarDecl
*, 4> Params
;
2095 TypeSourceInfo
*TInfo
= SubstFunctionType(D
, Params
);
2098 QualType T
= adjustFunctionTypeForInstantiation(SemaRef
.Context
, D
, TInfo
);
2100 if (TemplateParams
&& TemplateParams
->size()) {
2102 dyn_cast
<TemplateTypeParmDecl
>(TemplateParams
->asArray().back());
2103 if (LastParam
&& LastParam
->isImplicit() &&
2104 LastParam
->hasTypeConstraint()) {
2105 // In abbreviated templates, the type-constraints of invented template
2106 // type parameters are instantiated with the function type, invalidating
2107 // the TemplateParameterList which relied on the template type parameter
2108 // not having a type constraint. Recreate the TemplateParameterList with
2109 // the updated parameter list.
2110 TemplateParams
= TemplateParameterList::Create(
2111 SemaRef
.Context
, TemplateParams
->getTemplateLoc(),
2112 TemplateParams
->getLAngleLoc(), TemplateParams
->asArray(),
2113 TemplateParams
->getRAngleLoc(), TemplateParams
->getRequiresClause());
2117 NestedNameSpecifierLoc QualifierLoc
= D
->getQualifierLoc();
2119 QualifierLoc
= SemaRef
.SubstNestedNameSpecifierLoc(QualifierLoc
,
2125 Expr
*TrailingRequiresClause
= D
->getTrailingRequiresClause();
2127 // If we're instantiating a local function declaration, put the result
2128 // in the enclosing namespace; otherwise we need to find the instantiated
2131 if (D
->isLocalExternDecl()) {
2133 SemaRef
.adjustContextForLocalExternDecl(DC
);
2134 } else if (isFriend
&& QualifierLoc
) {
2136 SS
.Adopt(QualifierLoc
);
2137 DC
= SemaRef
.computeDeclContext(SS
);
2138 if (!DC
) return nullptr;
2140 DC
= SemaRef
.FindInstantiatedContext(D
->getLocation(), D
->getDeclContext(),
2144 DeclarationNameInfo NameInfo
2145 = SemaRef
.SubstDeclarationNameInfo(D
->getNameInfo(), TemplateArgs
);
2147 if (FunctionRewriteKind
!= RewriteKind::None
)
2148 adjustForRewrite(FunctionRewriteKind
, D
, T
, TInfo
, NameInfo
);
2150 FunctionDecl
*Function
;
2151 if (auto *DGuide
= dyn_cast
<CXXDeductionGuideDecl
>(D
)) {
2152 Function
= CXXDeductionGuideDecl::Create(
2153 SemaRef
.Context
, DC
, D
->getInnerLocStart(),
2154 InstantiatedExplicitSpecifier
, NameInfo
, T
, TInfo
,
2155 D
->getSourceRange().getEnd(), DGuide
->getCorrespondingConstructor(),
2156 DGuide
->getDeductionCandidateKind());
2157 Function
->setAccess(D
->getAccess());
2159 Function
= FunctionDecl::Create(
2160 SemaRef
.Context
, DC
, D
->getInnerLocStart(), NameInfo
, T
, TInfo
,
2161 D
->getCanonicalDecl()->getStorageClass(), D
->UsesFPIntrin(),
2162 D
->isInlineSpecified(), D
->hasWrittenPrototype(), D
->getConstexprKind(),
2163 TrailingRequiresClause
);
2164 Function
->setFriendConstraintRefersToEnclosingTemplate(
2165 D
->FriendConstraintRefersToEnclosingTemplate());
2166 Function
->setRangeEnd(D
->getSourceRange().getEnd());
2170 Function
->setImplicitlyInline();
2173 Function
->setQualifierInfo(QualifierLoc
);
2175 if (D
->isLocalExternDecl())
2176 Function
->setLocalExternDecl();
2178 DeclContext
*LexicalDC
= Owner
;
2179 if (!isFriend
&& D
->isOutOfLine() && !D
->isLocalExternDecl()) {
2180 assert(D
->getDeclContext()->isFileContext());
2181 LexicalDC
= D
->getDeclContext();
2183 else if (D
->isLocalExternDecl()) {
2184 LexicalDC
= SemaRef
.CurContext
;
2187 Function
->setLexicalDeclContext(LexicalDC
);
2189 // Attach the parameters
2190 for (unsigned P
= 0; P
< Params
.size(); ++P
)
2192 Params
[P
]->setOwningFunction(Function
);
2193 Function
->setParams(Params
);
2195 if (TrailingRequiresClause
)
2196 Function
->setTrailingRequiresClause(TrailingRequiresClause
);
2198 if (TemplateParams
) {
2199 // Our resulting instantiation is actually a function template, since we
2200 // are substituting only the outer template parameters. For example, given
2202 // template<typename T>
2204 // template<typename U> friend void f(T, U);
2209 // We are instantiating the friend function template "f" within X<int>,
2210 // which means substituting int for T, but leaving "f" as a friend function
2212 // Build the function template itself.
2213 FunctionTemplate
= FunctionTemplateDecl::Create(SemaRef
.Context
, DC
,
2214 Function
->getLocation(),
2215 Function
->getDeclName(),
2216 TemplateParams
, Function
);
2217 Function
->setDescribedFunctionTemplate(FunctionTemplate
);
2219 FunctionTemplate
->setLexicalDeclContext(LexicalDC
);
2221 if (isFriend
&& D
->isThisDeclarationADefinition()) {
2222 FunctionTemplate
->setInstantiatedFromMemberTemplate(
2223 D
->getDescribedFunctionTemplate());
2225 } else if (FunctionTemplate
) {
2226 // Record this function template specialization.
2227 ArrayRef
<TemplateArgument
> Innermost
= TemplateArgs
.getInnermost();
2228 Function
->setFunctionTemplateSpecialization(FunctionTemplate
,
2229 TemplateArgumentList::CreateCopy(SemaRef
.Context
,
2231 /*InsertPos=*/nullptr);
2232 } else if (isFriend
&& D
->isThisDeclarationADefinition()) {
2233 // Do not connect the friend to the template unless it's actually a
2234 // definition. We don't want non-template functions to be marked as being
2235 // template instantiations.
2236 Function
->setInstantiationOfMemberFunction(D
, TSK_ImplicitInstantiation
);
2237 } else if (!isFriend
) {
2238 // If this is not a function template, and this is not a friend (that is,
2239 // this is a locally declared function), save the instantiation relationship
2240 // for the purposes of constraint instantiation.
2241 Function
->setInstantiatedFromDecl(D
);
2245 Function
->setObjectOfFriendDecl();
2246 if (FunctionTemplateDecl
*FT
= Function
->getDescribedFunctionTemplate())
2247 FT
->setObjectOfFriendDecl();
2250 if (InitFunctionInstantiation(Function
, D
))
2251 Function
->setInvalidDecl();
2253 bool IsExplicitSpecialization
= false;
2255 LookupResult
Previous(
2256 SemaRef
, Function
->getDeclName(), SourceLocation(),
2257 D
->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
2258 : Sema::LookupOrdinaryName
,
2259 D
->isLocalExternDecl() ? Sema::ForExternalRedeclaration
2260 : SemaRef
.forRedeclarationInCurContext());
2262 if (DependentFunctionTemplateSpecializationInfo
*DFTSI
=
2263 D
->getDependentSpecializationInfo()) {
2264 assert(isFriend
&& "dependent specialization info on "
2265 "non-member non-friend function?");
2267 // Instantiate the explicit template arguments.
2268 TemplateArgumentListInfo ExplicitArgs
;
2269 if (const auto *ArgsWritten
= DFTSI
->TemplateArgumentsAsWritten
) {
2270 ExplicitArgs
.setLAngleLoc(ArgsWritten
->getLAngleLoc());
2271 ExplicitArgs
.setRAngleLoc(ArgsWritten
->getRAngleLoc());
2272 if (SemaRef
.SubstTemplateArguments(ArgsWritten
->arguments(), TemplateArgs
,
2277 // Map the candidates for the primary template to their instantiations.
2278 for (FunctionTemplateDecl
*FTD
: DFTSI
->getCandidates()) {
2280 SemaRef
.FindInstantiatedDecl(D
->getLocation(), FTD
, TemplateArgs
))
2281 Previous
.addDecl(ND
);
2286 if (SemaRef
.CheckFunctionTemplateSpecialization(
2288 DFTSI
->TemplateArgumentsAsWritten
? &ExplicitArgs
: nullptr,
2290 Function
->setInvalidDecl();
2292 IsExplicitSpecialization
= true;
2293 } else if (const ASTTemplateArgumentListInfo
*ArgsWritten
=
2294 D
->getTemplateSpecializationArgsAsWritten()) {
2295 // The name of this function was written as a template-id.
2296 SemaRef
.LookupQualifiedName(Previous
, DC
);
2298 // Instantiate the explicit template arguments.
2299 TemplateArgumentListInfo
ExplicitArgs(ArgsWritten
->getLAngleLoc(),
2300 ArgsWritten
->getRAngleLoc());
2301 if (SemaRef
.SubstTemplateArguments(ArgsWritten
->arguments(), TemplateArgs
,
2305 if (SemaRef
.CheckFunctionTemplateSpecialization(Function
,
2308 Function
->setInvalidDecl();
2310 IsExplicitSpecialization
= true;
2311 } else if (TemplateParams
|| !FunctionTemplate
) {
2312 // Look only into the namespace where the friend would be declared to
2313 // find a previous declaration. This is the innermost enclosing namespace,
2314 // as described in ActOnFriendFunctionDecl.
2315 SemaRef
.LookupQualifiedName(Previous
, DC
->getRedeclContext());
2317 // In C++, the previous declaration we find might be a tag type
2318 // (class or enum). In this case, the new declaration will hide the
2319 // tag type. Note that this does not apply if we're declaring a
2320 // typedef (C++ [dcl.typedef]p4).
2321 if (Previous
.isSingleTagDecl())
2324 // Filter out previous declarations that don't match the scope. The only
2325 // effect this has is to remove declarations found in inline namespaces
2326 // for friend declarations with unqualified names.
2327 if (isFriend
&& !QualifierLoc
) {
2328 SemaRef
.FilterLookupForScope(Previous
, DC
, /*Scope=*/ nullptr,
2329 /*ConsiderLinkage=*/ true,
2330 QualifierLoc
.hasQualifier());
2334 // Per [temp.inst], default arguments in function declarations at local scope
2335 // are instantiated along with the enclosing declaration. For example:
2337 // template<typename T>
2339 // void f(int = []{ return T::value; }());
2341 // template void ft<int>(); // error: type 'int' cannot be used prior
2342 // to '::' because it has no members
2344 // The error is issued during instantiation of ft<int>() because substitution
2345 // into the default argument fails; the default argument is instantiated even
2346 // though it is never used.
2347 if (Function
->isLocalExternDecl()) {
2348 for (ParmVarDecl
*PVD
: Function
->parameters()) {
2349 if (!PVD
->hasDefaultArg())
2351 if (SemaRef
.SubstDefaultArgument(D
->getInnerLocStart(), PVD
, TemplateArgs
)) {
2352 // If substitution fails, the default argument is set to a
2353 // RecoveryExpr that wraps the uninstantiated default argument so
2354 // that downstream diagnostics are omitted.
2355 Expr
*UninstExpr
= PVD
->getUninstantiatedDefaultArg();
2356 ExprResult ErrorResult
= SemaRef
.CreateRecoveryExpr(
2357 UninstExpr
->getBeginLoc(), UninstExpr
->getEndLoc(),
2358 { UninstExpr
}, UninstExpr
->getType());
2359 if (ErrorResult
.isUsable())
2360 PVD
->setDefaultArg(ErrorResult
.get());
2365 SemaRef
.CheckFunctionDeclaration(/*Scope*/ nullptr, Function
, Previous
,
2366 IsExplicitSpecialization
,
2367 Function
->isThisDeclarationADefinition());
2369 // Check the template parameter list against the previous declaration. The
2370 // goal here is to pick up default arguments added since the friend was
2371 // declared; we know the template parameter lists match, since otherwise
2372 // we would not have picked this template as the previous declaration.
2373 if (isFriend
&& TemplateParams
&& FunctionTemplate
->getPreviousDecl()) {
2374 SemaRef
.CheckTemplateParameterList(
2376 FunctionTemplate
->getPreviousDecl()->getTemplateParameters(),
2377 Function
->isThisDeclarationADefinition()
2378 ? Sema::TPC_FriendFunctionTemplateDefinition
2379 : Sema::TPC_FriendFunctionTemplate
);
2382 // If we're introducing a friend definition after the first use, trigger
2384 // FIXME: If this is a friend function template definition, we should check
2385 // to see if any specializations have been used.
2386 if (isFriend
&& D
->isThisDeclarationADefinition() && Function
->isUsed(false)) {
2387 if (MemberSpecializationInfo
*MSInfo
=
2388 Function
->getMemberSpecializationInfo()) {
2389 if (MSInfo
->getPointOfInstantiation().isInvalid()) {
2390 SourceLocation Loc
= D
->getLocation(); // FIXME
2391 MSInfo
->setPointOfInstantiation(Loc
);
2392 SemaRef
.PendingLocalImplicitInstantiations
.push_back(
2393 std::make_pair(Function
, Loc
));
2398 if (D
->isExplicitlyDefaulted()) {
2399 if (SubstDefaultedFunction(Function
, D
))
2403 SemaRef
.SetDeclDeleted(Function
, D
->getLocation());
2405 NamedDecl
*PrincipalDecl
=
2406 (TemplateParams
? cast
<NamedDecl
>(FunctionTemplate
) : Function
);
2408 // If this declaration lives in a different context from its lexical context,
2409 // add it to the corresponding lookup table.
2411 (Function
->isLocalExternDecl() && !Function
->getPreviousDecl()))
2412 DC
->makeDeclVisibleInContext(PrincipalDecl
);
2414 if (Function
->isOverloadedOperator() && !DC
->isRecord() &&
2415 PrincipalDecl
->isInIdentifierNamespace(Decl::IDNS_Ordinary
))
2416 PrincipalDecl
->setNonMemberOperator();
2421 Decl
*TemplateDeclInstantiator::VisitCXXMethodDecl(
2422 CXXMethodDecl
*D
, TemplateParameterList
*TemplateParams
,
2423 RewriteKind FunctionRewriteKind
) {
2424 FunctionTemplateDecl
*FunctionTemplate
= D
->getDescribedFunctionTemplate();
2425 if (FunctionTemplate
&& !TemplateParams
) {
2426 // We are creating a function template specialization from a function
2427 // template. Check whether there is already a function template
2428 // specialization for this particular set of template arguments.
2429 ArrayRef
<TemplateArgument
> Innermost
= TemplateArgs
.getInnermost();
2431 void *InsertPos
= nullptr;
2432 FunctionDecl
*SpecFunc
2433 = FunctionTemplate
->findSpecialization(Innermost
, InsertPos
);
2435 // If we already have a function template specialization, return it.
2441 if (FunctionTemplate
)
2442 isFriend
= (FunctionTemplate
->getFriendObjectKind() != Decl::FOK_None
);
2444 isFriend
= (D
->getFriendObjectKind() != Decl::FOK_None
);
2446 bool MergeWithParentScope
= (TemplateParams
!= nullptr) ||
2447 !(isa
<Decl
>(Owner
) &&
2448 cast
<Decl
>(Owner
)->isDefinedOutsideFunctionOrMethod());
2449 LocalInstantiationScope
Scope(SemaRef
, MergeWithParentScope
);
2451 Sema::LambdaScopeForCallOperatorInstantiationRAII
LambdaScope(
2452 SemaRef
, const_cast<CXXMethodDecl
*>(D
), TemplateArgs
, Scope
);
2454 // Instantiate enclosing template arguments for friends.
2455 SmallVector
<TemplateParameterList
*, 4> TempParamLists
;
2456 unsigned NumTempParamLists
= 0;
2457 if (isFriend
&& (NumTempParamLists
= D
->getNumTemplateParameterLists())) {
2458 TempParamLists
.resize(NumTempParamLists
);
2459 for (unsigned I
= 0; I
!= NumTempParamLists
; ++I
) {
2460 TemplateParameterList
*TempParams
= D
->getTemplateParameterList(I
);
2461 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
2464 TempParamLists
[I
] = InstParams
;
2468 auto InstantiatedExplicitSpecifier
= ExplicitSpecifier::getFromDecl(D
);
2469 // deduction guides need this
2470 const bool CouldInstantiate
=
2471 InstantiatedExplicitSpecifier
.getExpr() == nullptr ||
2472 !InstantiatedExplicitSpecifier
.getExpr()->isValueDependent();
2474 // Delay the instantiation of the explicit-specifier until after the
2475 // constraints are checked during template argument deduction.
2476 if (CouldInstantiate
||
2477 SemaRef
.CodeSynthesisContexts
.back().Kind
!=
2478 Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) {
2479 InstantiatedExplicitSpecifier
= SemaRef
.instantiateExplicitSpecifier(
2480 TemplateArgs
, InstantiatedExplicitSpecifier
);
2482 if (InstantiatedExplicitSpecifier
.isInvalid())
2485 InstantiatedExplicitSpecifier
.setKind(ExplicitSpecKind::Unresolved
);
2488 // Implicit destructors/constructors created for local classes in
2489 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2490 // Unfortunately there isn't enough context in those functions to
2491 // conditionally populate the TSI without breaking non-template related use
2492 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2493 // a proper transformation.
2494 if (cast
<CXXRecordDecl
>(D
->getParent())->isLambda() &&
2495 !D
->getTypeSourceInfo() &&
2496 isa
<CXXConstructorDecl
, CXXDestructorDecl
>(D
)) {
2497 TypeSourceInfo
*TSI
=
2498 SemaRef
.Context
.getTrivialTypeSourceInfo(D
->getType());
2499 D
->setTypeSourceInfo(TSI
);
2502 SmallVector
<ParmVarDecl
*, 4> Params
;
2503 TypeSourceInfo
*TInfo
= SubstFunctionType(D
, Params
);
2506 QualType T
= adjustFunctionTypeForInstantiation(SemaRef
.Context
, D
, TInfo
);
2508 if (TemplateParams
&& TemplateParams
->size()) {
2510 dyn_cast
<TemplateTypeParmDecl
>(TemplateParams
->asArray().back());
2511 if (LastParam
&& LastParam
->isImplicit() &&
2512 LastParam
->hasTypeConstraint()) {
2513 // In abbreviated templates, the type-constraints of invented template
2514 // type parameters are instantiated with the function type, invalidating
2515 // the TemplateParameterList which relied on the template type parameter
2516 // not having a type constraint. Recreate the TemplateParameterList with
2517 // the updated parameter list.
2518 TemplateParams
= TemplateParameterList::Create(
2519 SemaRef
.Context
, TemplateParams
->getTemplateLoc(),
2520 TemplateParams
->getLAngleLoc(), TemplateParams
->asArray(),
2521 TemplateParams
->getRAngleLoc(), TemplateParams
->getRequiresClause());
2525 NestedNameSpecifierLoc QualifierLoc
= D
->getQualifierLoc();
2527 QualifierLoc
= SemaRef
.SubstNestedNameSpecifierLoc(QualifierLoc
,
2533 DeclContext
*DC
= Owner
;
2537 SS
.Adopt(QualifierLoc
);
2538 DC
= SemaRef
.computeDeclContext(SS
);
2540 if (DC
&& SemaRef
.RequireCompleteDeclContext(SS
, DC
))
2543 DC
= SemaRef
.FindInstantiatedContext(D
->getLocation(),
2544 D
->getDeclContext(),
2547 if (!DC
) return nullptr;
2550 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(DC
);
2551 Expr
*TrailingRequiresClause
= D
->getTrailingRequiresClause();
2553 DeclarationNameInfo NameInfo
2554 = SemaRef
.SubstDeclarationNameInfo(D
->getNameInfo(), TemplateArgs
);
2556 if (FunctionRewriteKind
!= RewriteKind::None
)
2557 adjustForRewrite(FunctionRewriteKind
, D
, T
, TInfo
, NameInfo
);
2559 // Build the instantiated method declaration.
2560 CXXMethodDecl
*Method
= nullptr;
2562 SourceLocation StartLoc
= D
->getInnerLocStart();
2563 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(D
)) {
2564 Method
= CXXConstructorDecl::Create(
2565 SemaRef
.Context
, Record
, StartLoc
, NameInfo
, T
, TInfo
,
2566 InstantiatedExplicitSpecifier
, Constructor
->UsesFPIntrin(),
2567 Constructor
->isInlineSpecified(), false,
2568 Constructor
->getConstexprKind(), InheritedConstructor(),
2569 TrailingRequiresClause
);
2570 Method
->setRangeEnd(Constructor
->getEndLoc());
2571 } else if (CXXDestructorDecl
*Destructor
= dyn_cast
<CXXDestructorDecl
>(D
)) {
2572 Method
= CXXDestructorDecl::Create(
2573 SemaRef
.Context
, Record
, StartLoc
, NameInfo
, T
, TInfo
,
2574 Destructor
->UsesFPIntrin(), Destructor
->isInlineSpecified(), false,
2575 Destructor
->getConstexprKind(), TrailingRequiresClause
);
2576 Method
->setIneligibleOrNotSelected(true);
2577 Method
->setRangeEnd(Destructor
->getEndLoc());
2578 Method
->setDeclName(SemaRef
.Context
.DeclarationNames
.getCXXDestructorName(
2579 SemaRef
.Context
.getCanonicalType(
2580 SemaRef
.Context
.getTypeDeclType(Record
))));
2581 } else if (CXXConversionDecl
*Conversion
= dyn_cast
<CXXConversionDecl
>(D
)) {
2582 Method
= CXXConversionDecl::Create(
2583 SemaRef
.Context
, Record
, StartLoc
, NameInfo
, T
, TInfo
,
2584 Conversion
->UsesFPIntrin(), Conversion
->isInlineSpecified(),
2585 InstantiatedExplicitSpecifier
, Conversion
->getConstexprKind(),
2586 Conversion
->getEndLoc(), TrailingRequiresClause
);
2588 StorageClass SC
= D
->isStatic() ? SC_Static
: SC_None
;
2589 Method
= CXXMethodDecl::Create(
2590 SemaRef
.Context
, Record
, StartLoc
, NameInfo
, T
, TInfo
, SC
,
2591 D
->UsesFPIntrin(), D
->isInlineSpecified(), D
->getConstexprKind(),
2592 D
->getEndLoc(), TrailingRequiresClause
);
2596 Method
->setImplicitlyInline();
2599 Method
->setQualifierInfo(QualifierLoc
);
2601 if (TemplateParams
) {
2602 // Our resulting instantiation is actually a function template, since we
2603 // are substituting only the outer template parameters. For example, given
2605 // template<typename T>
2607 // template<typename U> void f(T, U);
2612 // We are instantiating the member template "f" within X<int>, which means
2613 // substituting int for T, but leaving "f" as a member function template.
2614 // Build the function template itself.
2615 FunctionTemplate
= FunctionTemplateDecl::Create(SemaRef
.Context
, Record
,
2616 Method
->getLocation(),
2617 Method
->getDeclName(),
2618 TemplateParams
, Method
);
2620 FunctionTemplate
->setLexicalDeclContext(Owner
);
2621 FunctionTemplate
->setObjectOfFriendDecl();
2622 } else if (D
->isOutOfLine())
2623 FunctionTemplate
->setLexicalDeclContext(D
->getLexicalDeclContext());
2624 Method
->setDescribedFunctionTemplate(FunctionTemplate
);
2625 } else if (FunctionTemplate
) {
2626 // Record this function template specialization.
2627 ArrayRef
<TemplateArgument
> Innermost
= TemplateArgs
.getInnermost();
2628 Method
->setFunctionTemplateSpecialization(FunctionTemplate
,
2629 TemplateArgumentList::CreateCopy(SemaRef
.Context
,
2631 /*InsertPos=*/nullptr);
2632 } else if (!isFriend
) {
2633 // Record that this is an instantiation of a member function.
2634 Method
->setInstantiationOfMemberFunction(D
, TSK_ImplicitInstantiation
);
2637 // If we are instantiating a member function defined
2638 // out-of-line, the instantiation will have the same lexical
2639 // context (which will be a namespace scope) as the template.
2641 if (NumTempParamLists
)
2642 Method
->setTemplateParameterListsInfo(
2644 llvm::ArrayRef(TempParamLists
.data(), NumTempParamLists
));
2646 Method
->setLexicalDeclContext(Owner
);
2647 Method
->setObjectOfFriendDecl();
2648 } else if (D
->isOutOfLine())
2649 Method
->setLexicalDeclContext(D
->getLexicalDeclContext());
2651 // Attach the parameters
2652 for (unsigned P
= 0; P
< Params
.size(); ++P
)
2653 Params
[P
]->setOwningFunction(Method
);
2654 Method
->setParams(Params
);
2656 if (InitMethodInstantiation(Method
, D
))
2657 Method
->setInvalidDecl();
2659 LookupResult
Previous(SemaRef
, NameInfo
, Sema::LookupOrdinaryName
,
2660 Sema::ForExternalRedeclaration
);
2662 bool IsExplicitSpecialization
= false;
2664 // If the name of this function was written as a template-id, instantiate
2665 // the explicit template arguments.
2666 if (DependentFunctionTemplateSpecializationInfo
*DFTSI
=
2667 D
->getDependentSpecializationInfo()) {
2668 // Instantiate the explicit template arguments.
2669 TemplateArgumentListInfo ExplicitArgs
;
2670 if (const auto *ArgsWritten
= DFTSI
->TemplateArgumentsAsWritten
) {
2671 ExplicitArgs
.setLAngleLoc(ArgsWritten
->getLAngleLoc());
2672 ExplicitArgs
.setRAngleLoc(ArgsWritten
->getRAngleLoc());
2673 if (SemaRef
.SubstTemplateArguments(ArgsWritten
->arguments(), TemplateArgs
,
2678 // Map the candidates for the primary template to their instantiations.
2679 for (FunctionTemplateDecl
*FTD
: DFTSI
->getCandidates()) {
2681 SemaRef
.FindInstantiatedDecl(D
->getLocation(), FTD
, TemplateArgs
))
2682 Previous
.addDecl(ND
);
2687 if (SemaRef
.CheckFunctionTemplateSpecialization(
2688 Method
, DFTSI
->TemplateArgumentsAsWritten
? &ExplicitArgs
: nullptr,
2690 Method
->setInvalidDecl();
2692 IsExplicitSpecialization
= true;
2693 } else if (const ASTTemplateArgumentListInfo
*ArgsWritten
=
2694 D
->getTemplateSpecializationArgsAsWritten()) {
2695 SemaRef
.LookupQualifiedName(Previous
, DC
);
2697 TemplateArgumentListInfo
ExplicitArgs(ArgsWritten
->getLAngleLoc(),
2698 ArgsWritten
->getRAngleLoc());
2700 if (SemaRef
.SubstTemplateArguments(ArgsWritten
->arguments(), TemplateArgs
,
2704 if (SemaRef
.CheckFunctionTemplateSpecialization(Method
,
2707 Method
->setInvalidDecl();
2709 IsExplicitSpecialization
= true;
2710 } else if (!FunctionTemplate
|| TemplateParams
|| isFriend
) {
2711 SemaRef
.LookupQualifiedName(Previous
, Record
);
2713 // In C++, the previous declaration we find might be a tag type
2714 // (class or enum). In this case, the new declaration will hide the
2715 // tag type. Note that this does not apply if we're declaring a
2716 // typedef (C++ [dcl.typedef]p4).
2717 if (Previous
.isSingleTagDecl())
2721 // Per [temp.inst], default arguments in member functions of local classes
2722 // are instantiated along with the member function declaration. For example:
2724 // template<typename T>
2727 // int operator()(int p = []{ return T::value; }());
2730 // template void ft<int>(); // error: type 'int' cannot be used prior
2731 // to '::'because it has no members
2733 // The error is issued during instantiation of ft<int>()::lc::operator()
2734 // because substitution into the default argument fails; the default argument
2735 // is instantiated even though it is never used.
2736 if (D
->isInLocalScopeForInstantiation()) {
2737 for (unsigned P
= 0; P
< Params
.size(); ++P
) {
2738 if (!Params
[P
]->hasDefaultArg())
2740 if (SemaRef
.SubstDefaultArgument(StartLoc
, Params
[P
], TemplateArgs
)) {
2741 // If substitution fails, the default argument is set to a
2742 // RecoveryExpr that wraps the uninstantiated default argument so
2743 // that downstream diagnostics are omitted.
2744 Expr
*UninstExpr
= Params
[P
]->getUninstantiatedDefaultArg();
2745 ExprResult ErrorResult
= SemaRef
.CreateRecoveryExpr(
2746 UninstExpr
->getBeginLoc(), UninstExpr
->getEndLoc(),
2747 { UninstExpr
}, UninstExpr
->getType());
2748 if (ErrorResult
.isUsable())
2749 Params
[P
]->setDefaultArg(ErrorResult
.get());
2754 SemaRef
.CheckFunctionDeclaration(nullptr, Method
, Previous
,
2755 IsExplicitSpecialization
,
2756 Method
->isThisDeclarationADefinition());
2759 SemaRef
.CheckPureMethod(Method
, SourceRange());
2761 // Propagate access. For a non-friend declaration, the access is
2762 // whatever we're propagating from. For a friend, it should be the
2763 // previous declaration we just found.
2764 if (isFriend
&& Method
->getPreviousDecl())
2765 Method
->setAccess(Method
->getPreviousDecl()->getAccess());
2767 Method
->setAccess(D
->getAccess());
2768 if (FunctionTemplate
)
2769 FunctionTemplate
->setAccess(Method
->getAccess());
2771 SemaRef
.CheckOverrideControl(Method
);
2773 // If a function is defined as defaulted or deleted, mark it as such now.
2774 if (D
->isExplicitlyDefaulted()) {
2775 if (SubstDefaultedFunction(Method
, D
))
2778 if (D
->isDeletedAsWritten())
2779 SemaRef
.SetDeclDeleted(Method
, Method
->getLocation());
2781 // If this is an explicit specialization, mark the implicitly-instantiated
2782 // template specialization as being an explicit specialization too.
2783 // FIXME: Is this necessary?
2784 if (IsExplicitSpecialization
&& !isFriend
)
2785 SemaRef
.CompleteMemberSpecialization(Method
, Previous
);
2787 // If the method is a special member function, we need to mark it as
2788 // ineligible so that Owner->addDecl() won't mark the class as non trivial.
2789 // At the end of the class instantiation, we calculate eligibility again and
2790 // then we adjust trivility if needed.
2791 // We need this check to happen only after the method parameters are set,
2792 // because being e.g. a copy constructor depends on the instantiated
2794 if (auto *Constructor
= dyn_cast
<CXXConstructorDecl
>(Method
)) {
2795 if (Constructor
->isDefaultConstructor() ||
2796 Constructor
->isCopyOrMoveConstructor())
2797 Method
->setIneligibleOrNotSelected(true);
2798 } else if (Method
->isCopyAssignmentOperator() ||
2799 Method
->isMoveAssignmentOperator()) {
2800 Method
->setIneligibleOrNotSelected(true);
2803 // If there's a function template, let our caller handle it.
2804 if (FunctionTemplate
) {
2807 // Don't hide a (potentially) valid declaration with an invalid one.
2808 } else if (Method
->isInvalidDecl() && !Previous
.empty()) {
2811 // Otherwise, check access to friends and make them visible.
2812 } else if (isFriend
) {
2813 // We only need to re-check access for methods which we didn't
2814 // manage to match during parsing.
2815 if (!D
->getPreviousDecl())
2816 SemaRef
.CheckFriendAccess(Method
);
2818 Record
->makeDeclVisibleInContext(Method
);
2820 // Otherwise, add the declaration. We don't need to do this for
2821 // class-scope specializations because we'll have matched them with
2822 // the appropriate template.
2824 Owner
->addDecl(Method
);
2827 // PR17480: Honor the used attribute to instantiate member function
2829 if (Method
->hasAttr
<UsedAttr
>()) {
2830 if (const auto *A
= dyn_cast
<CXXRecordDecl
>(Owner
)) {
2832 if (const MemberSpecializationInfo
*MSInfo
=
2833 A
->getMemberSpecializationInfo())
2834 Loc
= MSInfo
->getPointOfInstantiation();
2835 else if (const auto *Spec
= dyn_cast
<ClassTemplateSpecializationDecl
>(A
))
2836 Loc
= Spec
->getPointOfInstantiation();
2837 SemaRef
.MarkFunctionReferenced(Loc
, Method
);
2844 Decl
*TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl
*D
) {
2845 return VisitCXXMethodDecl(D
);
2848 Decl
*TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl
*D
) {
2849 return VisitCXXMethodDecl(D
);
2852 Decl
*TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl
*D
) {
2853 return VisitCXXMethodDecl(D
);
2856 Decl
*TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl
*D
) {
2857 return SemaRef
.SubstParmVarDecl(D
, TemplateArgs
, /*indexAdjustment*/ 0,
2859 /*ExpectParameterPack=*/false);
2862 Decl
*TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2863 TemplateTypeParmDecl
*D
) {
2864 assert(D
->getTypeForDecl()->isTemplateTypeParmType());
2866 std::optional
<unsigned> NumExpanded
;
2868 if (const TypeConstraint
*TC
= D
->getTypeConstraint()) {
2869 if (D
->isPackExpansion() && !D
->isExpandedParameterPack()) {
2870 assert(TC
->getTemplateArgsAsWritten() &&
2871 "type parameter can only be an expansion when explicit arguments "
2873 // The template type parameter pack's type is a pack expansion of types.
2874 // Determine whether we need to expand this parameter pack into separate
2876 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
2877 for (auto &ArgLoc
: TC
->getTemplateArgsAsWritten()->arguments())
2878 SemaRef
.collectUnexpandedParameterPacks(ArgLoc
, Unexpanded
);
2880 // Determine whether the set of unexpanded parameter packs can and should
2883 bool RetainExpansion
= false;
2884 if (SemaRef
.CheckParameterPacksForExpansion(
2885 cast
<CXXFoldExpr
>(TC
->getImmediatelyDeclaredConstraint())
2887 SourceRange(TC
->getConceptNameLoc(),
2888 TC
->hasExplicitTemplateArgs() ?
2889 TC
->getTemplateArgsAsWritten()->getRAngleLoc() :
2890 TC
->getConceptNameInfo().getEndLoc()),
2891 Unexpanded
, TemplateArgs
, Expand
, RetainExpansion
, NumExpanded
))
2896 TemplateTypeParmDecl
*Inst
= TemplateTypeParmDecl::Create(
2897 SemaRef
.Context
, Owner
, D
->getBeginLoc(), D
->getLocation(),
2898 D
->getDepth() - TemplateArgs
.getNumSubstitutedLevels(), D
->getIndex(),
2899 D
->getIdentifier(), D
->wasDeclaredWithTypename(), D
->isParameterPack(),
2900 D
->hasTypeConstraint(), NumExpanded
);
2902 Inst
->setAccess(AS_public
);
2903 Inst
->setImplicit(D
->isImplicit());
2904 if (auto *TC
= D
->getTypeConstraint()) {
2905 if (!D
->isImplicit()) {
2906 // Invented template parameter type constraints will be instantiated
2907 // with the corresponding auto-typed parameter as it might reference
2908 // other parameters.
2909 if (SemaRef
.SubstTypeConstraint(Inst
, TC
, TemplateArgs
,
2910 EvaluateConstraints
))
2914 if (D
->hasDefaultArgument() && !D
->defaultArgumentWasInherited()) {
2915 TypeSourceInfo
*InstantiatedDefaultArg
=
2916 SemaRef
.SubstType(D
->getDefaultArgumentInfo(), TemplateArgs
,
2917 D
->getDefaultArgumentLoc(), D
->getDeclName());
2918 if (InstantiatedDefaultArg
)
2919 Inst
->setDefaultArgument(InstantiatedDefaultArg
);
2922 // Introduce this template parameter's instantiation into the instantiation
2924 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Inst
);
2929 Decl
*TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2930 NonTypeTemplateParmDecl
*D
) {
2931 // Substitute into the type of the non-type template parameter.
2932 TypeLoc TL
= D
->getTypeSourceInfo()->getTypeLoc();
2933 SmallVector
<TypeSourceInfo
*, 4> ExpandedParameterPackTypesAsWritten
;
2934 SmallVector
<QualType
, 4> ExpandedParameterPackTypes
;
2935 bool IsExpandedParameterPack
= false;
2938 bool Invalid
= false;
2940 if (D
->isExpandedParameterPack()) {
2941 // The non-type template parameter pack is an already-expanded pack
2942 // expansion of types. Substitute into each of the expanded types.
2943 ExpandedParameterPackTypes
.reserve(D
->getNumExpansionTypes());
2944 ExpandedParameterPackTypesAsWritten
.reserve(D
->getNumExpansionTypes());
2945 for (unsigned I
= 0, N
= D
->getNumExpansionTypes(); I
!= N
; ++I
) {
2946 TypeSourceInfo
*NewDI
=
2947 SemaRef
.SubstType(D
->getExpansionTypeSourceInfo(I
), TemplateArgs
,
2948 D
->getLocation(), D
->getDeclName());
2953 SemaRef
.CheckNonTypeTemplateParameterType(NewDI
, D
->getLocation());
2957 ExpandedParameterPackTypesAsWritten
.push_back(NewDI
);
2958 ExpandedParameterPackTypes
.push_back(NewT
);
2961 IsExpandedParameterPack
= true;
2962 DI
= D
->getTypeSourceInfo();
2964 } else if (D
->isPackExpansion()) {
2965 // The non-type template parameter pack's type is a pack expansion of types.
2966 // Determine whether we need to expand this parameter pack into separate
2968 PackExpansionTypeLoc Expansion
= TL
.castAs
<PackExpansionTypeLoc
>();
2969 TypeLoc Pattern
= Expansion
.getPatternLoc();
2970 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
2971 SemaRef
.collectUnexpandedParameterPacks(Pattern
, Unexpanded
);
2973 // Determine whether the set of unexpanded parameter packs can and should
2976 bool RetainExpansion
= false;
2977 std::optional
<unsigned> OrigNumExpansions
=
2978 Expansion
.getTypePtr()->getNumExpansions();
2979 std::optional
<unsigned> NumExpansions
= OrigNumExpansions
;
2980 if (SemaRef
.CheckParameterPacksForExpansion(Expansion
.getEllipsisLoc(),
2981 Pattern
.getSourceRange(),
2984 Expand
, RetainExpansion
,
2989 for (unsigned I
= 0; I
!= *NumExpansions
; ++I
) {
2990 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, I
);
2991 TypeSourceInfo
*NewDI
= SemaRef
.SubstType(Pattern
, TemplateArgs
,
2998 SemaRef
.CheckNonTypeTemplateParameterType(NewDI
, D
->getLocation());
3002 ExpandedParameterPackTypesAsWritten
.push_back(NewDI
);
3003 ExpandedParameterPackTypes
.push_back(NewT
);
3006 // Note that we have an expanded parameter pack. The "type" of this
3007 // expanded parameter pack is the original expansion type, but callers
3008 // will end up using the expanded parameter pack types for type-checking.
3009 IsExpandedParameterPack
= true;
3010 DI
= D
->getTypeSourceInfo();
3013 // We cannot fully expand the pack expansion now, so substitute into the
3014 // pattern and create a new pack expansion type.
3015 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, -1);
3016 TypeSourceInfo
*NewPattern
= SemaRef
.SubstType(Pattern
, TemplateArgs
,
3022 SemaRef
.CheckNonTypeTemplateParameterType(NewPattern
, D
->getLocation());
3023 DI
= SemaRef
.CheckPackExpansion(NewPattern
, Expansion
.getEllipsisLoc(),
3031 // Simple case: substitution into a parameter that is not a parameter pack.
3032 DI
= SemaRef
.SubstType(D
->getTypeSourceInfo(), TemplateArgs
,
3033 D
->getLocation(), D
->getDeclName());
3037 // Check that this type is acceptable for a non-type template parameter.
3038 T
= SemaRef
.CheckNonTypeTemplateParameterType(DI
, D
->getLocation());
3040 T
= SemaRef
.Context
.IntTy
;
3045 NonTypeTemplateParmDecl
*Param
;
3046 if (IsExpandedParameterPack
)
3047 Param
= NonTypeTemplateParmDecl::Create(
3048 SemaRef
.Context
, Owner
, D
->getInnerLocStart(), D
->getLocation(),
3049 D
->getDepth() - TemplateArgs
.getNumSubstitutedLevels(),
3050 D
->getPosition(), D
->getIdentifier(), T
, DI
, ExpandedParameterPackTypes
,
3051 ExpandedParameterPackTypesAsWritten
);
3053 Param
= NonTypeTemplateParmDecl::Create(
3054 SemaRef
.Context
, Owner
, D
->getInnerLocStart(), D
->getLocation(),
3055 D
->getDepth() - TemplateArgs
.getNumSubstitutedLevels(),
3056 D
->getPosition(), D
->getIdentifier(), T
, D
->isParameterPack(), DI
);
3058 if (AutoTypeLoc AutoLoc
= DI
->getTypeLoc().getContainedAutoTypeLoc())
3059 if (AutoLoc
.isConstrained())
3060 // Note: We attach the uninstantiated constriant here, so that it can be
3061 // instantiated relative to the top level, like all our other constraints.
3062 if (SemaRef
.AttachTypeConstraint(
3064 IsExpandedParameterPack
3065 ? DI
->getTypeLoc().getAs
<PackExpansionTypeLoc
>()
3067 : SourceLocation()))
3070 Param
->setAccess(AS_public
);
3071 Param
->setImplicit(D
->isImplicit());
3073 Param
->setInvalidDecl();
3075 if (D
->hasDefaultArgument() && !D
->defaultArgumentWasInherited()) {
3076 EnterExpressionEvaluationContext
ConstantEvaluated(
3077 SemaRef
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
3078 ExprResult Value
= SemaRef
.SubstExpr(D
->getDefaultArgument(), TemplateArgs
);
3079 if (!Value
.isInvalid())
3080 Param
->setDefaultArgument(Value
.get());
3083 // Introduce this template parameter's instantiation into the instantiation
3085 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Param
);
3089 static void collectUnexpandedParameterPacks(
3091 TemplateParameterList
*Params
,
3092 SmallVectorImpl
<UnexpandedParameterPack
> &Unexpanded
) {
3093 for (const auto &P
: *Params
) {
3094 if (P
->isTemplateParameterPack())
3096 if (NonTypeTemplateParmDecl
*NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(P
))
3097 S
.collectUnexpandedParameterPacks(NTTP
->getTypeSourceInfo()->getTypeLoc(),
3099 if (TemplateTemplateParmDecl
*TTP
= dyn_cast
<TemplateTemplateParmDecl
>(P
))
3100 collectUnexpandedParameterPacks(S
, TTP
->getTemplateParameters(),
3106 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3107 TemplateTemplateParmDecl
*D
) {
3108 // Instantiate the template parameter list of the template template parameter.
3109 TemplateParameterList
*TempParams
= D
->getTemplateParameters();
3110 TemplateParameterList
*InstParams
;
3111 SmallVector
<TemplateParameterList
*, 8> ExpandedParams
;
3113 bool IsExpandedParameterPack
= false;
3115 if (D
->isExpandedParameterPack()) {
3116 // The template template parameter pack is an already-expanded pack
3117 // expansion of template parameters. Substitute into each of the expanded
3119 ExpandedParams
.reserve(D
->getNumExpansionTemplateParameters());
3120 for (unsigned I
= 0, N
= D
->getNumExpansionTemplateParameters();
3122 LocalInstantiationScope
Scope(SemaRef
);
3123 TemplateParameterList
*Expansion
=
3124 SubstTemplateParams(D
->getExpansionTemplateParameters(I
));
3127 ExpandedParams
.push_back(Expansion
);
3130 IsExpandedParameterPack
= true;
3131 InstParams
= TempParams
;
3132 } else if (D
->isPackExpansion()) {
3133 // The template template parameter pack expands to a pack of template
3134 // template parameters. Determine whether we need to expand this parameter
3135 // pack into separate parameters.
3136 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
3137 collectUnexpandedParameterPacks(SemaRef
, D
->getTemplateParameters(),
3140 // Determine whether the set of unexpanded parameter packs can and should
3143 bool RetainExpansion
= false;
3144 std::optional
<unsigned> NumExpansions
;
3145 if (SemaRef
.CheckParameterPacksForExpansion(D
->getLocation(),
3146 TempParams
->getSourceRange(),
3149 Expand
, RetainExpansion
,
3154 for (unsigned I
= 0; I
!= *NumExpansions
; ++I
) {
3155 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, I
);
3156 LocalInstantiationScope
Scope(SemaRef
);
3157 TemplateParameterList
*Expansion
= SubstTemplateParams(TempParams
);
3160 ExpandedParams
.push_back(Expansion
);
3163 // Note that we have an expanded parameter pack. The "type" of this
3164 // expanded parameter pack is the original expansion type, but callers
3165 // will end up using the expanded parameter pack types for type-checking.
3166 IsExpandedParameterPack
= true;
3167 InstParams
= TempParams
;
3169 // We cannot fully expand the pack expansion now, so just substitute
3170 // into the pattern.
3171 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, -1);
3173 LocalInstantiationScope
Scope(SemaRef
);
3174 InstParams
= SubstTemplateParams(TempParams
);
3179 // Perform the actual substitution of template parameters within a new,
3180 // local instantiation scope.
3181 LocalInstantiationScope
Scope(SemaRef
);
3182 InstParams
= SubstTemplateParams(TempParams
);
3187 // Build the template template parameter.
3188 TemplateTemplateParmDecl
*Param
;
3189 if (IsExpandedParameterPack
)
3190 Param
= TemplateTemplateParmDecl::Create(
3191 SemaRef
.Context
, Owner
, D
->getLocation(),
3192 D
->getDepth() - TemplateArgs
.getNumSubstitutedLevels(),
3193 D
->getPosition(), D
->getIdentifier(), InstParams
, ExpandedParams
);
3195 Param
= TemplateTemplateParmDecl::Create(
3196 SemaRef
.Context
, Owner
, D
->getLocation(),
3197 D
->getDepth() - TemplateArgs
.getNumSubstitutedLevels(),
3198 D
->getPosition(), D
->isParameterPack(), D
->getIdentifier(), InstParams
);
3199 if (D
->hasDefaultArgument() && !D
->defaultArgumentWasInherited()) {
3200 NestedNameSpecifierLoc QualifierLoc
=
3201 D
->getDefaultArgument().getTemplateQualifierLoc();
3203 SemaRef
.SubstNestedNameSpecifierLoc(QualifierLoc
, TemplateArgs
);
3204 TemplateName TName
= SemaRef
.SubstTemplateName(
3205 QualifierLoc
, D
->getDefaultArgument().getArgument().getAsTemplate(),
3206 D
->getDefaultArgument().getTemplateNameLoc(), TemplateArgs
);
3207 if (!TName
.isNull())
3208 Param
->setDefaultArgument(
3210 TemplateArgumentLoc(SemaRef
.Context
, TemplateArgument(TName
),
3211 D
->getDefaultArgument().getTemplateQualifierLoc(),
3212 D
->getDefaultArgument().getTemplateNameLoc()));
3214 Param
->setAccess(AS_public
);
3215 Param
->setImplicit(D
->isImplicit());
3217 // Introduce this template parameter's instantiation into the instantiation
3219 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Param
);
3224 Decl
*TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl
*D
) {
3225 // Using directives are never dependent (and never contain any types or
3226 // expressions), so they require no explicit instantiation work.
3228 UsingDirectiveDecl
*Inst
3229 = UsingDirectiveDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
3230 D
->getNamespaceKeyLocation(),
3231 D
->getQualifierLoc(),
3232 D
->getIdentLocation(),
3233 D
->getNominatedNamespace(),
3234 D
->getCommonAncestor());
3236 // Add the using directive to its declaration context
3237 // only if this is not a function or method.
3238 if (!Owner
->isFunctionOrMethod())
3239 Owner
->addDecl(Inst
);
3244 Decl
*TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl
*D
,
3245 BaseUsingDecl
*Inst
,
3246 LookupResult
*Lookup
) {
3248 bool isFunctionScope
= Owner
->isFunctionOrMethod();
3250 for (auto *Shadow
: D
->shadows()) {
3251 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3252 // reconstruct it in the case where it matters. Hm, can we extract it from
3253 // the DeclSpec when parsing and save it in the UsingDecl itself?
3254 NamedDecl
*OldTarget
= Shadow
->getTargetDecl();
3255 if (auto *CUSD
= dyn_cast
<ConstructorUsingShadowDecl
>(Shadow
))
3256 if (auto *BaseShadow
= CUSD
->getNominatedBaseClassShadowDecl())
3257 OldTarget
= BaseShadow
;
3259 NamedDecl
*InstTarget
= nullptr;
3261 dyn_cast
<UnresolvedUsingIfExistsDecl
>(Shadow
->getTargetDecl())) {
3262 InstTarget
= UnresolvedUsingIfExistsDecl::Create(
3263 SemaRef
.Context
, Owner
, EmptyD
->getLocation(), EmptyD
->getDeclName());
3265 InstTarget
= cast_or_null
<NamedDecl
>(SemaRef
.FindInstantiatedDecl(
3266 Shadow
->getLocation(), OldTarget
, TemplateArgs
));
3271 UsingShadowDecl
*PrevDecl
= nullptr;
3273 SemaRef
.CheckUsingShadowDecl(Inst
, InstTarget
, *Lookup
, PrevDecl
))
3276 if (UsingShadowDecl
*OldPrev
= getPreviousDeclForInstantiation(Shadow
))
3277 PrevDecl
= cast_or_null
<UsingShadowDecl
>(SemaRef
.FindInstantiatedDecl(
3278 Shadow
->getLocation(), OldPrev
, TemplateArgs
));
3280 UsingShadowDecl
*InstShadow
= SemaRef
.BuildUsingShadowDecl(
3281 /*Scope*/ nullptr, Inst
, InstTarget
, PrevDecl
);
3282 SemaRef
.Context
.setInstantiatedFromUsingShadowDecl(InstShadow
, Shadow
);
3284 if (isFunctionScope
)
3285 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(Shadow
, InstShadow
);
3291 Decl
*TemplateDeclInstantiator::VisitUsingDecl(UsingDecl
*D
) {
3293 // The nested name specifier may be dependent, for example
3294 // template <typename T> struct t {
3295 // struct s1 { T f1(); };
3296 // struct s2 : s1 { using s1::f1; };
3298 // template struct t<int>;
3299 // Here, in using s1::f1, s1 refers to t<T>::s1;
3300 // we need to substitute for t<int>::s1.
3301 NestedNameSpecifierLoc QualifierLoc
3302 = SemaRef
.SubstNestedNameSpecifierLoc(D
->getQualifierLoc(),
3307 // For an inheriting constructor declaration, the name of the using
3308 // declaration is the name of a constructor in this class, not in the
3310 DeclarationNameInfo NameInfo
= D
->getNameInfo();
3311 if (NameInfo
.getName().getNameKind() == DeclarationName::CXXConstructorName
)
3312 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(SemaRef
.CurContext
))
3313 NameInfo
.setName(SemaRef
.Context
.DeclarationNames
.getCXXConstructorName(
3314 SemaRef
.Context
.getCanonicalType(SemaRef
.Context
.getRecordType(RD
))));
3316 // We only need to do redeclaration lookups if we're in a class scope (in
3317 // fact, it's not really even possible in non-class scopes).
3318 bool CheckRedeclaration
= Owner
->isRecord();
3319 LookupResult
Prev(SemaRef
, NameInfo
, Sema::LookupUsingDeclName
,
3320 Sema::ForVisibleRedeclaration
);
3322 UsingDecl
*NewUD
= UsingDecl::Create(SemaRef
.Context
, Owner
,
3329 SS
.Adopt(QualifierLoc
);
3330 if (CheckRedeclaration
) {
3331 Prev
.setHideTags(false);
3332 SemaRef
.LookupQualifiedName(Prev
, Owner
);
3334 // Check for invalid redeclarations.
3335 if (SemaRef
.CheckUsingDeclRedeclaration(D
->getUsingLoc(),
3336 D
->hasTypename(), SS
,
3337 D
->getLocation(), Prev
))
3338 NewUD
->setInvalidDecl();
3341 if (!NewUD
->isInvalidDecl() &&
3342 SemaRef
.CheckUsingDeclQualifier(D
->getUsingLoc(), D
->hasTypename(), SS
,
3343 NameInfo
, D
->getLocation(), nullptr, D
))
3344 NewUD
->setInvalidDecl();
3346 SemaRef
.Context
.setInstantiatedFromUsingDecl(NewUD
, D
);
3347 NewUD
->setAccess(D
->getAccess());
3348 Owner
->addDecl(NewUD
);
3350 // Don't process the shadow decls for an invalid decl.
3351 if (NewUD
->isInvalidDecl())
3354 // If the using scope was dependent, or we had dependent bases, we need to
3355 // recheck the inheritance
3356 if (NameInfo
.getName().getNameKind() == DeclarationName::CXXConstructorName
)
3357 SemaRef
.CheckInheritingConstructorUsingDecl(NewUD
);
3359 return VisitBaseUsingDecls(D
, NewUD
, CheckRedeclaration
? &Prev
: nullptr);
3362 Decl
*TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl
*D
) {
3363 // Cannot be a dependent type, but still could be an instantiation
3364 EnumDecl
*EnumD
= cast_or_null
<EnumDecl
>(SemaRef
.FindInstantiatedDecl(
3365 D
->getLocation(), D
->getEnumDecl(), TemplateArgs
));
3367 if (SemaRef
.RequireCompleteEnumDecl(EnumD
, EnumD
->getLocation()))
3370 TypeSourceInfo
*TSI
= SemaRef
.SubstType(D
->getEnumType(), TemplateArgs
,
3371 D
->getLocation(), D
->getDeclName());
3372 UsingEnumDecl
*NewUD
=
3373 UsingEnumDecl::Create(SemaRef
.Context
, Owner
, D
->getUsingLoc(),
3374 D
->getEnumLoc(), D
->getLocation(), TSI
);
3376 SemaRef
.Context
.setInstantiatedFromUsingEnumDecl(NewUD
, D
);
3377 NewUD
->setAccess(D
->getAccess());
3378 Owner
->addDecl(NewUD
);
3380 // Don't process the shadow decls for an invalid decl.
3381 if (NewUD
->isInvalidDecl())
3384 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3385 // cannot be dependent, and will therefore have been checked during template
3388 return VisitBaseUsingDecls(D
, NewUD
, nullptr);
3391 Decl
*TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl
*D
) {
3392 // Ignore these; we handle them in bulk when processing the UsingDecl.
3396 Decl
*TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3397 ConstructorUsingShadowDecl
*D
) {
3398 // Ignore these; we handle them in bulk when processing the UsingDecl.
3402 template <typename T
>
3403 Decl
*TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3404 T
*D
, bool InstantiatingPackElement
) {
3405 // If this is a pack expansion, expand it now.
3406 if (D
->isPackExpansion() && !InstantiatingPackElement
) {
3407 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
3408 SemaRef
.collectUnexpandedParameterPacks(D
->getQualifierLoc(), Unexpanded
);
3409 SemaRef
.collectUnexpandedParameterPacks(D
->getNameInfo(), Unexpanded
);
3411 // Determine whether the set of unexpanded parameter packs can and should
3414 bool RetainExpansion
= false;
3415 std::optional
<unsigned> NumExpansions
;
3416 if (SemaRef
.CheckParameterPacksForExpansion(
3417 D
->getEllipsisLoc(), D
->getSourceRange(), Unexpanded
, TemplateArgs
,
3418 Expand
, RetainExpansion
, NumExpansions
))
3421 // This declaration cannot appear within a function template signature,
3422 // so we can't have a partial argument list for a parameter pack.
3423 assert(!RetainExpansion
&&
3424 "should never need to retain an expansion for UsingPackDecl");
3427 // We cannot fully expand the pack expansion now, so substitute into the
3428 // pattern and create a new pack expansion.
3429 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, -1);
3430 return instantiateUnresolvedUsingDecl(D
, true);
3433 // Within a function, we don't have any normal way to check for conflicts
3434 // between shadow declarations from different using declarations in the
3435 // same pack expansion, but this is always ill-formed because all expansions
3436 // must produce (conflicting) enumerators.
3438 // Sadly we can't just reject this in the template definition because it
3439 // could be valid if the pack is empty or has exactly one expansion.
3440 if (D
->getDeclContext()->isFunctionOrMethod() && *NumExpansions
> 1) {
3441 SemaRef
.Diag(D
->getEllipsisLoc(),
3442 diag::err_using_decl_redeclaration_expansion
);
3446 // Instantiate the slices of this pack and build a UsingPackDecl.
3447 SmallVector
<NamedDecl
*, 8> Expansions
;
3448 for (unsigned I
= 0; I
!= *NumExpansions
; ++I
) {
3449 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, I
);
3450 Decl
*Slice
= instantiateUnresolvedUsingDecl(D
, true);
3453 // Note that we can still get unresolved using declarations here, if we
3454 // had arguments for all packs but the pattern also contained other
3455 // template arguments (this only happens during partial substitution, eg
3456 // into the body of a generic lambda in a function template).
3457 Expansions
.push_back(cast
<NamedDecl
>(Slice
));
3460 auto *NewD
= SemaRef
.BuildUsingPackDecl(D
, Expansions
);
3461 if (isDeclWithinFunction(D
))
3462 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, NewD
);
3466 UnresolvedUsingTypenameDecl
*TD
= dyn_cast
<UnresolvedUsingTypenameDecl
>(D
);
3467 SourceLocation TypenameLoc
= TD
? TD
->getTypenameLoc() : SourceLocation();
3469 NestedNameSpecifierLoc QualifierLoc
3470 = SemaRef
.SubstNestedNameSpecifierLoc(D
->getQualifierLoc(),
3476 SS
.Adopt(QualifierLoc
);
3478 DeclarationNameInfo NameInfo
3479 = SemaRef
.SubstDeclarationNameInfo(D
->getNameInfo(), TemplateArgs
);
3481 // Produce a pack expansion only if we're not instantiating a particular
3482 // slice of a pack expansion.
3483 bool InstantiatingSlice
= D
->getEllipsisLoc().isValid() &&
3484 SemaRef
.ArgumentPackSubstitutionIndex
!= -1;
3485 SourceLocation EllipsisLoc
=
3486 InstantiatingSlice
? SourceLocation() : D
->getEllipsisLoc();
3488 bool IsUsingIfExists
= D
->template hasAttr
<UsingIfExistsAttr
>();
3489 NamedDecl
*UD
= SemaRef
.BuildUsingDeclaration(
3490 /*Scope*/ nullptr, D
->getAccess(), D
->getUsingLoc(),
3491 /*HasTypename*/ TD
, TypenameLoc
, SS
, NameInfo
, EllipsisLoc
,
3492 ParsedAttributesView(),
3493 /*IsInstantiation*/ true, IsUsingIfExists
);
3495 SemaRef
.InstantiateAttrs(TemplateArgs
, D
, UD
);
3496 SemaRef
.Context
.setInstantiatedFromUsingDecl(UD
, D
);
3502 Decl
*TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3503 UnresolvedUsingTypenameDecl
*D
) {
3504 return instantiateUnresolvedUsingDecl(D
);
3507 Decl
*TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3508 UnresolvedUsingValueDecl
*D
) {
3509 return instantiateUnresolvedUsingDecl(D
);
3512 Decl
*TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3513 UnresolvedUsingIfExistsDecl
*D
) {
3514 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3517 Decl
*TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl
*D
) {
3518 SmallVector
<NamedDecl
*, 8> Expansions
;
3519 for (auto *UD
: D
->expansions()) {
3520 if (NamedDecl
*NewUD
=
3521 SemaRef
.FindInstantiatedDecl(D
->getLocation(), UD
, TemplateArgs
))
3522 Expansions
.push_back(NewUD
);
3527 auto *NewD
= SemaRef
.BuildUsingPackDecl(D
, Expansions
);
3528 if (isDeclWithinFunction(D
))
3529 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, NewD
);
3533 Decl
*TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3534 OMPThreadPrivateDecl
*D
) {
3535 SmallVector
<Expr
*, 5> Vars
;
3536 for (auto *I
: D
->varlists()) {
3537 Expr
*Var
= SemaRef
.SubstExpr(I
, TemplateArgs
).get();
3538 assert(isa
<DeclRefExpr
>(Var
) && "threadprivate arg is not a DeclRefExpr");
3539 Vars
.push_back(Var
);
3542 OMPThreadPrivateDecl
*TD
=
3543 SemaRef
.CheckOMPThreadPrivateDecl(D
->getLocation(), Vars
);
3545 TD
->setAccess(AS_public
);
3551 Decl
*TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl
*D
) {
3552 SmallVector
<Expr
*, 5> Vars
;
3553 for (auto *I
: D
->varlists()) {
3554 Expr
*Var
= SemaRef
.SubstExpr(I
, TemplateArgs
).get();
3555 assert(isa
<DeclRefExpr
>(Var
) && "allocate arg is not a DeclRefExpr");
3556 Vars
.push_back(Var
);
3558 SmallVector
<OMPClause
*, 4> Clauses
;
3559 // Copy map clauses from the original mapper.
3560 for (OMPClause
*C
: D
->clauselists()) {
3561 OMPClause
*IC
= nullptr;
3562 if (auto *AC
= dyn_cast
<OMPAllocatorClause
>(C
)) {
3563 ExprResult NewE
= SemaRef
.SubstExpr(AC
->getAllocator(), TemplateArgs
);
3564 if (!NewE
.isUsable())
3566 IC
= SemaRef
.ActOnOpenMPAllocatorClause(
3567 NewE
.get(), AC
->getBeginLoc(), AC
->getLParenLoc(), AC
->getEndLoc());
3568 } else if (auto *AC
= dyn_cast
<OMPAlignClause
>(C
)) {
3569 ExprResult NewE
= SemaRef
.SubstExpr(AC
->getAlignment(), TemplateArgs
);
3570 if (!NewE
.isUsable())
3572 IC
= SemaRef
.ActOnOpenMPAlignClause(NewE
.get(), AC
->getBeginLoc(),
3573 AC
->getLParenLoc(), AC
->getEndLoc());
3574 // If align clause value ends up being invalid, this can end up null.
3578 Clauses
.push_back(IC
);
3581 Sema::DeclGroupPtrTy Res
= SemaRef
.ActOnOpenMPAllocateDirective(
3582 D
->getLocation(), Vars
, Clauses
, Owner
);
3583 if (Res
.get().isNull())
3585 return Res
.get().getSingleDecl();
3588 Decl
*TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl
*D
) {
3590 "Requires directive cannot be instantiated within a dependent context");
3593 Decl
*TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3594 OMPDeclareReductionDecl
*D
) {
3595 // Instantiate type and check if it is allowed.
3596 const bool RequiresInstantiation
=
3597 D
->getType()->isDependentType() ||
3598 D
->getType()->isInstantiationDependentType() ||
3599 D
->getType()->containsUnexpandedParameterPack();
3600 QualType SubstReductionType
;
3601 if (RequiresInstantiation
) {
3602 SubstReductionType
= SemaRef
.ActOnOpenMPDeclareReductionType(
3604 ParsedType::make(SemaRef
.SubstType(
3605 D
->getType(), TemplateArgs
, D
->getLocation(), DeclarationName())));
3607 SubstReductionType
= D
->getType();
3609 if (SubstReductionType
.isNull())
3611 Expr
*Combiner
= D
->getCombiner();
3612 Expr
*Init
= D
->getInitializer();
3613 bool IsCorrect
= true;
3614 // Create instantiated copy.
3615 std::pair
<QualType
, SourceLocation
> ReductionTypes
[] = {
3616 std::make_pair(SubstReductionType
, D
->getLocation())};
3617 auto *PrevDeclInScope
= D
->getPrevDeclInScope();
3618 if (PrevDeclInScope
&& !PrevDeclInScope
->isInvalidDecl()) {
3619 PrevDeclInScope
= cast
<OMPDeclareReductionDecl
>(
3620 SemaRef
.CurrentInstantiationScope
->findInstantiationOf(PrevDeclInScope
)
3623 auto DRD
= SemaRef
.ActOnOpenMPDeclareReductionDirectiveStart(
3624 /*S=*/nullptr, Owner
, D
->getDeclName(), ReductionTypes
, D
->getAccess(),
3626 auto *NewDRD
= cast
<OMPDeclareReductionDecl
>(DRD
.get().getSingleDecl());
3627 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, NewDRD
);
3628 Expr
*SubstCombiner
= nullptr;
3629 Expr
*SubstInitializer
= nullptr;
3630 // Combiners instantiation sequence.
3632 SemaRef
.ActOnOpenMPDeclareReductionCombinerStart(
3633 /*S=*/nullptr, NewDRD
);
3634 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(
3635 cast
<DeclRefExpr
>(D
->getCombinerIn())->getDecl(),
3636 cast
<DeclRefExpr
>(NewDRD
->getCombinerIn())->getDecl());
3637 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(
3638 cast
<DeclRefExpr
>(D
->getCombinerOut())->getDecl(),
3639 cast
<DeclRefExpr
>(NewDRD
->getCombinerOut())->getDecl());
3640 auto *ThisContext
= dyn_cast_or_null
<CXXRecordDecl
>(Owner
);
3641 Sema::CXXThisScopeRAII
ThisScope(SemaRef
, ThisContext
, Qualifiers(),
3643 SubstCombiner
= SemaRef
.SubstExpr(Combiner
, TemplateArgs
).get();
3644 SemaRef
.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD
, SubstCombiner
);
3646 // Initializers instantiation sequence.
3648 VarDecl
*OmpPrivParm
= SemaRef
.ActOnOpenMPDeclareReductionInitializerStart(
3649 /*S=*/nullptr, NewDRD
);
3650 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(
3651 cast
<DeclRefExpr
>(D
->getInitOrig())->getDecl(),
3652 cast
<DeclRefExpr
>(NewDRD
->getInitOrig())->getDecl());
3653 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(
3654 cast
<DeclRefExpr
>(D
->getInitPriv())->getDecl(),
3655 cast
<DeclRefExpr
>(NewDRD
->getInitPriv())->getDecl());
3656 if (D
->getInitializerKind() == OMPDeclareReductionInitKind::Call
) {
3657 SubstInitializer
= SemaRef
.SubstExpr(Init
, TemplateArgs
).get();
3660 cast
<VarDecl
>(cast
<DeclRefExpr
>(D
->getInitPriv())->getDecl());
3661 IsCorrect
= IsCorrect
&& OldPrivParm
->hasInit();
3663 SemaRef
.InstantiateVariableInitializer(OmpPrivParm
, OldPrivParm
,
3666 SemaRef
.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD
, SubstInitializer
,
3669 IsCorrect
= IsCorrect
&& SubstCombiner
&&
3671 (D
->getInitializerKind() == OMPDeclareReductionInitKind::Call
&&
3672 SubstInitializer
) ||
3673 (D
->getInitializerKind() != OMPDeclareReductionInitKind::Call
&&
3674 !SubstInitializer
));
3676 (void)SemaRef
.ActOnOpenMPDeclareReductionDirectiveEnd(
3677 /*S=*/nullptr, DRD
, IsCorrect
&& !D
->isInvalidDecl());
3683 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl
*D
) {
3684 // Instantiate type and check if it is allowed.
3685 const bool RequiresInstantiation
=
3686 D
->getType()->isDependentType() ||
3687 D
->getType()->isInstantiationDependentType() ||
3688 D
->getType()->containsUnexpandedParameterPack();
3689 QualType SubstMapperTy
;
3690 DeclarationName VN
= D
->getVarName();
3691 if (RequiresInstantiation
) {
3692 SubstMapperTy
= SemaRef
.ActOnOpenMPDeclareMapperType(
3694 ParsedType::make(SemaRef
.SubstType(D
->getType(), TemplateArgs
,
3695 D
->getLocation(), VN
)));
3697 SubstMapperTy
= D
->getType();
3699 if (SubstMapperTy
.isNull())
3701 // Create an instantiated copy of mapper.
3702 auto *PrevDeclInScope
= D
->getPrevDeclInScope();
3703 if (PrevDeclInScope
&& !PrevDeclInScope
->isInvalidDecl()) {
3704 PrevDeclInScope
= cast
<OMPDeclareMapperDecl
>(
3705 SemaRef
.CurrentInstantiationScope
->findInstantiationOf(PrevDeclInScope
)
3708 bool IsCorrect
= true;
3709 SmallVector
<OMPClause
*, 6> Clauses
;
3710 // Instantiate the mapper variable.
3711 DeclarationNameInfo DirName
;
3712 SemaRef
.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper
, DirName
,
3714 (*D
->clauselist_begin())->getBeginLoc());
3715 ExprResult MapperVarRef
= SemaRef
.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3716 /*S=*/nullptr, SubstMapperTy
, D
->getLocation(), VN
);
3717 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(
3718 cast
<DeclRefExpr
>(D
->getMapperVarRef())->getDecl(),
3719 cast
<DeclRefExpr
>(MapperVarRef
.get())->getDecl());
3720 auto *ThisContext
= dyn_cast_or_null
<CXXRecordDecl
>(Owner
);
3721 Sema::CXXThisScopeRAII
ThisScope(SemaRef
, ThisContext
, Qualifiers(),
3723 // Instantiate map clauses.
3724 for (OMPClause
*C
: D
->clauselists()) {
3725 auto *OldC
= cast
<OMPMapClause
>(C
);
3726 SmallVector
<Expr
*, 4> NewVars
;
3727 for (Expr
*OE
: OldC
->varlists()) {
3728 Expr
*NE
= SemaRef
.SubstExpr(OE
, TemplateArgs
).get();
3733 NewVars
.push_back(NE
);
3737 NestedNameSpecifierLoc NewQualifierLoc
=
3738 SemaRef
.SubstNestedNameSpecifierLoc(OldC
->getMapperQualifierLoc(),
3741 SS
.Adopt(NewQualifierLoc
);
3742 DeclarationNameInfo NewNameInfo
=
3743 SemaRef
.SubstDeclarationNameInfo(OldC
->getMapperIdInfo(), TemplateArgs
);
3744 OMPVarListLocTy
Locs(OldC
->getBeginLoc(), OldC
->getLParenLoc(),
3746 OMPClause
*NewC
= SemaRef
.ActOnOpenMPMapClause(
3747 OldC
->getIteratorModifier(), OldC
->getMapTypeModifiers(),
3748 OldC
->getMapTypeModifiersLoc(), SS
, NewNameInfo
, OldC
->getMapType(),
3749 OldC
->isImplicitMapType(), OldC
->getMapLoc(), OldC
->getColonLoc(),
3751 Clauses
.push_back(NewC
);
3753 SemaRef
.EndOpenMPDSABlock(nullptr);
3756 Sema::DeclGroupPtrTy DG
= SemaRef
.ActOnOpenMPDeclareMapperDirective(
3757 /*S=*/nullptr, Owner
, D
->getDeclName(), SubstMapperTy
, D
->getLocation(),
3758 VN
, D
->getAccess(), MapperVarRef
.get(), Clauses
, PrevDeclInScope
);
3759 Decl
*NewDMD
= DG
.get().getSingleDecl();
3760 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, NewDMD
);
3764 Decl
*TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3765 OMPCapturedExprDecl
* /*D*/) {
3766 llvm_unreachable("Should not be met in templates");
3769 Decl
*TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl
*D
) {
3770 return VisitFunctionDecl(D
, nullptr);
3774 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl
*D
) {
3775 Decl
*Inst
= VisitFunctionDecl(D
, nullptr);
3776 if (Inst
&& !D
->getDescribedFunctionTemplate())
3777 Owner
->addDecl(Inst
);
3781 Decl
*TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl
*D
) {
3782 return VisitCXXMethodDecl(D
, nullptr);
3785 Decl
*TemplateDeclInstantiator::VisitRecordDecl(RecordDecl
*D
) {
3786 llvm_unreachable("There are only CXXRecordDecls in C++");
3790 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3791 ClassTemplateSpecializationDecl
*D
) {
3792 // As a MS extension, we permit class-scope explicit specialization
3793 // of member class templates.
3794 ClassTemplateDecl
*ClassTemplate
= D
->getSpecializedTemplate();
3795 assert(ClassTemplate
->getDeclContext()->isRecord() &&
3796 D
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&&
3797 "can only instantiate an explicit specialization "
3798 "for a member class template");
3800 // Lookup the already-instantiated declaration in the instantiation
3801 // of the class template.
3802 ClassTemplateDecl
*InstClassTemplate
=
3803 cast_or_null
<ClassTemplateDecl
>(SemaRef
.FindInstantiatedDecl(
3804 D
->getLocation(), ClassTemplate
, TemplateArgs
));
3805 if (!InstClassTemplate
)
3808 // Substitute into the template arguments of the class template explicit
3810 TemplateSpecializationTypeLoc Loc
= D
->getTypeAsWritten()->getTypeLoc().
3811 castAs
<TemplateSpecializationTypeLoc
>();
3812 TemplateArgumentListInfo
InstTemplateArgs(Loc
.getLAngleLoc(),
3813 Loc
.getRAngleLoc());
3814 SmallVector
<TemplateArgumentLoc
, 4> ArgLocs
;
3815 for (unsigned I
= 0; I
!= Loc
.getNumArgs(); ++I
)
3816 ArgLocs
.push_back(Loc
.getArgLoc(I
));
3817 if (SemaRef
.SubstTemplateArguments(ArgLocs
, TemplateArgs
, InstTemplateArgs
))
3820 // Check that the template argument list is well-formed for this
3822 SmallVector
<TemplateArgument
, 4> SugaredConverted
, CanonicalConverted
;
3823 if (SemaRef
.CheckTemplateArgumentList(InstClassTemplate
, D
->getLocation(),
3824 InstTemplateArgs
, false,
3825 SugaredConverted
, CanonicalConverted
,
3826 /*UpdateArgsWithConversions=*/true))
3829 // Figure out where to insert this class template explicit specialization
3830 // in the member template's set of class template explicit specializations.
3831 void *InsertPos
= nullptr;
3832 ClassTemplateSpecializationDecl
*PrevDecl
=
3833 InstClassTemplate
->findSpecialization(CanonicalConverted
, InsertPos
);
3835 // Check whether we've already seen a conflicting instantiation of this
3836 // declaration (for instance, if there was a prior implicit instantiation).
3839 SemaRef
.CheckSpecializationInstantiationRedecl(D
->getLocation(),
3840 D
->getSpecializationKind(),
3842 PrevDecl
->getSpecializationKind(),
3843 PrevDecl
->getPointOfInstantiation(),
3847 // If PrevDecl was a definition and D is also a definition, diagnose.
3848 // This happens in cases like:
3850 // template<typename T, typename U>
3852 // template<typename X> struct Inner;
3853 // template<> struct Inner<T> {};
3854 // template<> struct Inner<U> {};
3857 // Outer<int, int> outer; // error: the explicit specializations of Inner
3858 // // have the same signature.
3859 if (PrevDecl
&& PrevDecl
->getDefinition() &&
3860 D
->isThisDeclarationADefinition()) {
3861 SemaRef
.Diag(D
->getLocation(), diag::err_redefinition
) << PrevDecl
;
3862 SemaRef
.Diag(PrevDecl
->getDefinition()->getLocation(),
3863 diag::note_previous_definition
);
3867 // Create the class template partial specialization declaration.
3868 ClassTemplateSpecializationDecl
*InstD
=
3869 ClassTemplateSpecializationDecl::Create(
3870 SemaRef
.Context
, D
->getTagKind(), Owner
, D
->getBeginLoc(),
3871 D
->getLocation(), InstClassTemplate
, CanonicalConverted
, PrevDecl
);
3873 // Add this partial specialization to the set of class template partial
3876 InstClassTemplate
->AddSpecialization(InstD
, InsertPos
);
3878 // Substitute the nested name specifier, if any.
3879 if (SubstQualifier(D
, InstD
))
3882 // Build the canonical type that describes the converted template
3883 // arguments of the class template explicit specialization.
3884 QualType CanonType
= SemaRef
.Context
.getTemplateSpecializationType(
3885 TemplateName(InstClassTemplate
), CanonicalConverted
,
3886 SemaRef
.Context
.getRecordType(InstD
));
3888 // Build the fully-sugared type for this class template
3889 // specialization as the user wrote in the specialization
3890 // itself. This means that we'll pretty-print the type retrieved
3891 // from the specialization's declaration the way that the user
3892 // actually wrote the specialization, rather than formatting the
3893 // name based on the "canonical" representation used to store the
3894 // template arguments in the specialization.
3895 TypeSourceInfo
*WrittenTy
= SemaRef
.Context
.getTemplateSpecializationTypeInfo(
3896 TemplateName(InstClassTemplate
), D
->getLocation(), InstTemplateArgs
,
3899 InstD
->setAccess(D
->getAccess());
3900 InstD
->setInstantiationOfMemberClass(D
, TSK_ImplicitInstantiation
);
3901 InstD
->setSpecializationKind(D
->getSpecializationKind());
3902 InstD
->setTypeAsWritten(WrittenTy
);
3903 InstD
->setExternLoc(D
->getExternLoc());
3904 InstD
->setTemplateKeywordLoc(D
->getTemplateKeywordLoc());
3906 Owner
->addDecl(InstD
);
3908 // Instantiate the members of the class-scope explicit specialization eagerly.
3909 // We don't have support for lazy instantiation of an explicit specialization
3910 // yet, and MSVC eagerly instantiates in this case.
3911 // FIXME: This is wrong in standard C++.
3912 if (D
->isThisDeclarationADefinition() &&
3913 SemaRef
.InstantiateClass(D
->getLocation(), InstD
, D
, TemplateArgs
,
3914 TSK_ImplicitInstantiation
,
3921 Decl
*TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3922 VarTemplateSpecializationDecl
*D
) {
3924 TemplateArgumentListInfo VarTemplateArgsInfo
;
3925 VarTemplateDecl
*VarTemplate
= D
->getSpecializedTemplate();
3926 assert(VarTemplate
&&
3927 "A template specialization without specialized template?");
3929 VarTemplateDecl
*InstVarTemplate
=
3930 cast_or_null
<VarTemplateDecl
>(SemaRef
.FindInstantiatedDecl(
3931 D
->getLocation(), VarTemplate
, TemplateArgs
));
3932 if (!InstVarTemplate
)
3935 // Substitute the current template arguments.
3936 if (const ASTTemplateArgumentListInfo
*TemplateArgsInfo
=
3937 D
->getTemplateArgsInfo()) {
3938 VarTemplateArgsInfo
.setLAngleLoc(TemplateArgsInfo
->getLAngleLoc());
3939 VarTemplateArgsInfo
.setRAngleLoc(TemplateArgsInfo
->getRAngleLoc());
3941 if (SemaRef
.SubstTemplateArguments(TemplateArgsInfo
->arguments(),
3942 TemplateArgs
, VarTemplateArgsInfo
))
3946 // Check that the template argument list is well-formed for this template.
3947 SmallVector
<TemplateArgument
, 4> SugaredConverted
, CanonicalConverted
;
3948 if (SemaRef
.CheckTemplateArgumentList(InstVarTemplate
, D
->getLocation(),
3949 VarTemplateArgsInfo
, false,
3950 SugaredConverted
, CanonicalConverted
,
3951 /*UpdateArgsWithConversions=*/true))
3954 // Check whether we've already seen a declaration of this specialization.
3955 void *InsertPos
= nullptr;
3956 VarTemplateSpecializationDecl
*PrevDecl
=
3957 InstVarTemplate
->findSpecialization(CanonicalConverted
, InsertPos
);
3959 // Check whether we've already seen a conflicting instantiation of this
3960 // declaration (for instance, if there was a prior implicit instantiation).
3962 if (PrevDecl
&& SemaRef
.CheckSpecializationInstantiationRedecl(
3963 D
->getLocation(), D
->getSpecializationKind(), PrevDecl
,
3964 PrevDecl
->getSpecializationKind(),
3965 PrevDecl
->getPointOfInstantiation(), Ignored
))
3968 return VisitVarTemplateSpecializationDecl(
3969 InstVarTemplate
, D
, VarTemplateArgsInfo
, CanonicalConverted
, PrevDecl
);
3972 Decl
*TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3973 VarTemplateDecl
*VarTemplate
, VarDecl
*D
,
3974 const TemplateArgumentListInfo
&TemplateArgsInfo
,
3975 ArrayRef
<TemplateArgument
> Converted
,
3976 VarTemplateSpecializationDecl
*PrevDecl
) {
3978 // Do substitution on the type of the declaration
3979 TypeSourceInfo
*DI
=
3980 SemaRef
.SubstType(D
->getTypeSourceInfo(), TemplateArgs
,
3981 D
->getTypeSpecStartLoc(), D
->getDeclName());
3985 if (DI
->getType()->isFunctionType()) {
3986 SemaRef
.Diag(D
->getLocation(), diag::err_variable_instantiates_to_function
)
3987 << D
->isStaticDataMember() << DI
->getType();
3991 // Build the instantiated declaration
3992 VarTemplateSpecializationDecl
*Var
= VarTemplateSpecializationDecl::Create(
3993 SemaRef
.Context
, Owner
, D
->getInnerLocStart(), D
->getLocation(),
3994 VarTemplate
, DI
->getType(), DI
, D
->getStorageClass(), Converted
);
3995 Var
->setTemplateArgsInfo(TemplateArgsInfo
);
3997 void *InsertPos
= nullptr;
3998 VarTemplate
->findSpecialization(Converted
, InsertPos
);
3999 VarTemplate
->AddSpecialization(Var
, InsertPos
);
4002 if (SemaRef
.getLangOpts().OpenCL
)
4003 SemaRef
.deduceOpenCLAddressSpace(Var
);
4005 // Substitute the nested name specifier, if any.
4006 if (SubstQualifier(D
, Var
))
4009 SemaRef
.BuildVariableInstantiation(Var
, D
, TemplateArgs
, LateAttrs
, Owner
,
4010 StartingScope
, false, PrevDecl
);
4015 Decl
*TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl
*D
) {
4016 llvm_unreachable("@defs is not supported in Objective-C++");
4019 Decl
*TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl
*D
) {
4020 // FIXME: We need to be able to instantiate FriendTemplateDecls.
4021 unsigned DiagID
= SemaRef
.getDiagnostics().getCustomDiagID(
4022 DiagnosticsEngine::Error
,
4023 "cannot instantiate %0 yet");
4024 SemaRef
.Diag(D
->getLocation(), DiagID
)
4025 << D
->getDeclKindName();
4030 Decl
*TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl
*D
) {
4031 llvm_unreachable("Concept definitions cannot reside inside a template");
4034 Decl
*TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4035 ImplicitConceptSpecializationDecl
*D
) {
4036 llvm_unreachable("Concept specializations cannot reside inside a template");
4040 TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl
*D
) {
4041 return RequiresExprBodyDecl::Create(SemaRef
.Context
, D
->getDeclContext(),
4045 Decl
*TemplateDeclInstantiator::VisitDecl(Decl
*D
) {
4046 llvm_unreachable("Unexpected decl");
4049 Decl
*Sema::SubstDecl(Decl
*D
, DeclContext
*Owner
,
4050 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
4051 TemplateDeclInstantiator
Instantiator(*this, Owner
, TemplateArgs
);
4052 if (D
->isInvalidDecl())
4056 runWithSufficientStackSpace(D
->getLocation(), [&] {
4057 SubstD
= Instantiator
.Visit(D
);
4062 void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK
,
4063 FunctionDecl
*Orig
, QualType
&T
,
4064 TypeSourceInfo
*&TInfo
,
4065 DeclarationNameInfo
&NameInfo
) {
4066 assert(RK
== RewriteKind::RewriteSpaceshipAsEqualEqual
);
4068 // C++2a [class.compare.default]p3:
4069 // the return type is replaced with bool
4070 auto *FPT
= T
->castAs
<FunctionProtoType
>();
4071 T
= SemaRef
.Context
.getFunctionType(
4072 SemaRef
.Context
.BoolTy
, FPT
->getParamTypes(), FPT
->getExtProtoInfo());
4074 // Update the return type in the source info too. The most straightforward
4075 // way is to create new TypeSourceInfo for the new type. Use the location of
4076 // the '= default' as the location of the new type.
4078 // FIXME: Set the correct return type when we initially transform the type,
4079 // rather than delaying it to now.
4080 TypeSourceInfo
*NewTInfo
=
4081 SemaRef
.Context
.getTrivialTypeSourceInfo(T
, Orig
->getEndLoc());
4082 auto OldLoc
= TInfo
->getTypeLoc().getAsAdjusted
<FunctionProtoTypeLoc
>();
4083 assert(OldLoc
&& "type of function is not a function type?");
4084 auto NewLoc
= NewTInfo
->getTypeLoc().castAs
<FunctionProtoTypeLoc
>();
4085 for (unsigned I
= 0, N
= OldLoc
.getNumParams(); I
!= N
; ++I
)
4086 NewLoc
.setParam(I
, OldLoc
.getParam(I
));
4089 // and the declarator-id is replaced with operator==
4091 SemaRef
.Context
.DeclarationNames
.getCXXOperatorName(OO_EqualEqual
));
4094 FunctionDecl
*Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl
*RD
,
4095 FunctionDecl
*Spaceship
) {
4096 if (Spaceship
->isInvalidDecl())
4099 // C++2a [class.compare.default]p3:
4100 // an == operator function is declared implicitly [...] with the same
4101 // access and function-definition and in the same class scope as the
4102 // three-way comparison operator function
4103 MultiLevelTemplateArgumentList NoTemplateArgs
;
4104 NoTemplateArgs
.setKind(TemplateSubstitutionKind::Rewrite
);
4105 NoTemplateArgs
.addOuterRetainedLevels(RD
->getTemplateDepth());
4106 TemplateDeclInstantiator
Instantiator(*this, RD
, NoTemplateArgs
);
4108 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(Spaceship
)) {
4109 R
= Instantiator
.VisitCXXMethodDecl(
4110 MD
, /*TemplateParams=*/nullptr,
4111 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual
);
4113 assert(Spaceship
->getFriendObjectKind() &&
4114 "defaulted spaceship is neither a member nor a friend");
4116 R
= Instantiator
.VisitFunctionDecl(
4117 Spaceship
, /*TemplateParams=*/nullptr,
4118 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual
);
4123 FriendDecl::Create(Context
, RD
, Spaceship
->getLocation(),
4124 cast
<NamedDecl
>(R
), Spaceship
->getBeginLoc());
4125 FD
->setAccess(AS_public
);
4128 return cast_or_null
<FunctionDecl
>(R
);
4131 /// Instantiates a nested template parameter list in the current
4132 /// instantiation context.
4134 /// \param L The parameter list to instantiate
4136 /// \returns NULL if there was an error
4137 TemplateParameterList
*
4138 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList
*L
) {
4139 // Get errors for all the parameters before bailing out.
4140 bool Invalid
= false;
4142 unsigned N
= L
->size();
4143 typedef SmallVector
<NamedDecl
*, 8> ParamVector
;
4146 for (auto &P
: *L
) {
4147 NamedDecl
*D
= cast_or_null
<NamedDecl
>(Visit(P
));
4148 Params
.push_back(D
);
4149 Invalid
= Invalid
|| !D
|| D
->isInvalidDecl();
4152 // Clean up if we had an error.
4156 Expr
*InstRequiresClause
= L
->getRequiresClause();
4158 TemplateParameterList
*InstL
4159 = TemplateParameterList::Create(SemaRef
.Context
, L
->getTemplateLoc(),
4160 L
->getLAngleLoc(), Params
,
4161 L
->getRAngleLoc(), InstRequiresClause
);
4165 TemplateParameterList
*
4166 Sema::SubstTemplateParams(TemplateParameterList
*Params
, DeclContext
*Owner
,
4167 const MultiLevelTemplateArgumentList
&TemplateArgs
,
4168 bool EvaluateConstraints
) {
4169 TemplateDeclInstantiator
Instantiator(*this, Owner
, TemplateArgs
);
4170 Instantiator
.setEvaluateConstraints(EvaluateConstraints
);
4171 return Instantiator
.SubstTemplateParams(Params
);
4174 /// Instantiate the declaration of a class template partial
4177 /// \param ClassTemplate the (instantiated) class template that is partially
4178 // specialized by the instantiation of \p PartialSpec.
4180 /// \param PartialSpec the (uninstantiated) class template partial
4181 /// specialization that we are instantiating.
4183 /// \returns The instantiated partial specialization, if successful; otherwise,
4184 /// NULL to indicate an error.
4185 ClassTemplatePartialSpecializationDecl
*
4186 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
4187 ClassTemplateDecl
*ClassTemplate
,
4188 ClassTemplatePartialSpecializationDecl
*PartialSpec
) {
4189 // Create a local instantiation scope for this class template partial
4190 // specialization, which will contain the instantiations of the template
4192 LocalInstantiationScope
Scope(SemaRef
);
4194 // Substitute into the template parameters of the class template partial
4196 TemplateParameterList
*TempParams
= PartialSpec
->getTemplateParameters();
4197 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
4201 // Substitute into the template arguments of the class template partial
4203 const ASTTemplateArgumentListInfo
*TemplArgInfo
4204 = PartialSpec
->getTemplateArgsAsWritten();
4205 TemplateArgumentListInfo
InstTemplateArgs(TemplArgInfo
->LAngleLoc
,
4206 TemplArgInfo
->RAngleLoc
);
4207 if (SemaRef
.SubstTemplateArguments(TemplArgInfo
->arguments(), TemplateArgs
,
4211 // Check that the template argument list is well-formed for this
4213 SmallVector
<TemplateArgument
, 4> SugaredConverted
, CanonicalConverted
;
4214 if (SemaRef
.CheckTemplateArgumentList(
4215 ClassTemplate
, PartialSpec
->getLocation(), InstTemplateArgs
,
4216 /*PartialTemplateArgs=*/false, SugaredConverted
, CanonicalConverted
))
4219 // Check these arguments are valid for a template partial specialization.
4220 if (SemaRef
.CheckTemplatePartialSpecializationArgs(
4221 PartialSpec
->getLocation(), ClassTemplate
, InstTemplateArgs
.size(),
4222 CanonicalConverted
))
4225 // Figure out where to insert this class template partial specialization
4226 // in the member template's set of class template partial specializations.
4227 void *InsertPos
= nullptr;
4228 ClassTemplateSpecializationDecl
*PrevDecl
=
4229 ClassTemplate
->findPartialSpecialization(CanonicalConverted
, InstParams
,
4232 // Build the canonical type that describes the converted template
4233 // arguments of the class template partial specialization.
4234 QualType CanonType
= SemaRef
.Context
.getTemplateSpecializationType(
4235 TemplateName(ClassTemplate
), CanonicalConverted
);
4237 // Build the fully-sugared type for this class template
4238 // specialization as the user wrote in the specialization
4239 // itself. This means that we'll pretty-print the type retrieved
4240 // from the specialization's declaration the way that the user
4241 // actually wrote the specialization, rather than formatting the
4242 // name based on the "canonical" representation used to store the
4243 // template arguments in the specialization.
4244 TypeSourceInfo
*WrittenTy
4245 = SemaRef
.Context
.getTemplateSpecializationTypeInfo(
4246 TemplateName(ClassTemplate
),
4247 PartialSpec
->getLocation(),
4252 // We've already seen a partial specialization with the same template
4253 // parameters and template arguments. This can happen, for example, when
4254 // substituting the outer template arguments ends up causing two
4255 // class template partial specializations of a member class template
4256 // to have identical forms, e.g.,
4258 // template<typename T, typename U>
4260 // template<typename X, typename Y> struct Inner;
4261 // template<typename Y> struct Inner<T, Y>;
4262 // template<typename Y> struct Inner<U, Y>;
4265 // Outer<int, int> outer; // error: the partial specializations of Inner
4266 // // have the same signature.
4267 SemaRef
.Diag(PartialSpec
->getLocation(), diag::err_partial_spec_redeclared
)
4268 << WrittenTy
->getType();
4269 SemaRef
.Diag(PrevDecl
->getLocation(), diag::note_prev_partial_spec_here
)
4270 << SemaRef
.Context
.getTypeDeclType(PrevDecl
);
4275 // Create the class template partial specialization declaration.
4276 ClassTemplatePartialSpecializationDecl
*InstPartialSpec
=
4277 ClassTemplatePartialSpecializationDecl::Create(
4278 SemaRef
.Context
, PartialSpec
->getTagKind(), Owner
,
4279 PartialSpec
->getBeginLoc(), PartialSpec
->getLocation(), InstParams
,
4280 ClassTemplate
, CanonicalConverted
, InstTemplateArgs
, CanonType
,
4282 // Substitute the nested name specifier, if any.
4283 if (SubstQualifier(PartialSpec
, InstPartialSpec
))
4286 InstPartialSpec
->setInstantiatedFromMember(PartialSpec
);
4287 InstPartialSpec
->setTypeAsWritten(WrittenTy
);
4289 // Check the completed partial specialization.
4290 SemaRef
.CheckTemplatePartialSpecialization(InstPartialSpec
);
4292 // Add this partial specialization to the set of class template partial
4294 ClassTemplate
->AddPartialSpecialization(InstPartialSpec
,
4295 /*InsertPos=*/nullptr);
4296 return InstPartialSpec
;
4299 /// Instantiate the declaration of a variable template partial
4302 /// \param VarTemplate the (instantiated) variable template that is partially
4303 /// specialized by the instantiation of \p PartialSpec.
4305 /// \param PartialSpec the (uninstantiated) variable template partial
4306 /// specialization that we are instantiating.
4308 /// \returns The instantiated partial specialization, if successful; otherwise,
4309 /// NULL to indicate an error.
4310 VarTemplatePartialSpecializationDecl
*
4311 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
4312 VarTemplateDecl
*VarTemplate
,
4313 VarTemplatePartialSpecializationDecl
*PartialSpec
) {
4314 // Create a local instantiation scope for this variable template partial
4315 // specialization, which will contain the instantiations of the template
4317 LocalInstantiationScope
Scope(SemaRef
);
4319 // Substitute into the template parameters of the variable template partial
4321 TemplateParameterList
*TempParams
= PartialSpec
->getTemplateParameters();
4322 TemplateParameterList
*InstParams
= SubstTemplateParams(TempParams
);
4326 // Substitute into the template arguments of the variable template partial
4328 const ASTTemplateArgumentListInfo
*TemplArgInfo
4329 = PartialSpec
->getTemplateArgsAsWritten();
4330 TemplateArgumentListInfo
InstTemplateArgs(TemplArgInfo
->LAngleLoc
,
4331 TemplArgInfo
->RAngleLoc
);
4332 if (SemaRef
.SubstTemplateArguments(TemplArgInfo
->arguments(), TemplateArgs
,
4336 // Check that the template argument list is well-formed for this
4338 SmallVector
<TemplateArgument
, 4> SugaredConverted
, CanonicalConverted
;
4339 if (SemaRef
.CheckTemplateArgumentList(
4340 VarTemplate
, PartialSpec
->getLocation(), InstTemplateArgs
,
4341 /*PartialTemplateArgs=*/false, SugaredConverted
, CanonicalConverted
))
4344 // Check these arguments are valid for a template partial specialization.
4345 if (SemaRef
.CheckTemplatePartialSpecializationArgs(
4346 PartialSpec
->getLocation(), VarTemplate
, InstTemplateArgs
.size(),
4347 CanonicalConverted
))
4350 // Figure out where to insert this variable template partial specialization
4351 // in the member template's set of variable template partial specializations.
4352 void *InsertPos
= nullptr;
4353 VarTemplateSpecializationDecl
*PrevDecl
=
4354 VarTemplate
->findPartialSpecialization(CanonicalConverted
, InstParams
,
4357 // Build the canonical type that describes the converted template
4358 // arguments of the variable template partial specialization.
4359 QualType CanonType
= SemaRef
.Context
.getTemplateSpecializationType(
4360 TemplateName(VarTemplate
), CanonicalConverted
);
4362 // Build the fully-sugared type for this variable template
4363 // specialization as the user wrote in the specialization
4364 // itself. This means that we'll pretty-print the type retrieved
4365 // from the specialization's declaration the way that the user
4366 // actually wrote the specialization, rather than formatting the
4367 // name based on the "canonical" representation used to store the
4368 // template arguments in the specialization.
4369 TypeSourceInfo
*WrittenTy
= SemaRef
.Context
.getTemplateSpecializationTypeInfo(
4370 TemplateName(VarTemplate
), PartialSpec
->getLocation(), InstTemplateArgs
,
4374 // We've already seen a partial specialization with the same template
4375 // parameters and template arguments. This can happen, for example, when
4376 // substituting the outer template arguments ends up causing two
4377 // variable template partial specializations of a member variable template
4378 // to have identical forms, e.g.,
4380 // template<typename T, typename U>
4382 // template<typename X, typename Y> pair<X,Y> p;
4383 // template<typename Y> pair<T, Y> p;
4384 // template<typename Y> pair<U, Y> p;
4387 // Outer<int, int> outer; // error: the partial specializations of Inner
4388 // // have the same signature.
4389 SemaRef
.Diag(PartialSpec
->getLocation(),
4390 diag::err_var_partial_spec_redeclared
)
4391 << WrittenTy
->getType();
4392 SemaRef
.Diag(PrevDecl
->getLocation(),
4393 diag::note_var_prev_partial_spec_here
);
4397 // Do substitution on the type of the declaration
4398 TypeSourceInfo
*DI
= SemaRef
.SubstType(
4399 PartialSpec
->getTypeSourceInfo(), TemplateArgs
,
4400 PartialSpec
->getTypeSpecStartLoc(), PartialSpec
->getDeclName());
4404 if (DI
->getType()->isFunctionType()) {
4405 SemaRef
.Diag(PartialSpec
->getLocation(),
4406 diag::err_variable_instantiates_to_function
)
4407 << PartialSpec
->isStaticDataMember() << DI
->getType();
4411 // Create the variable template partial specialization declaration.
4412 VarTemplatePartialSpecializationDecl
*InstPartialSpec
=
4413 VarTemplatePartialSpecializationDecl::Create(
4414 SemaRef
.Context
, Owner
, PartialSpec
->getInnerLocStart(),
4415 PartialSpec
->getLocation(), InstParams
, VarTemplate
, DI
->getType(),
4416 DI
, PartialSpec
->getStorageClass(), CanonicalConverted
,
4419 // Substitute the nested name specifier, if any.
4420 if (SubstQualifier(PartialSpec
, InstPartialSpec
))
4423 InstPartialSpec
->setInstantiatedFromMember(PartialSpec
);
4424 InstPartialSpec
->setTypeAsWritten(WrittenTy
);
4426 // Check the completed partial specialization.
4427 SemaRef
.CheckTemplatePartialSpecialization(InstPartialSpec
);
4429 // Add this partial specialization to the set of variable template partial
4430 // specializations. The instantiation of the initializer is not necessary.
4431 VarTemplate
->AddPartialSpecialization(InstPartialSpec
, /*InsertPos=*/nullptr);
4433 SemaRef
.BuildVariableInstantiation(InstPartialSpec
, PartialSpec
, TemplateArgs
,
4434 LateAttrs
, Owner
, StartingScope
);
4436 return InstPartialSpec
;
4440 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl
*D
,
4441 SmallVectorImpl
<ParmVarDecl
*> &Params
) {
4442 TypeSourceInfo
*OldTInfo
= D
->getTypeSourceInfo();
4443 assert(OldTInfo
&& "substituting function without type source info");
4444 assert(Params
.empty() && "parameter vector is non-empty at start");
4446 CXXRecordDecl
*ThisContext
= nullptr;
4447 Qualifiers ThisTypeQuals
;
4448 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(D
)) {
4449 ThisContext
= cast
<CXXRecordDecl
>(Owner
);
4450 ThisTypeQuals
= Method
->getFunctionObjectParameterType().getQualifiers();
4453 TypeSourceInfo
*NewTInfo
= SemaRef
.SubstFunctionDeclType(
4454 OldTInfo
, TemplateArgs
, D
->getTypeSpecStartLoc(), D
->getDeclName(),
4455 ThisContext
, ThisTypeQuals
, EvaluateConstraints
);
4459 TypeLoc OldTL
= OldTInfo
->getTypeLoc().IgnoreParens();
4460 if (FunctionProtoTypeLoc OldProtoLoc
= OldTL
.getAs
<FunctionProtoTypeLoc
>()) {
4461 if (NewTInfo
!= OldTInfo
) {
4462 // Get parameters from the new type info.
4463 TypeLoc NewTL
= NewTInfo
->getTypeLoc().IgnoreParens();
4464 FunctionProtoTypeLoc NewProtoLoc
= NewTL
.castAs
<FunctionProtoTypeLoc
>();
4465 unsigned NewIdx
= 0;
4466 for (unsigned OldIdx
= 0, NumOldParams
= OldProtoLoc
.getNumParams();
4467 OldIdx
!= NumOldParams
; ++OldIdx
) {
4468 ParmVarDecl
*OldParam
= OldProtoLoc
.getParam(OldIdx
);
4472 LocalInstantiationScope
*Scope
= SemaRef
.CurrentInstantiationScope
;
4474 std::optional
<unsigned> NumArgumentsInExpansion
;
4475 if (OldParam
->isParameterPack())
4476 NumArgumentsInExpansion
=
4477 SemaRef
.getNumArgumentsInExpansion(OldParam
->getType(),
4479 if (!NumArgumentsInExpansion
) {
4480 // Simple case: normal parameter, or a parameter pack that's
4481 // instantiated to a (still-dependent) parameter pack.
4482 ParmVarDecl
*NewParam
= NewProtoLoc
.getParam(NewIdx
++);
4483 Params
.push_back(NewParam
);
4484 Scope
->InstantiatedLocal(OldParam
, NewParam
);
4486 // Parameter pack expansion: make the instantiation an argument pack.
4487 Scope
->MakeInstantiatedLocalArgPack(OldParam
);
4488 for (unsigned I
= 0; I
!= *NumArgumentsInExpansion
; ++I
) {
4489 ParmVarDecl
*NewParam
= NewProtoLoc
.getParam(NewIdx
++);
4490 Params
.push_back(NewParam
);
4491 Scope
->InstantiatedLocalPackArg(OldParam
, NewParam
);
4496 // The function type itself was not dependent and therefore no
4497 // substitution occurred. However, we still need to instantiate
4498 // the function parameters themselves.
4499 const FunctionProtoType
*OldProto
=
4500 cast
<FunctionProtoType
>(OldProtoLoc
.getType());
4501 for (unsigned i
= 0, i_end
= OldProtoLoc
.getNumParams(); i
!= i_end
;
4503 ParmVarDecl
*OldParam
= OldProtoLoc
.getParam(i
);
4505 Params
.push_back(SemaRef
.BuildParmVarDeclForTypedef(
4506 D
, D
->getLocation(), OldProto
->getParamType(i
)));
4511 cast_or_null
<ParmVarDecl
>(VisitParmVarDecl(OldParam
));
4514 Params
.push_back(Parm
);
4518 // If the type of this function, after ignoring parentheses, is not
4519 // *directly* a function type, then we're instantiating a function that
4520 // was declared via a typedef or with attributes, e.g.,
4522 // typedef int functype(int, int);
4524 // int __cdecl meth(int, int);
4526 // In this case, we'll just go instantiate the ParmVarDecls that we
4527 // synthesized in the method declaration.
4528 SmallVector
<QualType
, 4> ParamTypes
;
4529 Sema::ExtParameterInfoBuilder ExtParamInfos
;
4530 if (SemaRef
.SubstParmTypes(D
->getLocation(), D
->parameters(), nullptr,
4531 TemplateArgs
, ParamTypes
, &Params
,
4539 /// Introduce the instantiated local variables into the local
4540 /// instantiation scope.
4541 void Sema::addInstantiatedLocalVarsToScope(FunctionDecl
*Function
,
4542 const FunctionDecl
*PatternDecl
,
4543 LocalInstantiationScope
&Scope
) {
4544 LambdaScopeInfo
*LSI
= cast
<LambdaScopeInfo
>(getFunctionScopes().back());
4546 for (auto *decl
: PatternDecl
->decls()) {
4547 if (!isa
<VarDecl
>(decl
) || isa
<ParmVarDecl
>(decl
))
4550 VarDecl
*VD
= cast
<VarDecl
>(decl
);
4551 IdentifierInfo
*II
= VD
->getIdentifier();
4553 auto it
= llvm::find_if(Function
->decls(), [&](Decl
*inst
) {
4554 VarDecl
*InstVD
= dyn_cast
<VarDecl
>(inst
);
4555 return InstVD
&& InstVD
->isLocalVarDecl() &&
4556 InstVD
->getIdentifier() == II
;
4559 if (it
== Function
->decls().end())
4562 Scope
.InstantiatedLocal(VD
, *it
);
4563 LSI
->addCapture(cast
<VarDecl
>(*it
), /*isBlock=*/false, /*isByref=*/false,
4564 /*isNested=*/false, VD
->getLocation(), SourceLocation(),
4565 VD
->getType(), /*Invalid=*/false);
4569 /// Introduce the instantiated function parameters into the local
4570 /// instantiation scope, and set the parameter names to those used
4571 /// in the template.
4572 bool Sema::addInstantiatedParametersToScope(
4573 FunctionDecl
*Function
, const FunctionDecl
*PatternDecl
,
4574 LocalInstantiationScope
&Scope
,
4575 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
4576 unsigned FParamIdx
= 0;
4577 for (unsigned I
= 0, N
= PatternDecl
->getNumParams(); I
!= N
; ++I
) {
4578 const ParmVarDecl
*PatternParam
= PatternDecl
->getParamDecl(I
);
4579 if (!PatternParam
->isParameterPack()) {
4580 // Simple case: not a parameter pack.
4581 assert(FParamIdx
< Function
->getNumParams());
4582 ParmVarDecl
*FunctionParam
= Function
->getParamDecl(FParamIdx
);
4583 FunctionParam
->setDeclName(PatternParam
->getDeclName());
4584 // If the parameter's type is not dependent, update it to match the type
4585 // in the pattern. They can differ in top-level cv-qualifiers, and we want
4586 // the pattern's type here. If the type is dependent, they can't differ,
4587 // per core issue 1668. Substitute into the type from the pattern, in case
4588 // it's instantiation-dependent.
4589 // FIXME: Updating the type to work around this is at best fragile.
4590 if (!PatternDecl
->getType()->isDependentType()) {
4591 QualType T
= SubstType(PatternParam
->getType(), TemplateArgs
,
4592 FunctionParam
->getLocation(),
4593 FunctionParam
->getDeclName());
4596 FunctionParam
->setType(T
);
4599 Scope
.InstantiatedLocal(PatternParam
, FunctionParam
);
4604 // Expand the parameter pack.
4605 Scope
.MakeInstantiatedLocalArgPack(PatternParam
);
4606 std::optional
<unsigned> NumArgumentsInExpansion
=
4607 getNumArgumentsInExpansion(PatternParam
->getType(), TemplateArgs
);
4608 if (NumArgumentsInExpansion
) {
4609 QualType PatternType
=
4610 PatternParam
->getType()->castAs
<PackExpansionType
>()->getPattern();
4611 for (unsigned Arg
= 0; Arg
< *NumArgumentsInExpansion
; ++Arg
) {
4612 ParmVarDecl
*FunctionParam
= Function
->getParamDecl(FParamIdx
);
4613 FunctionParam
->setDeclName(PatternParam
->getDeclName());
4614 if (!PatternDecl
->getType()->isDependentType()) {
4615 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(*this, Arg
);
4617 SubstType(PatternType
, TemplateArgs
, FunctionParam
->getLocation(),
4618 FunctionParam
->getDeclName());
4621 FunctionParam
->setType(T
);
4624 Scope
.InstantiatedLocalPackArg(PatternParam
, FunctionParam
);
4633 bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc
, FunctionDecl
*FD
,
4634 ParmVarDecl
*Param
) {
4635 assert(Param
->hasUninstantiatedDefaultArg());
4637 // Instantiate the expression.
4639 // FIXME: Pass in a correct Pattern argument, otherwise
4640 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4642 // template<typename T>
4644 // static int FooImpl();
4646 // template<typename Tp>
4647 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4648 // // template argument list [[T], [Tp]], should be [[Tp]].
4649 // friend A<Tp> Foo(int a);
4652 // template<typename T>
4653 // A<T> Foo(int a = A<T>::FooImpl());
4654 MultiLevelTemplateArgumentList TemplateArgs
= getTemplateInstantiationArgs(
4655 FD
, FD
->getLexicalDeclContext(), /*Final=*/false, nullptr,
4656 /*RelativeToPrimary=*/true);
4658 if (SubstDefaultArgument(CallLoc
, Param
, TemplateArgs
, /*ForCallExpr*/ true))
4661 if (ASTMutationListener
*L
= getASTMutationListener())
4662 L
->DefaultArgumentInstantiated(Param
);
4667 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation
,
4668 FunctionDecl
*Decl
) {
4669 const FunctionProtoType
*Proto
= Decl
->getType()->castAs
<FunctionProtoType
>();
4670 if (Proto
->getExceptionSpecType() != EST_Uninstantiated
)
4673 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, Decl
,
4674 InstantiatingTemplate::ExceptionSpecification());
4675 if (Inst
.isInvalid()) {
4676 // We hit the instantiation depth limit. Clear the exception specification
4677 // so that our callers don't have to cope with EST_Uninstantiated.
4678 UpdateExceptionSpec(Decl
, EST_None
);
4681 if (Inst
.isAlreadyInstantiating()) {
4682 // This exception specification indirectly depends on itself. Reject.
4683 // FIXME: Corresponding rule in the standard?
4684 Diag(PointOfInstantiation
, diag::err_exception_spec_cycle
) << Decl
;
4685 UpdateExceptionSpec(Decl
, EST_None
);
4689 // Enter the scope of this instantiation. We don't use
4690 // PushDeclContext because we don't have a scope.
4691 Sema::ContextRAII
savedContext(*this, Decl
);
4692 LocalInstantiationScope
Scope(*this);
4694 MultiLevelTemplateArgumentList TemplateArgs
= getTemplateInstantiationArgs(
4695 Decl
, Decl
->getLexicalDeclContext(), /*Final=*/false, nullptr,
4696 /*RelativeToPrimary*/ true);
4698 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4699 // here, because for a non-defining friend declaration in a class template,
4700 // we don't store enough information to map back to the friend declaration in
4702 FunctionDecl
*Template
= Proto
->getExceptionSpecTemplate();
4703 if (addInstantiatedParametersToScope(Decl
, Template
, Scope
, TemplateArgs
)) {
4704 UpdateExceptionSpec(Decl
, EST_None
);
4708 SubstExceptionSpec(Decl
, Template
->getType()->castAs
<FunctionProtoType
>(),
4712 /// Initializes the common fields of an instantiation function
4713 /// declaration (New) from the corresponding fields of its template (Tmpl).
4715 /// \returns true if there was an error
4717 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl
*New
,
4718 FunctionDecl
*Tmpl
) {
4719 New
->setImplicit(Tmpl
->isImplicit());
4721 // Forward the mangling number from the template to the instantiated decl.
4722 SemaRef
.Context
.setManglingNumber(New
,
4723 SemaRef
.Context
.getManglingNumber(Tmpl
));
4725 // If we are performing substituting explicitly-specified template arguments
4726 // or deduced template arguments into a function template and we reach this
4727 // point, we are now past the point where SFINAE applies and have committed
4728 // to keeping the new function template specialization. We therefore
4729 // convert the active template instantiation for the function template
4730 // into a template instantiation for this specific function template
4731 // specialization, which is not a SFINAE context, so that we diagnose any
4732 // further errors in the declaration itself.
4734 // FIXME: This is a hack.
4735 typedef Sema::CodeSynthesisContext ActiveInstType
;
4736 ActiveInstType
&ActiveInst
= SemaRef
.CodeSynthesisContexts
.back();
4737 if (ActiveInst
.Kind
== ActiveInstType::ExplicitTemplateArgumentSubstitution
||
4738 ActiveInst
.Kind
== ActiveInstType::DeducedTemplateArgumentSubstitution
) {
4739 if (isa
<FunctionTemplateDecl
>(ActiveInst
.Entity
)) {
4740 SemaRef
.InstantiatingSpecializations
.erase(
4741 {ActiveInst
.Entity
->getCanonicalDecl(), ActiveInst
.Kind
});
4742 atTemplateEnd(SemaRef
.TemplateInstCallbacks
, SemaRef
, ActiveInst
);
4743 ActiveInst
.Kind
= ActiveInstType::TemplateInstantiation
;
4744 ActiveInst
.Entity
= New
;
4745 atTemplateBegin(SemaRef
.TemplateInstCallbacks
, SemaRef
, ActiveInst
);
4749 const FunctionProtoType
*Proto
= Tmpl
->getType()->getAs
<FunctionProtoType
>();
4750 assert(Proto
&& "Function template without prototype?");
4752 if (Proto
->hasExceptionSpec() || Proto
->getNoReturnAttr()) {
4753 FunctionProtoType::ExtProtoInfo EPI
= Proto
->getExtProtoInfo();
4755 // DR1330: In C++11, defer instantiation of a non-trivial
4756 // exception specification.
4757 // DR1484: Local classes and their members are instantiated along with the
4758 // containing function.
4759 if (SemaRef
.getLangOpts().CPlusPlus11
&&
4760 EPI
.ExceptionSpec
.Type
!= EST_None
&&
4761 EPI
.ExceptionSpec
.Type
!= EST_DynamicNone
&&
4762 EPI
.ExceptionSpec
.Type
!= EST_BasicNoexcept
&&
4763 !Tmpl
->isInLocalScopeForInstantiation()) {
4764 FunctionDecl
*ExceptionSpecTemplate
= Tmpl
;
4765 if (EPI
.ExceptionSpec
.Type
== EST_Uninstantiated
)
4766 ExceptionSpecTemplate
= EPI
.ExceptionSpec
.SourceTemplate
;
4767 ExceptionSpecificationType NewEST
= EST_Uninstantiated
;
4768 if (EPI
.ExceptionSpec
.Type
== EST_Unevaluated
)
4769 NewEST
= EST_Unevaluated
;
4771 // Mark the function has having an uninstantiated exception specification.
4772 const FunctionProtoType
*NewProto
4773 = New
->getType()->getAs
<FunctionProtoType
>();
4774 assert(NewProto
&& "Template instantiation without function prototype?");
4775 EPI
= NewProto
->getExtProtoInfo();
4776 EPI
.ExceptionSpec
.Type
= NewEST
;
4777 EPI
.ExceptionSpec
.SourceDecl
= New
;
4778 EPI
.ExceptionSpec
.SourceTemplate
= ExceptionSpecTemplate
;
4779 New
->setType(SemaRef
.Context
.getFunctionType(
4780 NewProto
->getReturnType(), NewProto
->getParamTypes(), EPI
));
4782 Sema::ContextRAII
SwitchContext(SemaRef
, New
);
4783 SemaRef
.SubstExceptionSpec(New
, Proto
, TemplateArgs
);
4787 // Get the definition. Leaves the variable unchanged if undefined.
4788 const FunctionDecl
*Definition
= Tmpl
;
4789 Tmpl
->isDefined(Definition
);
4791 SemaRef
.InstantiateAttrs(TemplateArgs
, Definition
, New
,
4792 LateAttrs
, StartingScope
);
4797 /// Initializes common fields of an instantiated method
4798 /// declaration (New) from the corresponding fields of its template
4801 /// \returns true if there was an error
4803 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl
*New
,
4804 CXXMethodDecl
*Tmpl
) {
4805 if (InitFunctionInstantiation(New
, Tmpl
))
4808 if (isa
<CXXDestructorDecl
>(New
) && SemaRef
.getLangOpts().CPlusPlus11
)
4809 SemaRef
.AdjustDestructorExceptionSpec(cast
<CXXDestructorDecl
>(New
));
4811 New
->setAccess(Tmpl
->getAccess());
4812 if (Tmpl
->isVirtualAsWritten())
4813 New
->setVirtualAsWritten(true);
4815 // FIXME: New needs a pointer to Tmpl
4819 bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl
*New
,
4820 FunctionDecl
*Tmpl
) {
4821 // Transfer across any unqualified lookups.
4822 if (auto *DFI
= Tmpl
->getDefaultedFunctionInfo()) {
4823 SmallVector
<DeclAccessPair
, 32> Lookups
;
4824 Lookups
.reserve(DFI
->getUnqualifiedLookups().size());
4825 bool AnyChanged
= false;
4826 for (DeclAccessPair DA
: DFI
->getUnqualifiedLookups()) {
4827 NamedDecl
*D
= SemaRef
.FindInstantiatedDecl(New
->getLocation(),
4828 DA
.getDecl(), TemplateArgs
);
4831 AnyChanged
|= (D
!= DA
.getDecl());
4832 Lookups
.push_back(DeclAccessPair::make(D
, DA
.getAccess()));
4835 // It's unlikely that substitution will change any declarations. Don't
4836 // store an unnecessary copy in that case.
4837 New
->setDefaultedFunctionInfo(
4838 AnyChanged
? FunctionDecl::DefaultedFunctionInfo::Create(
4839 SemaRef
.Context
, Lookups
)
4843 SemaRef
.SetDeclDefaulted(New
, Tmpl
->getLocation());
4847 /// Instantiate (or find existing instantiation of) a function template with a
4848 /// given set of template arguments.
4850 /// Usually this should not be used, and template argument deduction should be
4851 /// used in its place.
4853 Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl
*FTD
,
4854 const TemplateArgumentList
*Args
,
4855 SourceLocation Loc
) {
4856 FunctionDecl
*FD
= FTD
->getTemplatedDecl();
4858 sema::TemplateDeductionInfo
Info(Loc
);
4859 InstantiatingTemplate
Inst(
4860 *this, Loc
, FTD
, Args
->asArray(),
4861 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
, Info
);
4862 if (Inst
.isInvalid())
4865 ContextRAII
SavedContext(*this, FD
);
4866 MultiLevelTemplateArgumentList
MArgs(FTD
, Args
->asArray(),
4869 return cast_or_null
<FunctionDecl
>(SubstDecl(FD
, FD
->getParent(), MArgs
));
4872 /// Instantiate the definition of the given function from its
4875 /// \param PointOfInstantiation the point at which the instantiation was
4876 /// required. Note that this is not precisely a "point of instantiation"
4877 /// for the function, but it's close.
4879 /// \param Function the already-instantiated declaration of a
4880 /// function template specialization or member function of a class template
4883 /// \param Recursive if true, recursively instantiates any functions that
4884 /// are required by this instantiation.
4886 /// \param DefinitionRequired if true, then we are performing an explicit
4887 /// instantiation where the body of the function is required. Complain if
4888 /// there is no such body.
4889 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation
,
4890 FunctionDecl
*Function
,
4892 bool DefinitionRequired
,
4894 if (Function
->isInvalidDecl() || isa
<CXXDeductionGuideDecl
>(Function
))
4897 // Never instantiate an explicit specialization except if it is a class scope
4898 // explicit specialization.
4899 TemplateSpecializationKind TSK
=
4900 Function
->getTemplateSpecializationKindForInstantiation();
4901 if (TSK
== TSK_ExplicitSpecialization
)
4904 // Never implicitly instantiate a builtin; we don't actually need a function
4906 if (Function
->getBuiltinID() && TSK
== TSK_ImplicitInstantiation
&&
4907 !DefinitionRequired
)
4910 // Don't instantiate a definition if we already have one.
4911 const FunctionDecl
*ExistingDefn
= nullptr;
4912 if (Function
->isDefined(ExistingDefn
,
4913 /*CheckForPendingFriendDefinition=*/true)) {
4914 if (ExistingDefn
->isThisDeclarationADefinition())
4917 // If we're asked to instantiate a function whose body comes from an
4918 // instantiated friend declaration, attach the instantiated body to the
4919 // corresponding declaration of the function.
4920 assert(ExistingDefn
->isThisDeclarationInstantiatedFromAFriendDefinition());
4921 Function
= const_cast<FunctionDecl
*>(ExistingDefn
);
4924 // Find the function body that we'll be substituting.
4925 const FunctionDecl
*PatternDecl
= Function
->getTemplateInstantiationPattern();
4926 assert(PatternDecl
&& "instantiating a non-template");
4928 const FunctionDecl
*PatternDef
= PatternDecl
->getDefinition();
4929 Stmt
*Pattern
= nullptr;
4931 Pattern
= PatternDef
->getBody(PatternDef
);
4932 PatternDecl
= PatternDef
;
4933 if (PatternDef
->willHaveBody())
4934 PatternDef
= nullptr;
4937 // FIXME: We need to track the instantiation stack in order to know which
4938 // definitions should be visible within this instantiation.
4939 if (DiagnoseUninstantiableTemplate(PointOfInstantiation
, Function
,
4940 Function
->getInstantiatedFromMemberFunction(),
4941 PatternDecl
, PatternDef
, TSK
,
4942 /*Complain*/DefinitionRequired
)) {
4943 if (DefinitionRequired
)
4944 Function
->setInvalidDecl();
4945 else if (TSK
== TSK_ExplicitInstantiationDefinition
||
4946 (Function
->isConstexpr() && !Recursive
)) {
4947 // Try again at the end of the translation unit (at which point a
4948 // definition will be required).
4950 Function
->setInstantiationIsPending(true);
4951 PendingInstantiations
.push_back(
4952 std::make_pair(Function
, PointOfInstantiation
));
4953 } else if (TSK
== TSK_ImplicitInstantiation
) {
4954 if (AtEndOfTU
&& !getDiagnostics().hasErrorOccurred() &&
4955 !getSourceManager().isInSystemHeader(PatternDecl
->getBeginLoc())) {
4956 Diag(PointOfInstantiation
, diag::warn_func_template_missing
)
4958 Diag(PatternDecl
->getLocation(), diag::note_forward_template_decl
);
4959 if (getLangOpts().CPlusPlus11
)
4960 Diag(PointOfInstantiation
, diag::note_inst_declaration_hint
)
4968 // Postpone late parsed template instantiations.
4969 if (PatternDecl
->isLateTemplateParsed() &&
4970 !LateTemplateParser
) {
4971 Function
->setInstantiationIsPending(true);
4972 LateParsedInstantiations
.push_back(
4973 std::make_pair(Function
, PointOfInstantiation
));
4977 llvm::TimeTraceScope
TimeScope("InstantiateFunction", [&]() {
4979 llvm::raw_string_ostream
OS(Name
);
4980 Function
->getNameForDiagnostic(OS
, getPrintingPolicy(),
4981 /*Qualified=*/true);
4985 // If we're performing recursive template instantiation, create our own
4986 // queue of pending implicit instantiations that we will instantiate later,
4987 // while we're still within our own instantiation context.
4988 // This has to happen before LateTemplateParser below is called, so that
4989 // it marks vtables used in late parsed templates as used.
4990 GlobalEagerInstantiationScope
GlobalInstantiations(*this,
4991 /*Enabled=*/Recursive
);
4992 LocalEagerInstantiationScope
LocalInstantiations(*this);
4994 // Call the LateTemplateParser callback if there is a need to late parse
4995 // a templated function definition.
4996 if (!Pattern
&& PatternDecl
->isLateTemplateParsed() &&
4997 LateTemplateParser
) {
4998 // FIXME: Optimize to allow individual templates to be deserialized.
4999 if (PatternDecl
->isFromASTFile())
5000 ExternalSource
->ReadLateParsedTemplates(LateParsedTemplateMap
);
5002 auto LPTIter
= LateParsedTemplateMap
.find(PatternDecl
);
5003 assert(LPTIter
!= LateParsedTemplateMap
.end() &&
5004 "missing LateParsedTemplate");
5005 LateTemplateParser(OpaqueParser
, *LPTIter
->second
);
5006 Pattern
= PatternDecl
->getBody(PatternDecl
);
5007 updateAttrsForLateParsedTemplate(PatternDecl
, Function
);
5010 // Note, we should never try to instantiate a deleted function template.
5011 assert((Pattern
|| PatternDecl
->isDefaulted() ||
5012 PatternDecl
->hasSkippedBody()) &&
5013 "unexpected kind of function template definition");
5015 // C++1y [temp.explicit]p10:
5016 // Except for inline functions, declarations with types deduced from their
5017 // initializer or return value, and class template specializations, other
5018 // explicit instantiation declarations have the effect of suppressing the
5019 // implicit instantiation of the entity to which they refer.
5020 if (TSK
== TSK_ExplicitInstantiationDeclaration
&&
5021 !PatternDecl
->isInlined() &&
5022 !PatternDecl
->getReturnType()->getContainedAutoType())
5025 if (PatternDecl
->isInlined()) {
5026 // Function, and all later redeclarations of it (from imported modules,
5027 // for instance), are now implicitly inline.
5028 for (auto *D
= Function
->getMostRecentDecl(); /**/;
5029 D
= D
->getPreviousDecl()) {
5030 D
->setImplicitlyInline();
5036 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, Function
);
5037 if (Inst
.isInvalid() || Inst
.isAlreadyInstantiating())
5039 PrettyDeclStackTraceEntry
CrashInfo(Context
, Function
, SourceLocation(),
5040 "instantiating function definition");
5042 // The instantiation is visible here, even if it was first declared in an
5043 // unimported module.
5044 Function
->setVisibleDespiteOwningModule();
5046 // Copy the source locations from the pattern.
5047 Function
->setLocation(PatternDecl
->getLocation());
5048 Function
->setInnerLocStart(PatternDecl
->getInnerLocStart());
5049 Function
->setRangeEnd(PatternDecl
->getEndLoc());
5051 EnterExpressionEvaluationContext
EvalContext(
5052 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated
);
5054 // Introduce a new scope where local variable instantiations will be
5055 // recorded, unless we're actually a member function within a local
5056 // class, in which case we need to merge our results with the parent
5057 // scope (of the enclosing function). The exception is instantiating
5058 // a function template specialization, since the template to be
5059 // instantiated already has references to locals properly substituted.
5060 bool MergeWithParentScope
= false;
5061 if (CXXRecordDecl
*Rec
= dyn_cast
<CXXRecordDecl
>(Function
->getDeclContext()))
5062 MergeWithParentScope
=
5063 Rec
->isLocalClass() && !Function
->isFunctionTemplateSpecialization();
5065 LocalInstantiationScope
Scope(*this, MergeWithParentScope
);
5066 auto RebuildTypeSourceInfoForDefaultSpecialMembers
= [&]() {
5067 // Special members might get their TypeSourceInfo set up w.r.t the
5068 // PatternDecl context, in which case parameters could still be pointing
5069 // back to the original class, make sure arguments are bound to the
5070 // instantiated record instead.
5071 assert(PatternDecl
->isDefaulted() &&
5072 "Special member needs to be defaulted");
5073 auto PatternSM
= getDefaultedFunctionKind(PatternDecl
).asSpecialMember();
5074 if (!(PatternSM
== Sema::CXXCopyConstructor
||
5075 PatternSM
== Sema::CXXCopyAssignment
||
5076 PatternSM
== Sema::CXXMoveConstructor
||
5077 PatternSM
== Sema::CXXMoveAssignment
))
5080 auto *NewRec
= dyn_cast
<CXXRecordDecl
>(Function
->getDeclContext());
5081 const auto *PatternRec
=
5082 dyn_cast
<CXXRecordDecl
>(PatternDecl
->getDeclContext());
5083 if (!NewRec
|| !PatternRec
)
5085 if (!PatternRec
->isLambda())
5088 struct SpecialMemberTypeInfoRebuilder
5089 : TreeTransform
<SpecialMemberTypeInfoRebuilder
> {
5090 using Base
= TreeTransform
<SpecialMemberTypeInfoRebuilder
>;
5091 const CXXRecordDecl
*OldDecl
;
5092 CXXRecordDecl
*NewDecl
;
5094 SpecialMemberTypeInfoRebuilder(Sema
&SemaRef
, const CXXRecordDecl
*O
,
5096 : TreeTransform(SemaRef
), OldDecl(O
), NewDecl(N
) {}
5098 bool TransformExceptionSpec(SourceLocation Loc
,
5099 FunctionProtoType::ExceptionSpecInfo
&ESI
,
5100 SmallVectorImpl
<QualType
> &Exceptions
,
5105 QualType
TransformRecordType(TypeLocBuilder
&TLB
, RecordTypeLoc TL
) {
5106 const RecordType
*T
= TL
.getTypePtr();
5107 RecordDecl
*Record
= cast_or_null
<RecordDecl
>(
5108 getDerived().TransformDecl(TL
.getNameLoc(), T
->getDecl()));
5109 if (Record
!= OldDecl
)
5110 return Base::TransformRecordType(TLB
, TL
);
5112 QualType Result
= getDerived().RebuildRecordType(NewDecl
);
5113 if (Result
.isNull())
5116 RecordTypeLoc NewTL
= TLB
.push
<RecordTypeLoc
>(Result
);
5117 NewTL
.setNameLoc(TL
.getNameLoc());
5120 } IR
{*this, PatternRec
, NewRec
};
5122 TypeSourceInfo
*NewSI
= IR
.TransformType(Function
->getTypeSourceInfo());
5123 assert(NewSI
&& "Type Transform failed?");
5124 Function
->setType(NewSI
->getType());
5125 Function
->setTypeSourceInfo(NewSI
);
5127 ParmVarDecl
*Parm
= Function
->getParamDecl(0);
5128 TypeSourceInfo
*NewParmSI
= IR
.TransformType(Parm
->getTypeSourceInfo());
5129 Parm
->setType(NewParmSI
->getType());
5130 Parm
->setTypeSourceInfo(NewParmSI
);
5133 if (PatternDecl
->isDefaulted()) {
5134 RebuildTypeSourceInfoForDefaultSpecialMembers();
5135 SetDeclDefaulted(Function
, PatternDecl
->getLocation());
5137 MultiLevelTemplateArgumentList TemplateArgs
= getTemplateInstantiationArgs(
5138 Function
, Function
->getLexicalDeclContext(), /*Final=*/false, nullptr,
5139 false, PatternDecl
);
5141 // Substitute into the qualifier; we can get a substitution failure here
5142 // through evil use of alias templates.
5143 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5144 // of the) lexical context of the pattern?
5145 SubstQualifier(*this, PatternDecl
, Function
, TemplateArgs
);
5147 ActOnStartOfFunctionDef(nullptr, Function
);
5149 // Enter the scope of this instantiation. We don't use
5150 // PushDeclContext because we don't have a scope.
5151 Sema::ContextRAII
savedContext(*this, Function
);
5153 FPFeaturesStateRAII
SavedFPFeatures(*this);
5154 CurFPFeatures
= FPOptions(getLangOpts());
5155 FpPragmaStack
.CurrentValue
= FPOptionsOverride();
5157 if (addInstantiatedParametersToScope(Function
, PatternDecl
, Scope
,
5162 if (PatternDecl
->hasSkippedBody()) {
5163 ActOnSkippedFunctionBody(Function
);
5166 if (CXXConstructorDecl
*Ctor
= dyn_cast
<CXXConstructorDecl
>(Function
)) {
5167 // If this is a constructor, instantiate the member initializers.
5168 InstantiateMemInitializers(Ctor
, cast
<CXXConstructorDecl
>(PatternDecl
),
5171 // If this is an MS ABI dllexport default constructor, instantiate any
5172 // default arguments.
5173 if (Context
.getTargetInfo().getCXXABI().isMicrosoft() &&
5174 Ctor
->isDefaultConstructor()) {
5175 InstantiateDefaultCtorDefaultArgs(Ctor
);
5179 // Instantiate the function body.
5180 Body
= SubstStmt(Pattern
, TemplateArgs
);
5182 if (Body
.isInvalid())
5183 Function
->setInvalidDecl();
5185 // FIXME: finishing the function body while in an expression evaluation
5186 // context seems wrong. Investigate more.
5187 ActOnFinishFunctionBody(Function
, Body
.get(), /*IsInstantiation=*/true);
5189 PerformDependentDiagnostics(PatternDecl
, TemplateArgs
);
5191 if (auto *Listener
= getASTMutationListener())
5192 Listener
->FunctionDefinitionInstantiated(Function
);
5197 DeclGroupRef
DG(Function
);
5198 Consumer
.HandleTopLevelDecl(DG
);
5200 // This class may have local implicit instantiations that need to be
5201 // instantiation within this scope.
5202 LocalInstantiations
.perform();
5204 GlobalInstantiations
.perform();
5207 VarTemplateSpecializationDecl
*Sema::BuildVarTemplateInstantiation(
5208 VarTemplateDecl
*VarTemplate
, VarDecl
*FromVar
,
5209 const TemplateArgumentList
&TemplateArgList
,
5210 const TemplateArgumentListInfo
&TemplateArgsInfo
,
5211 SmallVectorImpl
<TemplateArgument
> &Converted
,
5212 SourceLocation PointOfInstantiation
, LateInstantiatedAttrVec
*LateAttrs
,
5213 LocalInstantiationScope
*StartingScope
) {
5214 if (FromVar
->isInvalidDecl())
5217 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, FromVar
);
5218 if (Inst
.isInvalid())
5221 // Instantiate the first declaration of the variable template: for a partial
5222 // specialization of a static data member template, the first declaration may
5223 // or may not be the declaration in the class; if it's in the class, we want
5224 // to instantiate a member in the class (a declaration), and if it's outside,
5225 // we want to instantiate a definition.
5227 // If we're instantiating an explicitly-specialized member template or member
5228 // partial specialization, don't do this. The member specialization completely
5229 // replaces the original declaration in this case.
5230 bool IsMemberSpec
= false;
5231 MultiLevelTemplateArgumentList MultiLevelList
;
5232 if (auto *PartialSpec
=
5233 dyn_cast
<VarTemplatePartialSpecializationDecl
>(FromVar
)) {
5234 IsMemberSpec
= PartialSpec
->isMemberSpecialization();
5235 MultiLevelList
.addOuterTemplateArguments(
5236 PartialSpec
, TemplateArgList
.asArray(), /*Final=*/false);
5238 assert(VarTemplate
== FromVar
->getDescribedVarTemplate());
5239 IsMemberSpec
= VarTemplate
->isMemberSpecialization();
5240 MultiLevelList
.addOuterTemplateArguments(
5241 VarTemplate
, TemplateArgList
.asArray(), /*Final=*/false);
5244 FromVar
= FromVar
->getFirstDecl();
5246 TemplateDeclInstantiator
Instantiator(*this, FromVar
->getDeclContext(),
5249 // TODO: Set LateAttrs and StartingScope ...
5251 return cast_or_null
<VarTemplateSpecializationDecl
>(
5252 Instantiator
.VisitVarTemplateSpecializationDecl(
5253 VarTemplate
, FromVar
, TemplateArgsInfo
, Converted
));
5256 /// Instantiates a variable template specialization by completing it
5257 /// with appropriate type information and initializer.
5258 VarTemplateSpecializationDecl
*Sema::CompleteVarTemplateSpecializationDecl(
5259 VarTemplateSpecializationDecl
*VarSpec
, VarDecl
*PatternDecl
,
5260 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
5261 assert(PatternDecl
->isThisDeclarationADefinition() &&
5262 "don't have a definition to instantiate from");
5264 // Do substitution on the type of the declaration
5265 TypeSourceInfo
*DI
=
5266 SubstType(PatternDecl
->getTypeSourceInfo(), TemplateArgs
,
5267 PatternDecl
->getTypeSpecStartLoc(), PatternDecl
->getDeclName());
5271 // Update the type of this variable template specialization.
5272 VarSpec
->setType(DI
->getType());
5274 // Convert the declaration into a definition now.
5275 VarSpec
->setCompleteDefinition();
5277 // Instantiate the initializer.
5278 InstantiateVariableInitializer(VarSpec
, PatternDecl
, TemplateArgs
);
5280 if (getLangOpts().OpenCL
)
5281 deduceOpenCLAddressSpace(VarSpec
);
5286 /// BuildVariableInstantiation - Used after a new variable has been created.
5287 /// Sets basic variable data and decides whether to postpone the
5288 /// variable instantiation.
5289 void Sema::BuildVariableInstantiation(
5290 VarDecl
*NewVar
, VarDecl
*OldVar
,
5291 const MultiLevelTemplateArgumentList
&TemplateArgs
,
5292 LateInstantiatedAttrVec
*LateAttrs
, DeclContext
*Owner
,
5293 LocalInstantiationScope
*StartingScope
,
5294 bool InstantiatingVarTemplate
,
5295 VarTemplateSpecializationDecl
*PrevDeclForVarTemplateSpecialization
) {
5296 // Instantiating a partial specialization to produce a partial
5298 bool InstantiatingVarTemplatePartialSpec
=
5299 isa
<VarTemplatePartialSpecializationDecl
>(OldVar
) &&
5300 isa
<VarTemplatePartialSpecializationDecl
>(NewVar
);
5301 // Instantiating from a variable template (or partial specialization) to
5302 // produce a variable template specialization.
5303 bool InstantiatingSpecFromTemplate
=
5304 isa
<VarTemplateSpecializationDecl
>(NewVar
) &&
5305 (OldVar
->getDescribedVarTemplate() ||
5306 isa
<VarTemplatePartialSpecializationDecl
>(OldVar
));
5308 // If we are instantiating a local extern declaration, the
5309 // instantiation belongs lexically to the containing function.
5310 // If we are instantiating a static data member defined
5311 // out-of-line, the instantiation will have the same lexical
5312 // context (which will be a namespace scope) as the template.
5313 if (OldVar
->isLocalExternDecl()) {
5314 NewVar
->setLocalExternDecl();
5315 NewVar
->setLexicalDeclContext(Owner
);
5316 } else if (OldVar
->isOutOfLine())
5317 NewVar
->setLexicalDeclContext(OldVar
->getLexicalDeclContext());
5318 NewVar
->setTSCSpec(OldVar
->getTSCSpec());
5319 NewVar
->setInitStyle(OldVar
->getInitStyle());
5320 NewVar
->setCXXForRangeDecl(OldVar
->isCXXForRangeDecl());
5321 NewVar
->setObjCForDecl(OldVar
->isObjCForDecl());
5322 NewVar
->setConstexpr(OldVar
->isConstexpr());
5323 NewVar
->setInitCapture(OldVar
->isInitCapture());
5324 NewVar
->setPreviousDeclInSameBlockScope(
5325 OldVar
->isPreviousDeclInSameBlockScope());
5326 NewVar
->setAccess(OldVar
->getAccess());
5328 if (!OldVar
->isStaticDataMember()) {
5329 if (OldVar
->isUsed(false))
5330 NewVar
->setIsUsed();
5331 NewVar
->setReferenced(OldVar
->isReferenced());
5334 InstantiateAttrs(TemplateArgs
, OldVar
, NewVar
, LateAttrs
, StartingScope
);
5336 LookupResult
Previous(
5337 *this, NewVar
->getDeclName(), NewVar
->getLocation(),
5338 NewVar
->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
5339 : Sema::LookupOrdinaryName
,
5340 NewVar
->isLocalExternDecl() ? Sema::ForExternalRedeclaration
5341 : forRedeclarationInCurContext());
5343 if (NewVar
->isLocalExternDecl() && OldVar
->getPreviousDecl() &&
5344 (!OldVar
->getPreviousDecl()->getDeclContext()->isDependentContext() ||
5345 OldVar
->getPreviousDecl()->getDeclContext()==OldVar
->getDeclContext())) {
5346 // We have a previous declaration. Use that one, so we merge with the
5348 if (NamedDecl
*NewPrev
= FindInstantiatedDecl(
5349 NewVar
->getLocation(), OldVar
->getPreviousDecl(), TemplateArgs
))
5350 Previous
.addDecl(NewPrev
);
5351 } else if (!isa
<VarTemplateSpecializationDecl
>(NewVar
) &&
5352 OldVar
->hasLinkage()) {
5353 LookupQualifiedName(Previous
, NewVar
->getDeclContext(), false);
5354 } else if (PrevDeclForVarTemplateSpecialization
) {
5355 Previous
.addDecl(PrevDeclForVarTemplateSpecialization
);
5357 CheckVariableDeclaration(NewVar
, Previous
);
5359 if (!InstantiatingVarTemplate
) {
5360 NewVar
->getLexicalDeclContext()->addHiddenDecl(NewVar
);
5361 if (!NewVar
->isLocalExternDecl() || !NewVar
->getPreviousDecl())
5362 NewVar
->getDeclContext()->makeDeclVisibleInContext(NewVar
);
5365 if (!OldVar
->isOutOfLine()) {
5366 if (NewVar
->getDeclContext()->isFunctionOrMethod())
5367 CurrentInstantiationScope
->InstantiatedLocal(OldVar
, NewVar
);
5370 // Link instantiations of static data members back to the template from
5371 // which they were instantiated.
5373 // Don't do this when instantiating a template (we link the template itself
5374 // back in that case) nor when instantiating a static data member template
5375 // (that's not a member specialization).
5376 if (NewVar
->isStaticDataMember() && !InstantiatingVarTemplate
&&
5377 !InstantiatingSpecFromTemplate
)
5378 NewVar
->setInstantiationOfStaticDataMember(OldVar
,
5379 TSK_ImplicitInstantiation
);
5381 // If the pattern is an (in-class) explicit specialization, then the result
5382 // is also an explicit specialization.
5383 if (VarTemplateSpecializationDecl
*OldVTSD
=
5384 dyn_cast
<VarTemplateSpecializationDecl
>(OldVar
)) {
5385 if (OldVTSD
->getSpecializationKind() == TSK_ExplicitSpecialization
&&
5386 !isa
<VarTemplatePartialSpecializationDecl
>(OldVTSD
))
5387 cast
<VarTemplateSpecializationDecl
>(NewVar
)->setSpecializationKind(
5388 TSK_ExplicitSpecialization
);
5391 // Forward the mangling number from the template to the instantiated decl.
5392 Context
.setManglingNumber(NewVar
, Context
.getManglingNumber(OldVar
));
5393 Context
.setStaticLocalNumber(NewVar
, Context
.getStaticLocalNumber(OldVar
));
5395 // Figure out whether to eagerly instantiate the initializer.
5396 if (InstantiatingVarTemplate
|| InstantiatingVarTemplatePartialSpec
) {
5397 // We're producing a template. Don't instantiate the initializer yet.
5398 } else if (NewVar
->getType()->isUndeducedType()) {
5399 // We need the type to complete the declaration of the variable.
5400 InstantiateVariableInitializer(NewVar
, OldVar
, TemplateArgs
);
5401 } else if (InstantiatingSpecFromTemplate
||
5402 (OldVar
->isInline() && OldVar
->isThisDeclarationADefinition() &&
5403 !NewVar
->isThisDeclarationADefinition())) {
5404 // Delay instantiation of the initializer for variable template
5405 // specializations or inline static data members until a definition of the
5406 // variable is needed.
5408 InstantiateVariableInitializer(NewVar
, OldVar
, TemplateArgs
);
5411 // Diagnose unused local variables with dependent types, where the diagnostic
5412 // will have been deferred.
5413 if (!NewVar
->isInvalidDecl() &&
5414 NewVar
->getDeclContext()->isFunctionOrMethod() &&
5415 OldVar
->getType()->isDependentType())
5416 DiagnoseUnusedDecl(NewVar
);
5419 /// Instantiate the initializer of a variable.
5420 void Sema::InstantiateVariableInitializer(
5421 VarDecl
*Var
, VarDecl
*OldVar
,
5422 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
5423 if (ASTMutationListener
*L
= getASTContext().getASTMutationListener())
5424 L
->VariableDefinitionInstantiated(Var
);
5426 // We propagate the 'inline' flag with the initializer, because it
5427 // would otherwise imply that the variable is a definition for a
5428 // non-static data member.
5429 if (OldVar
->isInlineSpecified())
5430 Var
->setInlineSpecified();
5431 else if (OldVar
->isInline())
5432 Var
->setImplicitlyInline();
5434 if (OldVar
->getInit()) {
5435 EnterExpressionEvaluationContext
Evaluated(
5436 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated
, Var
);
5438 // Instantiate the initializer.
5442 ContextRAII
SwitchContext(*this, Var
->getDeclContext());
5443 Init
= SubstInitializer(OldVar
->getInit(), TemplateArgs
,
5444 OldVar
->getInitStyle() == VarDecl::CallInit
);
5447 if (!Init
.isInvalid()) {
5448 Expr
*InitExpr
= Init
.get();
5450 if (Var
->hasAttr
<DLLImportAttr
>() &&
5452 !InitExpr
->isConstantInitializer(getASTContext(), false))) {
5453 // Do not dynamically initialize dllimport variables.
5454 } else if (InitExpr
) {
5455 bool DirectInit
= OldVar
->isDirectInit();
5456 AddInitializerToDecl(Var
, InitExpr
, DirectInit
);
5458 ActOnUninitializedDecl(Var
);
5460 // FIXME: Not too happy about invalidating the declaration
5461 // because of a bogus initializer.
5462 Var
->setInvalidDecl();
5465 // `inline` variables are a definition and declaration all in one; we won't
5466 // pick up an initializer from anywhere else.
5467 if (Var
->isStaticDataMember() && !Var
->isInline()) {
5468 if (!Var
->isOutOfLine())
5471 // If the declaration inside the class had an initializer, don't add
5472 // another one to the out-of-line definition.
5473 if (OldVar
->getFirstDecl()->hasInit())
5477 // We'll add an initializer to a for-range declaration later.
5478 if (Var
->isCXXForRangeDecl() || Var
->isObjCForDecl())
5481 ActOnUninitializedDecl(Var
);
5484 if (getLangOpts().CUDA
)
5485 checkAllowedCUDAInitializer(Var
);
5488 /// Instantiate the definition of the given variable from its
5491 /// \param PointOfInstantiation the point at which the instantiation was
5492 /// required. Note that this is not precisely a "point of instantiation"
5493 /// for the variable, but it's close.
5495 /// \param Var the already-instantiated declaration of a templated variable.
5497 /// \param Recursive if true, recursively instantiates any functions that
5498 /// are required by this instantiation.
5500 /// \param DefinitionRequired if true, then we are performing an explicit
5501 /// instantiation where a definition of the variable is required. Complain
5502 /// if there is no such definition.
5503 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation
,
5504 VarDecl
*Var
, bool Recursive
,
5505 bool DefinitionRequired
, bool AtEndOfTU
) {
5506 if (Var
->isInvalidDecl())
5509 // Never instantiate an explicitly-specialized entity.
5510 TemplateSpecializationKind TSK
=
5511 Var
->getTemplateSpecializationKindForInstantiation();
5512 if (TSK
== TSK_ExplicitSpecialization
)
5515 // Find the pattern and the arguments to substitute into it.
5516 VarDecl
*PatternDecl
= Var
->getTemplateInstantiationPattern();
5517 assert(PatternDecl
&& "no pattern for templated variable");
5518 MultiLevelTemplateArgumentList TemplateArgs
=
5519 getTemplateInstantiationArgs(Var
);
5521 VarTemplateSpecializationDecl
*VarSpec
=
5522 dyn_cast
<VarTemplateSpecializationDecl
>(Var
);
5524 // If this is a static data member template, there might be an
5525 // uninstantiated initializer on the declaration. If so, instantiate
5528 // FIXME: This largely duplicates what we would do below. The difference
5529 // is that along this path we may instantiate an initializer from an
5530 // in-class declaration of the template and instantiate the definition
5531 // from a separate out-of-class definition.
5532 if (PatternDecl
->isStaticDataMember() &&
5533 (PatternDecl
= PatternDecl
->getFirstDecl())->hasInit() &&
5535 // FIXME: Factor out the duplicated instantiation context setup/tear down
5537 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, Var
);
5538 if (Inst
.isInvalid() || Inst
.isAlreadyInstantiating())
5540 PrettyDeclStackTraceEntry
CrashInfo(Context
, Var
, SourceLocation(),
5541 "instantiating variable initializer");
5543 // The instantiation is visible here, even if it was first declared in an
5544 // unimported module.
5545 Var
->setVisibleDespiteOwningModule();
5547 // If we're performing recursive template instantiation, create our own
5548 // queue of pending implicit instantiations that we will instantiate
5549 // later, while we're still within our own instantiation context.
5550 GlobalEagerInstantiationScope
GlobalInstantiations(*this,
5551 /*Enabled=*/Recursive
);
5552 LocalInstantiationScope
Local(*this);
5553 LocalEagerInstantiationScope
LocalInstantiations(*this);
5555 // Enter the scope of this instantiation. We don't use
5556 // PushDeclContext because we don't have a scope.
5557 ContextRAII
PreviousContext(*this, Var
->getDeclContext());
5558 InstantiateVariableInitializer(Var
, PatternDecl
, TemplateArgs
);
5559 PreviousContext
.pop();
5561 // This variable may have local implicit instantiations that need to be
5562 // instantiated within this scope.
5563 LocalInstantiations
.perform();
5565 GlobalInstantiations
.perform();
5568 assert(Var
->isStaticDataMember() && PatternDecl
->isStaticDataMember() &&
5569 "not a static data member?");
5572 VarDecl
*Def
= PatternDecl
->getDefinition(getASTContext());
5574 // If we don't have a definition of the variable template, we won't perform
5575 // any instantiation. Rather, we rely on the user to instantiate this
5576 // definition (or provide a specialization for it) in another translation
5578 if (!Def
&& !DefinitionRequired
) {
5579 if (TSK
== TSK_ExplicitInstantiationDefinition
) {
5580 PendingInstantiations
.push_back(
5581 std::make_pair(Var
, PointOfInstantiation
));
5582 } else if (TSK
== TSK_ImplicitInstantiation
) {
5583 // Warn about missing definition at the end of translation unit.
5584 if (AtEndOfTU
&& !getDiagnostics().hasErrorOccurred() &&
5585 !getSourceManager().isInSystemHeader(PatternDecl
->getBeginLoc())) {
5586 Diag(PointOfInstantiation
, diag::warn_var_template_missing
)
5588 Diag(PatternDecl
->getLocation(), diag::note_forward_template_decl
);
5589 if (getLangOpts().CPlusPlus11
)
5590 Diag(PointOfInstantiation
, diag::note_inst_declaration_hint
) << Var
;
5596 // FIXME: We need to track the instantiation stack in order to know which
5597 // definitions should be visible within this instantiation.
5598 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
5599 if (DiagnoseUninstantiableTemplate(PointOfInstantiation
, Var
,
5600 /*InstantiatedFromMember*/false,
5601 PatternDecl
, Def
, TSK
,
5602 /*Complain*/DefinitionRequired
))
5605 // C++11 [temp.explicit]p10:
5606 // Except for inline functions, const variables of literal types, variables
5607 // of reference types, [...] explicit instantiation declarations
5608 // have the effect of suppressing the implicit instantiation of the entity
5609 // to which they refer.
5611 // FIXME: That's not exactly the same as "might be usable in constant
5612 // expressions", which only allows constexpr variables and const integral
5613 // types, not arbitrary const literal types.
5614 if (TSK
== TSK_ExplicitInstantiationDeclaration
&&
5615 !Var
->mightBeUsableInConstantExpressions(getASTContext()))
5618 // Make sure to pass the instantiated variable to the consumer at the end.
5619 struct PassToConsumerRAII
{
5620 ASTConsumer
&Consumer
;
5623 PassToConsumerRAII(ASTConsumer
&Consumer
, VarDecl
*Var
)
5624 : Consumer(Consumer
), Var(Var
) { }
5626 ~PassToConsumerRAII() {
5627 Consumer
.HandleCXXStaticMemberVarInstantiation(Var
);
5629 } PassToConsumerRAII(Consumer
, Var
);
5631 // If we already have a definition, we're done.
5632 if (VarDecl
*Def
= Var
->getDefinition()) {
5633 // We may be explicitly instantiating something we've already implicitly
5635 Def
->setTemplateSpecializationKind(Var
->getTemplateSpecializationKind(),
5636 PointOfInstantiation
);
5640 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, Var
);
5641 if (Inst
.isInvalid() || Inst
.isAlreadyInstantiating())
5643 PrettyDeclStackTraceEntry
CrashInfo(Context
, Var
, SourceLocation(),
5644 "instantiating variable definition");
5646 // If we're performing recursive template instantiation, create our own
5647 // queue of pending implicit instantiations that we will instantiate later,
5648 // while we're still within our own instantiation context.
5649 GlobalEagerInstantiationScope
GlobalInstantiations(*this,
5650 /*Enabled=*/Recursive
);
5652 // Enter the scope of this instantiation. We don't use
5653 // PushDeclContext because we don't have a scope.
5654 ContextRAII
PreviousContext(*this, Var
->getDeclContext());
5655 LocalInstantiationScope
Local(*this);
5657 LocalEagerInstantiationScope
LocalInstantiations(*this);
5659 VarDecl
*OldVar
= Var
;
5660 if (Def
->isStaticDataMember() && !Def
->isOutOfLine()) {
5661 // We're instantiating an inline static data member whose definition was
5662 // provided inside the class.
5663 InstantiateVariableInitializer(Var
, Def
, TemplateArgs
);
5664 } else if (!VarSpec
) {
5665 Var
= cast_or_null
<VarDecl
>(SubstDecl(Def
, Var
->getDeclContext(),
5667 } else if (Var
->isStaticDataMember() &&
5668 Var
->getLexicalDeclContext()->isRecord()) {
5669 // We need to instantiate the definition of a static data member template,
5670 // and all we have is the in-class declaration of it. Instantiate a separate
5671 // declaration of the definition.
5672 TemplateDeclInstantiator
Instantiator(*this, Var
->getDeclContext(),
5675 TemplateArgumentListInfo TemplateArgInfo
;
5676 if (const ASTTemplateArgumentListInfo
*ArgInfo
=
5677 VarSpec
->getTemplateArgsInfo()) {
5678 TemplateArgInfo
.setLAngleLoc(ArgInfo
->getLAngleLoc());
5679 TemplateArgInfo
.setRAngleLoc(ArgInfo
->getRAngleLoc());
5680 for (const TemplateArgumentLoc
&Arg
: ArgInfo
->arguments())
5681 TemplateArgInfo
.addArgument(Arg
);
5684 Var
= cast_or_null
<VarDecl
>(Instantiator
.VisitVarTemplateSpecializationDecl(
5685 VarSpec
->getSpecializedTemplate(), Def
, TemplateArgInfo
,
5686 VarSpec
->getTemplateArgs().asArray(), VarSpec
));
5688 llvm::PointerUnion
<VarTemplateDecl
*,
5689 VarTemplatePartialSpecializationDecl
*> PatternPtr
=
5690 VarSpec
->getSpecializedTemplateOrPartial();
5691 if (VarTemplatePartialSpecializationDecl
*Partial
=
5692 PatternPtr
.dyn_cast
<VarTemplatePartialSpecializationDecl
*>())
5693 cast
<VarTemplateSpecializationDecl
>(Var
)->setInstantiationOf(
5694 Partial
, &VarSpec
->getTemplateInstantiationArgs());
5696 // Attach the initializer.
5697 InstantiateVariableInitializer(Var
, Def
, TemplateArgs
);
5700 // Complete the existing variable's definition with an appropriately
5701 // substituted type and initializer.
5702 Var
= CompleteVarTemplateSpecializationDecl(VarSpec
, Def
, TemplateArgs
);
5704 PreviousContext
.pop();
5707 PassToConsumerRAII
.Var
= Var
;
5708 Var
->setTemplateSpecializationKind(OldVar
->getTemplateSpecializationKind(),
5709 OldVar
->getPointOfInstantiation());
5712 // This variable may have local implicit instantiations that need to be
5713 // instantiated within this scope.
5714 LocalInstantiations
.perform();
5716 GlobalInstantiations
.perform();
5720 Sema::InstantiateMemInitializers(CXXConstructorDecl
*New
,
5721 const CXXConstructorDecl
*Tmpl
,
5722 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
5724 SmallVector
<CXXCtorInitializer
*, 4> NewInits
;
5725 bool AnyErrors
= Tmpl
->isInvalidDecl();
5727 // Instantiate all the initializers.
5728 for (const auto *Init
: Tmpl
->inits()) {
5729 // Only instantiate written initializers, let Sema re-construct implicit
5731 if (!Init
->isWritten())
5734 SourceLocation EllipsisLoc
;
5736 if (Init
->isPackExpansion()) {
5737 // This is a pack expansion. We should expand it now.
5738 TypeLoc BaseTL
= Init
->getTypeSourceInfo()->getTypeLoc();
5739 SmallVector
<UnexpandedParameterPack
, 4> Unexpanded
;
5740 collectUnexpandedParameterPacks(BaseTL
, Unexpanded
);
5741 collectUnexpandedParameterPacks(Init
->getInit(), Unexpanded
);
5742 bool ShouldExpand
= false;
5743 bool RetainExpansion
= false;
5744 std::optional
<unsigned> NumExpansions
;
5745 if (CheckParameterPacksForExpansion(Init
->getEllipsisLoc(),
5746 BaseTL
.getSourceRange(),
5748 TemplateArgs
, ShouldExpand
,
5752 New
->setInvalidDecl();
5755 assert(ShouldExpand
&& "Partial instantiation of base initializer?");
5757 // Loop over all of the arguments in the argument pack(s),
5758 for (unsigned I
= 0; I
!= *NumExpansions
; ++I
) {
5759 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(*this, I
);
5761 // Instantiate the initializer.
5762 ExprResult TempInit
= SubstInitializer(Init
->getInit(), TemplateArgs
,
5763 /*CXXDirectInit=*/true);
5764 if (TempInit
.isInvalid()) {
5769 // Instantiate the base type.
5770 TypeSourceInfo
*BaseTInfo
= SubstType(Init
->getTypeSourceInfo(),
5772 Init
->getSourceLocation(),
5773 New
->getDeclName());
5779 // Build the initializer.
5780 MemInitResult NewInit
= BuildBaseInitializer(BaseTInfo
->getType(),
5781 BaseTInfo
, TempInit
.get(),
5784 if (NewInit
.isInvalid()) {
5789 NewInits
.push_back(NewInit
.get());
5795 // Instantiate the initializer.
5796 ExprResult TempInit
= SubstInitializer(Init
->getInit(), TemplateArgs
,
5797 /*CXXDirectInit=*/true);
5798 if (TempInit
.isInvalid()) {
5803 MemInitResult NewInit
;
5804 if (Init
->isDelegatingInitializer() || Init
->isBaseInitializer()) {
5805 TypeSourceInfo
*TInfo
= SubstType(Init
->getTypeSourceInfo(),
5807 Init
->getSourceLocation(),
5808 New
->getDeclName());
5811 New
->setInvalidDecl();
5815 if (Init
->isBaseInitializer())
5816 NewInit
= BuildBaseInitializer(TInfo
->getType(), TInfo
, TempInit
.get(),
5817 New
->getParent(), EllipsisLoc
);
5819 NewInit
= BuildDelegatingInitializer(TInfo
, TempInit
.get(),
5820 cast
<CXXRecordDecl
>(CurContext
->getParent()));
5821 } else if (Init
->isMemberInitializer()) {
5822 FieldDecl
*Member
= cast_or_null
<FieldDecl
>(FindInstantiatedDecl(
5823 Init
->getMemberLocation(),
5828 New
->setInvalidDecl();
5832 NewInit
= BuildMemberInitializer(Member
, TempInit
.get(),
5833 Init
->getSourceLocation());
5834 } else if (Init
->isIndirectMemberInitializer()) {
5835 IndirectFieldDecl
*IndirectMember
=
5836 cast_or_null
<IndirectFieldDecl
>(FindInstantiatedDecl(
5837 Init
->getMemberLocation(),
5838 Init
->getIndirectMember(), TemplateArgs
));
5840 if (!IndirectMember
) {
5842 New
->setInvalidDecl();
5846 NewInit
= BuildMemberInitializer(IndirectMember
, TempInit
.get(),
5847 Init
->getSourceLocation());
5850 if (NewInit
.isInvalid()) {
5852 New
->setInvalidDecl();
5854 NewInits
.push_back(NewInit
.get());
5858 // Assign all the initializers to the new constructor.
5859 ActOnMemInitializers(New
,
5860 /*FIXME: ColonLoc */
5866 // TODO: this could be templated if the various decl types used the
5867 // same method name.
5868 static bool isInstantiationOf(ClassTemplateDecl
*Pattern
,
5869 ClassTemplateDecl
*Instance
) {
5870 Pattern
= Pattern
->getCanonicalDecl();
5873 Instance
= Instance
->getCanonicalDecl();
5874 if (Pattern
== Instance
) return true;
5875 Instance
= Instance
->getInstantiatedFromMemberTemplate();
5881 static bool isInstantiationOf(FunctionTemplateDecl
*Pattern
,
5882 FunctionTemplateDecl
*Instance
) {
5883 Pattern
= Pattern
->getCanonicalDecl();
5886 Instance
= Instance
->getCanonicalDecl();
5887 if (Pattern
== Instance
) return true;
5888 Instance
= Instance
->getInstantiatedFromMemberTemplate();
5895 isInstantiationOf(ClassTemplatePartialSpecializationDecl
*Pattern
,
5896 ClassTemplatePartialSpecializationDecl
*Instance
) {
5898 = cast
<ClassTemplatePartialSpecializationDecl
>(Pattern
->getCanonicalDecl());
5900 Instance
= cast
<ClassTemplatePartialSpecializationDecl
>(
5901 Instance
->getCanonicalDecl());
5902 if (Pattern
== Instance
)
5904 Instance
= Instance
->getInstantiatedFromMember();
5910 static bool isInstantiationOf(CXXRecordDecl
*Pattern
,
5911 CXXRecordDecl
*Instance
) {
5912 Pattern
= Pattern
->getCanonicalDecl();
5915 Instance
= Instance
->getCanonicalDecl();
5916 if (Pattern
== Instance
) return true;
5917 Instance
= Instance
->getInstantiatedFromMemberClass();
5923 static bool isInstantiationOf(FunctionDecl
*Pattern
,
5924 FunctionDecl
*Instance
) {
5925 Pattern
= Pattern
->getCanonicalDecl();
5928 Instance
= Instance
->getCanonicalDecl();
5929 if (Pattern
== Instance
) return true;
5930 Instance
= Instance
->getInstantiatedFromMemberFunction();
5936 static bool isInstantiationOf(EnumDecl
*Pattern
,
5937 EnumDecl
*Instance
) {
5938 Pattern
= Pattern
->getCanonicalDecl();
5941 Instance
= Instance
->getCanonicalDecl();
5942 if (Pattern
== Instance
) return true;
5943 Instance
= Instance
->getInstantiatedFromMemberEnum();
5949 static bool isInstantiationOf(UsingShadowDecl
*Pattern
,
5950 UsingShadowDecl
*Instance
,
5952 return declaresSameEntity(C
.getInstantiatedFromUsingShadowDecl(Instance
),
5956 static bool isInstantiationOf(UsingDecl
*Pattern
, UsingDecl
*Instance
,
5958 return declaresSameEntity(C
.getInstantiatedFromUsingDecl(Instance
), Pattern
);
5961 template<typename T
>
5962 static bool isInstantiationOfUnresolvedUsingDecl(T
*Pattern
, Decl
*Other
,
5964 // An unresolved using declaration can instantiate to an unresolved using
5965 // declaration, or to a using declaration or a using declaration pack.
5967 // Multiple declarations can claim to be instantiated from an unresolved
5968 // using declaration if it's a pack expansion. We want the UsingPackDecl
5969 // in that case, not the individual UsingDecls within the pack.
5970 bool OtherIsPackExpansion
;
5971 NamedDecl
*OtherFrom
;
5972 if (auto *OtherUUD
= dyn_cast
<T
>(Other
)) {
5973 OtherIsPackExpansion
= OtherUUD
->isPackExpansion();
5974 OtherFrom
= Ctx
.getInstantiatedFromUsingDecl(OtherUUD
);
5975 } else if (auto *OtherUPD
= dyn_cast
<UsingPackDecl
>(Other
)) {
5976 OtherIsPackExpansion
= true;
5977 OtherFrom
= OtherUPD
->getInstantiatedFromUsingDecl();
5978 } else if (auto *OtherUD
= dyn_cast
<UsingDecl
>(Other
)) {
5979 OtherIsPackExpansion
= false;
5980 OtherFrom
= Ctx
.getInstantiatedFromUsingDecl(OtherUD
);
5984 return Pattern
->isPackExpansion() == OtherIsPackExpansion
&&
5985 declaresSameEntity(OtherFrom
, Pattern
);
5988 static bool isInstantiationOfStaticDataMember(VarDecl
*Pattern
,
5989 VarDecl
*Instance
) {
5990 assert(Instance
->isStaticDataMember());
5992 Pattern
= Pattern
->getCanonicalDecl();
5995 Instance
= Instance
->getCanonicalDecl();
5996 if (Pattern
== Instance
) return true;
5997 Instance
= Instance
->getInstantiatedFromStaticDataMember();
6003 // Other is the prospective instantiation
6004 // D is the prospective pattern
6005 static bool isInstantiationOf(ASTContext
&Ctx
, NamedDecl
*D
, Decl
*Other
) {
6006 if (auto *UUD
= dyn_cast
<UnresolvedUsingTypenameDecl
>(D
))
6007 return isInstantiationOfUnresolvedUsingDecl(UUD
, Other
, Ctx
);
6009 if (auto *UUD
= dyn_cast
<UnresolvedUsingValueDecl
>(D
))
6010 return isInstantiationOfUnresolvedUsingDecl(UUD
, Other
, Ctx
);
6012 if (D
->getKind() != Other
->getKind())
6015 if (auto *Record
= dyn_cast
<CXXRecordDecl
>(Other
))
6016 return isInstantiationOf(cast
<CXXRecordDecl
>(D
), Record
);
6018 if (auto *Function
= dyn_cast
<FunctionDecl
>(Other
))
6019 return isInstantiationOf(cast
<FunctionDecl
>(D
), Function
);
6021 if (auto *Enum
= dyn_cast
<EnumDecl
>(Other
))
6022 return isInstantiationOf(cast
<EnumDecl
>(D
), Enum
);
6024 if (auto *Var
= dyn_cast
<VarDecl
>(Other
))
6025 if (Var
->isStaticDataMember())
6026 return isInstantiationOfStaticDataMember(cast
<VarDecl
>(D
), Var
);
6028 if (auto *Temp
= dyn_cast
<ClassTemplateDecl
>(Other
))
6029 return isInstantiationOf(cast
<ClassTemplateDecl
>(D
), Temp
);
6031 if (auto *Temp
= dyn_cast
<FunctionTemplateDecl
>(Other
))
6032 return isInstantiationOf(cast
<FunctionTemplateDecl
>(D
), Temp
);
6034 if (auto *PartialSpec
=
6035 dyn_cast
<ClassTemplatePartialSpecializationDecl
>(Other
))
6036 return isInstantiationOf(cast
<ClassTemplatePartialSpecializationDecl
>(D
),
6039 if (auto *Field
= dyn_cast
<FieldDecl
>(Other
)) {
6040 if (!Field
->getDeclName()) {
6041 // This is an unnamed field.
6042 return declaresSameEntity(Ctx
.getInstantiatedFromUnnamedFieldDecl(Field
),
6043 cast
<FieldDecl
>(D
));
6047 if (auto *Using
= dyn_cast
<UsingDecl
>(Other
))
6048 return isInstantiationOf(cast
<UsingDecl
>(D
), Using
, Ctx
);
6050 if (auto *Shadow
= dyn_cast
<UsingShadowDecl
>(Other
))
6051 return isInstantiationOf(cast
<UsingShadowDecl
>(D
), Shadow
, Ctx
);
6053 return D
->getDeclName() &&
6054 D
->getDeclName() == cast
<NamedDecl
>(Other
)->getDeclName();
6057 template<typename ForwardIterator
>
6058 static NamedDecl
*findInstantiationOf(ASTContext
&Ctx
,
6060 ForwardIterator first
,
6061 ForwardIterator last
) {
6062 for (; first
!= last
; ++first
)
6063 if (isInstantiationOf(Ctx
, D
, *first
))
6064 return cast
<NamedDecl
>(*first
);
6069 /// Finds the instantiation of the given declaration context
6070 /// within the current instantiation.
6072 /// \returns NULL if there was an error
6073 DeclContext
*Sema::FindInstantiatedContext(SourceLocation Loc
, DeclContext
* DC
,
6074 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
6075 if (NamedDecl
*D
= dyn_cast
<NamedDecl
>(DC
)) {
6076 Decl
* ID
= FindInstantiatedDecl(Loc
, D
, TemplateArgs
, true);
6077 return cast_or_null
<DeclContext
>(ID
);
6081 /// Determine whether the given context is dependent on template parameters at
6082 /// level \p Level or below.
6084 /// Sometimes we only substitute an inner set of template arguments and leave
6085 /// the outer templates alone. In such cases, contexts dependent only on the
6086 /// outer levels are not effectively dependent.
6087 static bool isDependentContextAtLevel(DeclContext
*DC
, unsigned Level
) {
6088 if (!DC
->isDependentContext())
6092 return cast
<Decl
>(DC
)->getTemplateDepth() > Level
;
6095 /// Find the instantiation of the given declaration within the
6096 /// current instantiation.
6098 /// This routine is intended to be used when \p D is a declaration
6099 /// referenced from within a template, that needs to mapped into the
6100 /// corresponding declaration within an instantiation. For example,
6104 /// template<typename T>
6107 /// KnownValue = sizeof(T)
6110 /// bool getKind() const { return KnownValue; }
6113 /// template struct X<int>;
6116 /// In the instantiation of X<int>::getKind(), we need to map the \p
6117 /// EnumConstantDecl for \p KnownValue (which refers to
6118 /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
6119 /// \p FindInstantiatedDecl performs this mapping from within the instantiation
6121 NamedDecl
*Sema::FindInstantiatedDecl(SourceLocation Loc
, NamedDecl
*D
,
6122 const MultiLevelTemplateArgumentList
&TemplateArgs
,
6123 bool FindingInstantiatedContext
) {
6124 DeclContext
*ParentDC
= D
->getDeclContext();
6125 // Determine whether our parent context depends on any of the template
6126 // arguments we're currently substituting.
6127 bool ParentDependsOnArgs
= isDependentContextAtLevel(
6128 ParentDC
, TemplateArgs
.getNumRetainedOuterLevels());
6129 // FIXME: Parameters of pointer to functions (y below) that are themselves
6130 // parameters (p below) can have their ParentDC set to the translation-unit
6131 // - thus we can not consistently check if the ParentDC of such a parameter
6132 // is Dependent or/and a FunctionOrMethod.
6133 // For e.g. this code, during Template argument deduction tries to
6134 // find an instantiated decl for (T y) when the ParentDC for y is
6135 // the translation unit.
6136 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6137 // float baz(float(*)()) { return 0.0; }
6139 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6140 // it gets here, always has a FunctionOrMethod as its ParentDC??
6142 // - as long as we have a ParmVarDecl whose parent is non-dependent and
6143 // whose type is not instantiation dependent, do nothing to the decl
6144 // - otherwise find its instantiated decl.
6145 if (isa
<ParmVarDecl
>(D
) && !ParentDependsOnArgs
&&
6146 !cast
<ParmVarDecl
>(D
)->getType()->isInstantiationDependentType())
6148 if (isa
<ParmVarDecl
>(D
) || isa
<NonTypeTemplateParmDecl
>(D
) ||
6149 isa
<TemplateTypeParmDecl
>(D
) || isa
<TemplateTemplateParmDecl
>(D
) ||
6150 (ParentDependsOnArgs
&& (ParentDC
->isFunctionOrMethod() ||
6151 isa
<OMPDeclareReductionDecl
>(ParentDC
) ||
6152 isa
<OMPDeclareMapperDecl
>(ParentDC
))) ||
6153 (isa
<CXXRecordDecl
>(D
) && cast
<CXXRecordDecl
>(D
)->isLambda() &&
6154 cast
<CXXRecordDecl
>(D
)->getTemplateDepth() >
6155 TemplateArgs
.getNumRetainedOuterLevels())) {
6156 // D is a local of some kind. Look into the map of local
6157 // declarations to their instantiations.
6158 if (CurrentInstantiationScope
) {
6159 if (auto Found
= CurrentInstantiationScope
->findInstantiationOf(D
)) {
6160 if (Decl
*FD
= Found
->dyn_cast
<Decl
*>())
6161 return cast
<NamedDecl
>(FD
);
6163 int PackIdx
= ArgumentPackSubstitutionIndex
;
6164 assert(PackIdx
!= -1 &&
6165 "found declaration pack but not pack expanding");
6166 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack
;
6167 return cast
<NamedDecl
>((*Found
->get
<DeclArgumentPack
*>())[PackIdx
]);
6171 // If we're performing a partial substitution during template argument
6172 // deduction, we may not have values for template parameters yet. They
6173 // just map to themselves.
6174 if (isa
<NonTypeTemplateParmDecl
>(D
) || isa
<TemplateTypeParmDecl
>(D
) ||
6175 isa
<TemplateTemplateParmDecl
>(D
))
6178 if (D
->isInvalidDecl())
6181 // Normally this function only searches for already instantiated declaration
6182 // however we have to make an exclusion for local types used before
6183 // definition as in the code:
6185 // template<typename T> void f1() {
6186 // void g1(struct x1);
6190 // In this case instantiation of the type of 'g1' requires definition of
6191 // 'x1', which is defined later. Error recovery may produce an enum used
6192 // before definition. In these cases we need to instantiate relevant
6193 // declarations here.
6194 bool NeedInstantiate
= false;
6195 if (CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(D
))
6196 NeedInstantiate
= RD
->isLocalClass();
6197 else if (isa
<TypedefNameDecl
>(D
) &&
6198 isa
<CXXDeductionGuideDecl
>(D
->getDeclContext()))
6199 NeedInstantiate
= true;
6201 NeedInstantiate
= isa
<EnumDecl
>(D
);
6202 if (NeedInstantiate
) {
6203 Decl
*Inst
= SubstDecl(D
, CurContext
, TemplateArgs
);
6204 CurrentInstantiationScope
->InstantiatedLocal(D
, Inst
);
6205 return cast
<TypeDecl
>(Inst
);
6208 // If we didn't find the decl, then we must have a label decl that hasn't
6209 // been found yet. Lazily instantiate it and return it now.
6210 assert(isa
<LabelDecl
>(D
));
6212 Decl
*Inst
= SubstDecl(D
, CurContext
, TemplateArgs
);
6213 assert(Inst
&& "Failed to instantiate label??");
6215 CurrentInstantiationScope
->InstantiatedLocal(D
, Inst
);
6216 return cast
<LabelDecl
>(Inst
);
6219 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(D
)) {
6220 if (!Record
->isDependentContext())
6223 // Determine whether this record is the "templated" declaration describing
6224 // a class template or class template specialization.
6225 ClassTemplateDecl
*ClassTemplate
= Record
->getDescribedClassTemplate();
6227 ClassTemplate
= ClassTemplate
->getCanonicalDecl();
6228 else if (ClassTemplateSpecializationDecl
*Spec
=
6229 dyn_cast
<ClassTemplateSpecializationDecl
>(Record
))
6230 ClassTemplate
= Spec
->getSpecializedTemplate()->getCanonicalDecl();
6232 // Walk the current context to find either the record or an instantiation of
6234 DeclContext
*DC
= CurContext
;
6235 while (!DC
->isFileContext()) {
6236 // If we're performing substitution while we're inside the template
6237 // definition, we'll find our own context. We're done.
6238 if (DC
->Equals(Record
))
6241 if (CXXRecordDecl
*InstRecord
= dyn_cast
<CXXRecordDecl
>(DC
)) {
6242 // Check whether we're in the process of instantiating a class template
6243 // specialization of the template we're mapping.
6244 if (ClassTemplateSpecializationDecl
*InstSpec
6245 = dyn_cast
<ClassTemplateSpecializationDecl
>(InstRecord
)){
6246 ClassTemplateDecl
*SpecTemplate
= InstSpec
->getSpecializedTemplate();
6247 if (ClassTemplate
&& isInstantiationOf(ClassTemplate
, SpecTemplate
))
6251 // Check whether we're in the process of instantiating a member class.
6252 if (isInstantiationOf(Record
, InstRecord
))
6256 // Move to the outer template scope.
6257 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(DC
)) {
6258 if (FD
->getFriendObjectKind() &&
6259 FD
->getNonTransparentDeclContext()->isFileContext()) {
6260 DC
= FD
->getLexicalDeclContext();
6263 // An implicit deduction guide acts as if it's within the class template
6264 // specialization described by its name and first N template params.
6265 auto *Guide
= dyn_cast
<CXXDeductionGuideDecl
>(FD
);
6266 if (Guide
&& Guide
->isImplicit()) {
6267 TemplateDecl
*TD
= Guide
->getDeducedTemplate();
6268 // Convert the arguments to an "as-written" list.
6269 TemplateArgumentListInfo
Args(Loc
, Loc
);
6270 for (TemplateArgument Arg
: TemplateArgs
.getInnermost().take_front(
6271 TD
->getTemplateParameters()->size())) {
6272 ArrayRef
<TemplateArgument
> Unpacked(Arg
);
6273 if (Arg
.getKind() == TemplateArgument::Pack
)
6274 Unpacked
= Arg
.pack_elements();
6275 for (TemplateArgument UnpackedArg
: Unpacked
)
6277 getTrivialTemplateArgumentLoc(UnpackedArg
, QualType(), Loc
));
6279 QualType T
= CheckTemplateIdType(TemplateName(TD
), Loc
, Args
);
6282 auto *SubstRecord
= T
->getAsCXXRecordDecl();
6283 assert(SubstRecord
&& "class template id not a class type?");
6284 // Check that this template-id names the primary template and not a
6285 // partial or explicit specialization. (In the latter cases, it's
6286 // meaningless to attempt to find an instantiation of D within the
6288 // FIXME: The standard doesn't say what should happen here.
6289 if (FindingInstantiatedContext
&&
6290 usesPartialOrExplicitSpecialization(
6291 Loc
, cast
<ClassTemplateSpecializationDecl
>(SubstRecord
))) {
6292 Diag(Loc
, diag::err_specialization_not_primary_template
)
6293 << T
<< (SubstRecord
->getTemplateSpecializationKind() ==
6294 TSK_ExplicitSpecialization
);
6302 DC
= DC
->getParent();
6305 // Fall through to deal with other dependent record types (e.g.,
6306 // anonymous unions in class templates).
6309 if (!ParentDependsOnArgs
)
6312 ParentDC
= FindInstantiatedContext(Loc
, ParentDC
, TemplateArgs
);
6316 if (ParentDC
!= D
->getDeclContext()) {
6317 // We performed some kind of instantiation in the parent context,
6318 // so now we need to look into the instantiated parent context to
6319 // find the instantiation of the declaration D.
6321 // If our context used to be dependent, we may need to instantiate
6322 // it before performing lookup into that context.
6323 bool IsBeingInstantiated
= false;
6324 if (CXXRecordDecl
*Spec
= dyn_cast
<CXXRecordDecl
>(ParentDC
)) {
6325 if (!Spec
->isDependentContext()) {
6326 QualType T
= Context
.getTypeDeclType(Spec
);
6327 const RecordType
*Tag
= T
->getAs
<RecordType
>();
6328 assert(Tag
&& "type of non-dependent record is not a RecordType");
6329 if (Tag
->isBeingDefined())
6330 IsBeingInstantiated
= true;
6331 if (!Tag
->isBeingDefined() &&
6332 RequireCompleteType(Loc
, T
, diag::err_incomplete_type
))
6335 ParentDC
= Tag
->getDecl();
6339 NamedDecl
*Result
= nullptr;
6340 // FIXME: If the name is a dependent name, this lookup won't necessarily
6341 // find it. Does that ever matter?
6342 if (auto Name
= D
->getDeclName()) {
6343 DeclarationNameInfo
NameInfo(Name
, D
->getLocation());
6344 DeclarationNameInfo NewNameInfo
=
6345 SubstDeclarationNameInfo(NameInfo
, TemplateArgs
);
6346 Name
= NewNameInfo
.getName();
6349 DeclContext::lookup_result Found
= ParentDC
->lookup(Name
);
6351 Result
= findInstantiationOf(Context
, D
, Found
.begin(), Found
.end());
6353 // Since we don't have a name for the entity we're looking for,
6354 // our only option is to walk through all of the declarations to
6355 // find that name. This will occur in a few cases:
6357 // - anonymous struct/union within a template
6358 // - unnamed class/struct/union/enum within a template
6360 // FIXME: Find a better way to find these instantiations!
6361 Result
= findInstantiationOf(Context
, D
,
6362 ParentDC
->decls_begin(),
6363 ParentDC
->decls_end());
6367 if (isa
<UsingShadowDecl
>(D
)) {
6368 // UsingShadowDecls can instantiate to nothing because of using hiding.
6369 } else if (hasUncompilableErrorOccurred()) {
6370 // We've already complained about some ill-formed code, so most likely
6371 // this declaration failed to instantiate. There's no point in
6372 // complaining further, since this is normal in invalid code.
6373 // FIXME: Use more fine-grained 'invalid' tracking for this.
6374 } else if (IsBeingInstantiated
) {
6375 // The class in which this member exists is currently being
6376 // instantiated, and we haven't gotten around to instantiating this
6377 // member yet. This can happen when the code uses forward declarations
6378 // of member classes, and introduces ordering dependencies via
6379 // template instantiation.
6380 Diag(Loc
, diag::err_member_not_yet_instantiated
)
6382 << Context
.getTypeDeclType(cast
<CXXRecordDecl
>(ParentDC
));
6383 Diag(D
->getLocation(), diag::note_non_instantiated_member_here
);
6384 } else if (EnumConstantDecl
*ED
= dyn_cast
<EnumConstantDecl
>(D
)) {
6385 // This enumeration constant was found when the template was defined,
6386 // but can't be found in the instantiation. This can happen if an
6387 // unscoped enumeration member is explicitly specialized.
6388 EnumDecl
*Enum
= cast
<EnumDecl
>(ED
->getLexicalDeclContext());
6389 EnumDecl
*Spec
= cast
<EnumDecl
>(FindInstantiatedDecl(Loc
, Enum
,
6391 assert(Spec
->getTemplateSpecializationKind() ==
6392 TSK_ExplicitSpecialization
);
6393 Diag(Loc
, diag::err_enumerator_does_not_exist
)
6395 << Context
.getTypeDeclType(cast
<TypeDecl
>(Spec
->getDeclContext()));
6396 Diag(Spec
->getLocation(), diag::note_enum_specialized_here
)
6397 << Context
.getTypeDeclType(Spec
);
6399 // We should have found something, but didn't.
6400 llvm_unreachable("Unable to find instantiation of declaration!");
6410 /// Performs template instantiation for all implicit template
6411 /// instantiations we have seen until this point.
6412 void Sema::PerformPendingInstantiations(bool LocalOnly
) {
6413 std::deque
<PendingImplicitInstantiation
> delayedPCHInstantiations
;
6414 while (!PendingLocalImplicitInstantiations
.empty() ||
6415 (!LocalOnly
&& !PendingInstantiations
.empty())) {
6416 PendingImplicitInstantiation Inst
;
6418 if (PendingLocalImplicitInstantiations
.empty()) {
6419 Inst
= PendingInstantiations
.front();
6420 PendingInstantiations
.pop_front();
6422 Inst
= PendingLocalImplicitInstantiations
.front();
6423 PendingLocalImplicitInstantiations
.pop_front();
6426 // Instantiate function definitions
6427 if (FunctionDecl
*Function
= dyn_cast
<FunctionDecl
>(Inst
.first
)) {
6428 bool DefinitionRequired
= Function
->getTemplateSpecializationKind() ==
6429 TSK_ExplicitInstantiationDefinition
;
6430 if (Function
->isMultiVersion()) {
6431 getASTContext().forEachMultiversionedFunctionVersion(
6432 Function
, [this, Inst
, DefinitionRequired
](FunctionDecl
*CurFD
) {
6433 InstantiateFunctionDefinition(/*FIXME:*/ Inst
.second
, CurFD
, true,
6434 DefinitionRequired
, true);
6435 if (CurFD
->isDefined())
6436 CurFD
->setInstantiationIsPending(false);
6439 InstantiateFunctionDefinition(/*FIXME:*/ Inst
.second
, Function
, true,
6440 DefinitionRequired
, true);
6441 if (Function
->isDefined())
6442 Function
->setInstantiationIsPending(false);
6444 // Definition of a PCH-ed template declaration may be available only in the TU.
6445 if (!LocalOnly
&& LangOpts
.PCHInstantiateTemplates
&&
6446 TUKind
== TU_Prefix
&& Function
->instantiationIsPending())
6447 delayedPCHInstantiations
.push_back(Inst
);
6451 // Instantiate variable definitions
6452 VarDecl
*Var
= cast
<VarDecl
>(Inst
.first
);
6454 assert((Var
->isStaticDataMember() ||
6455 isa
<VarTemplateSpecializationDecl
>(Var
)) &&
6456 "Not a static data member, nor a variable template"
6457 " specialization?");
6459 // Don't try to instantiate declarations if the most recent redeclaration
6461 if (Var
->getMostRecentDecl()->isInvalidDecl())
6464 // Check if the most recent declaration has changed the specialization kind
6465 // and removed the need for implicit instantiation.
6466 switch (Var
->getMostRecentDecl()
6467 ->getTemplateSpecializationKindForInstantiation()) {
6468 case TSK_Undeclared
:
6469 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
6470 case TSK_ExplicitInstantiationDeclaration
:
6471 case TSK_ExplicitSpecialization
:
6472 continue; // No longer need to instantiate this type.
6473 case TSK_ExplicitInstantiationDefinition
:
6474 // We only need an instantiation if the pending instantiation *is* the
6475 // explicit instantiation.
6476 if (Var
!= Var
->getMostRecentDecl())
6479 case TSK_ImplicitInstantiation
:
6483 PrettyDeclStackTraceEntry
CrashInfo(Context
, Var
, SourceLocation(),
6484 "instantiating variable definition");
6485 bool DefinitionRequired
= Var
->getTemplateSpecializationKind() ==
6486 TSK_ExplicitInstantiationDefinition
;
6488 // Instantiate static data member definitions or variable template
6490 InstantiateVariableDefinition(/*FIXME:*/ Inst
.second
, Var
, true,
6491 DefinitionRequired
, true);
6494 if (!LocalOnly
&& LangOpts
.PCHInstantiateTemplates
)
6495 PendingInstantiations
.swap(delayedPCHInstantiations
);
6498 void Sema::PerformDependentDiagnostics(const DeclContext
*Pattern
,
6499 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
6500 for (auto *DD
: Pattern
->ddiags()) {
6501 switch (DD
->getKind()) {
6502 case DependentDiagnostic::Access
:
6503 HandleDependentAccessCheck(*DD
, TemplateArgs
);