[lld][WebAssembly] Add `--table-base` setting
[llvm-project.git] / clang / lib / Sema / SemaTemplateInstantiateDecl.cpp
blob63f022d5c2ff094ccc121061358b103afb02b961
1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2 //
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 //===----------------------------------------------------------------------===/
7 //
8 // This file implements C++ template instantiation for declarations.
9 //
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"
33 #include <optional>
35 using namespace clang;
37 static bool isDeclWithinFunction(const Decl *D) {
38 const DeclContext *DC = D->getDeclContext();
39 if (DC->isFunctionOrMethod())
40 return true;
42 if (DC->isRecord())
43 return cast<CXXRecordDecl>(DC)->isLocalClass();
45 return false;
48 template<typename DeclT>
49 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
50 const MultiLevelTemplateArgumentList &TemplateArgs) {
51 if (!OldDecl->getQualifierLoc())
52 return false;
54 assert((NewDecl->getFriendObjectKind() ||
55 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
56 "non-friend with qualified name defined in dependent context");
57 Sema::ContextRAII SavedContext(
58 SemaRef,
59 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
60 ? NewDecl->getLexicalDeclContext()
61 : OldDecl->getLexicalDeclContext()));
63 NestedNameSpecifierLoc NewQualifierLoc
64 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
65 TemplateArgs);
67 if (!NewQualifierLoc)
68 return true;
70 NewDecl->setQualifierInfo(NewQualifierLoc);
71 return false;
74 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
75 DeclaratorDecl *NewDecl) {
76 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
79 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
80 TagDecl *NewDecl) {
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);
97 } else {
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);
114 return;
117 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
118 if (Aligned->isAlignmentExpr())
119 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
120 Unexpanded);
121 else
122 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
123 Unexpanded);
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))
134 return;
136 if (!Expand) {
137 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
138 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
139 } else {
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())
157 return;
158 E = Result.getAs<Expr>();
160 if (Aligned->getOffset()) {
161 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
162 if (Result.isInvalid())
163 return;
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(
185 S.getASTContext(),
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 =
202 HasDelayedArgs
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))
209 return;
211 StringRef Str = Attr->getAnnotation();
212 if (HasDelayedArgs) {
213 if (Args.size() < 1) {
214 S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
215 << Attr << 1;
216 return;
219 if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
220 return;
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())
239 return nullptr;
240 Cond = Result.getAs<Expr>();
242 if (!Cond->isTypeDependent()) {
243 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
244 if (Converted.isInvalid())
245 return nullptr;
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);
255 return nullptr;
257 return Cond;
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);
266 if (Cond)
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);
277 if (Cond)
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())
294 return;
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())
301 return;
302 MinBlocks = Result.getAs<Expr>();
305 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks);
308 static void
309 instantiateDependentModeAttr(Sema &S,
310 const MultiLevelTemplateArgumentList &TemplateArgs,
311 const ModeAttr &Attr, Decl *New) {
312 S.AddModeAttr(New, Attr, Attr.getMode(),
313 /*InInstantiation=*/true);
316 /// Instantiation of 'declare simd' attribute and its arguments.
317 static void instantiateOMPDeclareSimdDeclAttr(
318 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
319 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
320 // Allow 'this' in clauses with varlists.
321 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
322 New = FTD->getTemplatedDecl();
323 auto *FD = cast<FunctionDecl>(New);
324 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
325 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
326 SmallVector<unsigned, 4> LinModifiers;
328 auto SubstExpr = [&](Expr *E) -> ExprResult {
329 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
330 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
331 Sema::ContextRAII SavedContext(S, FD);
332 LocalInstantiationScope Local(S);
333 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
334 Local.InstantiatedLocal(
335 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
336 return S.SubstExpr(E, TemplateArgs);
338 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
339 FD->isCXXInstanceMember());
340 return S.SubstExpr(E, TemplateArgs);
343 // Substitute a single OpenMP clause, which is a potentially-evaluated
344 // full-expression.
345 auto Subst = [&](Expr *E) -> ExprResult {
346 EnterExpressionEvaluationContext Evaluated(
347 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
348 ExprResult Res = SubstExpr(E);
349 if (Res.isInvalid())
350 return Res;
351 return S.ActOnFinishFullExpr(Res.get(), false);
354 ExprResult Simdlen;
355 if (auto *E = Attr.getSimdlen())
356 Simdlen = Subst(E);
358 if (Attr.uniforms_size() > 0) {
359 for(auto *E : Attr.uniforms()) {
360 ExprResult Inst = Subst(E);
361 if (Inst.isInvalid())
362 continue;
363 Uniforms.push_back(Inst.get());
367 auto AI = Attr.alignments_begin();
368 for (auto *E : Attr.aligneds()) {
369 ExprResult Inst = Subst(E);
370 if (Inst.isInvalid())
371 continue;
372 Aligneds.push_back(Inst.get());
373 Inst = ExprEmpty();
374 if (*AI)
375 Inst = S.SubstExpr(*AI, TemplateArgs);
376 Alignments.push_back(Inst.get());
377 ++AI;
380 auto SI = Attr.steps_begin();
381 for (auto *E : Attr.linears()) {
382 ExprResult Inst = Subst(E);
383 if (Inst.isInvalid())
384 continue;
385 Linears.push_back(Inst.get());
386 Inst = ExprEmpty();
387 if (*SI)
388 Inst = S.SubstExpr(*SI, TemplateArgs);
389 Steps.push_back(Inst.get());
390 ++SI;
392 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
393 (void)S.ActOnOpenMPDeclareSimdDirective(
394 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
395 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
396 Attr.getRange());
399 /// Instantiation of 'declare variant' attribute and its arguments.
400 static void instantiateOMPDeclareVariantAttr(
401 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
402 const OMPDeclareVariantAttr &Attr, Decl *New) {
403 // Allow 'this' in clauses with varlists.
404 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
405 New = FTD->getTemplatedDecl();
406 auto *FD = cast<FunctionDecl>(New);
407 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
409 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
410 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
411 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
412 Sema::ContextRAII SavedContext(S, FD);
413 LocalInstantiationScope Local(S);
414 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
415 Local.InstantiatedLocal(
416 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
417 return S.SubstExpr(E, TemplateArgs);
419 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
420 FD->isCXXInstanceMember());
421 return S.SubstExpr(E, TemplateArgs);
424 // Substitute a single OpenMP clause, which is a potentially-evaluated
425 // full-expression.
426 auto &&Subst = [&SubstExpr, &S](Expr *E) {
427 EnterExpressionEvaluationContext Evaluated(
428 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
429 ExprResult Res = SubstExpr(E);
430 if (Res.isInvalid())
431 return Res;
432 return S.ActOnFinishFullExpr(Res.get(), false);
435 ExprResult VariantFuncRef;
436 if (Expr *E = Attr.getVariantFuncRef()) {
437 // Do not mark function as is used to prevent its emission if this is the
438 // only place where it is used.
439 EnterExpressionEvaluationContext Unevaluated(
440 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
441 VariantFuncRef = Subst(E);
444 // Copy the template version of the OMPTraitInfo and run substitute on all
445 // score and condition expressiosn.
446 OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo();
447 TI = *Attr.getTraitInfos();
449 // Try to substitute template parameters in score and condition expressions.
450 auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
451 if (E) {
452 EnterExpressionEvaluationContext Unevaluated(
453 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
454 ExprResult ER = Subst(E);
455 if (ER.isUsable())
456 E = ER.get();
457 else
458 return true;
460 return false;
462 if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
463 return;
465 Expr *E = VariantFuncRef.get();
467 // Check function/variant ref for `omp declare variant` but not for `omp
468 // begin declare variant` (which use implicit attributes).
469 std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
470 S.checkOpenMPDeclareVariantFunction(S.ConvertDeclToDeclGroup(New), E, TI,
471 Attr.appendArgs_size(),
472 Attr.getRange());
474 if (!DeclVarData)
475 return;
477 E = DeclVarData->second;
478 FD = DeclVarData->first;
480 if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
481 if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
482 if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
483 if (!VariantFTD->isThisDeclarationADefinition())
484 return;
485 Sema::TentativeAnalysisScope Trap(S);
486 const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy(
487 S.Context, TemplateArgs.getInnermost());
489 auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
490 New->getLocation());
491 if (!SubstFD)
492 return;
493 QualType NewType = S.Context.mergeFunctionTypes(
494 SubstFD->getType(), FD->getType(),
495 /* OfBlockPointer */ false,
496 /* Unqualified */ false, /* AllowCXX */ true);
497 if (NewType.isNull())
498 return;
499 S.InstantiateFunctionDefinition(
500 New->getLocation(), SubstFD, /* Recursive */ true,
501 /* DefinitionRequired */ false, /* AtEndOfTU */ false);
502 SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
503 E = DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(),
504 SourceLocation(), SubstFD,
505 /* RefersToEnclosingVariableOrCapture */ false,
506 /* NameLoc */ SubstFD->getLocation(),
507 SubstFD->getType(), ExprValueKind::VK_PRValue);
512 SmallVector<Expr *, 8> NothingExprs;
513 SmallVector<Expr *, 8> NeedDevicePtrExprs;
514 SmallVector<OMPInteropInfo, 4> AppendArgs;
516 for (Expr *E : Attr.adjustArgsNothing()) {
517 ExprResult ER = Subst(E);
518 if (ER.isInvalid())
519 continue;
520 NothingExprs.push_back(ER.get());
522 for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
523 ExprResult ER = Subst(E);
524 if (ER.isInvalid())
525 continue;
526 NeedDevicePtrExprs.push_back(ER.get());
528 for (OMPInteropInfo &II : Attr.appendArgs()) {
529 // When prefer_type is implemented for append_args handle them here too.
530 AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
533 S.ActOnOpenMPDeclareVariantDirective(
534 FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
535 SourceLocation(), Attr.getRange());
538 static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
539 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
540 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
541 // Both min and max expression are constant expressions.
542 EnterExpressionEvaluationContext Unevaluated(
543 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
545 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
546 if (Result.isInvalid())
547 return;
548 Expr *MinExpr = Result.getAs<Expr>();
550 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
551 if (Result.isInvalid())
552 return;
553 Expr *MaxExpr = Result.getAs<Expr>();
555 S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
558 static ExplicitSpecifier
559 instantiateExplicitSpecifier(Sema &S,
560 const MultiLevelTemplateArgumentList &TemplateArgs,
561 ExplicitSpecifier ES, FunctionDecl *New) {
562 if (!ES.getExpr())
563 return ES;
564 Expr *OldCond = ES.getExpr();
565 Expr *Cond = nullptr;
567 EnterExpressionEvaluationContext Unevaluated(
568 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
569 ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
570 if (SubstResult.isInvalid()) {
571 return ExplicitSpecifier::Invalid();
573 Cond = SubstResult.get();
575 ExplicitSpecifier Result(Cond, ES.getKind());
576 if (!Cond->isTypeDependent())
577 S.tryResolveExplicitSpecifier(Result);
578 return Result;
581 static void instantiateDependentAMDGPUWavesPerEUAttr(
582 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
583 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
584 // Both min and max expression are constant expressions.
585 EnterExpressionEvaluationContext Unevaluated(
586 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
588 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
589 if (Result.isInvalid())
590 return;
591 Expr *MinExpr = Result.getAs<Expr>();
593 Expr *MaxExpr = nullptr;
594 if (auto Max = Attr.getMax()) {
595 Result = S.SubstExpr(Max, TemplateArgs);
596 if (Result.isInvalid())
597 return;
598 MaxExpr = Result.getAs<Expr>();
601 S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
604 // This doesn't take any template parameters, but we have a custom action that
605 // needs to happen when the kernel itself is instantiated. We need to run the
606 // ItaniumMangler to mark the names required to name this kernel.
607 static void instantiateDependentSYCLKernelAttr(
608 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
609 const SYCLKernelAttr &Attr, Decl *New) {
610 New->addAttr(Attr.clone(S.getASTContext()));
613 /// Determine whether the attribute A might be relevant to the declaration D.
614 /// If not, we can skip instantiating it. The attribute may or may not have
615 /// been instantiated yet.
616 static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
617 // 'preferred_name' is only relevant to the matching specialization of the
618 // template.
619 if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
620 QualType T = PNA->getTypedefType();
621 const auto *RD = cast<CXXRecordDecl>(D);
622 if (!T->isDependentType() && !RD->isDependentContext() &&
623 !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
624 return false;
625 for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
626 if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
627 PNA->getTypedefType()))
628 return false;
629 return true;
632 if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
633 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
634 switch (BA->getID()) {
635 case Builtin::BIforward:
636 // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
637 // type and returns an lvalue reference type. The library implementation
638 // will produce an error in this case; don't get in its way.
639 if (FD && FD->getNumParams() >= 1 &&
640 FD->getParamDecl(0)->getType()->isRValueReferenceType() &&
641 FD->getReturnType()->isLValueReferenceType()) {
642 return false;
644 [[fallthrough]];
645 case Builtin::BImove:
646 case Builtin::BImove_if_noexcept:
647 // HACK: Super-old versions of libc++ (3.1 and earlier) provide
648 // std::forward and std::move overloads that sometimes return by value
649 // instead of by reference when building in C++98 mode. Don't treat such
650 // cases as builtins.
651 if (FD && !FD->getReturnType()->isReferenceType())
652 return false;
653 break;
657 return true;
660 void Sema::InstantiateAttrsForDecl(
661 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
662 Decl *New, LateInstantiatedAttrVec *LateAttrs,
663 LocalInstantiationScope *OuterMostScope) {
664 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
665 // FIXME: This function is called multiple times for the same template
666 // specialization. We should only instantiate attributes that were added
667 // since the previous instantiation.
668 for (const auto *TmplAttr : Tmpl->attrs()) {
669 if (!isRelevantAttr(*this, New, TmplAttr))
670 continue;
672 // FIXME: If any of the special case versions from InstantiateAttrs become
673 // applicable to template declaration, we'll need to add them here.
674 CXXThisScopeRAII ThisScope(
675 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
676 Qualifiers(), ND->isCXXInstanceMember());
678 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
679 TmplAttr, Context, *this, TemplateArgs);
680 if (NewAttr && isRelevantAttr(*this, New, NewAttr))
681 New->addAttr(NewAttr);
686 static Sema::RetainOwnershipKind
687 attrToRetainOwnershipKind(const Attr *A) {
688 switch (A->getKind()) {
689 case clang::attr::CFConsumed:
690 return Sema::RetainOwnershipKind::CF;
691 case clang::attr::OSConsumed:
692 return Sema::RetainOwnershipKind::OS;
693 case clang::attr::NSConsumed:
694 return Sema::RetainOwnershipKind::NS;
695 default:
696 llvm_unreachable("Wrong argument supplied");
700 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
701 const Decl *Tmpl, Decl *New,
702 LateInstantiatedAttrVec *LateAttrs,
703 LocalInstantiationScope *OuterMostScope) {
704 for (const auto *TmplAttr : Tmpl->attrs()) {
705 if (!isRelevantAttr(*this, New, TmplAttr))
706 continue;
708 // FIXME: This should be generalized to more than just the AlignedAttr.
709 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
710 if (Aligned && Aligned->isAlignmentDependent()) {
711 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
712 continue;
715 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
716 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
717 continue;
720 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
721 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
722 continue;
725 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
726 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
727 continue;
730 if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
731 instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
732 continue;
735 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
736 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
737 cast<FunctionDecl>(New));
738 continue;
741 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
742 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
743 cast<FunctionDecl>(New));
744 continue;
747 if (const auto *CUDALaunchBounds =
748 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
749 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
750 *CUDALaunchBounds, New);
751 continue;
754 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
755 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
756 continue;
759 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
760 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
761 continue;
764 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
765 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
766 continue;
769 if (const auto *AMDGPUFlatWorkGroupSize =
770 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
771 instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
772 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
775 if (const auto *AMDGPUFlatWorkGroupSize =
776 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
777 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
778 *AMDGPUFlatWorkGroupSize, New);
781 // Existing DLL attribute on the instantiation takes precedence.
782 if (TmplAttr->getKind() == attr::DLLExport ||
783 TmplAttr->getKind() == attr::DLLImport) {
784 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
785 continue;
789 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
790 AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
791 continue;
794 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
795 isa<CFConsumedAttr>(TmplAttr)) {
796 AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
797 /*template instantiation=*/true);
798 continue;
801 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
802 if (!New->hasAttr<PointerAttr>())
803 New->addAttr(A->clone(Context));
804 continue;
807 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
808 if (!New->hasAttr<OwnerAttr>())
809 New->addAttr(A->clone(Context));
810 continue;
813 if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
814 instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
815 continue;
818 assert(!TmplAttr->isPackExpansion());
819 if (TmplAttr->isLateParsed() && LateAttrs) {
820 // Late parsed attributes must be instantiated and attached after the
821 // enclosing class has been instantiated. See Sema::InstantiateClass.
822 LocalInstantiationScope *Saved = nullptr;
823 if (CurrentInstantiationScope)
824 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
825 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
826 } else {
827 // Allow 'this' within late-parsed attributes.
828 auto *ND = cast<NamedDecl>(New);
829 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
830 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
831 ND->isCXXInstanceMember());
833 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
834 *this, TemplateArgs);
835 if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
836 New->addAttr(NewAttr);
841 /// Update instantiation attributes after template was late parsed.
843 /// Some attributes are evaluated based on the body of template. If it is
844 /// late parsed, such attributes cannot be evaluated when declaration is
845 /// instantiated. This function is used to update instantiation attributes when
846 /// template definition is ready.
847 void Sema::updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst) {
848 for (const auto *Attr : Pattern->attrs()) {
849 if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
850 if (!Inst->hasAttr<StrictFPAttr>())
851 Inst->addAttr(A->clone(getASTContext()));
852 continue;
857 /// In the MS ABI, we need to instantiate default arguments of dllexported
858 /// default constructors along with the constructor definition. This allows IR
859 /// gen to emit a constructor closure which calls the default constructor with
860 /// its default arguments.
861 void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) {
862 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
863 Ctor->isDefaultConstructor());
864 unsigned NumParams = Ctor->getNumParams();
865 if (NumParams == 0)
866 return;
867 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
868 if (!Attr)
869 return;
870 for (unsigned I = 0; I != NumParams; ++I) {
871 (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
872 Ctor->getParamDecl(I));
873 CleanupVarDeclMarking();
877 /// Get the previous declaration of a declaration for the purposes of template
878 /// instantiation. If this finds a previous declaration, then the previous
879 /// declaration of the instantiation of D should be an instantiation of the
880 /// result of this function.
881 template<typename DeclT>
882 static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
883 DeclT *Result = D->getPreviousDecl();
885 // If the declaration is within a class, and the previous declaration was
886 // merged from a different definition of that class, then we don't have a
887 // previous declaration for the purpose of template instantiation.
888 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
889 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
890 return nullptr;
892 return Result;
895 Decl *
896 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
897 llvm_unreachable("Translation units cannot be instantiated");
900 Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
901 llvm_unreachable("HLSL buffer declarations cannot be instantiated");
904 Decl *
905 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
906 llvm_unreachable("pragma comment cannot be instantiated");
909 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
910 PragmaDetectMismatchDecl *D) {
911 llvm_unreachable("pragma comment cannot be instantiated");
914 Decl *
915 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
916 llvm_unreachable("extern \"C\" context cannot be instantiated");
919 Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
920 llvm_unreachable("GUID declaration cannot be instantiated");
923 Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
924 UnnamedGlobalConstantDecl *D) {
925 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
928 Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
929 TemplateParamObjectDecl *D) {
930 llvm_unreachable("template parameter objects cannot be instantiated");
933 Decl *
934 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
935 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
936 D->getIdentifier());
937 Owner->addDecl(Inst);
938 return Inst;
941 Decl *
942 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
943 llvm_unreachable("Namespaces cannot be instantiated");
946 Decl *
947 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
948 NamespaceAliasDecl *Inst
949 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
950 D->getNamespaceLoc(),
951 D->getAliasLoc(),
952 D->getIdentifier(),
953 D->getQualifierLoc(),
954 D->getTargetNameLoc(),
955 D->getNamespace());
956 Owner->addDecl(Inst);
957 return Inst;
960 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
961 bool IsTypeAlias) {
962 bool Invalid = false;
963 TypeSourceInfo *DI = D->getTypeSourceInfo();
964 if (DI->getType()->isInstantiationDependentType() ||
965 DI->getType()->isVariablyModifiedType()) {
966 DI = SemaRef.SubstType(DI, TemplateArgs,
967 D->getLocation(), D->getDeclName());
968 if (!DI) {
969 Invalid = true;
970 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
972 } else {
973 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
976 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
977 // libstdc++ relies upon this bug in its implementation of common_type. If we
978 // happen to be processing that implementation, fake up the g++ ?:
979 // semantics. See LWG issue 2141 for more information on the bug. The bugs
980 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
981 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
982 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
983 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
984 DT->isReferenceType() &&
985 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
986 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
987 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
988 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
989 // Fold it to the (non-reference) type which g++ would have produced.
990 DI = SemaRef.Context.getTrivialTypeSourceInfo(
991 DI->getType().getNonReferenceType());
993 // Create the new typedef
994 TypedefNameDecl *Typedef;
995 if (IsTypeAlias)
996 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
997 D->getLocation(), D->getIdentifier(), DI);
998 else
999 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1000 D->getLocation(), D->getIdentifier(), DI);
1001 if (Invalid)
1002 Typedef->setInvalidDecl();
1004 // If the old typedef was the name for linkage purposes of an anonymous
1005 // tag decl, re-establish that relationship for the new typedef.
1006 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1007 TagDecl *oldTag = oldTagType->getDecl();
1008 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1009 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
1010 assert(!newTag->hasNameForLinkage());
1011 newTag->setTypedefNameForAnonDecl(Typedef);
1015 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
1016 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1017 TemplateArgs);
1018 if (!InstPrev)
1019 return nullptr;
1021 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1023 // If the typedef types are not identical, reject them.
1024 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1026 Typedef->setPreviousDecl(InstPrevTypedef);
1029 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1031 if (D->getUnderlyingType()->getAs<DependentNameType>())
1032 SemaRef.inferGslPointerAttribute(Typedef);
1034 Typedef->setAccess(D->getAccess());
1035 Typedef->setReferenced(D->isReferenced());
1037 return Typedef;
1040 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1041 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1042 if (Typedef)
1043 Owner->addDecl(Typedef);
1044 return Typedef;
1047 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1048 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1049 if (Typedef)
1050 Owner->addDecl(Typedef);
1051 return Typedef;
1054 Decl *
1055 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1056 // Create a local instantiation scope for this type alias template, which
1057 // will contain the instantiations of the template parameters.
1058 LocalInstantiationScope Scope(SemaRef);
1060 TemplateParameterList *TempParams = D->getTemplateParameters();
1061 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1062 if (!InstParams)
1063 return nullptr;
1065 TypeAliasDecl *Pattern = D->getTemplatedDecl();
1067 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1068 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
1069 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1070 if (!Found.empty()) {
1071 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1075 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1076 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1077 if (!AliasInst)
1078 return nullptr;
1080 TypeAliasTemplateDecl *Inst
1081 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1082 D->getDeclName(), InstParams, AliasInst);
1083 AliasInst->setDescribedAliasTemplate(Inst);
1084 if (PrevAliasTemplate)
1085 Inst->setPreviousDecl(PrevAliasTemplate);
1087 Inst->setAccess(D->getAccess());
1089 if (!PrevAliasTemplate)
1090 Inst->setInstantiatedFromMemberTemplate(D);
1092 Owner->addDecl(Inst);
1094 return Inst;
1097 Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1098 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1099 D->getIdentifier());
1100 NewBD->setReferenced(D->isReferenced());
1101 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
1102 return NewBD;
1105 Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1106 // Transform the bindings first.
1107 SmallVector<BindingDecl*, 16> NewBindings;
1108 for (auto *OldBD : D->bindings())
1109 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1110 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1112 auto *NewDD = cast_or_null<DecompositionDecl>(
1113 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1115 if (!NewDD || NewDD->isInvalidDecl())
1116 for (auto *NewBD : NewBindings)
1117 NewBD->setInvalidDecl();
1119 return NewDD;
1122 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
1123 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1126 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
1127 bool InstantiatingVarTemplate,
1128 ArrayRef<BindingDecl*> *Bindings) {
1130 // Do substitution on the type of the declaration
1131 TypeSourceInfo *DI = SemaRef.SubstType(
1132 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1133 D->getDeclName(), /*AllowDeducedTST*/true);
1134 if (!DI)
1135 return nullptr;
1137 if (DI->getType()->isFunctionType()) {
1138 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1139 << D->isStaticDataMember() << DI->getType();
1140 return nullptr;
1143 DeclContext *DC = Owner;
1144 if (D->isLocalExternDecl())
1145 SemaRef.adjustContextForLocalExternDecl(DC);
1147 // Build the instantiated declaration.
1148 VarDecl *Var;
1149 if (Bindings)
1150 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1151 D->getLocation(), DI->getType(), DI,
1152 D->getStorageClass(), *Bindings);
1153 else
1154 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1155 D->getLocation(), D->getIdentifier(), DI->getType(),
1156 DI, D->getStorageClass());
1158 // In ARC, infer 'retaining' for variables of retainable type.
1159 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1160 SemaRef.inferObjCARCLifetime(Var))
1161 Var->setInvalidDecl();
1163 if (SemaRef.getLangOpts().OpenCL)
1164 SemaRef.deduceOpenCLAddressSpace(Var);
1166 // Substitute the nested name specifier, if any.
1167 if (SubstQualifier(D, Var))
1168 return nullptr;
1170 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1171 StartingScope, InstantiatingVarTemplate);
1172 if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1173 QualType RT;
1174 if (auto *F = dyn_cast<FunctionDecl>(DC))
1175 RT = F->getReturnType();
1176 else if (isa<BlockDecl>(DC))
1177 RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1178 ->getReturnType();
1179 else
1180 llvm_unreachable("Unknown context type");
1182 // This is the last chance we have of checking copy elision eligibility
1183 // for functions in dependent contexts. The sema actions for building
1184 // the return statement during template instantiation will have no effect
1185 // regarding copy elision, since NRVO propagation runs on the scope exit
1186 // actions, and these are not run on instantiation.
1187 // This might run through some VarDecls which were returned from non-taken
1188 // 'if constexpr' branches, and these will end up being constructed on the
1189 // return slot even if they will never be returned, as a sort of accidental
1190 // 'optimization'. Notably, functions with 'auto' return types won't have it
1191 // deduced by this point. Coupled with the limitation described
1192 // previously, this makes it very hard to support copy elision for these.
1193 Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1194 bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1195 Var->setNRVOVariable(NRVO);
1198 Var->setImplicit(D->isImplicit());
1200 if (Var->isStaticLocal())
1201 SemaRef.CheckStaticLocalForDllExport(Var);
1203 if (Var->getTLSKind())
1204 SemaRef.CheckThreadLocalForLargeAlignment(Var);
1206 return Var;
1209 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1210 AccessSpecDecl* AD
1211 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1212 D->getAccessSpecifierLoc(), D->getColonLoc());
1213 Owner->addHiddenDecl(AD);
1214 return AD;
1217 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1218 bool Invalid = false;
1219 TypeSourceInfo *DI = D->getTypeSourceInfo();
1220 if (DI->getType()->isInstantiationDependentType() ||
1221 DI->getType()->isVariablyModifiedType()) {
1222 DI = SemaRef.SubstType(DI, TemplateArgs,
1223 D->getLocation(), D->getDeclName());
1224 if (!DI) {
1225 DI = D->getTypeSourceInfo();
1226 Invalid = true;
1227 } else if (DI->getType()->isFunctionType()) {
1228 // C++ [temp.arg.type]p3:
1229 // If a declaration acquires a function type through a type
1230 // dependent on a template-parameter and this causes a
1231 // declaration that does not use the syntactic form of a
1232 // function declarator to have function type, the program is
1233 // ill-formed.
1234 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1235 << DI->getType();
1236 Invalid = true;
1238 } else {
1239 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1242 Expr *BitWidth = D->getBitWidth();
1243 if (Invalid)
1244 BitWidth = nullptr;
1245 else if (BitWidth) {
1246 // The bit-width expression is a constant expression.
1247 EnterExpressionEvaluationContext Unevaluated(
1248 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1250 ExprResult InstantiatedBitWidth
1251 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1252 if (InstantiatedBitWidth.isInvalid()) {
1253 Invalid = true;
1254 BitWidth = nullptr;
1255 } else
1256 BitWidth = InstantiatedBitWidth.getAs<Expr>();
1259 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1260 DI->getType(), DI,
1261 cast<RecordDecl>(Owner),
1262 D->getLocation(),
1263 D->isMutable(),
1264 BitWidth,
1265 D->getInClassInitStyle(),
1266 D->getInnerLocStart(),
1267 D->getAccess(),
1268 nullptr);
1269 if (!Field) {
1270 cast<Decl>(Owner)->setInvalidDecl();
1271 return nullptr;
1274 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1276 if (Field->hasAttrs())
1277 SemaRef.CheckAlignasUnderalignment(Field);
1279 if (Invalid)
1280 Field->setInvalidDecl();
1282 if (!Field->getDeclName()) {
1283 // Keep track of where this decl came from.
1284 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1286 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1287 if (Parent->isAnonymousStructOrUnion() &&
1288 Parent->getRedeclContext()->isFunctionOrMethod())
1289 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1292 Field->setImplicit(D->isImplicit());
1293 Field->setAccess(D->getAccess());
1294 Owner->addDecl(Field);
1296 return Field;
1299 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1300 bool Invalid = false;
1301 TypeSourceInfo *DI = D->getTypeSourceInfo();
1303 if (DI->getType()->isVariablyModifiedType()) {
1304 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1305 << D;
1306 Invalid = true;
1307 } else if (DI->getType()->isInstantiationDependentType()) {
1308 DI = SemaRef.SubstType(DI, TemplateArgs,
1309 D->getLocation(), D->getDeclName());
1310 if (!DI) {
1311 DI = D->getTypeSourceInfo();
1312 Invalid = true;
1313 } else if (DI->getType()->isFunctionType()) {
1314 // C++ [temp.arg.type]p3:
1315 // If a declaration acquires a function type through a type
1316 // dependent on a template-parameter and this causes a
1317 // declaration that does not use the syntactic form of a
1318 // function declarator to have function type, the program is
1319 // ill-formed.
1320 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1321 << DI->getType();
1322 Invalid = true;
1324 } else {
1325 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1328 MSPropertyDecl *Property = MSPropertyDecl::Create(
1329 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1330 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1332 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1333 StartingScope);
1335 if (Invalid)
1336 Property->setInvalidDecl();
1338 Property->setAccess(D->getAccess());
1339 Owner->addDecl(Property);
1341 return Property;
1344 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1345 NamedDecl **NamedChain =
1346 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1348 int i = 0;
1349 for (auto *PI : D->chain()) {
1350 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1351 TemplateArgs);
1352 if (!Next)
1353 return nullptr;
1355 NamedChain[i++] = Next;
1358 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1359 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1360 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1361 {NamedChain, D->getChainingSize()});
1363 for (const auto *Attr : D->attrs())
1364 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1366 IndirectField->setImplicit(D->isImplicit());
1367 IndirectField->setAccess(D->getAccess());
1368 Owner->addDecl(IndirectField);
1369 return IndirectField;
1372 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1373 // Handle friend type expressions by simply substituting template
1374 // parameters into the pattern type and checking the result.
1375 if (TypeSourceInfo *Ty = D->getFriendType()) {
1376 TypeSourceInfo *InstTy;
1377 // If this is an unsupported friend, don't bother substituting template
1378 // arguments into it. The actual type referred to won't be used by any
1379 // parts of Clang, and may not be valid for instantiating. Just use the
1380 // same info for the instantiated friend.
1381 if (D->isUnsupportedFriend()) {
1382 InstTy = Ty;
1383 } else {
1384 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1385 D->getLocation(), DeclarationName());
1387 if (!InstTy)
1388 return nullptr;
1390 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
1391 D->getFriendLoc(), InstTy);
1392 if (!FD)
1393 return nullptr;
1395 FD->setAccess(AS_public);
1396 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1397 Owner->addDecl(FD);
1398 return FD;
1401 NamedDecl *ND = D->getFriendDecl();
1402 assert(ND && "friend decl must be a decl or a type!");
1404 // All of the Visit implementations for the various potential friend
1405 // declarations have to be carefully written to work for friend
1406 // objects, with the most important detail being that the target
1407 // decl should almost certainly not be placed in Owner.
1408 Decl *NewND = Visit(ND);
1409 if (!NewND) return nullptr;
1411 FriendDecl *FD =
1412 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1413 cast<NamedDecl>(NewND), D->getFriendLoc());
1414 FD->setAccess(AS_public);
1415 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1416 Owner->addDecl(FD);
1417 return FD;
1420 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1421 Expr *AssertExpr = D->getAssertExpr();
1423 // The expression in a static assertion is a constant expression.
1424 EnterExpressionEvaluationContext Unevaluated(
1425 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1427 ExprResult InstantiatedAssertExpr
1428 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1429 if (InstantiatedAssertExpr.isInvalid())
1430 return nullptr;
1432 ExprResult InstantiatedMessageExpr =
1433 SemaRef.SubstExpr(D->getMessage(), TemplateArgs);
1434 if (InstantiatedMessageExpr.isInvalid())
1435 return nullptr;
1437 return SemaRef.BuildStaticAssertDeclaration(
1438 D->getLocation(), InstantiatedAssertExpr.get(),
1439 InstantiatedMessageExpr.get(), D->getRParenLoc(), D->isFailed());
1442 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1443 EnumDecl *PrevDecl = nullptr;
1444 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1445 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1446 PatternPrev,
1447 TemplateArgs);
1448 if (!Prev) return nullptr;
1449 PrevDecl = cast<EnumDecl>(Prev);
1452 EnumDecl *Enum =
1453 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1454 D->getLocation(), D->getIdentifier(), PrevDecl,
1455 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1456 if (D->isFixed()) {
1457 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1458 // If we have type source information for the underlying type, it means it
1459 // has been explicitly set by the user. Perform substitution on it before
1460 // moving on.
1461 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1462 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1463 DeclarationName());
1464 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1465 Enum->setIntegerType(SemaRef.Context.IntTy);
1466 else
1467 Enum->setIntegerTypeSourceInfo(NewTI);
1468 } else {
1469 assert(!D->getIntegerType()->isDependentType()
1470 && "Dependent type without type source info");
1471 Enum->setIntegerType(D->getIntegerType());
1475 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1477 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1478 Enum->setAccess(D->getAccess());
1479 // Forward the mangling number from the template to the instantiated decl.
1480 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1481 // See if the old tag was defined along with a declarator.
1482 // If it did, mark the new tag as being associated with that declarator.
1483 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1484 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1485 // See if the old tag was defined along with a typedef.
1486 // If it did, mark the new tag as being associated with that typedef.
1487 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1488 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1489 if (SubstQualifier(D, Enum)) return nullptr;
1490 Owner->addDecl(Enum);
1492 EnumDecl *Def = D->getDefinition();
1493 if (Def && Def != D) {
1494 // If this is an out-of-line definition of an enum member template, check
1495 // that the underlying types match in the instantiation of both
1496 // declarations.
1497 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1498 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1499 QualType DefnUnderlying =
1500 SemaRef.SubstType(TI->getType(), TemplateArgs,
1501 UnderlyingLoc, DeclarationName());
1502 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1503 DefnUnderlying, /*IsFixed=*/true, Enum);
1507 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1508 // specialization causes the implicit instantiation of the declarations, but
1509 // not the definitions of scoped member enumerations.
1511 // DR1484 clarifies that enumeration definitions inside of a template
1512 // declaration aren't considered entities that can be separately instantiated
1513 // from the rest of the entity they are declared inside of.
1514 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1515 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1516 InstantiateEnumDefinition(Enum, Def);
1519 return Enum;
1522 void TemplateDeclInstantiator::InstantiateEnumDefinition(
1523 EnumDecl *Enum, EnumDecl *Pattern) {
1524 Enum->startDefinition();
1526 // Update the location to refer to the definition.
1527 Enum->setLocation(Pattern->getLocation());
1529 SmallVector<Decl*, 4> Enumerators;
1531 EnumConstantDecl *LastEnumConst = nullptr;
1532 for (auto *EC : Pattern->enumerators()) {
1533 // The specified value for the enumerator.
1534 ExprResult Value((Expr *)nullptr);
1535 if (Expr *UninstValue = EC->getInitExpr()) {
1536 // The enumerator's value expression is a constant expression.
1537 EnterExpressionEvaluationContext Unevaluated(
1538 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1540 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1543 // Drop the initial value and continue.
1544 bool isInvalid = false;
1545 if (Value.isInvalid()) {
1546 Value = nullptr;
1547 isInvalid = true;
1550 EnumConstantDecl *EnumConst
1551 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1552 EC->getLocation(), EC->getIdentifier(),
1553 Value.get());
1555 if (isInvalid) {
1556 if (EnumConst)
1557 EnumConst->setInvalidDecl();
1558 Enum->setInvalidDecl();
1561 if (EnumConst) {
1562 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1564 EnumConst->setAccess(Enum->getAccess());
1565 Enum->addDecl(EnumConst);
1566 Enumerators.push_back(EnumConst);
1567 LastEnumConst = EnumConst;
1569 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1570 !Enum->isScoped()) {
1571 // If the enumeration is within a function or method, record the enum
1572 // constant as a local.
1573 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1578 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1579 Enumerators, nullptr, ParsedAttributesView());
1582 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1583 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1586 Decl *
1587 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1588 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1591 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1592 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1594 // Create a local instantiation scope for this class template, which
1595 // will contain the instantiations of the template parameters.
1596 LocalInstantiationScope Scope(SemaRef);
1597 TemplateParameterList *TempParams = D->getTemplateParameters();
1598 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1599 if (!InstParams)
1600 return nullptr;
1602 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1604 // Instantiate the qualifier. We have to do this first in case
1605 // we're a friend declaration, because if we are then we need to put
1606 // the new declaration in the appropriate context.
1607 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1608 if (QualifierLoc) {
1609 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1610 TemplateArgs);
1611 if (!QualifierLoc)
1612 return nullptr;
1615 CXXRecordDecl *PrevDecl = nullptr;
1616 ClassTemplateDecl *PrevClassTemplate = nullptr;
1618 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1619 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1620 if (!Found.empty()) {
1621 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1622 if (PrevClassTemplate)
1623 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1627 // If this isn't a friend, then it's a member template, in which
1628 // case we just want to build the instantiation in the
1629 // specialization. If it is a friend, we want to build it in
1630 // the appropriate context.
1631 DeclContext *DC = Owner;
1632 if (isFriend) {
1633 if (QualifierLoc) {
1634 CXXScopeSpec SS;
1635 SS.Adopt(QualifierLoc);
1636 DC = SemaRef.computeDeclContext(SS);
1637 if (!DC) return nullptr;
1638 } else {
1639 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1640 Pattern->getDeclContext(),
1641 TemplateArgs);
1644 // Look for a previous declaration of the template in the owning
1645 // context.
1646 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1647 Sema::LookupOrdinaryName,
1648 SemaRef.forRedeclarationInCurContext());
1649 SemaRef.LookupQualifiedName(R, DC);
1651 if (R.isSingleResult()) {
1652 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1653 if (PrevClassTemplate)
1654 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1657 if (!PrevClassTemplate && QualifierLoc) {
1658 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1659 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1660 << QualifierLoc.getSourceRange();
1661 return nullptr;
1665 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1666 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1667 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1668 /*DelayTypeCreation=*/true);
1669 if (QualifierLoc)
1670 RecordInst->setQualifierInfo(QualifierLoc);
1672 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1673 StartingScope);
1675 ClassTemplateDecl *Inst
1676 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1677 D->getIdentifier(), InstParams, RecordInst);
1678 RecordInst->setDescribedClassTemplate(Inst);
1680 if (isFriend) {
1681 assert(!Owner->isDependentContext());
1682 Inst->setLexicalDeclContext(Owner);
1683 RecordInst->setLexicalDeclContext(Owner);
1685 if (PrevClassTemplate) {
1686 Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
1687 RecordInst->setTypeForDecl(
1688 PrevClassTemplate->getTemplatedDecl()->getTypeForDecl());
1689 const ClassTemplateDecl *MostRecentPrevCT =
1690 PrevClassTemplate->getMostRecentDecl();
1691 TemplateParameterList *PrevParams =
1692 MostRecentPrevCT->getTemplateParameters();
1694 // Make sure the parameter lists match.
1695 if (!SemaRef.TemplateParameterListsAreEqual(
1696 RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
1697 PrevParams, true, Sema::TPL_TemplateMatch))
1698 return nullptr;
1700 // Do some additional validation, then merge default arguments
1701 // from the existing declarations.
1702 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1703 Sema::TPC_ClassTemplate))
1704 return nullptr;
1706 Inst->setAccess(PrevClassTemplate->getAccess());
1707 } else {
1708 Inst->setAccess(D->getAccess());
1711 Inst->setObjectOfFriendDecl();
1712 // TODO: do we want to track the instantiation progeny of this
1713 // friend target decl?
1714 } else {
1715 Inst->setAccess(D->getAccess());
1716 if (!PrevClassTemplate)
1717 Inst->setInstantiatedFromMemberTemplate(D);
1720 Inst->setPreviousDecl(PrevClassTemplate);
1722 // Trigger creation of the type for the instantiation.
1723 SemaRef.Context.getInjectedClassNameType(
1724 RecordInst, Inst->getInjectedClassNameSpecialization());
1726 // Finish handling of friends.
1727 if (isFriend) {
1728 DC->makeDeclVisibleInContext(Inst);
1729 return Inst;
1732 if (D->isOutOfLine()) {
1733 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1734 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1737 Owner->addDecl(Inst);
1739 if (!PrevClassTemplate) {
1740 // Queue up any out-of-line partial specializations of this member
1741 // class template; the client will force their instantiation once
1742 // the enclosing class has been instantiated.
1743 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1744 D->getPartialSpecializations(PartialSpecs);
1745 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1746 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1747 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1750 return Inst;
1753 Decl *
1754 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1755 ClassTemplatePartialSpecializationDecl *D) {
1756 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1758 // Lookup the already-instantiated declaration in the instantiation
1759 // of the class template and return that.
1760 DeclContext::lookup_result Found
1761 = Owner->lookup(ClassTemplate->getDeclName());
1762 if (Found.empty())
1763 return nullptr;
1765 ClassTemplateDecl *InstClassTemplate
1766 = dyn_cast<ClassTemplateDecl>(Found.front());
1767 if (!InstClassTemplate)
1768 return nullptr;
1770 if (ClassTemplatePartialSpecializationDecl *Result
1771 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1772 return Result;
1774 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1777 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1778 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1779 "Only static data member templates are allowed.");
1781 // Create a local instantiation scope for this variable template, which
1782 // will contain the instantiations of the template parameters.
1783 LocalInstantiationScope Scope(SemaRef);
1784 TemplateParameterList *TempParams = D->getTemplateParameters();
1785 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1786 if (!InstParams)
1787 return nullptr;
1789 VarDecl *Pattern = D->getTemplatedDecl();
1790 VarTemplateDecl *PrevVarTemplate = nullptr;
1792 if (getPreviousDeclForInstantiation(Pattern)) {
1793 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1794 if (!Found.empty())
1795 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1798 VarDecl *VarInst =
1799 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1800 /*InstantiatingVarTemplate=*/true));
1801 if (!VarInst) return nullptr;
1803 DeclContext *DC = Owner;
1805 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1806 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1807 VarInst);
1808 VarInst->setDescribedVarTemplate(Inst);
1809 Inst->setPreviousDecl(PrevVarTemplate);
1811 Inst->setAccess(D->getAccess());
1812 if (!PrevVarTemplate)
1813 Inst->setInstantiatedFromMemberTemplate(D);
1815 if (D->isOutOfLine()) {
1816 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1817 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1820 Owner->addDecl(Inst);
1822 if (!PrevVarTemplate) {
1823 // Queue up any out-of-line partial specializations of this member
1824 // variable template; the client will force their instantiation once
1825 // the enclosing class has been instantiated.
1826 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1827 D->getPartialSpecializations(PartialSpecs);
1828 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1829 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1830 OutOfLineVarPartialSpecs.push_back(
1831 std::make_pair(Inst, PartialSpecs[I]));
1834 return Inst;
1837 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1838 VarTemplatePartialSpecializationDecl *D) {
1839 assert(D->isStaticDataMember() &&
1840 "Only static data member templates are allowed.");
1842 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1844 // Lookup the already-instantiated declaration and return that.
1845 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1846 assert(!Found.empty() && "Instantiation found nothing?");
1848 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1849 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1851 if (VarTemplatePartialSpecializationDecl *Result =
1852 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1853 return Result;
1855 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1858 Decl *
1859 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1860 // Create a local instantiation scope for this function template, which
1861 // will contain the instantiations of the template parameters and then get
1862 // merged with the local instantiation scope for the function template
1863 // itself.
1864 LocalInstantiationScope Scope(SemaRef);
1865 Sema::ConstraintEvalRAII<TemplateDeclInstantiator> RAII(*this);
1867 TemplateParameterList *TempParams = D->getTemplateParameters();
1868 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1869 if (!InstParams)
1870 return nullptr;
1872 FunctionDecl *Instantiated = nullptr;
1873 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1874 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1875 InstParams));
1876 else
1877 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1878 D->getTemplatedDecl(),
1879 InstParams));
1881 if (!Instantiated)
1882 return nullptr;
1884 // Link the instantiated function template declaration to the function
1885 // template from which it was instantiated.
1886 FunctionTemplateDecl *InstTemplate
1887 = Instantiated->getDescribedFunctionTemplate();
1888 InstTemplate->setAccess(D->getAccess());
1889 assert(InstTemplate &&
1890 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1892 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1894 // Link the instantiation back to the pattern *unless* this is a
1895 // non-definition friend declaration.
1896 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1897 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1898 InstTemplate->setInstantiatedFromMemberTemplate(D);
1900 // Make declarations visible in the appropriate context.
1901 if (!isFriend) {
1902 Owner->addDecl(InstTemplate);
1903 } else if (InstTemplate->getDeclContext()->isRecord() &&
1904 !getPreviousDeclForInstantiation(D)) {
1905 SemaRef.CheckFriendAccess(InstTemplate);
1908 return InstTemplate;
1911 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1912 CXXRecordDecl *PrevDecl = nullptr;
1913 if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1914 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1915 PatternPrev,
1916 TemplateArgs);
1917 if (!Prev) return nullptr;
1918 PrevDecl = cast<CXXRecordDecl>(Prev);
1921 CXXRecordDecl *Record = nullptr;
1922 bool IsInjectedClassName = D->isInjectedClassName();
1923 if (D->isLambda())
1924 Record = CXXRecordDecl::CreateLambda(
1925 SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
1926 D->getLambdaDependencyKind(), D->isGenericLambda(),
1927 D->getLambdaCaptureDefault());
1928 else
1929 Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1930 D->getBeginLoc(), D->getLocation(),
1931 D->getIdentifier(), PrevDecl,
1932 /*DelayTypeCreation=*/IsInjectedClassName);
1933 // Link the type of the injected-class-name to that of the outer class.
1934 if (IsInjectedClassName)
1935 (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
1937 // Substitute the nested name specifier, if any.
1938 if (SubstQualifier(D, Record))
1939 return nullptr;
1941 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1942 StartingScope);
1944 Record->setImplicit(D->isImplicit());
1945 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1946 // the tag decls introduced by friend class declarations don't have an access
1947 // specifier. Remove once this area of the code gets sorted out.
1948 if (D->getAccess() != AS_none)
1949 Record->setAccess(D->getAccess());
1950 if (!IsInjectedClassName)
1951 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1953 // If the original function was part of a friend declaration,
1954 // inherit its namespace state.
1955 if (D->getFriendObjectKind())
1956 Record->setObjectOfFriendDecl();
1958 // Make sure that anonymous structs and unions are recorded.
1959 if (D->isAnonymousStructOrUnion())
1960 Record->setAnonymousStructOrUnion(true);
1962 if (D->isLocalClass())
1963 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1965 // Forward the mangling number from the template to the instantiated decl.
1966 SemaRef.Context.setManglingNumber(Record,
1967 SemaRef.Context.getManglingNumber(D));
1969 // See if the old tag was defined along with a declarator.
1970 // If it did, mark the new tag as being associated with that declarator.
1971 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1972 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1974 // See if the old tag was defined along with a typedef.
1975 // If it did, mark the new tag as being associated with that typedef.
1976 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1977 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1979 Owner->addDecl(Record);
1981 // DR1484 clarifies that the members of a local class are instantiated as part
1982 // of the instantiation of their enclosing entity.
1983 if (D->isCompleteDefinition() && D->isLocalClass()) {
1984 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
1986 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1987 TSK_ImplicitInstantiation,
1988 /*Complain=*/true);
1990 // For nested local classes, we will instantiate the members when we
1991 // reach the end of the outermost (non-nested) local class.
1992 if (!D->isCXXClassMember())
1993 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1994 TSK_ImplicitInstantiation);
1996 // This class may have local implicit instantiations that need to be
1997 // performed within this scope.
1998 LocalInstantiations.perform();
2001 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
2003 if (IsInjectedClassName)
2004 assert(Record->isInjectedClassName() && "Broken injected-class-name");
2006 return Record;
2009 /// Adjust the given function type for an instantiation of the
2010 /// given declaration, to cope with modifications to the function's type that
2011 /// aren't reflected in the type-source information.
2013 /// \param D The declaration we're instantiating.
2014 /// \param TInfo The already-instantiated type.
2015 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
2016 FunctionDecl *D,
2017 TypeSourceInfo *TInfo) {
2018 const FunctionProtoType *OrigFunc
2019 = D->getType()->castAs<FunctionProtoType>();
2020 const FunctionProtoType *NewFunc
2021 = TInfo->getType()->castAs<FunctionProtoType>();
2022 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2023 return TInfo->getType();
2025 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2026 NewEPI.ExtInfo = OrigFunc->getExtInfo();
2027 return Context.getFunctionType(NewFunc->getReturnType(),
2028 NewFunc->getParamTypes(), NewEPI);
2031 /// Normal class members are of more specific types and therefore
2032 /// don't make it here. This function serves three purposes:
2033 /// 1) instantiating function templates
2034 /// 2) substituting friend and local function declarations
2035 /// 3) substituting deduction guide declarations for nested class templates
2036 Decl *TemplateDeclInstantiator::VisitFunctionDecl(
2037 FunctionDecl *D, TemplateParameterList *TemplateParams,
2038 RewriteKind FunctionRewriteKind) {
2039 // Check whether there is already a function template specialization for
2040 // this declaration.
2041 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2042 if (FunctionTemplate && !TemplateParams) {
2043 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2045 void *InsertPos = nullptr;
2046 FunctionDecl *SpecFunc
2047 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2049 // If we already have a function template specialization, return it.
2050 if (SpecFunc)
2051 return SpecFunc;
2054 bool isFriend;
2055 if (FunctionTemplate)
2056 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2057 else
2058 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2060 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2061 Owner->isFunctionOrMethod() ||
2062 !(isa<Decl>(Owner) &&
2063 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2064 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2066 ExplicitSpecifier InstantiatedExplicitSpecifier;
2067 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2068 InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
2069 SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
2070 if (InstantiatedExplicitSpecifier.isInvalid())
2071 return nullptr;
2074 SmallVector<ParmVarDecl *, 4> Params;
2075 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2076 if (!TInfo)
2077 return nullptr;
2078 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2080 if (TemplateParams && TemplateParams->size()) {
2081 auto *LastParam =
2082 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2083 if (LastParam && LastParam->isImplicit() &&
2084 LastParam->hasTypeConstraint()) {
2085 // In abbreviated templates, the type-constraints of invented template
2086 // type parameters are instantiated with the function type, invalidating
2087 // the TemplateParameterList which relied on the template type parameter
2088 // not having a type constraint. Recreate the TemplateParameterList with
2089 // the updated parameter list.
2090 TemplateParams = TemplateParameterList::Create(
2091 SemaRef.Context, TemplateParams->getTemplateLoc(),
2092 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2093 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2097 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2098 if (QualifierLoc) {
2099 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2100 TemplateArgs);
2101 if (!QualifierLoc)
2102 return nullptr;
2105 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2107 // If we're instantiating a local function declaration, put the result
2108 // in the enclosing namespace; otherwise we need to find the instantiated
2109 // context.
2110 DeclContext *DC;
2111 if (D->isLocalExternDecl()) {
2112 DC = Owner;
2113 SemaRef.adjustContextForLocalExternDecl(DC);
2114 } else if (isFriend && QualifierLoc) {
2115 CXXScopeSpec SS;
2116 SS.Adopt(QualifierLoc);
2117 DC = SemaRef.computeDeclContext(SS);
2118 if (!DC) return nullptr;
2119 } else {
2120 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2121 TemplateArgs);
2124 DeclarationNameInfo NameInfo
2125 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2127 if (FunctionRewriteKind != RewriteKind::None)
2128 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2130 FunctionDecl *Function;
2131 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2132 Function = CXXDeductionGuideDecl::Create(
2133 SemaRef.Context, DC, D->getInnerLocStart(),
2134 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2135 D->getSourceRange().getEnd(), /*Ctor=*/nullptr,
2136 DGuide->getDeductionCandidateKind());
2137 Function->setAccess(D->getAccess());
2138 } else {
2139 Function = FunctionDecl::Create(
2140 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2141 D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(),
2142 D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(),
2143 TrailingRequiresClause);
2144 Function->setFriendConstraintRefersToEnclosingTemplate(
2145 D->FriendConstraintRefersToEnclosingTemplate());
2146 Function->setRangeEnd(D->getSourceRange().getEnd());
2149 if (D->isInlined())
2150 Function->setImplicitlyInline();
2152 if (QualifierLoc)
2153 Function->setQualifierInfo(QualifierLoc);
2155 if (D->isLocalExternDecl())
2156 Function->setLocalExternDecl();
2158 DeclContext *LexicalDC = Owner;
2159 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2160 assert(D->getDeclContext()->isFileContext());
2161 LexicalDC = D->getDeclContext();
2163 else if (D->isLocalExternDecl()) {
2164 LexicalDC = SemaRef.CurContext;
2167 Function->setLexicalDeclContext(LexicalDC);
2169 // Attach the parameters
2170 for (unsigned P = 0; P < Params.size(); ++P)
2171 if (Params[P])
2172 Params[P]->setOwningFunction(Function);
2173 Function->setParams(Params);
2175 if (TrailingRequiresClause)
2176 Function->setTrailingRequiresClause(TrailingRequiresClause);
2178 if (TemplateParams) {
2179 // Our resulting instantiation is actually a function template, since we
2180 // are substituting only the outer template parameters. For example, given
2182 // template<typename T>
2183 // struct X {
2184 // template<typename U> friend void f(T, U);
2185 // };
2187 // X<int> x;
2189 // We are instantiating the friend function template "f" within X<int>,
2190 // which means substituting int for T, but leaving "f" as a friend function
2191 // template.
2192 // Build the function template itself.
2193 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2194 Function->getLocation(),
2195 Function->getDeclName(),
2196 TemplateParams, Function);
2197 Function->setDescribedFunctionTemplate(FunctionTemplate);
2199 FunctionTemplate->setLexicalDeclContext(LexicalDC);
2201 if (isFriend && D->isThisDeclarationADefinition()) {
2202 FunctionTemplate->setInstantiatedFromMemberTemplate(
2203 D->getDescribedFunctionTemplate());
2205 } else if (FunctionTemplate) {
2206 // Record this function template specialization.
2207 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2208 Function->setFunctionTemplateSpecialization(FunctionTemplate,
2209 TemplateArgumentList::CreateCopy(SemaRef.Context,
2210 Innermost),
2211 /*InsertPos=*/nullptr);
2212 } else if (isFriend && D->isThisDeclarationADefinition()) {
2213 // Do not connect the friend to the template unless it's actually a
2214 // definition. We don't want non-template functions to be marked as being
2215 // template instantiations.
2216 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2217 } else if (!isFriend) {
2218 // If this is not a function template, and this is not a friend (that is,
2219 // this is a locally declared function), save the instantiation relationship
2220 // for the purposes of constraint instantiation.
2221 Function->setInstantiatedFromDecl(D);
2224 if (isFriend) {
2225 Function->setObjectOfFriendDecl();
2226 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2227 FT->setObjectOfFriendDecl();
2230 if (InitFunctionInstantiation(Function, D))
2231 Function->setInvalidDecl();
2233 bool IsExplicitSpecialization = false;
2235 LookupResult Previous(
2236 SemaRef, Function->getDeclName(), SourceLocation(),
2237 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
2238 : Sema::LookupOrdinaryName,
2239 D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
2240 : SemaRef.forRedeclarationInCurContext());
2242 if (DependentFunctionTemplateSpecializationInfo *Info
2243 = D->getDependentSpecializationInfo()) {
2244 assert(isFriend && "non-friend has dependent specialization info?");
2246 // Instantiate the explicit template arguments.
2247 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2248 Info->getRAngleLoc());
2249 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2250 ExplicitArgs))
2251 return nullptr;
2253 // Map the candidate templates to their instantiations.
2254 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2255 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2256 Info->getTemplate(I),
2257 TemplateArgs);
2258 if (!Temp) return nullptr;
2260 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2263 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2264 &ExplicitArgs,
2265 Previous))
2266 Function->setInvalidDecl();
2268 IsExplicitSpecialization = true;
2269 } else if (const ASTTemplateArgumentListInfo *Info =
2270 D->getTemplateSpecializationArgsAsWritten()) {
2271 // The name of this function was written as a template-id.
2272 SemaRef.LookupQualifiedName(Previous, DC);
2274 // Instantiate the explicit template arguments.
2275 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2276 Info->getRAngleLoc());
2277 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2278 ExplicitArgs))
2279 return nullptr;
2281 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2282 &ExplicitArgs,
2283 Previous))
2284 Function->setInvalidDecl();
2286 IsExplicitSpecialization = true;
2287 } else if (TemplateParams || !FunctionTemplate) {
2288 // Look only into the namespace where the friend would be declared to
2289 // find a previous declaration. This is the innermost enclosing namespace,
2290 // as described in ActOnFriendFunctionDecl.
2291 SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
2293 // In C++, the previous declaration we find might be a tag type
2294 // (class or enum). In this case, the new declaration will hide the
2295 // tag type. Note that this does not apply if we're declaring a
2296 // typedef (C++ [dcl.typedef]p4).
2297 if (Previous.isSingleTagDecl())
2298 Previous.clear();
2300 // Filter out previous declarations that don't match the scope. The only
2301 // effect this has is to remove declarations found in inline namespaces
2302 // for friend declarations with unqualified names.
2303 if (isFriend && !QualifierLoc) {
2304 SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2305 /*ConsiderLinkage=*/ true,
2306 QualifierLoc.hasQualifier());
2310 // Per [temp.inst], default arguments in function declarations at local scope
2311 // are instantiated along with the enclosing declaration. For example:
2313 // template<typename T>
2314 // void ft() {
2315 // void f(int = []{ return T::value; }());
2316 // }
2317 // template void ft<int>(); // error: type 'int' cannot be used prior
2318 // to '::' because it has no members
2320 // The error is issued during instantiation of ft<int>() because substitution
2321 // into the default argument fails; the default argument is instantiated even
2322 // though it is never used.
2323 if (Function->isLocalExternDecl()) {
2324 for (ParmVarDecl *PVD : Function->parameters()) {
2325 if (!PVD->hasDefaultArg())
2326 continue;
2327 if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2328 // If substitution fails, the default argument is set to a
2329 // RecoveryExpr that wraps the uninstantiated default argument so
2330 // that downstream diagnostics are omitted.
2331 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
2332 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2333 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2334 { UninstExpr }, UninstExpr->getType());
2335 if (ErrorResult.isUsable())
2336 PVD->setDefaultArg(ErrorResult.get());
2341 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2342 IsExplicitSpecialization,
2343 Function->isThisDeclarationADefinition());
2345 // Check the template parameter list against the previous declaration. The
2346 // goal here is to pick up default arguments added since the friend was
2347 // declared; we know the template parameter lists match, since otherwise
2348 // we would not have picked this template as the previous declaration.
2349 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2350 SemaRef.CheckTemplateParameterList(
2351 TemplateParams,
2352 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2353 Function->isThisDeclarationADefinition()
2354 ? Sema::TPC_FriendFunctionTemplateDefinition
2355 : Sema::TPC_FriendFunctionTemplate);
2358 // If we're introducing a friend definition after the first use, trigger
2359 // instantiation.
2360 // FIXME: If this is a friend function template definition, we should check
2361 // to see if any specializations have been used.
2362 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2363 if (MemberSpecializationInfo *MSInfo =
2364 Function->getMemberSpecializationInfo()) {
2365 if (MSInfo->getPointOfInstantiation().isInvalid()) {
2366 SourceLocation Loc = D->getLocation(); // FIXME
2367 MSInfo->setPointOfInstantiation(Loc);
2368 SemaRef.PendingLocalImplicitInstantiations.push_back(
2369 std::make_pair(Function, Loc));
2374 if (D->isExplicitlyDefaulted()) {
2375 if (SubstDefaultedFunction(Function, D))
2376 return nullptr;
2378 if (D->isDeleted())
2379 SemaRef.SetDeclDeleted(Function, D->getLocation());
2381 NamedDecl *PrincipalDecl =
2382 (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2384 // If this declaration lives in a different context from its lexical context,
2385 // add it to the corresponding lookup table.
2386 if (isFriend ||
2387 (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2388 DC->makeDeclVisibleInContext(PrincipalDecl);
2390 if (Function->isOverloadedOperator() && !DC->isRecord() &&
2391 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
2392 PrincipalDecl->setNonMemberOperator();
2394 return Function;
2397 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
2398 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2399 std::optional<const ASTTemplateArgumentListInfo *>
2400 ClassScopeSpecializationArgs,
2401 RewriteKind FunctionRewriteKind) {
2402 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2403 if (FunctionTemplate && !TemplateParams) {
2404 // We are creating a function template specialization from a function
2405 // template. Check whether there is already a function template
2406 // specialization for this particular set of template arguments.
2407 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2409 void *InsertPos = nullptr;
2410 FunctionDecl *SpecFunc
2411 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2413 // If we already have a function template specialization, return it.
2414 if (SpecFunc)
2415 return SpecFunc;
2418 bool isFriend;
2419 if (FunctionTemplate)
2420 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2421 else
2422 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2424 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2425 !(isa<Decl>(Owner) &&
2426 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2427 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2429 // Instantiate enclosing template arguments for friends.
2430 SmallVector<TemplateParameterList *, 4> TempParamLists;
2431 unsigned NumTempParamLists = 0;
2432 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2433 TempParamLists.resize(NumTempParamLists);
2434 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2435 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2436 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2437 if (!InstParams)
2438 return nullptr;
2439 TempParamLists[I] = InstParams;
2443 ExplicitSpecifier InstantiatedExplicitSpecifier =
2444 instantiateExplicitSpecifier(SemaRef, TemplateArgs,
2445 ExplicitSpecifier::getFromDecl(D), D);
2446 if (InstantiatedExplicitSpecifier.isInvalid())
2447 return nullptr;
2449 // Implicit destructors/constructors created for local classes in
2450 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2451 // Unfortunately there isn't enough context in those functions to
2452 // conditionally populate the TSI without breaking non-template related use
2453 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2454 // a proper transformation.
2455 if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
2456 !D->getTypeSourceInfo() &&
2457 isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2458 TypeSourceInfo *TSI =
2459 SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
2460 D->setTypeSourceInfo(TSI);
2463 SmallVector<ParmVarDecl *, 4> Params;
2464 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2465 if (!TInfo)
2466 return nullptr;
2467 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2469 if (TemplateParams && TemplateParams->size()) {
2470 auto *LastParam =
2471 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2472 if (LastParam && LastParam->isImplicit() &&
2473 LastParam->hasTypeConstraint()) {
2474 // In abbreviated templates, the type-constraints of invented template
2475 // type parameters are instantiated with the function type, invalidating
2476 // the TemplateParameterList which relied on the template type parameter
2477 // not having a type constraint. Recreate the TemplateParameterList with
2478 // the updated parameter list.
2479 TemplateParams = TemplateParameterList::Create(
2480 SemaRef.Context, TemplateParams->getTemplateLoc(),
2481 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2482 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2486 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2487 if (QualifierLoc) {
2488 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2489 TemplateArgs);
2490 if (!QualifierLoc)
2491 return nullptr;
2494 DeclContext *DC = Owner;
2495 if (isFriend) {
2496 if (QualifierLoc) {
2497 CXXScopeSpec SS;
2498 SS.Adopt(QualifierLoc);
2499 DC = SemaRef.computeDeclContext(SS);
2501 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2502 return nullptr;
2503 } else {
2504 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2505 D->getDeclContext(),
2506 TemplateArgs);
2508 if (!DC) return nullptr;
2511 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2512 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2514 DeclarationNameInfo NameInfo
2515 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2517 if (FunctionRewriteKind != RewriteKind::None)
2518 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2520 // Build the instantiated method declaration.
2521 CXXMethodDecl *Method = nullptr;
2523 SourceLocation StartLoc = D->getInnerLocStart();
2524 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2525 Method = CXXConstructorDecl::Create(
2526 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2527 InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2528 Constructor->isInlineSpecified(), false,
2529 Constructor->getConstexprKind(), InheritedConstructor(),
2530 TrailingRequiresClause);
2531 Method->setRangeEnd(Constructor->getEndLoc());
2532 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2533 Method = CXXDestructorDecl::Create(
2534 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2535 Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2536 Destructor->getConstexprKind(), TrailingRequiresClause);
2537 Method->setIneligibleOrNotSelected(true);
2538 Method->setRangeEnd(Destructor->getEndLoc());
2539 Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
2540 SemaRef.Context.getCanonicalType(
2541 SemaRef.Context.getTypeDeclType(Record))));
2542 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2543 Method = CXXConversionDecl::Create(
2544 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2545 Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2546 InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2547 Conversion->getEndLoc(), TrailingRequiresClause);
2548 } else {
2549 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2550 Method = CXXMethodDecl::Create(
2551 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2552 D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(),
2553 D->getEndLoc(), TrailingRequiresClause);
2556 if (D->isInlined())
2557 Method->setImplicitlyInline();
2559 if (QualifierLoc)
2560 Method->setQualifierInfo(QualifierLoc);
2562 if (TemplateParams) {
2563 // Our resulting instantiation is actually a function template, since we
2564 // are substituting only the outer template parameters. For example, given
2566 // template<typename T>
2567 // struct X {
2568 // template<typename U> void f(T, U);
2569 // };
2571 // X<int> x;
2573 // We are instantiating the member template "f" within X<int>, which means
2574 // substituting int for T, but leaving "f" as a member function template.
2575 // Build the function template itself.
2576 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2577 Method->getLocation(),
2578 Method->getDeclName(),
2579 TemplateParams, Method);
2580 if (isFriend) {
2581 FunctionTemplate->setLexicalDeclContext(Owner);
2582 FunctionTemplate->setObjectOfFriendDecl();
2583 } else if (D->isOutOfLine())
2584 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2585 Method->setDescribedFunctionTemplate(FunctionTemplate);
2586 } else if (FunctionTemplate) {
2587 // Record this function template specialization.
2588 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2589 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2590 TemplateArgumentList::CreateCopy(SemaRef.Context,
2591 Innermost),
2592 /*InsertPos=*/nullptr);
2593 } else if (!isFriend) {
2594 // Record that this is an instantiation of a member function.
2595 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2598 // If we are instantiating a member function defined
2599 // out-of-line, the instantiation will have the same lexical
2600 // context (which will be a namespace scope) as the template.
2601 if (isFriend) {
2602 if (NumTempParamLists)
2603 Method->setTemplateParameterListsInfo(
2604 SemaRef.Context,
2605 llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
2607 Method->setLexicalDeclContext(Owner);
2608 Method->setObjectOfFriendDecl();
2609 } else if (D->isOutOfLine())
2610 Method->setLexicalDeclContext(D->getLexicalDeclContext());
2612 // Attach the parameters
2613 for (unsigned P = 0; P < Params.size(); ++P)
2614 Params[P]->setOwningFunction(Method);
2615 Method->setParams(Params);
2617 if (InitMethodInstantiation(Method, D))
2618 Method->setInvalidDecl();
2620 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2621 Sema::ForExternalRedeclaration);
2623 bool IsExplicitSpecialization = false;
2625 // If the name of this function was written as a template-id, instantiate
2626 // the explicit template arguments.
2627 if (DependentFunctionTemplateSpecializationInfo *Info
2628 = D->getDependentSpecializationInfo()) {
2629 assert(isFriend && "non-friend has dependent specialization info?");
2631 // Instantiate the explicit template arguments.
2632 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2633 Info->getRAngleLoc());
2634 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2635 ExplicitArgs))
2636 return nullptr;
2638 // Map the candidate templates to their instantiations.
2639 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2640 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2641 Info->getTemplate(I),
2642 TemplateArgs);
2643 if (!Temp) return nullptr;
2645 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2648 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2649 &ExplicitArgs,
2650 Previous))
2651 Method->setInvalidDecl();
2653 IsExplicitSpecialization = true;
2654 } else if (const ASTTemplateArgumentListInfo *Info =
2655 ClassScopeSpecializationArgs.value_or(
2656 D->getTemplateSpecializationArgsAsWritten())) {
2657 SemaRef.LookupQualifiedName(Previous, DC);
2659 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2660 Info->getRAngleLoc());
2661 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2662 ExplicitArgs))
2663 return nullptr;
2665 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2666 &ExplicitArgs,
2667 Previous))
2668 Method->setInvalidDecl();
2670 IsExplicitSpecialization = true;
2671 } else if (ClassScopeSpecializationArgs) {
2672 // Class-scope explicit specialization written without explicit template
2673 // arguments.
2674 SemaRef.LookupQualifiedName(Previous, DC);
2675 if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
2676 Method->setInvalidDecl();
2678 IsExplicitSpecialization = true;
2679 } else if (!FunctionTemplate || TemplateParams || isFriend) {
2680 SemaRef.LookupQualifiedName(Previous, Record);
2682 // In C++, the previous declaration we find might be a tag type
2683 // (class or enum). In this case, the new declaration will hide the
2684 // tag type. Note that this does not apply if we're declaring a
2685 // typedef (C++ [dcl.typedef]p4).
2686 if (Previous.isSingleTagDecl())
2687 Previous.clear();
2690 // Per [temp.inst], default arguments in member functions of local classes
2691 // are instantiated along with the member function declaration. For example:
2693 // template<typename T>
2694 // void ft() {
2695 // struct lc {
2696 // int operator()(int p = []{ return T::value; }());
2697 // };
2698 // }
2699 // template void ft<int>(); // error: type 'int' cannot be used prior
2700 // to '::'because it has no members
2702 // The error is issued during instantiation of ft<int>()::lc::operator()
2703 // because substitution into the default argument fails; the default argument
2704 // is instantiated even though it is never used.
2705 if (D->isInLocalScopeForInstantiation()) {
2706 for (unsigned P = 0; P < Params.size(); ++P) {
2707 if (!Params[P]->hasDefaultArg())
2708 continue;
2709 if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
2710 // If substitution fails, the default argument is set to a
2711 // RecoveryExpr that wraps the uninstantiated default argument so
2712 // that downstream diagnostics are omitted.
2713 Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
2714 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2715 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2716 { UninstExpr }, UninstExpr->getType());
2717 if (ErrorResult.isUsable())
2718 Params[P]->setDefaultArg(ErrorResult.get());
2723 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2724 IsExplicitSpecialization,
2725 Method->isThisDeclarationADefinition());
2727 if (D->isPure())
2728 SemaRef.CheckPureMethod(Method, SourceRange());
2730 // Propagate access. For a non-friend declaration, the access is
2731 // whatever we're propagating from. For a friend, it should be the
2732 // previous declaration we just found.
2733 if (isFriend && Method->getPreviousDecl())
2734 Method->setAccess(Method->getPreviousDecl()->getAccess());
2735 else
2736 Method->setAccess(D->getAccess());
2737 if (FunctionTemplate)
2738 FunctionTemplate->setAccess(Method->getAccess());
2740 SemaRef.CheckOverrideControl(Method);
2742 // If a function is defined as defaulted or deleted, mark it as such now.
2743 if (D->isExplicitlyDefaulted()) {
2744 if (SubstDefaultedFunction(Method, D))
2745 return nullptr;
2747 if (D->isDeletedAsWritten())
2748 SemaRef.SetDeclDeleted(Method, Method->getLocation());
2750 // If this is an explicit specialization, mark the implicitly-instantiated
2751 // template specialization as being an explicit specialization too.
2752 // FIXME: Is this necessary?
2753 if (IsExplicitSpecialization && !isFriend)
2754 SemaRef.CompleteMemberSpecialization(Method, Previous);
2756 // If the method is a special member function, we need to mark it as
2757 // ineligible so that Owner->addDecl() won't mark the class as non trivial.
2758 // At the end of the class instantiation, we calculate eligibility again and
2759 // then we adjust trivility if needed.
2760 // We need this check to happen only after the method parameters are set,
2761 // because being e.g. a copy constructor depends on the instantiated
2762 // arguments.
2763 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
2764 if (Constructor->isDefaultConstructor() ||
2765 Constructor->isCopyOrMoveConstructor())
2766 Method->setIneligibleOrNotSelected(true);
2767 } else if (Method->isCopyAssignmentOperator() ||
2768 Method->isMoveAssignmentOperator()) {
2769 Method->setIneligibleOrNotSelected(true);
2772 // If there's a function template, let our caller handle it.
2773 if (FunctionTemplate) {
2774 // do nothing
2776 // Don't hide a (potentially) valid declaration with an invalid one.
2777 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2778 // do nothing
2780 // Otherwise, check access to friends and make them visible.
2781 } else if (isFriend) {
2782 // We only need to re-check access for methods which we didn't
2783 // manage to match during parsing.
2784 if (!D->getPreviousDecl())
2785 SemaRef.CheckFriendAccess(Method);
2787 Record->makeDeclVisibleInContext(Method);
2789 // Otherwise, add the declaration. We don't need to do this for
2790 // class-scope specializations because we'll have matched them with
2791 // the appropriate template.
2792 } else {
2793 Owner->addDecl(Method);
2796 // PR17480: Honor the used attribute to instantiate member function
2797 // definitions
2798 if (Method->hasAttr<UsedAttr>()) {
2799 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2800 SourceLocation Loc;
2801 if (const MemberSpecializationInfo *MSInfo =
2802 A->getMemberSpecializationInfo())
2803 Loc = MSInfo->getPointOfInstantiation();
2804 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2805 Loc = Spec->getPointOfInstantiation();
2806 SemaRef.MarkFunctionReferenced(Loc, Method);
2810 return Method;
2813 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2814 return VisitCXXMethodDecl(D);
2817 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2818 return VisitCXXMethodDecl(D);
2821 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2822 return VisitCXXMethodDecl(D);
2825 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2826 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
2827 std::nullopt,
2828 /*ExpectParameterPack=*/false);
2831 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2832 TemplateTypeParmDecl *D) {
2833 assert(D->getTypeForDecl()->isTemplateTypeParmType());
2835 std::optional<unsigned> NumExpanded;
2837 if (const TypeConstraint *TC = D->getTypeConstraint()) {
2838 if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2839 assert(TC->getTemplateArgsAsWritten() &&
2840 "type parameter can only be an expansion when explicit arguments "
2841 "are specified");
2842 // The template type parameter pack's type is a pack expansion of types.
2843 // Determine whether we need to expand this parameter pack into separate
2844 // types.
2845 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2846 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2847 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2849 // Determine whether the set of unexpanded parameter packs can and should
2850 // be expanded.
2851 bool Expand = true;
2852 bool RetainExpansion = false;
2853 if (SemaRef.CheckParameterPacksForExpansion(
2854 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2855 ->getEllipsisLoc(),
2856 SourceRange(TC->getConceptNameLoc(),
2857 TC->hasExplicitTemplateArgs() ?
2858 TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2859 TC->getConceptNameInfo().getEndLoc()),
2860 Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2861 return nullptr;
2865 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2866 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2867 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2868 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
2869 D->hasTypeConstraint(), NumExpanded);
2871 Inst->setAccess(AS_public);
2872 Inst->setImplicit(D->isImplicit());
2873 if (auto *TC = D->getTypeConstraint()) {
2874 if (!D->isImplicit()) {
2875 // Invented template parameter type constraints will be instantiated
2876 // with the corresponding auto-typed parameter as it might reference
2877 // other parameters.
2878 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
2879 EvaluateConstraints))
2880 return nullptr;
2883 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2884 TypeSourceInfo *InstantiatedDefaultArg =
2885 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2886 D->getDefaultArgumentLoc(), D->getDeclName());
2887 if (InstantiatedDefaultArg)
2888 Inst->setDefaultArgument(InstantiatedDefaultArg);
2891 // Introduce this template parameter's instantiation into the instantiation
2892 // scope.
2893 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2895 return Inst;
2898 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2899 NonTypeTemplateParmDecl *D) {
2900 // Substitute into the type of the non-type template parameter.
2901 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2902 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2903 SmallVector<QualType, 4> ExpandedParameterPackTypes;
2904 bool IsExpandedParameterPack = false;
2905 TypeSourceInfo *DI;
2906 QualType T;
2907 bool Invalid = false;
2909 if (D->isExpandedParameterPack()) {
2910 // The non-type template parameter pack is an already-expanded pack
2911 // expansion of types. Substitute into each of the expanded types.
2912 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2913 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2914 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2915 TypeSourceInfo *NewDI =
2916 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2917 D->getLocation(), D->getDeclName());
2918 if (!NewDI)
2919 return nullptr;
2921 QualType NewT =
2922 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2923 if (NewT.isNull())
2924 return nullptr;
2926 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2927 ExpandedParameterPackTypes.push_back(NewT);
2930 IsExpandedParameterPack = true;
2931 DI = D->getTypeSourceInfo();
2932 T = DI->getType();
2933 } else if (D->isPackExpansion()) {
2934 // The non-type template parameter pack's type is a pack expansion of types.
2935 // Determine whether we need to expand this parameter pack into separate
2936 // types.
2937 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2938 TypeLoc Pattern = Expansion.getPatternLoc();
2939 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2940 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2942 // Determine whether the set of unexpanded parameter packs can and should
2943 // be expanded.
2944 bool Expand = true;
2945 bool RetainExpansion = false;
2946 std::optional<unsigned> OrigNumExpansions =
2947 Expansion.getTypePtr()->getNumExpansions();
2948 std::optional<unsigned> NumExpansions = OrigNumExpansions;
2949 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2950 Pattern.getSourceRange(),
2951 Unexpanded,
2952 TemplateArgs,
2953 Expand, RetainExpansion,
2954 NumExpansions))
2955 return nullptr;
2957 if (Expand) {
2958 for (unsigned I = 0; I != *NumExpansions; ++I) {
2959 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2960 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2961 D->getLocation(),
2962 D->getDeclName());
2963 if (!NewDI)
2964 return nullptr;
2966 QualType NewT =
2967 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2968 if (NewT.isNull())
2969 return nullptr;
2971 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2972 ExpandedParameterPackTypes.push_back(NewT);
2975 // Note that we have an expanded parameter pack. The "type" of this
2976 // expanded parameter pack is the original expansion type, but callers
2977 // will end up using the expanded parameter pack types for type-checking.
2978 IsExpandedParameterPack = true;
2979 DI = D->getTypeSourceInfo();
2980 T = DI->getType();
2981 } else {
2982 // We cannot fully expand the pack expansion now, so substitute into the
2983 // pattern and create a new pack expansion type.
2984 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2985 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2986 D->getLocation(),
2987 D->getDeclName());
2988 if (!NewPattern)
2989 return nullptr;
2991 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
2992 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2993 NumExpansions);
2994 if (!DI)
2995 return nullptr;
2997 T = DI->getType();
2999 } else {
3000 // Simple case: substitution into a parameter that is not a parameter pack.
3001 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3002 D->getLocation(), D->getDeclName());
3003 if (!DI)
3004 return nullptr;
3006 // Check that this type is acceptable for a non-type template parameter.
3007 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
3008 if (T.isNull()) {
3009 T = SemaRef.Context.IntTy;
3010 Invalid = true;
3014 NonTypeTemplateParmDecl *Param;
3015 if (IsExpandedParameterPack)
3016 Param = NonTypeTemplateParmDecl::Create(
3017 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3018 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3019 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
3020 ExpandedParameterPackTypesAsWritten);
3021 else
3022 Param = NonTypeTemplateParmDecl::Create(
3023 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3024 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3025 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
3027 if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
3028 if (AutoLoc.isConstrained())
3029 // Note: We attach the uninstantiated constriant here, so that it can be
3030 // instantiated relative to the top level, like all our other constraints.
3031 if (SemaRef.AttachTypeConstraint(
3032 AutoLoc, Param, D,
3033 IsExpandedParameterPack
3034 ? DI->getTypeLoc().getAs<PackExpansionTypeLoc>()
3035 .getEllipsisLoc()
3036 : SourceLocation()))
3037 Invalid = true;
3039 Param->setAccess(AS_public);
3040 Param->setImplicit(D->isImplicit());
3041 if (Invalid)
3042 Param->setInvalidDecl();
3044 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3045 EnterExpressionEvaluationContext ConstantEvaluated(
3046 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3047 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
3048 if (!Value.isInvalid())
3049 Param->setDefaultArgument(Value.get());
3052 // Introduce this template parameter's instantiation into the instantiation
3053 // scope.
3054 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3055 return Param;
3058 static void collectUnexpandedParameterPacks(
3059 Sema &S,
3060 TemplateParameterList *Params,
3061 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
3062 for (const auto &P : *Params) {
3063 if (P->isTemplateParameterPack())
3064 continue;
3065 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3066 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3067 Unexpanded);
3068 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3069 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3070 Unexpanded);
3074 Decl *
3075 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3076 TemplateTemplateParmDecl *D) {
3077 // Instantiate the template parameter list of the template template parameter.
3078 TemplateParameterList *TempParams = D->getTemplateParameters();
3079 TemplateParameterList *InstParams;
3080 SmallVector<TemplateParameterList*, 8> ExpandedParams;
3082 bool IsExpandedParameterPack = false;
3084 if (D->isExpandedParameterPack()) {
3085 // The template template parameter pack is an already-expanded pack
3086 // expansion of template parameters. Substitute into each of the expanded
3087 // parameters.
3088 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3089 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3090 I != N; ++I) {
3091 LocalInstantiationScope Scope(SemaRef);
3092 TemplateParameterList *Expansion =
3093 SubstTemplateParams(D->getExpansionTemplateParameters(I));
3094 if (!Expansion)
3095 return nullptr;
3096 ExpandedParams.push_back(Expansion);
3099 IsExpandedParameterPack = true;
3100 InstParams = TempParams;
3101 } else if (D->isPackExpansion()) {
3102 // The template template parameter pack expands to a pack of template
3103 // template parameters. Determine whether we need to expand this parameter
3104 // pack into separate parameters.
3105 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3106 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
3107 Unexpanded);
3109 // Determine whether the set of unexpanded parameter packs can and should
3110 // be expanded.
3111 bool Expand = true;
3112 bool RetainExpansion = false;
3113 std::optional<unsigned> NumExpansions;
3114 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
3115 TempParams->getSourceRange(),
3116 Unexpanded,
3117 TemplateArgs,
3118 Expand, RetainExpansion,
3119 NumExpansions))
3120 return nullptr;
3122 if (Expand) {
3123 for (unsigned I = 0; I != *NumExpansions; ++I) {
3124 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3125 LocalInstantiationScope Scope(SemaRef);
3126 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3127 if (!Expansion)
3128 return nullptr;
3129 ExpandedParams.push_back(Expansion);
3132 // Note that we have an expanded parameter pack. The "type" of this
3133 // expanded parameter pack is the original expansion type, but callers
3134 // will end up using the expanded parameter pack types for type-checking.
3135 IsExpandedParameterPack = true;
3136 InstParams = TempParams;
3137 } else {
3138 // We cannot fully expand the pack expansion now, so just substitute
3139 // into the pattern.
3140 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3142 LocalInstantiationScope Scope(SemaRef);
3143 InstParams = SubstTemplateParams(TempParams);
3144 if (!InstParams)
3145 return nullptr;
3147 } else {
3148 // Perform the actual substitution of template parameters within a new,
3149 // local instantiation scope.
3150 LocalInstantiationScope Scope(SemaRef);
3151 InstParams = SubstTemplateParams(TempParams);
3152 if (!InstParams)
3153 return nullptr;
3156 // Build the template template parameter.
3157 TemplateTemplateParmDecl *Param;
3158 if (IsExpandedParameterPack)
3159 Param = TemplateTemplateParmDecl::Create(
3160 SemaRef.Context, Owner, D->getLocation(),
3161 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3162 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
3163 else
3164 Param = TemplateTemplateParmDecl::Create(
3165 SemaRef.Context, Owner, D->getLocation(),
3166 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3167 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
3168 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3169 NestedNameSpecifierLoc QualifierLoc =
3170 D->getDefaultArgument().getTemplateQualifierLoc();
3171 QualifierLoc =
3172 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3173 TemplateName TName = SemaRef.SubstTemplateName(
3174 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3175 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3176 if (!TName.isNull())
3177 Param->setDefaultArgument(
3178 SemaRef.Context,
3179 TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
3180 D->getDefaultArgument().getTemplateQualifierLoc(),
3181 D->getDefaultArgument().getTemplateNameLoc()));
3183 Param->setAccess(AS_public);
3184 Param->setImplicit(D->isImplicit());
3186 // Introduce this template parameter's instantiation into the instantiation
3187 // scope.
3188 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3190 return Param;
3193 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3194 // Using directives are never dependent (and never contain any types or
3195 // expressions), so they require no explicit instantiation work.
3197 UsingDirectiveDecl *Inst
3198 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3199 D->getNamespaceKeyLocation(),
3200 D->getQualifierLoc(),
3201 D->getIdentLocation(),
3202 D->getNominatedNamespace(),
3203 D->getCommonAncestor());
3205 // Add the using directive to its declaration context
3206 // only if this is not a function or method.
3207 if (!Owner->isFunctionOrMethod())
3208 Owner->addDecl(Inst);
3210 return Inst;
3213 Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D,
3214 BaseUsingDecl *Inst,
3215 LookupResult *Lookup) {
3217 bool isFunctionScope = Owner->isFunctionOrMethod();
3219 for (auto *Shadow : D->shadows()) {
3220 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3221 // reconstruct it in the case where it matters. Hm, can we extract it from
3222 // the DeclSpec when parsing and save it in the UsingDecl itself?
3223 NamedDecl *OldTarget = Shadow->getTargetDecl();
3224 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3225 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3226 OldTarget = BaseShadow;
3228 NamedDecl *InstTarget = nullptr;
3229 if (auto *EmptyD =
3230 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3231 InstTarget = UnresolvedUsingIfExistsDecl::Create(
3232 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3233 } else {
3234 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3235 Shadow->getLocation(), OldTarget, TemplateArgs));
3237 if (!InstTarget)
3238 return nullptr;
3240 UsingShadowDecl *PrevDecl = nullptr;
3241 if (Lookup &&
3242 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3243 continue;
3245 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3246 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3247 Shadow->getLocation(), OldPrev, TemplateArgs));
3249 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3250 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3251 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3253 if (isFunctionScope)
3254 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3257 return Inst;
3260 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3262 // The nested name specifier may be dependent, for example
3263 // template <typename T> struct t {
3264 // struct s1 { T f1(); };
3265 // struct s2 : s1 { using s1::f1; };
3266 // };
3267 // template struct t<int>;
3268 // Here, in using s1::f1, s1 refers to t<T>::s1;
3269 // we need to substitute for t<int>::s1.
3270 NestedNameSpecifierLoc QualifierLoc
3271 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3272 TemplateArgs);
3273 if (!QualifierLoc)
3274 return nullptr;
3276 // For an inheriting constructor declaration, the name of the using
3277 // declaration is the name of a constructor in this class, not in the
3278 // base class.
3279 DeclarationNameInfo NameInfo = D->getNameInfo();
3280 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3281 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3282 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
3283 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3285 // We only need to do redeclaration lookups if we're in a class scope (in
3286 // fact, it's not really even possible in non-class scopes).
3287 bool CheckRedeclaration = Owner->isRecord();
3288 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3289 Sema::ForVisibleRedeclaration);
3291 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3292 D->getUsingLoc(),
3293 QualifierLoc,
3294 NameInfo,
3295 D->hasTypename());
3297 CXXScopeSpec SS;
3298 SS.Adopt(QualifierLoc);
3299 if (CheckRedeclaration) {
3300 Prev.setHideTags(false);
3301 SemaRef.LookupQualifiedName(Prev, Owner);
3303 // Check for invalid redeclarations.
3304 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3305 D->hasTypename(), SS,
3306 D->getLocation(), Prev))
3307 NewUD->setInvalidDecl();
3310 if (!NewUD->isInvalidDecl() &&
3311 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3312 NameInfo, D->getLocation(), nullptr, D))
3313 NewUD->setInvalidDecl();
3315 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3316 NewUD->setAccess(D->getAccess());
3317 Owner->addDecl(NewUD);
3319 // Don't process the shadow decls for an invalid decl.
3320 if (NewUD->isInvalidDecl())
3321 return NewUD;
3323 // If the using scope was dependent, or we had dependent bases, we need to
3324 // recheck the inheritance
3325 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3326 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
3328 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3331 Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3332 // Cannot be a dependent type, but still could be an instantiation
3333 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3334 D->getLocation(), D->getEnumDecl(), TemplateArgs));
3336 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3337 return nullptr;
3339 TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3340 D->getLocation(), D->getDeclName());
3341 UsingEnumDecl *NewUD =
3342 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3343 D->getEnumLoc(), D->getLocation(), TSI);
3345 SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
3346 NewUD->setAccess(D->getAccess());
3347 Owner->addDecl(NewUD);
3349 // Don't process the shadow decls for an invalid decl.
3350 if (NewUD->isInvalidDecl())
3351 return NewUD;
3353 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3354 // cannot be dependent, and will therefore have been checked during template
3355 // definition.
3357 return VisitBaseUsingDecls(D, NewUD, nullptr);
3360 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3361 // Ignore these; we handle them in bulk when processing the UsingDecl.
3362 return nullptr;
3365 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3366 ConstructorUsingShadowDecl *D) {
3367 // Ignore these; we handle them in bulk when processing the UsingDecl.
3368 return nullptr;
3371 template <typename T>
3372 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3373 T *D, bool InstantiatingPackElement) {
3374 // If this is a pack expansion, expand it now.
3375 if (D->isPackExpansion() && !InstantiatingPackElement) {
3376 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3377 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3378 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3380 // Determine whether the set of unexpanded parameter packs can and should
3381 // be expanded.
3382 bool Expand = true;
3383 bool RetainExpansion = false;
3384 std::optional<unsigned> NumExpansions;
3385 if (SemaRef.CheckParameterPacksForExpansion(
3386 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3387 Expand, RetainExpansion, NumExpansions))
3388 return nullptr;
3390 // This declaration cannot appear within a function template signature,
3391 // so we can't have a partial argument list for a parameter pack.
3392 assert(!RetainExpansion &&
3393 "should never need to retain an expansion for UsingPackDecl");
3395 if (!Expand) {
3396 // We cannot fully expand the pack expansion now, so substitute into the
3397 // pattern and create a new pack expansion.
3398 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3399 return instantiateUnresolvedUsingDecl(D, true);
3402 // Within a function, we don't have any normal way to check for conflicts
3403 // between shadow declarations from different using declarations in the
3404 // same pack expansion, but this is always ill-formed because all expansions
3405 // must produce (conflicting) enumerators.
3407 // Sadly we can't just reject this in the template definition because it
3408 // could be valid if the pack is empty or has exactly one expansion.
3409 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3410 SemaRef.Diag(D->getEllipsisLoc(),
3411 diag::err_using_decl_redeclaration_expansion);
3412 return nullptr;
3415 // Instantiate the slices of this pack and build a UsingPackDecl.
3416 SmallVector<NamedDecl*, 8> Expansions;
3417 for (unsigned I = 0; I != *NumExpansions; ++I) {
3418 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3419 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3420 if (!Slice)
3421 return nullptr;
3422 // Note that we can still get unresolved using declarations here, if we
3423 // had arguments for all packs but the pattern also contained other
3424 // template arguments (this only happens during partial substitution, eg
3425 // into the body of a generic lambda in a function template).
3426 Expansions.push_back(cast<NamedDecl>(Slice));
3429 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3430 if (isDeclWithinFunction(D))
3431 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3432 return NewD;
3435 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3436 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3438 NestedNameSpecifierLoc QualifierLoc
3439 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3440 TemplateArgs);
3441 if (!QualifierLoc)
3442 return nullptr;
3444 CXXScopeSpec SS;
3445 SS.Adopt(QualifierLoc);
3447 DeclarationNameInfo NameInfo
3448 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3450 // Produce a pack expansion only if we're not instantiating a particular
3451 // slice of a pack expansion.
3452 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3453 SemaRef.ArgumentPackSubstitutionIndex != -1;
3454 SourceLocation EllipsisLoc =
3455 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3457 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3458 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3459 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3460 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3461 ParsedAttributesView(),
3462 /*IsInstantiation*/ true, IsUsingIfExists);
3463 if (UD) {
3464 SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3465 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3468 return UD;
3471 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3472 UnresolvedUsingTypenameDecl *D) {
3473 return instantiateUnresolvedUsingDecl(D);
3476 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3477 UnresolvedUsingValueDecl *D) {
3478 return instantiateUnresolvedUsingDecl(D);
3481 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3482 UnresolvedUsingIfExistsDecl *D) {
3483 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3486 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3487 SmallVector<NamedDecl*, 8> Expansions;
3488 for (auto *UD : D->expansions()) {
3489 if (NamedDecl *NewUD =
3490 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3491 Expansions.push_back(NewUD);
3492 else
3493 return nullptr;
3496 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3497 if (isDeclWithinFunction(D))
3498 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3499 return NewD;
3502 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
3503 ClassScopeFunctionSpecializationDecl *Decl) {
3504 CXXMethodDecl *OldFD = Decl->getSpecialization();
3505 return cast_or_null<CXXMethodDecl>(
3506 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
3509 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3510 OMPThreadPrivateDecl *D) {
3511 SmallVector<Expr *, 5> Vars;
3512 for (auto *I : D->varlists()) {
3513 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3514 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3515 Vars.push_back(Var);
3518 OMPThreadPrivateDecl *TD =
3519 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3521 TD->setAccess(AS_public);
3522 Owner->addDecl(TD);
3524 return TD;
3527 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3528 SmallVector<Expr *, 5> Vars;
3529 for (auto *I : D->varlists()) {
3530 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3531 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3532 Vars.push_back(Var);
3534 SmallVector<OMPClause *, 4> Clauses;
3535 // Copy map clauses from the original mapper.
3536 for (OMPClause *C : D->clauselists()) {
3537 OMPClause *IC = nullptr;
3538 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3539 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3540 if (!NewE.isUsable())
3541 continue;
3542 IC = SemaRef.ActOnOpenMPAllocatorClause(
3543 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3544 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
3545 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3546 if (!NewE.isUsable())
3547 continue;
3548 IC = SemaRef.ActOnOpenMPAlignClause(NewE.get(), AC->getBeginLoc(),
3549 AC->getLParenLoc(), AC->getEndLoc());
3550 // If align clause value ends up being invalid, this can end up null.
3551 if (!IC)
3552 continue;
3554 Clauses.push_back(IC);
3557 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
3558 D->getLocation(), Vars, Clauses, Owner);
3559 if (Res.get().isNull())
3560 return nullptr;
3561 return Res.get().getSingleDecl();
3564 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3565 llvm_unreachable(
3566 "Requires directive cannot be instantiated within a dependent context");
3569 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3570 OMPDeclareReductionDecl *D) {
3571 // Instantiate type and check if it is allowed.
3572 const bool RequiresInstantiation =
3573 D->getType()->isDependentType() ||
3574 D->getType()->isInstantiationDependentType() ||
3575 D->getType()->containsUnexpandedParameterPack();
3576 QualType SubstReductionType;
3577 if (RequiresInstantiation) {
3578 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
3579 D->getLocation(),
3580 ParsedType::make(SemaRef.SubstType(
3581 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3582 } else {
3583 SubstReductionType = D->getType();
3585 if (SubstReductionType.isNull())
3586 return nullptr;
3587 Expr *Combiner = D->getCombiner();
3588 Expr *Init = D->getInitializer();
3589 bool IsCorrect = true;
3590 // Create instantiated copy.
3591 std::pair<QualType, SourceLocation> ReductionTypes[] = {
3592 std::make_pair(SubstReductionType, D->getLocation())};
3593 auto *PrevDeclInScope = D->getPrevDeclInScope();
3594 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3595 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3596 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3597 ->get<Decl *>());
3599 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
3600 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3601 PrevDeclInScope);
3602 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3603 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3604 Expr *SubstCombiner = nullptr;
3605 Expr *SubstInitializer = nullptr;
3606 // Combiners instantiation sequence.
3607 if (Combiner) {
3608 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
3609 /*S=*/nullptr, NewDRD);
3610 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3611 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3612 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3613 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3614 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3615 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3616 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3617 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3618 ThisContext);
3619 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3620 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3622 // Initializers instantiation sequence.
3623 if (Init) {
3624 VarDecl *OmpPrivParm = SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
3625 /*S=*/nullptr, NewDRD);
3626 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3627 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3628 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3629 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3630 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3631 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3632 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3633 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3634 } else {
3635 auto *OldPrivParm =
3636 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3637 IsCorrect = IsCorrect && OldPrivParm->hasInit();
3638 if (IsCorrect)
3639 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3640 TemplateArgs);
3642 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD, SubstInitializer,
3643 OmpPrivParm);
3645 IsCorrect = IsCorrect && SubstCombiner &&
3646 (!Init ||
3647 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
3648 SubstInitializer) ||
3649 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
3650 !SubstInitializer));
3652 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
3653 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3655 return NewDRD;
3658 Decl *
3659 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3660 // Instantiate type and check if it is allowed.
3661 const bool RequiresInstantiation =
3662 D->getType()->isDependentType() ||
3663 D->getType()->isInstantiationDependentType() ||
3664 D->getType()->containsUnexpandedParameterPack();
3665 QualType SubstMapperTy;
3666 DeclarationName VN = D->getVarName();
3667 if (RequiresInstantiation) {
3668 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3669 D->getLocation(),
3670 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3671 D->getLocation(), VN)));
3672 } else {
3673 SubstMapperTy = D->getType();
3675 if (SubstMapperTy.isNull())
3676 return nullptr;
3677 // Create an instantiated copy of mapper.
3678 auto *PrevDeclInScope = D->getPrevDeclInScope();
3679 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3680 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3681 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3682 ->get<Decl *>());
3684 bool IsCorrect = true;
3685 SmallVector<OMPClause *, 6> Clauses;
3686 // Instantiate the mapper variable.
3687 DeclarationNameInfo DirName;
3688 SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3689 /*S=*/nullptr,
3690 (*D->clauselist_begin())->getBeginLoc());
3691 ExprResult MapperVarRef = SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3692 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3693 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3694 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3695 cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3696 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3697 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3698 ThisContext);
3699 // Instantiate map clauses.
3700 for (OMPClause *C : D->clauselists()) {
3701 auto *OldC = cast<OMPMapClause>(C);
3702 SmallVector<Expr *, 4> NewVars;
3703 for (Expr *OE : OldC->varlists()) {
3704 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3705 if (!NE) {
3706 IsCorrect = false;
3707 break;
3709 NewVars.push_back(NE);
3711 if (!IsCorrect)
3712 break;
3713 NestedNameSpecifierLoc NewQualifierLoc =
3714 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3715 TemplateArgs);
3716 CXXScopeSpec SS;
3717 SS.Adopt(NewQualifierLoc);
3718 DeclarationNameInfo NewNameInfo =
3719 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3720 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3721 OldC->getEndLoc());
3722 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
3723 OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
3724 OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
3725 OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
3726 NewVars, Locs);
3727 Clauses.push_back(NewC);
3729 SemaRef.EndOpenMPDSABlock(nullptr);
3730 if (!IsCorrect)
3731 return nullptr;
3732 Sema::DeclGroupPtrTy DG = SemaRef.ActOnOpenMPDeclareMapperDirective(
3733 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3734 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3735 Decl *NewDMD = DG.get().getSingleDecl();
3736 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3737 return NewDMD;
3740 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3741 OMPCapturedExprDecl * /*D*/) {
3742 llvm_unreachable("Should not be met in templates");
3745 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3746 return VisitFunctionDecl(D, nullptr);
3749 Decl *
3750 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3751 Decl *Inst = VisitFunctionDecl(D, nullptr);
3752 if (Inst && !D->getDescribedFunctionTemplate())
3753 Owner->addDecl(Inst);
3754 return Inst;
3757 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3758 return VisitCXXMethodDecl(D, nullptr);
3761 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3762 llvm_unreachable("There are only CXXRecordDecls in C++");
3765 Decl *
3766 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3767 ClassTemplateSpecializationDecl *D) {
3768 // As a MS extension, we permit class-scope explicit specialization
3769 // of member class templates.
3770 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3771 assert(ClassTemplate->getDeclContext()->isRecord() &&
3772 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3773 "can only instantiate an explicit specialization "
3774 "for a member class template");
3776 // Lookup the already-instantiated declaration in the instantiation
3777 // of the class template.
3778 ClassTemplateDecl *InstClassTemplate =
3779 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3780 D->getLocation(), ClassTemplate, TemplateArgs));
3781 if (!InstClassTemplate)
3782 return nullptr;
3784 // Substitute into the template arguments of the class template explicit
3785 // specialization.
3786 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3787 castAs<TemplateSpecializationTypeLoc>();
3788 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3789 Loc.getRAngleLoc());
3790 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3791 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
3792 ArgLocs.push_back(Loc.getArgLoc(I));
3793 if (SemaRef.SubstTemplateArguments(ArgLocs, TemplateArgs, InstTemplateArgs))
3794 return nullptr;
3796 // Check that the template argument list is well-formed for this
3797 // class template.
3798 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3799 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, D->getLocation(),
3800 InstTemplateArgs, false,
3801 SugaredConverted, CanonicalConverted,
3802 /*UpdateArgsWithConversions=*/true))
3803 return nullptr;
3805 // Figure out where to insert this class template explicit specialization
3806 // in the member template's set of class template explicit specializations.
3807 void *InsertPos = nullptr;
3808 ClassTemplateSpecializationDecl *PrevDecl =
3809 InstClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3811 // Check whether we've already seen a conflicting instantiation of this
3812 // declaration (for instance, if there was a prior implicit instantiation).
3813 bool Ignored;
3814 if (PrevDecl &&
3815 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3816 D->getSpecializationKind(),
3817 PrevDecl,
3818 PrevDecl->getSpecializationKind(),
3819 PrevDecl->getPointOfInstantiation(),
3820 Ignored))
3821 return nullptr;
3823 // If PrevDecl was a definition and D is also a definition, diagnose.
3824 // This happens in cases like:
3826 // template<typename T, typename U>
3827 // struct Outer {
3828 // template<typename X> struct Inner;
3829 // template<> struct Inner<T> {};
3830 // template<> struct Inner<U> {};
3831 // };
3833 // Outer<int, int> outer; // error: the explicit specializations of Inner
3834 // // have the same signature.
3835 if (PrevDecl && PrevDecl->getDefinition() &&
3836 D->isThisDeclarationADefinition()) {
3837 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3838 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3839 diag::note_previous_definition);
3840 return nullptr;
3843 // Create the class template partial specialization declaration.
3844 ClassTemplateSpecializationDecl *InstD =
3845 ClassTemplateSpecializationDecl::Create(
3846 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3847 D->getLocation(), InstClassTemplate, CanonicalConverted, PrevDecl);
3849 // Add this partial specialization to the set of class template partial
3850 // specializations.
3851 if (!PrevDecl)
3852 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3854 // Substitute the nested name specifier, if any.
3855 if (SubstQualifier(D, InstD))
3856 return nullptr;
3858 // Build the canonical type that describes the converted template
3859 // arguments of the class template explicit specialization.
3860 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3861 TemplateName(InstClassTemplate), CanonicalConverted,
3862 SemaRef.Context.getRecordType(InstD));
3864 // Build the fully-sugared type for this class template
3865 // specialization as the user wrote in the specialization
3866 // itself. This means that we'll pretty-print the type retrieved
3867 // from the specialization's declaration the way that the user
3868 // actually wrote the specialization, rather than formatting the
3869 // name based on the "canonical" representation used to store the
3870 // template arguments in the specialization.
3871 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3872 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3873 CanonType);
3875 InstD->setAccess(D->getAccess());
3876 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3877 InstD->setSpecializationKind(D->getSpecializationKind());
3878 InstD->setTypeAsWritten(WrittenTy);
3879 InstD->setExternLoc(D->getExternLoc());
3880 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3882 Owner->addDecl(InstD);
3884 // Instantiate the members of the class-scope explicit specialization eagerly.
3885 // We don't have support for lazy instantiation of an explicit specialization
3886 // yet, and MSVC eagerly instantiates in this case.
3887 // FIXME: This is wrong in standard C++.
3888 if (D->isThisDeclarationADefinition() &&
3889 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3890 TSK_ImplicitInstantiation,
3891 /*Complain=*/true))
3892 return nullptr;
3894 return InstD;
3897 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3898 VarTemplateSpecializationDecl *D) {
3900 TemplateArgumentListInfo VarTemplateArgsInfo;
3901 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3902 assert(VarTemplate &&
3903 "A template specialization without specialized template?");
3905 VarTemplateDecl *InstVarTemplate =
3906 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3907 D->getLocation(), VarTemplate, TemplateArgs));
3908 if (!InstVarTemplate)
3909 return nullptr;
3911 // Substitute the current template arguments.
3912 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3913 D->getTemplateArgsInfo()) {
3914 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3915 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3917 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3918 TemplateArgs, VarTemplateArgsInfo))
3919 return nullptr;
3922 // Check that the template argument list is well-formed for this template.
3923 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3924 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3925 VarTemplateArgsInfo, false,
3926 SugaredConverted, CanonicalConverted,
3927 /*UpdateArgsWithConversions=*/true))
3928 return nullptr;
3930 // Check whether we've already seen a declaration of this specialization.
3931 void *InsertPos = nullptr;
3932 VarTemplateSpecializationDecl *PrevDecl =
3933 InstVarTemplate->findSpecialization(CanonicalConverted, InsertPos);
3935 // Check whether we've already seen a conflicting instantiation of this
3936 // declaration (for instance, if there was a prior implicit instantiation).
3937 bool Ignored;
3938 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3939 D->getLocation(), D->getSpecializationKind(), PrevDecl,
3940 PrevDecl->getSpecializationKind(),
3941 PrevDecl->getPointOfInstantiation(), Ignored))
3942 return nullptr;
3944 return VisitVarTemplateSpecializationDecl(
3945 InstVarTemplate, D, VarTemplateArgsInfo, CanonicalConverted, PrevDecl);
3948 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3949 VarTemplateDecl *VarTemplate, VarDecl *D,
3950 const TemplateArgumentListInfo &TemplateArgsInfo,
3951 ArrayRef<TemplateArgument> Converted,
3952 VarTemplateSpecializationDecl *PrevDecl) {
3954 // Do substitution on the type of the declaration
3955 TypeSourceInfo *DI =
3956 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3957 D->getTypeSpecStartLoc(), D->getDeclName());
3958 if (!DI)
3959 return nullptr;
3961 if (DI->getType()->isFunctionType()) {
3962 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3963 << D->isStaticDataMember() << DI->getType();
3964 return nullptr;
3967 // Build the instantiated declaration
3968 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3969 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3970 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
3971 Var->setTemplateArgsInfo(TemplateArgsInfo);
3972 if (!PrevDecl) {
3973 void *InsertPos = nullptr;
3974 VarTemplate->findSpecialization(Converted, InsertPos);
3975 VarTemplate->AddSpecialization(Var, InsertPos);
3978 if (SemaRef.getLangOpts().OpenCL)
3979 SemaRef.deduceOpenCLAddressSpace(Var);
3981 // Substitute the nested name specifier, if any.
3982 if (SubstQualifier(D, Var))
3983 return nullptr;
3985 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
3986 StartingScope, false, PrevDecl);
3988 return Var;
3991 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3992 llvm_unreachable("@defs is not supported in Objective-C++");
3995 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3996 // FIXME: We need to be able to instantiate FriendTemplateDecls.
3997 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3998 DiagnosticsEngine::Error,
3999 "cannot instantiate %0 yet");
4000 SemaRef.Diag(D->getLocation(), DiagID)
4001 << D->getDeclKindName();
4003 return nullptr;
4006 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
4007 llvm_unreachable("Concept definitions cannot reside inside a template");
4010 Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4011 ImplicitConceptSpecializationDecl *D) {
4012 llvm_unreachable("Concept specializations cannot reside inside a template");
4015 Decl *
4016 TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4017 return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
4018 D->getBeginLoc());
4021 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
4022 llvm_unreachable("Unexpected decl");
4025 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
4026 const MultiLevelTemplateArgumentList &TemplateArgs) {
4027 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4028 if (D->isInvalidDecl())
4029 return nullptr;
4031 Decl *SubstD;
4032 runWithSufficientStackSpace(D->getLocation(), [&] {
4033 SubstD = Instantiator.Visit(D);
4035 return SubstD;
4038 void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
4039 FunctionDecl *Orig, QualType &T,
4040 TypeSourceInfo *&TInfo,
4041 DeclarationNameInfo &NameInfo) {
4042 assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual);
4044 // C++2a [class.compare.default]p3:
4045 // the return type is replaced with bool
4046 auto *FPT = T->castAs<FunctionProtoType>();
4047 T = SemaRef.Context.getFunctionType(
4048 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4050 // Update the return type in the source info too. The most straightforward
4051 // way is to create new TypeSourceInfo for the new type. Use the location of
4052 // the '= default' as the location of the new type.
4054 // FIXME: Set the correct return type when we initially transform the type,
4055 // rather than delaying it to now.
4056 TypeSourceInfo *NewTInfo =
4057 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4058 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4059 assert(OldLoc && "type of function is not a function type?");
4060 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4061 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4062 NewLoc.setParam(I, OldLoc.getParam(I));
4063 TInfo = NewTInfo;
4065 // and the declarator-id is replaced with operator==
4066 NameInfo.setName(
4067 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4070 FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
4071 FunctionDecl *Spaceship) {
4072 if (Spaceship->isInvalidDecl())
4073 return nullptr;
4075 // C++2a [class.compare.default]p3:
4076 // an == operator function is declared implicitly [...] with the same
4077 // access and function-definition and in the same class scope as the
4078 // three-way comparison operator function
4079 MultiLevelTemplateArgumentList NoTemplateArgs;
4080 NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite);
4081 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4082 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4083 Decl *R;
4084 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4085 R = Instantiator.VisitCXXMethodDecl(
4086 MD, nullptr, std::nullopt,
4087 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
4088 } else {
4089 assert(Spaceship->getFriendObjectKind() &&
4090 "defaulted spaceship is neither a member nor a friend");
4092 R = Instantiator.VisitFunctionDecl(
4093 Spaceship, nullptr,
4094 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
4095 if (!R)
4096 return nullptr;
4098 FriendDecl *FD =
4099 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4100 cast<NamedDecl>(R), Spaceship->getBeginLoc());
4101 FD->setAccess(AS_public);
4102 RD->addDecl(FD);
4104 return cast_or_null<FunctionDecl>(R);
4107 /// Instantiates a nested template parameter list in the current
4108 /// instantiation context.
4110 /// \param L The parameter list to instantiate
4112 /// \returns NULL if there was an error
4113 TemplateParameterList *
4114 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
4115 // Get errors for all the parameters before bailing out.
4116 bool Invalid = false;
4118 unsigned N = L->size();
4119 typedef SmallVector<NamedDecl *, 8> ParamVector;
4120 ParamVector Params;
4121 Params.reserve(N);
4122 for (auto &P : *L) {
4123 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4124 Params.push_back(D);
4125 Invalid = Invalid || !D || D->isInvalidDecl();
4128 // Clean up if we had an error.
4129 if (Invalid)
4130 return nullptr;
4132 Expr *InstRequiresClause = L->getRequiresClause();
4134 TemplateParameterList *InstL
4135 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
4136 L->getLAngleLoc(), Params,
4137 L->getRAngleLoc(), InstRequiresClause);
4138 return InstL;
4141 TemplateParameterList *
4142 Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
4143 const MultiLevelTemplateArgumentList &TemplateArgs,
4144 bool EvaluateConstraints) {
4145 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4146 Instantiator.setEvaluateConstraints(EvaluateConstraints);
4147 return Instantiator.SubstTemplateParams(Params);
4150 /// Instantiate the declaration of a class template partial
4151 /// specialization.
4153 /// \param ClassTemplate the (instantiated) class template that is partially
4154 // specialized by the instantiation of \p PartialSpec.
4156 /// \param PartialSpec the (uninstantiated) class template partial
4157 /// specialization that we are instantiating.
4159 /// \returns The instantiated partial specialization, if successful; otherwise,
4160 /// NULL to indicate an error.
4161 ClassTemplatePartialSpecializationDecl *
4162 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
4163 ClassTemplateDecl *ClassTemplate,
4164 ClassTemplatePartialSpecializationDecl *PartialSpec) {
4165 // Create a local instantiation scope for this class template partial
4166 // specialization, which will contain the instantiations of the template
4167 // parameters.
4168 LocalInstantiationScope Scope(SemaRef);
4170 // Substitute into the template parameters of the class template partial
4171 // specialization.
4172 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4173 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4174 if (!InstParams)
4175 return nullptr;
4177 // Substitute into the template arguments of the class template partial
4178 // specialization.
4179 const ASTTemplateArgumentListInfo *TemplArgInfo
4180 = PartialSpec->getTemplateArgsAsWritten();
4181 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4182 TemplArgInfo->RAngleLoc);
4183 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4184 InstTemplateArgs))
4185 return nullptr;
4187 // Check that the template argument list is well-formed for this
4188 // class template.
4189 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4190 if (SemaRef.CheckTemplateArgumentList(
4191 ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4192 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4193 return nullptr;
4195 // Check these arguments are valid for a template partial specialization.
4196 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4197 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4198 CanonicalConverted))
4199 return nullptr;
4201 // Figure out where to insert this class template partial specialization
4202 // in the member template's set of class template partial specializations.
4203 void *InsertPos = nullptr;
4204 ClassTemplateSpecializationDecl *PrevDecl =
4205 ClassTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4206 InsertPos);
4208 // Build the canonical type that describes the converted template
4209 // arguments of the class template partial specialization.
4210 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4211 TemplateName(ClassTemplate), CanonicalConverted);
4213 // Build the fully-sugared type for this class template
4214 // specialization as the user wrote in the specialization
4215 // itself. This means that we'll pretty-print the type retrieved
4216 // from the specialization's declaration the way that the user
4217 // actually wrote the specialization, rather than formatting the
4218 // name based on the "canonical" representation used to store the
4219 // template arguments in the specialization.
4220 TypeSourceInfo *WrittenTy
4221 = SemaRef.Context.getTemplateSpecializationTypeInfo(
4222 TemplateName(ClassTemplate),
4223 PartialSpec->getLocation(),
4224 InstTemplateArgs,
4225 CanonType);
4227 if (PrevDecl) {
4228 // We've already seen a partial specialization with the same template
4229 // parameters and template arguments. This can happen, for example, when
4230 // substituting the outer template arguments ends up causing two
4231 // class template partial specializations of a member class template
4232 // to have identical forms, e.g.,
4234 // template<typename T, typename U>
4235 // struct Outer {
4236 // template<typename X, typename Y> struct Inner;
4237 // template<typename Y> struct Inner<T, Y>;
4238 // template<typename Y> struct Inner<U, Y>;
4239 // };
4241 // Outer<int, int> outer; // error: the partial specializations of Inner
4242 // // have the same signature.
4243 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
4244 << WrittenTy->getType();
4245 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4246 << SemaRef.Context.getTypeDeclType(PrevDecl);
4247 return nullptr;
4251 // Create the class template partial specialization declaration.
4252 ClassTemplatePartialSpecializationDecl *InstPartialSpec =
4253 ClassTemplatePartialSpecializationDecl::Create(
4254 SemaRef.Context, PartialSpec->getTagKind(), Owner,
4255 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4256 ClassTemplate, CanonicalConverted, InstTemplateArgs, CanonType,
4257 nullptr);
4258 // Substitute the nested name specifier, if any.
4259 if (SubstQualifier(PartialSpec, InstPartialSpec))
4260 return nullptr;
4262 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4263 InstPartialSpec->setTypeAsWritten(WrittenTy);
4265 // Check the completed partial specialization.
4266 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4268 // Add this partial specialization to the set of class template partial
4269 // specializations.
4270 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4271 /*InsertPos=*/nullptr);
4272 return InstPartialSpec;
4275 /// Instantiate the declaration of a variable template partial
4276 /// specialization.
4278 /// \param VarTemplate the (instantiated) variable template that is partially
4279 /// specialized by the instantiation of \p PartialSpec.
4281 /// \param PartialSpec the (uninstantiated) variable template partial
4282 /// specialization that we are instantiating.
4284 /// \returns The instantiated partial specialization, if successful; otherwise,
4285 /// NULL to indicate an error.
4286 VarTemplatePartialSpecializationDecl *
4287 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
4288 VarTemplateDecl *VarTemplate,
4289 VarTemplatePartialSpecializationDecl *PartialSpec) {
4290 // Create a local instantiation scope for this variable template partial
4291 // specialization, which will contain the instantiations of the template
4292 // parameters.
4293 LocalInstantiationScope Scope(SemaRef);
4295 // Substitute into the template parameters of the variable template partial
4296 // specialization.
4297 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4298 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4299 if (!InstParams)
4300 return nullptr;
4302 // Substitute into the template arguments of the variable template partial
4303 // specialization.
4304 const ASTTemplateArgumentListInfo *TemplArgInfo
4305 = PartialSpec->getTemplateArgsAsWritten();
4306 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4307 TemplArgInfo->RAngleLoc);
4308 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4309 InstTemplateArgs))
4310 return nullptr;
4312 // Check that the template argument list is well-formed for this
4313 // class template.
4314 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4315 if (SemaRef.CheckTemplateArgumentList(
4316 VarTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4317 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4318 return nullptr;
4320 // Check these arguments are valid for a template partial specialization.
4321 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4322 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4323 CanonicalConverted))
4324 return nullptr;
4326 // Figure out where to insert this variable template partial specialization
4327 // in the member template's set of variable template partial specializations.
4328 void *InsertPos = nullptr;
4329 VarTemplateSpecializationDecl *PrevDecl =
4330 VarTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4331 InsertPos);
4333 // Build the canonical type that describes the converted template
4334 // arguments of the variable template partial specialization.
4335 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4336 TemplateName(VarTemplate), CanonicalConverted);
4338 // Build the fully-sugared type for this variable template
4339 // specialization as the user wrote in the specialization
4340 // itself. This means that we'll pretty-print the type retrieved
4341 // from the specialization's declaration the way that the user
4342 // actually wrote the specialization, rather than formatting the
4343 // name based on the "canonical" representation used to store the
4344 // template arguments in the specialization.
4345 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
4346 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
4347 CanonType);
4349 if (PrevDecl) {
4350 // We've already seen a partial specialization with the same template
4351 // parameters and template arguments. This can happen, for example, when
4352 // substituting the outer template arguments ends up causing two
4353 // variable template partial specializations of a member variable template
4354 // to have identical forms, e.g.,
4356 // template<typename T, typename U>
4357 // struct Outer {
4358 // template<typename X, typename Y> pair<X,Y> p;
4359 // template<typename Y> pair<T, Y> p;
4360 // template<typename Y> pair<U, Y> p;
4361 // };
4363 // Outer<int, int> outer; // error: the partial specializations of Inner
4364 // // have the same signature.
4365 SemaRef.Diag(PartialSpec->getLocation(),
4366 diag::err_var_partial_spec_redeclared)
4367 << WrittenTy->getType();
4368 SemaRef.Diag(PrevDecl->getLocation(),
4369 diag::note_var_prev_partial_spec_here);
4370 return nullptr;
4373 // Do substitution on the type of the declaration
4374 TypeSourceInfo *DI = SemaRef.SubstType(
4375 PartialSpec->getTypeSourceInfo(), TemplateArgs,
4376 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4377 if (!DI)
4378 return nullptr;
4380 if (DI->getType()->isFunctionType()) {
4381 SemaRef.Diag(PartialSpec->getLocation(),
4382 diag::err_variable_instantiates_to_function)
4383 << PartialSpec->isStaticDataMember() << DI->getType();
4384 return nullptr;
4387 // Create the variable template partial specialization declaration.
4388 VarTemplatePartialSpecializationDecl *InstPartialSpec =
4389 VarTemplatePartialSpecializationDecl::Create(
4390 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4391 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4392 DI, PartialSpec->getStorageClass(), CanonicalConverted,
4393 InstTemplateArgs);
4395 // Substitute the nested name specifier, if any.
4396 if (SubstQualifier(PartialSpec, InstPartialSpec))
4397 return nullptr;
4399 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4400 InstPartialSpec->setTypeAsWritten(WrittenTy);
4402 // Check the completed partial specialization.
4403 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4405 // Add this partial specialization to the set of variable template partial
4406 // specializations. The instantiation of the initializer is not necessary.
4407 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4409 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4410 LateAttrs, Owner, StartingScope);
4412 return InstPartialSpec;
4415 TypeSourceInfo*
4416 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
4417 SmallVectorImpl<ParmVarDecl *> &Params) {
4418 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4419 assert(OldTInfo && "substituting function without type source info");
4420 assert(Params.empty() && "parameter vector is non-empty at start");
4422 CXXRecordDecl *ThisContext = nullptr;
4423 Qualifiers ThisTypeQuals;
4424 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4425 ThisContext = cast<CXXRecordDecl>(Owner);
4426 ThisTypeQuals = Method->getMethodQualifiers();
4429 TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
4430 OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
4431 ThisContext, ThisTypeQuals, EvaluateConstraints);
4432 if (!NewTInfo)
4433 return nullptr;
4435 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4436 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4437 if (NewTInfo != OldTInfo) {
4438 // Get parameters from the new type info.
4439 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4440 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4441 unsigned NewIdx = 0;
4442 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4443 OldIdx != NumOldParams; ++OldIdx) {
4444 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4445 if (!OldParam)
4446 return nullptr;
4448 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
4450 std::optional<unsigned> NumArgumentsInExpansion;
4451 if (OldParam->isParameterPack())
4452 NumArgumentsInExpansion =
4453 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4454 TemplateArgs);
4455 if (!NumArgumentsInExpansion) {
4456 // Simple case: normal parameter, or a parameter pack that's
4457 // instantiated to a (still-dependent) parameter pack.
4458 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4459 Params.push_back(NewParam);
4460 Scope->InstantiatedLocal(OldParam, NewParam);
4461 } else {
4462 // Parameter pack expansion: make the instantiation an argument pack.
4463 Scope->MakeInstantiatedLocalArgPack(OldParam);
4464 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4465 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4466 Params.push_back(NewParam);
4467 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4471 } else {
4472 // The function type itself was not dependent and therefore no
4473 // substitution occurred. However, we still need to instantiate
4474 // the function parameters themselves.
4475 const FunctionProtoType *OldProto =
4476 cast<FunctionProtoType>(OldProtoLoc.getType());
4477 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4478 ++i) {
4479 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4480 if (!OldParam) {
4481 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4482 D, D->getLocation(), OldProto->getParamType(i)));
4483 continue;
4486 ParmVarDecl *Parm =
4487 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4488 if (!Parm)
4489 return nullptr;
4490 Params.push_back(Parm);
4493 } else {
4494 // If the type of this function, after ignoring parentheses, is not
4495 // *directly* a function type, then we're instantiating a function that
4496 // was declared via a typedef or with attributes, e.g.,
4498 // typedef int functype(int, int);
4499 // functype func;
4500 // int __cdecl meth(int, int);
4502 // In this case, we'll just go instantiate the ParmVarDecls that we
4503 // synthesized in the method declaration.
4504 SmallVector<QualType, 4> ParamTypes;
4505 Sema::ExtParameterInfoBuilder ExtParamInfos;
4506 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4507 TemplateArgs, ParamTypes, &Params,
4508 ExtParamInfos))
4509 return nullptr;
4512 return NewTInfo;
4515 /// Introduce the instantiated function parameters into the local
4516 /// instantiation scope, and set the parameter names to those used
4517 /// in the template.
4518 bool Sema::addInstantiatedParametersToScope(
4519 FunctionDecl *Function, const FunctionDecl *PatternDecl,
4520 LocalInstantiationScope &Scope,
4521 const MultiLevelTemplateArgumentList &TemplateArgs) {
4522 unsigned FParamIdx = 0;
4523 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4524 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4525 if (!PatternParam->isParameterPack()) {
4526 // Simple case: not a parameter pack.
4527 assert(FParamIdx < Function->getNumParams());
4528 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4529 FunctionParam->setDeclName(PatternParam->getDeclName());
4530 // If the parameter's type is not dependent, update it to match the type
4531 // in the pattern. They can differ in top-level cv-qualifiers, and we want
4532 // the pattern's type here. If the type is dependent, they can't differ,
4533 // per core issue 1668. Substitute into the type from the pattern, in case
4534 // it's instantiation-dependent.
4535 // FIXME: Updating the type to work around this is at best fragile.
4536 if (!PatternDecl->getType()->isDependentType()) {
4537 QualType T = SubstType(PatternParam->getType(), TemplateArgs,
4538 FunctionParam->getLocation(),
4539 FunctionParam->getDeclName());
4540 if (T.isNull())
4541 return true;
4542 FunctionParam->setType(T);
4545 Scope.InstantiatedLocal(PatternParam, FunctionParam);
4546 ++FParamIdx;
4547 continue;
4550 // Expand the parameter pack.
4551 Scope.MakeInstantiatedLocalArgPack(PatternParam);
4552 std::optional<unsigned> NumArgumentsInExpansion =
4553 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4554 if (NumArgumentsInExpansion) {
4555 QualType PatternType =
4556 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4557 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4558 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4559 FunctionParam->setDeclName(PatternParam->getDeclName());
4560 if (!PatternDecl->getType()->isDependentType()) {
4561 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
4562 QualType T =
4563 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
4564 FunctionParam->getDeclName());
4565 if (T.isNull())
4566 return true;
4567 FunctionParam->setType(T);
4570 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4571 ++FParamIdx;
4576 return false;
4579 bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
4580 ParmVarDecl *Param) {
4581 assert(Param->hasUninstantiatedDefaultArg());
4583 // Instantiate the expression.
4585 // FIXME: Pass in a correct Pattern argument, otherwise
4586 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4588 // template<typename T>
4589 // struct A {
4590 // static int FooImpl();
4592 // template<typename Tp>
4593 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4594 // // template argument list [[T], [Tp]], should be [[Tp]].
4595 // friend A<Tp> Foo(int a);
4596 // };
4598 // template<typename T>
4599 // A<T> Foo(int a = A<T>::FooImpl());
4600 MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
4601 FD, /*Final=*/false, nullptr, /*RelativeToPrimary=*/true);
4603 if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
4604 return true;
4606 if (ASTMutationListener *L = getASTMutationListener())
4607 L->DefaultArgumentInstantiated(Param);
4609 return false;
4612 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
4613 FunctionDecl *Decl) {
4614 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4615 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
4616 return;
4618 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4619 InstantiatingTemplate::ExceptionSpecification());
4620 if (Inst.isInvalid()) {
4621 // We hit the instantiation depth limit. Clear the exception specification
4622 // so that our callers don't have to cope with EST_Uninstantiated.
4623 UpdateExceptionSpec(Decl, EST_None);
4624 return;
4626 if (Inst.isAlreadyInstantiating()) {
4627 // This exception specification indirectly depends on itself. Reject.
4628 // FIXME: Corresponding rule in the standard?
4629 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4630 UpdateExceptionSpec(Decl, EST_None);
4631 return;
4634 // Enter the scope of this instantiation. We don't use
4635 // PushDeclContext because we don't have a scope.
4636 Sema::ContextRAII savedContext(*this, Decl);
4637 LocalInstantiationScope Scope(*this);
4639 MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
4640 Decl, /*Final=*/false, nullptr, /*RelativeToPrimary*/ true);
4642 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4643 // here, because for a non-defining friend declaration in a class template,
4644 // we don't store enough information to map back to the friend declaration in
4645 // the template.
4646 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4647 if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
4648 UpdateExceptionSpec(Decl, EST_None);
4649 return;
4652 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
4653 TemplateArgs);
4656 /// Initializes the common fields of an instantiation function
4657 /// declaration (New) from the corresponding fields of its template (Tmpl).
4659 /// \returns true if there was an error
4660 bool
4661 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
4662 FunctionDecl *Tmpl) {
4663 New->setImplicit(Tmpl->isImplicit());
4665 // Forward the mangling number from the template to the instantiated decl.
4666 SemaRef.Context.setManglingNumber(New,
4667 SemaRef.Context.getManglingNumber(Tmpl));
4669 // If we are performing substituting explicitly-specified template arguments
4670 // or deduced template arguments into a function template and we reach this
4671 // point, we are now past the point where SFINAE applies and have committed
4672 // to keeping the new function template specialization. We therefore
4673 // convert the active template instantiation for the function template
4674 // into a template instantiation for this specific function template
4675 // specialization, which is not a SFINAE context, so that we diagnose any
4676 // further errors in the declaration itself.
4678 // FIXME: This is a hack.
4679 typedef Sema::CodeSynthesisContext ActiveInstType;
4680 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4681 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4682 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4683 if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
4684 SemaRef.InstantiatingSpecializations.erase(
4685 {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4686 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4687 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4688 ActiveInst.Entity = New;
4689 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4693 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4694 assert(Proto && "Function template without prototype?");
4696 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4697 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4699 // DR1330: In C++11, defer instantiation of a non-trivial
4700 // exception specification.
4701 // DR1484: Local classes and their members are instantiated along with the
4702 // containing function.
4703 if (SemaRef.getLangOpts().CPlusPlus11 &&
4704 EPI.ExceptionSpec.Type != EST_None &&
4705 EPI.ExceptionSpec.Type != EST_DynamicNone &&
4706 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
4707 !Tmpl->isInLocalScopeForInstantiation()) {
4708 FunctionDecl *ExceptionSpecTemplate = Tmpl;
4709 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
4710 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4711 ExceptionSpecificationType NewEST = EST_Uninstantiated;
4712 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
4713 NewEST = EST_Unevaluated;
4715 // Mark the function has having an uninstantiated exception specification.
4716 const FunctionProtoType *NewProto
4717 = New->getType()->getAs<FunctionProtoType>();
4718 assert(NewProto && "Template instantiation without function prototype?");
4719 EPI = NewProto->getExtProtoInfo();
4720 EPI.ExceptionSpec.Type = NewEST;
4721 EPI.ExceptionSpec.SourceDecl = New;
4722 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4723 New->setType(SemaRef.Context.getFunctionType(
4724 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4725 } else {
4726 Sema::ContextRAII SwitchContext(SemaRef, New);
4727 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4731 // Get the definition. Leaves the variable unchanged if undefined.
4732 const FunctionDecl *Definition = Tmpl;
4733 Tmpl->isDefined(Definition);
4735 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4736 LateAttrs, StartingScope);
4738 return false;
4741 /// Initializes common fields of an instantiated method
4742 /// declaration (New) from the corresponding fields of its template
4743 /// (Tmpl).
4745 /// \returns true if there was an error
4746 bool
4747 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4748 CXXMethodDecl *Tmpl) {
4749 if (InitFunctionInstantiation(New, Tmpl))
4750 return true;
4752 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4753 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4755 New->setAccess(Tmpl->getAccess());
4756 if (Tmpl->isVirtualAsWritten())
4757 New->setVirtualAsWritten(true);
4759 // FIXME: New needs a pointer to Tmpl
4760 return false;
4763 bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
4764 FunctionDecl *Tmpl) {
4765 // Transfer across any unqualified lookups.
4766 if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) {
4767 SmallVector<DeclAccessPair, 32> Lookups;
4768 Lookups.reserve(DFI->getUnqualifiedLookups().size());
4769 bool AnyChanged = false;
4770 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4771 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4772 DA.getDecl(), TemplateArgs);
4773 if (!D)
4774 return true;
4775 AnyChanged |= (D != DA.getDecl());
4776 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4779 // It's unlikely that substitution will change any declarations. Don't
4780 // store an unnecessary copy in that case.
4781 New->setDefaultedFunctionInfo(
4782 AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create(
4783 SemaRef.Context, Lookups)
4784 : DFI);
4787 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4788 return false;
4791 /// Instantiate (or find existing instantiation of) a function template with a
4792 /// given set of template arguments.
4794 /// Usually this should not be used, and template argument deduction should be
4795 /// used in its place.
4796 FunctionDecl *
4797 Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4798 const TemplateArgumentList *Args,
4799 SourceLocation Loc) {
4800 FunctionDecl *FD = FTD->getTemplatedDecl();
4802 sema::TemplateDeductionInfo Info(Loc);
4803 InstantiatingTemplate Inst(
4804 *this, Loc, FTD, Args->asArray(),
4805 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
4806 if (Inst.isInvalid())
4807 return nullptr;
4809 ContextRAII SavedContext(*this, FD);
4810 MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
4811 /*Final=*/false);
4813 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4816 /// Instantiate the definition of the given function from its
4817 /// template.
4819 /// \param PointOfInstantiation the point at which the instantiation was
4820 /// required. Note that this is not precisely a "point of instantiation"
4821 /// for the function, but it's close.
4823 /// \param Function the already-instantiated declaration of a
4824 /// function template specialization or member function of a class template
4825 /// specialization.
4827 /// \param Recursive if true, recursively instantiates any functions that
4828 /// are required by this instantiation.
4830 /// \param DefinitionRequired if true, then we are performing an explicit
4831 /// instantiation where the body of the function is required. Complain if
4832 /// there is no such body.
4833 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4834 FunctionDecl *Function,
4835 bool Recursive,
4836 bool DefinitionRequired,
4837 bool AtEndOfTU) {
4838 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
4839 return;
4841 // Never instantiate an explicit specialization except if it is a class scope
4842 // explicit specialization.
4843 TemplateSpecializationKind TSK =
4844 Function->getTemplateSpecializationKindForInstantiation();
4845 if (TSK == TSK_ExplicitSpecialization)
4846 return;
4848 // Never implicitly instantiate a builtin; we don't actually need a function
4849 // body.
4850 if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
4851 !DefinitionRequired)
4852 return;
4854 // Don't instantiate a definition if we already have one.
4855 const FunctionDecl *ExistingDefn = nullptr;
4856 if (Function->isDefined(ExistingDefn,
4857 /*CheckForPendingFriendDefinition=*/true)) {
4858 if (ExistingDefn->isThisDeclarationADefinition())
4859 return;
4861 // If we're asked to instantiate a function whose body comes from an
4862 // instantiated friend declaration, attach the instantiated body to the
4863 // corresponding declaration of the function.
4864 assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition());
4865 Function = const_cast<FunctionDecl*>(ExistingDefn);
4868 // Find the function body that we'll be substituting.
4869 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4870 assert(PatternDecl && "instantiating a non-template");
4872 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4873 Stmt *Pattern = nullptr;
4874 if (PatternDef) {
4875 Pattern = PatternDef->getBody(PatternDef);
4876 PatternDecl = PatternDef;
4877 if (PatternDef->willHaveBody())
4878 PatternDef = nullptr;
4881 // FIXME: We need to track the instantiation stack in order to know which
4882 // definitions should be visible within this instantiation.
4883 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4884 Function->getInstantiatedFromMemberFunction(),
4885 PatternDecl, PatternDef, TSK,
4886 /*Complain*/DefinitionRequired)) {
4887 if (DefinitionRequired)
4888 Function->setInvalidDecl();
4889 else if (TSK == TSK_ExplicitInstantiationDefinition ||
4890 (Function->isConstexpr() && !Recursive)) {
4891 // Try again at the end of the translation unit (at which point a
4892 // definition will be required).
4893 assert(!Recursive);
4894 Function->setInstantiationIsPending(true);
4895 PendingInstantiations.push_back(
4896 std::make_pair(Function, PointOfInstantiation));
4897 } else if (TSK == TSK_ImplicitInstantiation) {
4898 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4899 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4900 Diag(PointOfInstantiation, diag::warn_func_template_missing)
4901 << Function;
4902 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4903 if (getLangOpts().CPlusPlus11)
4904 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4905 << Function;
4909 return;
4912 // Postpone late parsed template instantiations.
4913 if (PatternDecl->isLateTemplateParsed() &&
4914 !LateTemplateParser) {
4915 Function->setInstantiationIsPending(true);
4916 LateParsedInstantiations.push_back(
4917 std::make_pair(Function, PointOfInstantiation));
4918 return;
4921 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
4922 std::string Name;
4923 llvm::raw_string_ostream OS(Name);
4924 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4925 /*Qualified=*/true);
4926 return Name;
4929 // If we're performing recursive template instantiation, create our own
4930 // queue of pending implicit instantiations that we will instantiate later,
4931 // while we're still within our own instantiation context.
4932 // This has to happen before LateTemplateParser below is called, so that
4933 // it marks vtables used in late parsed templates as used.
4934 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4935 /*Enabled=*/Recursive);
4936 LocalEagerInstantiationScope LocalInstantiations(*this);
4938 // Call the LateTemplateParser callback if there is a need to late parse
4939 // a templated function definition.
4940 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
4941 LateTemplateParser) {
4942 // FIXME: Optimize to allow individual templates to be deserialized.
4943 if (PatternDecl->isFromASTFile())
4944 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4946 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
4947 assert(LPTIter != LateParsedTemplateMap.end() &&
4948 "missing LateParsedTemplate");
4949 LateTemplateParser(OpaqueParser, *LPTIter->second);
4950 Pattern = PatternDecl->getBody(PatternDecl);
4951 updateAttrsForLateParsedTemplate(PatternDecl, Function);
4954 // Note, we should never try to instantiate a deleted function template.
4955 assert((Pattern || PatternDecl->isDefaulted() ||
4956 PatternDecl->hasSkippedBody()) &&
4957 "unexpected kind of function template definition");
4959 // C++1y [temp.explicit]p10:
4960 // Except for inline functions, declarations with types deduced from their
4961 // initializer or return value, and class template specializations, other
4962 // explicit instantiation declarations have the effect of suppressing the
4963 // implicit instantiation of the entity to which they refer.
4964 if (TSK == TSK_ExplicitInstantiationDeclaration &&
4965 !PatternDecl->isInlined() &&
4966 !PatternDecl->getReturnType()->getContainedAutoType())
4967 return;
4969 if (PatternDecl->isInlined()) {
4970 // Function, and all later redeclarations of it (from imported modules,
4971 // for instance), are now implicitly inline.
4972 for (auto *D = Function->getMostRecentDecl(); /**/;
4973 D = D->getPreviousDecl()) {
4974 D->setImplicitlyInline();
4975 if (D == Function)
4976 break;
4980 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
4981 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4982 return;
4983 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
4984 "instantiating function definition");
4986 // The instantiation is visible here, even if it was first declared in an
4987 // unimported module.
4988 Function->setVisibleDespiteOwningModule();
4990 // Copy the inner loc start from the pattern.
4991 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4993 EnterExpressionEvaluationContext EvalContext(
4994 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4996 // Introduce a new scope where local variable instantiations will be
4997 // recorded, unless we're actually a member function within a local
4998 // class, in which case we need to merge our results with the parent
4999 // scope (of the enclosing function). The exception is instantiating
5000 // a function template specialization, since the template to be
5001 // instantiated already has references to locals properly substituted.
5002 bool MergeWithParentScope = false;
5003 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
5004 MergeWithParentScope =
5005 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
5007 LocalInstantiationScope Scope(*this, MergeWithParentScope);
5008 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
5009 // Special members might get their TypeSourceInfo set up w.r.t the
5010 // PatternDecl context, in which case parameters could still be pointing
5011 // back to the original class, make sure arguments are bound to the
5012 // instantiated record instead.
5013 assert(PatternDecl->isDefaulted() &&
5014 "Special member needs to be defaulted");
5015 auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
5016 if (!(PatternSM == Sema::CXXCopyConstructor ||
5017 PatternSM == Sema::CXXCopyAssignment ||
5018 PatternSM == Sema::CXXMoveConstructor ||
5019 PatternSM == Sema::CXXMoveAssignment))
5020 return;
5022 auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
5023 const auto *PatternRec =
5024 dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
5025 if (!NewRec || !PatternRec)
5026 return;
5027 if (!PatternRec->isLambda())
5028 return;
5030 struct SpecialMemberTypeInfoRebuilder
5031 : TreeTransform<SpecialMemberTypeInfoRebuilder> {
5032 using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>;
5033 const CXXRecordDecl *OldDecl;
5034 CXXRecordDecl *NewDecl;
5036 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5037 CXXRecordDecl *N)
5038 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5040 bool TransformExceptionSpec(SourceLocation Loc,
5041 FunctionProtoType::ExceptionSpecInfo &ESI,
5042 SmallVectorImpl<QualType> &Exceptions,
5043 bool &Changed) {
5044 return false;
5047 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5048 const RecordType *T = TL.getTypePtr();
5049 RecordDecl *Record = cast_or_null<RecordDecl>(
5050 getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5051 if (Record != OldDecl)
5052 return Base::TransformRecordType(TLB, TL);
5054 QualType Result = getDerived().RebuildRecordType(NewDecl);
5055 if (Result.isNull())
5056 return QualType();
5058 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5059 NewTL.setNameLoc(TL.getNameLoc());
5060 return Result;
5062 } IR{*this, PatternRec, NewRec};
5064 TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5065 assert(NewSI && "Type Transform failed?");
5066 Function->setType(NewSI->getType());
5067 Function->setTypeSourceInfo(NewSI);
5069 ParmVarDecl *Parm = Function->getParamDecl(0);
5070 TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5071 Parm->setType(NewParmSI->getType());
5072 Parm->setTypeSourceInfo(NewParmSI);
5075 if (PatternDecl->isDefaulted()) {
5076 RebuildTypeSourceInfoForDefaultSpecialMembers();
5077 SetDeclDefaulted(Function, PatternDecl->getLocation());
5078 } else {
5079 MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
5080 Function, /*Final=*/false, nullptr, false, PatternDecl);
5082 // Substitute into the qualifier; we can get a substitution failure here
5083 // through evil use of alias templates.
5084 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5085 // of the) lexical context of the pattern?
5086 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5088 ActOnStartOfFunctionDef(nullptr, Function);
5090 // Enter the scope of this instantiation. We don't use
5091 // PushDeclContext because we don't have a scope.
5092 Sema::ContextRAII savedContext(*this, Function);
5094 FPFeaturesStateRAII SavedFPFeatures(*this);
5095 CurFPFeatures = FPOptions(getLangOpts());
5096 FpPragmaStack.CurrentValue = FPOptionsOverride();
5098 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5099 TemplateArgs))
5100 return;
5102 StmtResult Body;
5103 if (PatternDecl->hasSkippedBody()) {
5104 ActOnSkippedFunctionBody(Function);
5105 Body = nullptr;
5106 } else {
5107 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5108 // If this is a constructor, instantiate the member initializers.
5109 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
5110 TemplateArgs);
5112 // If this is an MS ABI dllexport default constructor, instantiate any
5113 // default arguments.
5114 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5115 Ctor->isDefaultConstructor()) {
5116 InstantiateDefaultCtorDefaultArgs(Ctor);
5120 // Instantiate the function body.
5121 Body = SubstStmt(Pattern, TemplateArgs);
5123 if (Body.isInvalid())
5124 Function->setInvalidDecl();
5126 // FIXME: finishing the function body while in an expression evaluation
5127 // context seems wrong. Investigate more.
5128 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5130 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5132 if (auto *Listener = getASTMutationListener())
5133 Listener->FunctionDefinitionInstantiated(Function);
5135 savedContext.pop();
5138 DeclGroupRef DG(Function);
5139 Consumer.HandleTopLevelDecl(DG);
5141 // This class may have local implicit instantiations that need to be
5142 // instantiation within this scope.
5143 LocalInstantiations.perform();
5144 Scope.Exit();
5145 GlobalInstantiations.perform();
5148 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
5149 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
5150 const TemplateArgumentList &TemplateArgList,
5151 const TemplateArgumentListInfo &TemplateArgsInfo,
5152 SmallVectorImpl<TemplateArgument> &Converted,
5153 SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
5154 LocalInstantiationScope *StartingScope) {
5155 if (FromVar->isInvalidDecl())
5156 return nullptr;
5158 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5159 if (Inst.isInvalid())
5160 return nullptr;
5162 // Instantiate the first declaration of the variable template: for a partial
5163 // specialization of a static data member template, the first declaration may
5164 // or may not be the declaration in the class; if it's in the class, we want
5165 // to instantiate a member in the class (a declaration), and if it's outside,
5166 // we want to instantiate a definition.
5168 // If we're instantiating an explicitly-specialized member template or member
5169 // partial specialization, don't do this. The member specialization completely
5170 // replaces the original declaration in this case.
5171 bool IsMemberSpec = false;
5172 MultiLevelTemplateArgumentList MultiLevelList;
5173 if (auto *PartialSpec =
5174 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
5175 IsMemberSpec = PartialSpec->isMemberSpecialization();
5176 MultiLevelList.addOuterTemplateArguments(
5177 PartialSpec, TemplateArgList.asArray(), /*Final=*/false);
5178 } else {
5179 assert(VarTemplate == FromVar->getDescribedVarTemplate());
5180 IsMemberSpec = VarTemplate->isMemberSpecialization();
5181 MultiLevelList.addOuterTemplateArguments(
5182 VarTemplate, TemplateArgList.asArray(), /*Final=*/false);
5184 if (!IsMemberSpec)
5185 FromVar = FromVar->getFirstDecl();
5187 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
5188 MultiLevelList);
5190 // TODO: Set LateAttrs and StartingScope ...
5192 return cast_or_null<VarTemplateSpecializationDecl>(
5193 Instantiator.VisitVarTemplateSpecializationDecl(
5194 VarTemplate, FromVar, TemplateArgsInfo, Converted));
5197 /// Instantiates a variable template specialization by completing it
5198 /// with appropriate type information and initializer.
5199 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
5200 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
5201 const MultiLevelTemplateArgumentList &TemplateArgs) {
5202 assert(PatternDecl->isThisDeclarationADefinition() &&
5203 "don't have a definition to instantiate from");
5205 // Do substitution on the type of the declaration
5206 TypeSourceInfo *DI =
5207 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
5208 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
5209 if (!DI)
5210 return nullptr;
5212 // Update the type of this variable template specialization.
5213 VarSpec->setType(DI->getType());
5215 // Convert the declaration into a definition now.
5216 VarSpec->setCompleteDefinition();
5218 // Instantiate the initializer.
5219 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
5221 if (getLangOpts().OpenCL)
5222 deduceOpenCLAddressSpace(VarSpec);
5224 return VarSpec;
5227 /// BuildVariableInstantiation - Used after a new variable has been created.
5228 /// Sets basic variable data and decides whether to postpone the
5229 /// variable instantiation.
5230 void Sema::BuildVariableInstantiation(
5231 VarDecl *NewVar, VarDecl *OldVar,
5232 const MultiLevelTemplateArgumentList &TemplateArgs,
5233 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
5234 LocalInstantiationScope *StartingScope,
5235 bool InstantiatingVarTemplate,
5236 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
5237 // Instantiating a partial specialization to produce a partial
5238 // specialization.
5239 bool InstantiatingVarTemplatePartialSpec =
5240 isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
5241 isa<VarTemplatePartialSpecializationDecl>(NewVar);
5242 // Instantiating from a variable template (or partial specialization) to
5243 // produce a variable template specialization.
5244 bool InstantiatingSpecFromTemplate =
5245 isa<VarTemplateSpecializationDecl>(NewVar) &&
5246 (OldVar->getDescribedVarTemplate() ||
5247 isa<VarTemplatePartialSpecializationDecl>(OldVar));
5249 // If we are instantiating a local extern declaration, the
5250 // instantiation belongs lexically to the containing function.
5251 // If we are instantiating a static data member defined
5252 // out-of-line, the instantiation will have the same lexical
5253 // context (which will be a namespace scope) as the template.
5254 if (OldVar->isLocalExternDecl()) {
5255 NewVar->setLocalExternDecl();
5256 NewVar->setLexicalDeclContext(Owner);
5257 } else if (OldVar->isOutOfLine())
5258 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
5259 NewVar->setTSCSpec(OldVar->getTSCSpec());
5260 NewVar->setInitStyle(OldVar->getInitStyle());
5261 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
5262 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
5263 NewVar->setConstexpr(OldVar->isConstexpr());
5264 NewVar->setInitCapture(OldVar->isInitCapture());
5265 NewVar->setPreviousDeclInSameBlockScope(
5266 OldVar->isPreviousDeclInSameBlockScope());
5267 NewVar->setAccess(OldVar->getAccess());
5269 if (!OldVar->isStaticDataMember()) {
5270 if (OldVar->isUsed(false))
5271 NewVar->setIsUsed();
5272 NewVar->setReferenced(OldVar->isReferenced());
5275 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
5277 LookupResult Previous(
5278 *this, NewVar->getDeclName(), NewVar->getLocation(),
5279 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
5280 : Sema::LookupOrdinaryName,
5281 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
5282 : forRedeclarationInCurContext());
5284 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
5285 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
5286 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
5287 // We have a previous declaration. Use that one, so we merge with the
5288 // right type.
5289 if (NamedDecl *NewPrev = FindInstantiatedDecl(
5290 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
5291 Previous.addDecl(NewPrev);
5292 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
5293 OldVar->hasLinkage()) {
5294 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
5295 } else if (PrevDeclForVarTemplateSpecialization) {
5296 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
5298 CheckVariableDeclaration(NewVar, Previous);
5300 if (!InstantiatingVarTemplate) {
5301 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
5302 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
5303 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
5306 if (!OldVar->isOutOfLine()) {
5307 if (NewVar->getDeclContext()->isFunctionOrMethod())
5308 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
5311 // Link instantiations of static data members back to the template from
5312 // which they were instantiated.
5314 // Don't do this when instantiating a template (we link the template itself
5315 // back in that case) nor when instantiating a static data member template
5316 // (that's not a member specialization).
5317 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
5318 !InstantiatingSpecFromTemplate)
5319 NewVar->setInstantiationOfStaticDataMember(OldVar,
5320 TSK_ImplicitInstantiation);
5322 // If the pattern is an (in-class) explicit specialization, then the result
5323 // is also an explicit specialization.
5324 if (VarTemplateSpecializationDecl *OldVTSD =
5325 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
5326 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
5327 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
5328 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
5329 TSK_ExplicitSpecialization);
5332 // Forward the mangling number from the template to the instantiated decl.
5333 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
5334 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
5336 // Figure out whether to eagerly instantiate the initializer.
5337 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
5338 // We're producing a template. Don't instantiate the initializer yet.
5339 } else if (NewVar->getType()->isUndeducedType()) {
5340 // We need the type to complete the declaration of the variable.
5341 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5342 } else if (InstantiatingSpecFromTemplate ||
5343 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
5344 !NewVar->isThisDeclarationADefinition())) {
5345 // Delay instantiation of the initializer for variable template
5346 // specializations or inline static data members until a definition of the
5347 // variable is needed.
5348 } else {
5349 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5352 // Diagnose unused local variables with dependent types, where the diagnostic
5353 // will have been deferred.
5354 if (!NewVar->isInvalidDecl() &&
5355 NewVar->getDeclContext()->isFunctionOrMethod() &&
5356 OldVar->getType()->isDependentType())
5357 DiagnoseUnusedDecl(NewVar);
5360 /// Instantiate the initializer of a variable.
5361 void Sema::InstantiateVariableInitializer(
5362 VarDecl *Var, VarDecl *OldVar,
5363 const MultiLevelTemplateArgumentList &TemplateArgs) {
5364 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
5365 L->VariableDefinitionInstantiated(Var);
5367 // We propagate the 'inline' flag with the initializer, because it
5368 // would otherwise imply that the variable is a definition for a
5369 // non-static data member.
5370 if (OldVar->isInlineSpecified())
5371 Var->setInlineSpecified();
5372 else if (OldVar->isInline())
5373 Var->setImplicitlyInline();
5375 if (OldVar->getInit()) {
5376 EnterExpressionEvaluationContext Evaluated(
5377 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
5379 // Instantiate the initializer.
5380 ExprResult Init;
5383 ContextRAII SwitchContext(*this, Var->getDeclContext());
5384 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
5385 OldVar->getInitStyle() == VarDecl::CallInit);
5388 if (!Init.isInvalid()) {
5389 Expr *InitExpr = Init.get();
5391 if (Var->hasAttr<DLLImportAttr>() &&
5392 (!InitExpr ||
5393 !InitExpr->isConstantInitializer(getASTContext(), false))) {
5394 // Do not dynamically initialize dllimport variables.
5395 } else if (InitExpr) {
5396 bool DirectInit = OldVar->isDirectInit();
5397 AddInitializerToDecl(Var, InitExpr, DirectInit);
5398 } else
5399 ActOnUninitializedDecl(Var);
5400 } else {
5401 // FIXME: Not too happy about invalidating the declaration
5402 // because of a bogus initializer.
5403 Var->setInvalidDecl();
5405 } else {
5406 // `inline` variables are a definition and declaration all in one; we won't
5407 // pick up an initializer from anywhere else.
5408 if (Var->isStaticDataMember() && !Var->isInline()) {
5409 if (!Var->isOutOfLine())
5410 return;
5412 // If the declaration inside the class had an initializer, don't add
5413 // another one to the out-of-line definition.
5414 if (OldVar->getFirstDecl()->hasInit())
5415 return;
5418 // We'll add an initializer to a for-range declaration later.
5419 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
5420 return;
5422 ActOnUninitializedDecl(Var);
5425 if (getLangOpts().CUDA)
5426 checkAllowedCUDAInitializer(Var);
5429 /// Instantiate the definition of the given variable from its
5430 /// template.
5432 /// \param PointOfInstantiation the point at which the instantiation was
5433 /// required. Note that this is not precisely a "point of instantiation"
5434 /// for the variable, but it's close.
5436 /// \param Var the already-instantiated declaration of a templated variable.
5438 /// \param Recursive if true, recursively instantiates any functions that
5439 /// are required by this instantiation.
5441 /// \param DefinitionRequired if true, then we are performing an explicit
5442 /// instantiation where a definition of the variable is required. Complain
5443 /// if there is no such definition.
5444 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
5445 VarDecl *Var, bool Recursive,
5446 bool DefinitionRequired, bool AtEndOfTU) {
5447 if (Var->isInvalidDecl())
5448 return;
5450 // Never instantiate an explicitly-specialized entity.
5451 TemplateSpecializationKind TSK =
5452 Var->getTemplateSpecializationKindForInstantiation();
5453 if (TSK == TSK_ExplicitSpecialization)
5454 return;
5456 // Find the pattern and the arguments to substitute into it.
5457 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
5458 assert(PatternDecl && "no pattern for templated variable");
5459 MultiLevelTemplateArgumentList TemplateArgs =
5460 getTemplateInstantiationArgs(Var);
5462 VarTemplateSpecializationDecl *VarSpec =
5463 dyn_cast<VarTemplateSpecializationDecl>(Var);
5464 if (VarSpec) {
5465 // If this is a static data member template, there might be an
5466 // uninstantiated initializer on the declaration. If so, instantiate
5467 // it now.
5469 // FIXME: This largely duplicates what we would do below. The difference
5470 // is that along this path we may instantiate an initializer from an
5471 // in-class declaration of the template and instantiate the definition
5472 // from a separate out-of-class definition.
5473 if (PatternDecl->isStaticDataMember() &&
5474 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
5475 !Var->hasInit()) {
5476 // FIXME: Factor out the duplicated instantiation context setup/tear down
5477 // code here.
5478 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5479 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5480 return;
5481 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5482 "instantiating variable initializer");
5484 // The instantiation is visible here, even if it was first declared in an
5485 // unimported module.
5486 Var->setVisibleDespiteOwningModule();
5488 // If we're performing recursive template instantiation, create our own
5489 // queue of pending implicit instantiations that we will instantiate
5490 // later, while we're still within our own instantiation context.
5491 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5492 /*Enabled=*/Recursive);
5493 LocalInstantiationScope Local(*this);
5494 LocalEagerInstantiationScope LocalInstantiations(*this);
5496 // Enter the scope of this instantiation. We don't use
5497 // PushDeclContext because we don't have a scope.
5498 ContextRAII PreviousContext(*this, Var->getDeclContext());
5499 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
5500 PreviousContext.pop();
5502 // This variable may have local implicit instantiations that need to be
5503 // instantiated within this scope.
5504 LocalInstantiations.perform();
5505 Local.Exit();
5506 GlobalInstantiations.perform();
5508 } else {
5509 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
5510 "not a static data member?");
5513 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
5515 // If we don't have a definition of the variable template, we won't perform
5516 // any instantiation. Rather, we rely on the user to instantiate this
5517 // definition (or provide a specialization for it) in another translation
5518 // unit.
5519 if (!Def && !DefinitionRequired) {
5520 if (TSK == TSK_ExplicitInstantiationDefinition) {
5521 PendingInstantiations.push_back(
5522 std::make_pair(Var, PointOfInstantiation));
5523 } else if (TSK == TSK_ImplicitInstantiation) {
5524 // Warn about missing definition at the end of translation unit.
5525 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5526 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5527 Diag(PointOfInstantiation, diag::warn_var_template_missing)
5528 << Var;
5529 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5530 if (getLangOpts().CPlusPlus11)
5531 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
5533 return;
5537 // FIXME: We need to track the instantiation stack in order to know which
5538 // definitions should be visible within this instantiation.
5539 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
5540 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
5541 /*InstantiatedFromMember*/false,
5542 PatternDecl, Def, TSK,
5543 /*Complain*/DefinitionRequired))
5544 return;
5546 // C++11 [temp.explicit]p10:
5547 // Except for inline functions, const variables of literal types, variables
5548 // of reference types, [...] explicit instantiation declarations
5549 // have the effect of suppressing the implicit instantiation of the entity
5550 // to which they refer.
5552 // FIXME: That's not exactly the same as "might be usable in constant
5553 // expressions", which only allows constexpr variables and const integral
5554 // types, not arbitrary const literal types.
5555 if (TSK == TSK_ExplicitInstantiationDeclaration &&
5556 !Var->mightBeUsableInConstantExpressions(getASTContext()))
5557 return;
5559 // Make sure to pass the instantiated variable to the consumer at the end.
5560 struct PassToConsumerRAII {
5561 ASTConsumer &Consumer;
5562 VarDecl *Var;
5564 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
5565 : Consumer(Consumer), Var(Var) { }
5567 ~PassToConsumerRAII() {
5568 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
5570 } PassToConsumerRAII(Consumer, Var);
5572 // If we already have a definition, we're done.
5573 if (VarDecl *Def = Var->getDefinition()) {
5574 // We may be explicitly instantiating something we've already implicitly
5575 // instantiated.
5576 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
5577 PointOfInstantiation);
5578 return;
5581 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5582 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5583 return;
5584 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5585 "instantiating variable definition");
5587 // If we're performing recursive template instantiation, create our own
5588 // queue of pending implicit instantiations that we will instantiate later,
5589 // while we're still within our own instantiation context.
5590 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5591 /*Enabled=*/Recursive);
5593 // Enter the scope of this instantiation. We don't use
5594 // PushDeclContext because we don't have a scope.
5595 ContextRAII PreviousContext(*this, Var->getDeclContext());
5596 LocalInstantiationScope Local(*this);
5598 LocalEagerInstantiationScope LocalInstantiations(*this);
5600 VarDecl *OldVar = Var;
5601 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
5602 // We're instantiating an inline static data member whose definition was
5603 // provided inside the class.
5604 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5605 } else if (!VarSpec) {
5606 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
5607 TemplateArgs));
5608 } else if (Var->isStaticDataMember() &&
5609 Var->getLexicalDeclContext()->isRecord()) {
5610 // We need to instantiate the definition of a static data member template,
5611 // and all we have is the in-class declaration of it. Instantiate a separate
5612 // declaration of the definition.
5613 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
5614 TemplateArgs);
5616 TemplateArgumentListInfo TemplateArgInfo;
5617 if (const ASTTemplateArgumentListInfo *ArgInfo =
5618 VarSpec->getTemplateArgsInfo()) {
5619 TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
5620 TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
5621 for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
5622 TemplateArgInfo.addArgument(Arg);
5625 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5626 VarSpec->getSpecializedTemplate(), Def, TemplateArgInfo,
5627 VarSpec->getTemplateArgs().asArray(), VarSpec));
5628 if (Var) {
5629 llvm::PointerUnion<VarTemplateDecl *,
5630 VarTemplatePartialSpecializationDecl *> PatternPtr =
5631 VarSpec->getSpecializedTemplateOrPartial();
5632 if (VarTemplatePartialSpecializationDecl *Partial =
5633 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
5634 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
5635 Partial, &VarSpec->getTemplateInstantiationArgs());
5637 // Attach the initializer.
5638 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5640 } else
5641 // Complete the existing variable's definition with an appropriately
5642 // substituted type and initializer.
5643 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
5645 PreviousContext.pop();
5647 if (Var) {
5648 PassToConsumerRAII.Var = Var;
5649 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
5650 OldVar->getPointOfInstantiation());
5653 // This variable may have local implicit instantiations that need to be
5654 // instantiated within this scope.
5655 LocalInstantiations.perform();
5656 Local.Exit();
5657 GlobalInstantiations.perform();
5660 void
5661 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
5662 const CXXConstructorDecl *Tmpl,
5663 const MultiLevelTemplateArgumentList &TemplateArgs) {
5665 SmallVector<CXXCtorInitializer*, 4> NewInits;
5666 bool AnyErrors = Tmpl->isInvalidDecl();
5668 // Instantiate all the initializers.
5669 for (const auto *Init : Tmpl->inits()) {
5670 // Only instantiate written initializers, let Sema re-construct implicit
5671 // ones.
5672 if (!Init->isWritten())
5673 continue;
5675 SourceLocation EllipsisLoc;
5677 if (Init->isPackExpansion()) {
5678 // This is a pack expansion. We should expand it now.
5679 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
5680 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5681 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
5682 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
5683 bool ShouldExpand = false;
5684 bool RetainExpansion = false;
5685 std::optional<unsigned> NumExpansions;
5686 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
5687 BaseTL.getSourceRange(),
5688 Unexpanded,
5689 TemplateArgs, ShouldExpand,
5690 RetainExpansion,
5691 NumExpansions)) {
5692 AnyErrors = true;
5693 New->setInvalidDecl();
5694 continue;
5696 assert(ShouldExpand && "Partial instantiation of base initializer?");
5698 // Loop over all of the arguments in the argument pack(s),
5699 for (unsigned I = 0; I != *NumExpansions; ++I) {
5700 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
5702 // Instantiate the initializer.
5703 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5704 /*CXXDirectInit=*/true);
5705 if (TempInit.isInvalid()) {
5706 AnyErrors = true;
5707 break;
5710 // Instantiate the base type.
5711 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
5712 TemplateArgs,
5713 Init->getSourceLocation(),
5714 New->getDeclName());
5715 if (!BaseTInfo) {
5716 AnyErrors = true;
5717 break;
5720 // Build the initializer.
5721 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
5722 BaseTInfo, TempInit.get(),
5723 New->getParent(),
5724 SourceLocation());
5725 if (NewInit.isInvalid()) {
5726 AnyErrors = true;
5727 break;
5730 NewInits.push_back(NewInit.get());
5733 continue;
5736 // Instantiate the initializer.
5737 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5738 /*CXXDirectInit=*/true);
5739 if (TempInit.isInvalid()) {
5740 AnyErrors = true;
5741 continue;
5744 MemInitResult NewInit;
5745 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
5746 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
5747 TemplateArgs,
5748 Init->getSourceLocation(),
5749 New->getDeclName());
5750 if (!TInfo) {
5751 AnyErrors = true;
5752 New->setInvalidDecl();
5753 continue;
5756 if (Init->isBaseInitializer())
5757 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
5758 New->getParent(), EllipsisLoc);
5759 else
5760 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
5761 cast<CXXRecordDecl>(CurContext->getParent()));
5762 } else if (Init->isMemberInitializer()) {
5763 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
5764 Init->getMemberLocation(),
5765 Init->getMember(),
5766 TemplateArgs));
5767 if (!Member) {
5768 AnyErrors = true;
5769 New->setInvalidDecl();
5770 continue;
5773 NewInit = BuildMemberInitializer(Member, TempInit.get(),
5774 Init->getSourceLocation());
5775 } else if (Init->isIndirectMemberInitializer()) {
5776 IndirectFieldDecl *IndirectMember =
5777 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
5778 Init->getMemberLocation(),
5779 Init->getIndirectMember(), TemplateArgs));
5781 if (!IndirectMember) {
5782 AnyErrors = true;
5783 New->setInvalidDecl();
5784 continue;
5787 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
5788 Init->getSourceLocation());
5791 if (NewInit.isInvalid()) {
5792 AnyErrors = true;
5793 New->setInvalidDecl();
5794 } else {
5795 NewInits.push_back(NewInit.get());
5799 // Assign all the initializers to the new constructor.
5800 ActOnMemInitializers(New,
5801 /*FIXME: ColonLoc */
5802 SourceLocation(),
5803 NewInits,
5804 AnyErrors);
5807 // TODO: this could be templated if the various decl types used the
5808 // same method name.
5809 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
5810 ClassTemplateDecl *Instance) {
5811 Pattern = Pattern->getCanonicalDecl();
5813 do {
5814 Instance = Instance->getCanonicalDecl();
5815 if (Pattern == Instance) return true;
5816 Instance = Instance->getInstantiatedFromMemberTemplate();
5817 } while (Instance);
5819 return false;
5822 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
5823 FunctionTemplateDecl *Instance) {
5824 Pattern = Pattern->getCanonicalDecl();
5826 do {
5827 Instance = Instance->getCanonicalDecl();
5828 if (Pattern == Instance) return true;
5829 Instance = Instance->getInstantiatedFromMemberTemplate();
5830 } while (Instance);
5832 return false;
5835 static bool
5836 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
5837 ClassTemplatePartialSpecializationDecl *Instance) {
5838 Pattern
5839 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5840 do {
5841 Instance = cast<ClassTemplatePartialSpecializationDecl>(
5842 Instance->getCanonicalDecl());
5843 if (Pattern == Instance)
5844 return true;
5845 Instance = Instance->getInstantiatedFromMember();
5846 } while (Instance);
5848 return false;
5851 static bool isInstantiationOf(CXXRecordDecl *Pattern,
5852 CXXRecordDecl *Instance) {
5853 Pattern = Pattern->getCanonicalDecl();
5855 do {
5856 Instance = Instance->getCanonicalDecl();
5857 if (Pattern == Instance) return true;
5858 Instance = Instance->getInstantiatedFromMemberClass();
5859 } while (Instance);
5861 return false;
5864 static bool isInstantiationOf(FunctionDecl *Pattern,
5865 FunctionDecl *Instance) {
5866 Pattern = Pattern->getCanonicalDecl();
5868 do {
5869 Instance = Instance->getCanonicalDecl();
5870 if (Pattern == Instance) return true;
5871 Instance = Instance->getInstantiatedFromMemberFunction();
5872 } while (Instance);
5874 return false;
5877 static bool isInstantiationOf(EnumDecl *Pattern,
5878 EnumDecl *Instance) {
5879 Pattern = Pattern->getCanonicalDecl();
5881 do {
5882 Instance = Instance->getCanonicalDecl();
5883 if (Pattern == Instance) return true;
5884 Instance = Instance->getInstantiatedFromMemberEnum();
5885 } while (Instance);
5887 return false;
5890 static bool isInstantiationOf(UsingShadowDecl *Pattern,
5891 UsingShadowDecl *Instance,
5892 ASTContext &C) {
5893 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
5894 Pattern);
5897 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
5898 ASTContext &C) {
5899 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
5902 template<typename T>
5903 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
5904 ASTContext &Ctx) {
5905 // An unresolved using declaration can instantiate to an unresolved using
5906 // declaration, or to a using declaration or a using declaration pack.
5908 // Multiple declarations can claim to be instantiated from an unresolved
5909 // using declaration if it's a pack expansion. We want the UsingPackDecl
5910 // in that case, not the individual UsingDecls within the pack.
5911 bool OtherIsPackExpansion;
5912 NamedDecl *OtherFrom;
5913 if (auto *OtherUUD = dyn_cast<T>(Other)) {
5914 OtherIsPackExpansion = OtherUUD->isPackExpansion();
5915 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
5916 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
5917 OtherIsPackExpansion = true;
5918 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
5919 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
5920 OtherIsPackExpansion = false;
5921 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
5922 } else {
5923 return false;
5925 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
5926 declaresSameEntity(OtherFrom, Pattern);
5929 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
5930 VarDecl *Instance) {
5931 assert(Instance->isStaticDataMember());
5933 Pattern = Pattern->getCanonicalDecl();
5935 do {
5936 Instance = Instance->getCanonicalDecl();
5937 if (Pattern == Instance) return true;
5938 Instance = Instance->getInstantiatedFromStaticDataMember();
5939 } while (Instance);
5941 return false;
5944 // Other is the prospective instantiation
5945 // D is the prospective pattern
5946 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
5947 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
5948 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5950 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
5951 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5953 if (D->getKind() != Other->getKind())
5954 return false;
5956 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
5957 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
5959 if (auto *Function = dyn_cast<FunctionDecl>(Other))
5960 return isInstantiationOf(cast<FunctionDecl>(D), Function);
5962 if (auto *Enum = dyn_cast<EnumDecl>(Other))
5963 return isInstantiationOf(cast<EnumDecl>(D), Enum);
5965 if (auto *Var = dyn_cast<VarDecl>(Other))
5966 if (Var->isStaticDataMember())
5967 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
5969 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
5970 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
5972 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
5973 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
5975 if (auto *PartialSpec =
5976 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
5977 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
5978 PartialSpec);
5980 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
5981 if (!Field->getDeclName()) {
5982 // This is an unnamed field.
5983 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
5984 cast<FieldDecl>(D));
5988 if (auto *Using = dyn_cast<UsingDecl>(Other))
5989 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
5991 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
5992 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
5994 return D->getDeclName() &&
5995 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
5998 template<typename ForwardIterator>
5999 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
6000 NamedDecl *D,
6001 ForwardIterator first,
6002 ForwardIterator last) {
6003 for (; first != last; ++first)
6004 if (isInstantiationOf(Ctx, D, *first))
6005 return cast<NamedDecl>(*first);
6007 return nullptr;
6010 /// Finds the instantiation of the given declaration context
6011 /// within the current instantiation.
6013 /// \returns NULL if there was an error
6014 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
6015 const MultiLevelTemplateArgumentList &TemplateArgs) {
6016 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
6017 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
6018 return cast_or_null<DeclContext>(ID);
6019 } else return DC;
6022 /// Determine whether the given context is dependent on template parameters at
6023 /// level \p Level or below.
6025 /// Sometimes we only substitute an inner set of template arguments and leave
6026 /// the outer templates alone. In such cases, contexts dependent only on the
6027 /// outer levels are not effectively dependent.
6028 static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
6029 if (!DC->isDependentContext())
6030 return false;
6031 if (!Level)
6032 return true;
6033 return cast<Decl>(DC)->getTemplateDepth() > Level;
6036 /// Find the instantiation of the given declaration within the
6037 /// current instantiation.
6039 /// This routine is intended to be used when \p D is a declaration
6040 /// referenced from within a template, that needs to mapped into the
6041 /// corresponding declaration within an instantiation. For example,
6042 /// given:
6044 /// \code
6045 /// template<typename T>
6046 /// struct X {
6047 /// enum Kind {
6048 /// KnownValue = sizeof(T)
6049 /// };
6051 /// bool getKind() const { return KnownValue; }
6052 /// };
6054 /// template struct X<int>;
6055 /// \endcode
6057 /// In the instantiation of X<int>::getKind(), we need to map the \p
6058 /// EnumConstantDecl for \p KnownValue (which refers to
6059 /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
6060 /// \p FindInstantiatedDecl performs this mapping from within the instantiation
6061 /// of X<int>.
6062 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6063 const MultiLevelTemplateArgumentList &TemplateArgs,
6064 bool FindingInstantiatedContext) {
6065 DeclContext *ParentDC = D->getDeclContext();
6066 // Determine whether our parent context depends on any of the template
6067 // arguments we're currently substituting.
6068 bool ParentDependsOnArgs = isDependentContextAtLevel(
6069 ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6070 // FIXME: Parameters of pointer to functions (y below) that are themselves
6071 // parameters (p below) can have their ParentDC set to the translation-unit
6072 // - thus we can not consistently check if the ParentDC of such a parameter
6073 // is Dependent or/and a FunctionOrMethod.
6074 // For e.g. this code, during Template argument deduction tries to
6075 // find an instantiated decl for (T y) when the ParentDC for y is
6076 // the translation unit.
6077 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6078 // float baz(float(*)()) { return 0.0; }
6079 // Foo(baz);
6080 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6081 // it gets here, always has a FunctionOrMethod as its ParentDC??
6082 // For now:
6083 // - as long as we have a ParmVarDecl whose parent is non-dependent and
6084 // whose type is not instantiation dependent, do nothing to the decl
6085 // - otherwise find its instantiated decl.
6086 if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6087 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6088 return D;
6089 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
6090 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
6091 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6092 isa<OMPDeclareReductionDecl>(ParentDC) ||
6093 isa<OMPDeclareMapperDecl>(ParentDC))) ||
6094 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6095 cast<CXXRecordDecl>(D)->getTemplateDepth() >
6096 TemplateArgs.getNumRetainedOuterLevels())) {
6097 // D is a local of some kind. Look into the map of local
6098 // declarations to their instantiations.
6099 if (CurrentInstantiationScope) {
6100 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
6101 if (Decl *FD = Found->dyn_cast<Decl *>())
6102 return cast<NamedDecl>(FD);
6104 int PackIdx = ArgumentPackSubstitutionIndex;
6105 assert(PackIdx != -1 &&
6106 "found declaration pack but not pack expanding");
6107 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6108 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
6112 // If we're performing a partial substitution during template argument
6113 // deduction, we may not have values for template parameters yet. They
6114 // just map to themselves.
6115 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
6116 isa<TemplateTemplateParmDecl>(D))
6117 return D;
6119 if (D->isInvalidDecl())
6120 return nullptr;
6122 // Normally this function only searches for already instantiated declaration
6123 // however we have to make an exclusion for local types used before
6124 // definition as in the code:
6126 // template<typename T> void f1() {
6127 // void g1(struct x1);
6128 // struct x1 {};
6129 // }
6131 // In this case instantiation of the type of 'g1' requires definition of
6132 // 'x1', which is defined later. Error recovery may produce an enum used
6133 // before definition. In these cases we need to instantiate relevant
6134 // declarations here.
6135 bool NeedInstantiate = false;
6136 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6137 NeedInstantiate = RD->isLocalClass();
6138 else if (isa<TypedefNameDecl>(D) &&
6139 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
6140 NeedInstantiate = true;
6141 else
6142 NeedInstantiate = isa<EnumDecl>(D);
6143 if (NeedInstantiate) {
6144 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6145 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6146 return cast<TypeDecl>(Inst);
6149 // If we didn't find the decl, then we must have a label decl that hasn't
6150 // been found yet. Lazily instantiate it and return it now.
6151 assert(isa<LabelDecl>(D));
6153 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6154 assert(Inst && "Failed to instantiate label??");
6156 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6157 return cast<LabelDecl>(Inst);
6160 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
6161 if (!Record->isDependentContext())
6162 return D;
6164 // Determine whether this record is the "templated" declaration describing
6165 // a class template or class template partial specialization.
6166 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
6167 if (ClassTemplate)
6168 ClassTemplate = ClassTemplate->getCanonicalDecl();
6169 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6170 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
6171 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
6173 // Walk the current context to find either the record or an instantiation of
6174 // it.
6175 DeclContext *DC = CurContext;
6176 while (!DC->isFileContext()) {
6177 // If we're performing substitution while we're inside the template
6178 // definition, we'll find our own context. We're done.
6179 if (DC->Equals(Record))
6180 return Record;
6182 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
6183 // Check whether we're in the process of instantiating a class template
6184 // specialization of the template we're mapping.
6185 if (ClassTemplateSpecializationDecl *InstSpec
6186 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
6187 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
6188 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
6189 return InstRecord;
6192 // Check whether we're in the process of instantiating a member class.
6193 if (isInstantiationOf(Record, InstRecord))
6194 return InstRecord;
6197 // Move to the outer template scope.
6198 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
6199 if (FD->getFriendObjectKind() &&
6200 FD->getNonTransparentDeclContext()->isFileContext()) {
6201 DC = FD->getLexicalDeclContext();
6202 continue;
6204 // An implicit deduction guide acts as if it's within the class template
6205 // specialization described by its name and first N template params.
6206 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
6207 if (Guide && Guide->isImplicit()) {
6208 TemplateDecl *TD = Guide->getDeducedTemplate();
6209 // Convert the arguments to an "as-written" list.
6210 TemplateArgumentListInfo Args(Loc, Loc);
6211 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
6212 TD->getTemplateParameters()->size())) {
6213 ArrayRef<TemplateArgument> Unpacked(Arg);
6214 if (Arg.getKind() == TemplateArgument::Pack)
6215 Unpacked = Arg.pack_elements();
6216 for (TemplateArgument UnpackedArg : Unpacked)
6217 Args.addArgument(
6218 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
6220 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
6221 if (T.isNull())
6222 return nullptr;
6223 auto *SubstRecord = T->getAsCXXRecordDecl();
6224 assert(SubstRecord && "class template id not a class type?");
6225 // Check that this template-id names the primary template and not a
6226 // partial or explicit specialization. (In the latter cases, it's
6227 // meaningless to attempt to find an instantiation of D within the
6228 // specialization.)
6229 // FIXME: The standard doesn't say what should happen here.
6230 if (FindingInstantiatedContext &&
6231 usesPartialOrExplicitSpecialization(
6232 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
6233 Diag(Loc, diag::err_specialization_not_primary_template)
6234 << T << (SubstRecord->getTemplateSpecializationKind() ==
6235 TSK_ExplicitSpecialization);
6236 return nullptr;
6238 DC = SubstRecord;
6239 continue;
6243 DC = DC->getParent();
6246 // Fall through to deal with other dependent record types (e.g.,
6247 // anonymous unions in class templates).
6250 if (!ParentDependsOnArgs)
6251 return D;
6253 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
6254 if (!ParentDC)
6255 return nullptr;
6257 if (ParentDC != D->getDeclContext()) {
6258 // We performed some kind of instantiation in the parent context,
6259 // so now we need to look into the instantiated parent context to
6260 // find the instantiation of the declaration D.
6262 // If our context used to be dependent, we may need to instantiate
6263 // it before performing lookup into that context.
6264 bool IsBeingInstantiated = false;
6265 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
6266 if (!Spec->isDependentContext()) {
6267 QualType T = Context.getTypeDeclType(Spec);
6268 const RecordType *Tag = T->getAs<RecordType>();
6269 assert(Tag && "type of non-dependent record is not a RecordType");
6270 if (Tag->isBeingDefined())
6271 IsBeingInstantiated = true;
6272 if (!Tag->isBeingDefined() &&
6273 RequireCompleteType(Loc, T, diag::err_incomplete_type))
6274 return nullptr;
6276 ParentDC = Tag->getDecl();
6280 NamedDecl *Result = nullptr;
6281 // FIXME: If the name is a dependent name, this lookup won't necessarily
6282 // find it. Does that ever matter?
6283 if (auto Name = D->getDeclName()) {
6284 DeclarationNameInfo NameInfo(Name, D->getLocation());
6285 DeclarationNameInfo NewNameInfo =
6286 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
6287 Name = NewNameInfo.getName();
6288 if (!Name)
6289 return nullptr;
6290 DeclContext::lookup_result Found = ParentDC->lookup(Name);
6292 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
6293 } else {
6294 // Since we don't have a name for the entity we're looking for,
6295 // our only option is to walk through all of the declarations to
6296 // find that name. This will occur in a few cases:
6298 // - anonymous struct/union within a template
6299 // - unnamed class/struct/union/enum within a template
6301 // FIXME: Find a better way to find these instantiations!
6302 Result = findInstantiationOf(Context, D,
6303 ParentDC->decls_begin(),
6304 ParentDC->decls_end());
6307 if (!Result) {
6308 if (isa<UsingShadowDecl>(D)) {
6309 // UsingShadowDecls can instantiate to nothing because of using hiding.
6310 } else if (hasUncompilableErrorOccurred()) {
6311 // We've already complained about some ill-formed code, so most likely
6312 // this declaration failed to instantiate. There's no point in
6313 // complaining further, since this is normal in invalid code.
6314 // FIXME: Use more fine-grained 'invalid' tracking for this.
6315 } else if (IsBeingInstantiated) {
6316 // The class in which this member exists is currently being
6317 // instantiated, and we haven't gotten around to instantiating this
6318 // member yet. This can happen when the code uses forward declarations
6319 // of member classes, and introduces ordering dependencies via
6320 // template instantiation.
6321 Diag(Loc, diag::err_member_not_yet_instantiated)
6322 << D->getDeclName()
6323 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
6324 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
6325 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
6326 // This enumeration constant was found when the template was defined,
6327 // but can't be found in the instantiation. This can happen if an
6328 // unscoped enumeration member is explicitly specialized.
6329 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
6330 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
6331 TemplateArgs));
6332 assert(Spec->getTemplateSpecializationKind() ==
6333 TSK_ExplicitSpecialization);
6334 Diag(Loc, diag::err_enumerator_does_not_exist)
6335 << D->getDeclName()
6336 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
6337 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
6338 << Context.getTypeDeclType(Spec);
6339 } else {
6340 // We should have found something, but didn't.
6341 llvm_unreachable("Unable to find instantiation of declaration!");
6345 D = Result;
6348 return D;
6351 /// Performs template instantiation for all implicit template
6352 /// instantiations we have seen until this point.
6353 void Sema::PerformPendingInstantiations(bool LocalOnly) {
6354 std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
6355 while (!PendingLocalImplicitInstantiations.empty() ||
6356 (!LocalOnly && !PendingInstantiations.empty())) {
6357 PendingImplicitInstantiation Inst;
6359 if (PendingLocalImplicitInstantiations.empty()) {
6360 Inst = PendingInstantiations.front();
6361 PendingInstantiations.pop_front();
6362 } else {
6363 Inst = PendingLocalImplicitInstantiations.front();
6364 PendingLocalImplicitInstantiations.pop_front();
6367 // Instantiate function definitions
6368 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
6369 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
6370 TSK_ExplicitInstantiationDefinition;
6371 if (Function->isMultiVersion()) {
6372 getASTContext().forEachMultiversionedFunctionVersion(
6373 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
6374 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
6375 DefinitionRequired, true);
6376 if (CurFD->isDefined())
6377 CurFD->setInstantiationIsPending(false);
6379 } else {
6380 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
6381 DefinitionRequired, true);
6382 if (Function->isDefined())
6383 Function->setInstantiationIsPending(false);
6385 // Definition of a PCH-ed template declaration may be available only in the TU.
6386 if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
6387 TUKind == TU_Prefix && Function->instantiationIsPending())
6388 delayedPCHInstantiations.push_back(Inst);
6389 continue;
6392 // Instantiate variable definitions
6393 VarDecl *Var = cast<VarDecl>(Inst.first);
6395 assert((Var->isStaticDataMember() ||
6396 isa<VarTemplateSpecializationDecl>(Var)) &&
6397 "Not a static data member, nor a variable template"
6398 " specialization?");
6400 // Don't try to instantiate declarations if the most recent redeclaration
6401 // is invalid.
6402 if (Var->getMostRecentDecl()->isInvalidDecl())
6403 continue;
6405 // Check if the most recent declaration has changed the specialization kind
6406 // and removed the need for implicit instantiation.
6407 switch (Var->getMostRecentDecl()
6408 ->getTemplateSpecializationKindForInstantiation()) {
6409 case TSK_Undeclared:
6410 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
6411 case TSK_ExplicitInstantiationDeclaration:
6412 case TSK_ExplicitSpecialization:
6413 continue; // No longer need to instantiate this type.
6414 case TSK_ExplicitInstantiationDefinition:
6415 // We only need an instantiation if the pending instantiation *is* the
6416 // explicit instantiation.
6417 if (Var != Var->getMostRecentDecl())
6418 continue;
6419 break;
6420 case TSK_ImplicitInstantiation:
6421 break;
6424 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
6425 "instantiating variable definition");
6426 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
6427 TSK_ExplicitInstantiationDefinition;
6429 // Instantiate static data member definitions or variable template
6430 // specializations.
6431 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
6432 DefinitionRequired, true);
6435 if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
6436 PendingInstantiations.swap(delayedPCHInstantiations);
6439 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
6440 const MultiLevelTemplateArgumentList &TemplateArgs) {
6441 for (auto *DD : Pattern->ddiags()) {
6442 switch (DD->getKind()) {
6443 case DependentDiagnostic::Access:
6444 HandleDependentAccessCheck(*DD, TemplateArgs);
6445 break;