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//===----------------------------------------------------------------------===/
11
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/DependentDiagnostic.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/PrettyDeclStackTrace.h"
21#include "clang/AST/TypeLoc.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/TargetInfo.h"
24#include "clang/Sema/EnterExpressionEvaluationContext.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ScopeInfo.h"
28#include "clang/Sema/SemaAMDGPU.h"
29#include "clang/Sema/SemaCUDA.h"
30#include "clang/Sema/SemaHLSL.h"
31#include "clang/Sema/SemaObjC.h"
32#include "clang/Sema/SemaOpenMP.h"
33#include "clang/Sema/SemaSwift.h"
34#include "clang/Sema/Template.h"
35#include "llvm/Support/SaveAndRestore.h"
36#include "llvm/Support/TimeProfiler.h"
37#include <optional>
38
39using namespace clang;
40
41static bool isDeclWithinFunction(const Decl *D) {
42 const DeclContext *DC = D->getDeclContext();
43 if (DC->isFunctionOrMethod())
44 return true;
45
46 if (DC->isRecord())
47 return cast<CXXRecordDecl>(Val: DC)->isLocalClass();
48
49 return false;
50}
51
52template<typename DeclT>
53static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
54 const MultiLevelTemplateArgumentList &TemplateArgs) {
55 if (!OldDecl->getQualifierLoc())
56 return false;
57
58 assert((NewDecl->getFriendObjectKind() ||
59 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
60 "non-friend with qualified name defined in dependent context");
61 Sema::ContextRAII SavedContext(
62 SemaRef,
63 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
64 ? NewDecl->getLexicalDeclContext()
65 : OldDecl->getLexicalDeclContext()));
66
67 NestedNameSpecifierLoc NewQualifierLoc
68 = SemaRef.SubstNestedNameSpecifierLoc(NNS: OldDecl->getQualifierLoc(),
69 TemplateArgs);
70
71 if (!NewQualifierLoc)
72 return true;
73
74 NewDecl->setQualifierInfo(NewQualifierLoc);
75 return false;
76}
77
78bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
79 DeclaratorDecl *NewDecl) {
80 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
81}
82
83bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
84 TagDecl *NewDecl) {
85 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
86}
87
88// Include attribute instantiation code.
89#include "clang/Sema/AttrTemplateInstantiate.inc"
90
91static void instantiateDependentAlignedAttr(
92 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
93 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
94 if (Aligned->isAlignmentExpr()) {
95 // The alignment expression is a constant expression.
96 EnterExpressionEvaluationContext Unevaluated(
97 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
98 ExprResult Result = S.SubstExpr(E: Aligned->getAlignmentExpr(), TemplateArgs);
99 if (!Result.isInvalid())
100 S.AddAlignedAttr(D: New, CI: *Aligned, E: Result.getAs<Expr>(), IsPackExpansion);
101 } else {
102 if (TypeSourceInfo *Result =
103 S.SubstType(T: Aligned->getAlignmentType(), TemplateArgs,
104 Loc: Aligned->getLocation(), Entity: DeclarationName())) {
105 if (!S.CheckAlignasTypeArgument(KWName: Aligned->getSpelling(), TInfo: Result,
106 OpLoc: Aligned->getLocation(),
107 R: Result->getTypeLoc().getSourceRange()))
108 S.AddAlignedAttr(D: New, CI: *Aligned, T: Result, IsPackExpansion);
109 }
110 }
111}
112
113static void instantiateDependentAlignedAttr(
114 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
115 const AlignedAttr *Aligned, Decl *New) {
116 if (!Aligned->isPackExpansion()) {
117 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, IsPackExpansion: false);
118 return;
119 }
120
121 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
122 if (Aligned->isAlignmentExpr())
123 S.collectUnexpandedParameterPacks(E: Aligned->getAlignmentExpr(),
124 Unexpanded);
125 else
126 S.collectUnexpandedParameterPacks(TL: Aligned->getAlignmentType()->getTypeLoc(),
127 Unexpanded);
128 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
129
130 // Determine whether we can expand this attribute pack yet.
131 bool Expand = true, RetainExpansion = false;
132 UnsignedOrNone NumExpansions = std::nullopt;
133 // FIXME: Use the actual location of the ellipsis.
134 SourceLocation EllipsisLoc = Aligned->getLocation();
135 if (S.CheckParameterPacksForExpansion(EllipsisLoc, PatternRange: Aligned->getRange(),
136 Unexpanded, TemplateArgs,
137 /*FailOnPackProducingTemplates=*/true,
138 ShouldExpand&: Expand, RetainExpansion, NumExpansions))
139 return;
140
141 if (!Expand) {
142 Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt);
143 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, IsPackExpansion: true);
144 } else {
145 for (unsigned I = 0; I != *NumExpansions; ++I) {
146 Sema::ArgPackSubstIndexRAII SubstIndex(S, I);
147 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, IsPackExpansion: false);
148 }
149 }
150}
151
152static void instantiateDependentAssumeAlignedAttr(
153 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
154 const AssumeAlignedAttr *Aligned, Decl *New) {
155 // The alignment expression is a constant expression.
156 EnterExpressionEvaluationContext Unevaluated(
157 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
158
159 Expr *E, *OE = nullptr;
160 ExprResult Result = S.SubstExpr(E: Aligned->getAlignment(), TemplateArgs);
161 if (Result.isInvalid())
162 return;
163 E = Result.getAs<Expr>();
164
165 if (Aligned->getOffset()) {
166 Result = S.SubstExpr(E: Aligned->getOffset(), TemplateArgs);
167 if (Result.isInvalid())
168 return;
169 OE = Result.getAs<Expr>();
170 }
171
172 S.AddAssumeAlignedAttr(D: New, CI: *Aligned, E, OE);
173}
174
175static void instantiateDependentAlignValueAttr(
176 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
177 const AlignValueAttr *Aligned, Decl *New) {
178 // The alignment expression is a constant expression.
179 EnterExpressionEvaluationContext Unevaluated(
180 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
181 ExprResult Result = S.SubstExpr(E: Aligned->getAlignment(), TemplateArgs);
182 if (!Result.isInvalid())
183 S.AddAlignValueAttr(D: New, CI: *Aligned, E: Result.getAs<Expr>());
184}
185
186static void instantiateDependentAllocAlignAttr(
187 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
188 const AllocAlignAttr *Align, Decl *New) {
189 Expr *Param = IntegerLiteral::Create(
190 C: S.getASTContext(),
191 V: llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
192 type: S.getASTContext().UnsignedLongLongTy, l: Align->getLocation());
193 S.AddAllocAlignAttr(D: New, CI: *Align, ParamExpr: Param);
194}
195
196static void instantiateDependentAnnotationAttr(
197 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
198 const AnnotateAttr *Attr, Decl *New) {
199 EnterExpressionEvaluationContext Unevaluated(
200 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
201
202 // If the attribute has delayed arguments it will have to instantiate those
203 // and handle them as new arguments for the attribute.
204 bool HasDelayedArgs = Attr->delayedArgs_size();
205
206 ArrayRef<Expr *> ArgsToInstantiate =
207 HasDelayedArgs
208 ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
209 : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
210
211 SmallVector<Expr *, 4> Args;
212 if (S.SubstExprs(Exprs: ArgsToInstantiate,
213 /*IsCall=*/false, TemplateArgs, Outputs&: Args))
214 return;
215
216 StringRef Str = Attr->getAnnotation();
217 if (HasDelayedArgs) {
218 if (Args.size() < 1) {
219 S.Diag(Loc: Attr->getLoc(), DiagID: diag::err_attribute_too_few_arguments)
220 << Attr << 1;
221 return;
222 }
223
224 if (!S.checkStringLiteralArgumentAttr(CI: *Attr, E: Args[0], Str))
225 return;
226
227 llvm::SmallVector<Expr *, 4> ActualArgs;
228 ActualArgs.insert(I: ActualArgs.begin(), From: Args.begin() + 1, To: Args.end());
229 std::swap(LHS&: Args, RHS&: ActualArgs);
230 }
231 auto *AA = S.CreateAnnotationAttr(CI: *Attr, Annot: Str, Args);
232 if (AA) {
233 New->addAttr(A: AA);
234 }
235}
236
237template <typename Attr>
238static void sharedInstantiateConstructorDestructorAttr(
239 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const Attr *A,
240 Decl *New, ASTContext &C) {
241 Expr *tempInstPriority = nullptr;
242 {
243 EnterExpressionEvaluationContext Unevaluated(
244 S, Sema::ExpressionEvaluationContext::Unevaluated);
245 ExprResult Result = S.SubstExpr(E: A->getPriority(), TemplateArgs);
246 if (Result.isInvalid())
247 return;
248 if (Result.isUsable()) {
249 tempInstPriority = Result.get();
250 if (std::optional<llvm::APSInt> CE =
251 tempInstPriority->getIntegerConstantExpr(Ctx: C)) {
252 // Consistent with non-templated priority arguments, which must fit in a
253 // 32-bit unsigned integer.
254 if (!CE->isIntN(N: 32)) {
255 S.Diag(Loc: tempInstPriority->getExprLoc(), DiagID: diag::err_ice_too_large)
256 << toString(I: *CE, Radix: 10, Signed: false) << /*Size=*/32 << /*Unsigned=*/1;
257 return;
258 }
259 }
260 }
261 }
262 New->addAttr(A: Attr::Create(C, tempInstPriority, *A));
263}
264
265static Expr *instantiateDependentFunctionAttrCondition(
266 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
267 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
268 Expr *Cond = nullptr;
269 {
270 Sema::ContextRAII SwitchContext(S, New);
271 EnterExpressionEvaluationContext Unevaluated(
272 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
273 ExprResult Result = S.SubstExpr(E: OldCond, TemplateArgs);
274 if (Result.isInvalid())
275 return nullptr;
276 Cond = Result.getAs<Expr>();
277 }
278 if (!Cond->isTypeDependent()) {
279 ExprResult Converted = S.PerformContextuallyConvertToBool(From: Cond);
280 if (Converted.isInvalid())
281 return nullptr;
282 Cond = Converted.get();
283 }
284
285 SmallVector<PartialDiagnosticAt, 8> Diags;
286 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
287 !Expr::isPotentialConstantExprUnevaluated(E: Cond, FD: New, Diags)) {
288 S.Diag(Loc: A->getLocation(), DiagID: diag::err_attr_cond_never_constant_expr) << A;
289 for (const auto &P : Diags)
290 S.Diag(Loc: P.first, PD: P.second);
291 return nullptr;
292 }
293 return Cond;
294}
295
296static void instantiateDependentEnableIfAttr(
297 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
298 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
299 Expr *Cond = instantiateDependentFunctionAttrCondition(
300 S, TemplateArgs, A: EIA, OldCond: EIA->getCond(), Tmpl, New);
301
302 if (Cond)
303 New->addAttr(A: new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
304 Cond, EIA->getMessage()));
305}
306
307static void instantiateDependentDiagnoseIfAttr(
308 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
309 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
310 Expr *Cond = instantiateDependentFunctionAttrCondition(
311 S, TemplateArgs, A: DIA, OldCond: DIA->getCond(), Tmpl, New);
312
313 if (Cond)
314 New->addAttr(A: new (S.getASTContext()) DiagnoseIfAttr(
315 S.getASTContext(), *DIA, Cond, DIA->getMessage(),
316 DIA->getDefaultSeverity(), DIA->getWarningGroup(),
317 DIA->getArgDependent(), New));
318}
319
320// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
321// template A as the base and arguments from TemplateArgs.
322static void instantiateDependentCUDALaunchBoundsAttr(
323 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
324 const CUDALaunchBoundsAttr &Attr, Decl *New) {
325 // The alignment expression is a constant expression.
326 EnterExpressionEvaluationContext Unevaluated(
327 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
328
329 ExprResult Result = S.SubstExpr(E: Attr.getMaxThreads(), TemplateArgs);
330 if (Result.isInvalid())
331 return;
332 Expr *MaxThreads = Result.getAs<Expr>();
333
334 Expr *MinBlocks = nullptr;
335 if (Attr.getMinBlocks()) {
336 Result = S.SubstExpr(E: Attr.getMinBlocks(), TemplateArgs);
337 if (Result.isInvalid())
338 return;
339 MinBlocks = Result.getAs<Expr>();
340 }
341
342 Expr *MaxBlocks = nullptr;
343 if (Attr.getMaxBlocks()) {
344 Result = S.SubstExpr(E: Attr.getMaxBlocks(), TemplateArgs);
345 if (Result.isInvalid())
346 return;
347 MaxBlocks = Result.getAs<Expr>();
348 }
349
350 S.AddLaunchBoundsAttr(D: New, CI: Attr, MaxThreads, MinBlocks, MaxBlocks);
351}
352
353static void
354instantiateDependentModeAttr(Sema &S,
355 const MultiLevelTemplateArgumentList &TemplateArgs,
356 const ModeAttr &Attr, Decl *New) {
357 S.AddModeAttr(D: New, CI: Attr, Name: Attr.getMode(),
358 /*InInstantiation=*/true);
359}
360
361/// Instantiation of 'declare simd' attribute and its arguments.
362static void instantiateOMPDeclareSimdDeclAttr(
363 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
364 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
365 // Allow 'this' in clauses with varlist.
366 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: New))
367 New = FTD->getTemplatedDecl();
368 auto *FD = cast<FunctionDecl>(Val: New);
369 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: FD->getDeclContext());
370 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
371 SmallVector<unsigned, 4> LinModifiers;
372
373 auto SubstExpr = [&](Expr *E) -> ExprResult {
374 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()))
375 if (auto *PVD = dyn_cast<ParmVarDecl>(Val: DRE->getDecl())) {
376 Sema::ContextRAII SavedContext(S, FD);
377 LocalInstantiationScope Local(S);
378 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
379 Local.InstantiatedLocal(
380 D: PVD, Inst: FD->getParamDecl(i: PVD->getFunctionScopeIndex()));
381 return S.SubstExpr(E, TemplateArgs);
382 }
383 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
384 FD->isCXXInstanceMember());
385 return S.SubstExpr(E, TemplateArgs);
386 };
387
388 // Substitute a single OpenMP clause, which is a potentially-evaluated
389 // full-expression.
390 auto Subst = [&](Expr *E) -> ExprResult {
391 EnterExpressionEvaluationContext Evaluated(
392 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
393 ExprResult Res = SubstExpr(E);
394 if (Res.isInvalid())
395 return Res;
396 return S.ActOnFinishFullExpr(Expr: Res.get(), DiscardedValue: false);
397 };
398
399 ExprResult Simdlen;
400 if (auto *E = Attr.getSimdlen())
401 Simdlen = Subst(E);
402
403 if (Attr.uniforms_size() > 0) {
404 for(auto *E : Attr.uniforms()) {
405 ExprResult Inst = Subst(E);
406 if (Inst.isInvalid())
407 continue;
408 Uniforms.push_back(Elt: Inst.get());
409 }
410 }
411
412 auto AI = Attr.alignments_begin();
413 for (auto *E : Attr.aligneds()) {
414 ExprResult Inst = Subst(E);
415 if (Inst.isInvalid())
416 continue;
417 Aligneds.push_back(Elt: Inst.get());
418 Inst = ExprEmpty();
419 if (*AI)
420 Inst = S.SubstExpr(E: *AI, TemplateArgs);
421 Alignments.push_back(Elt: Inst.get());
422 ++AI;
423 }
424
425 auto SI = Attr.steps_begin();
426 for (auto *E : Attr.linears()) {
427 ExprResult Inst = Subst(E);
428 if (Inst.isInvalid())
429 continue;
430 Linears.push_back(Elt: Inst.get());
431 Inst = ExprEmpty();
432 if (*SI)
433 Inst = S.SubstExpr(E: *SI, TemplateArgs);
434 Steps.push_back(Elt: Inst.get());
435 ++SI;
436 }
437 LinModifiers.append(in_start: Attr.modifiers_begin(), in_end: Attr.modifiers_end());
438 (void)S.OpenMP().ActOnOpenMPDeclareSimdDirective(
439 DG: S.ConvertDeclToDeclGroup(Ptr: New), BS: Attr.getBranchState(), Simdlen: Simdlen.get(),
440 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
441 SR: Attr.getRange());
442}
443
444/// Instantiation of 'declare variant' attribute and its arguments.
445static void instantiateOMPDeclareVariantAttr(
446 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
447 const OMPDeclareVariantAttr &Attr, Decl *New) {
448 // Allow 'this' in clauses with varlist.
449 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: New))
450 New = FTD->getTemplatedDecl();
451 auto *FD = cast<FunctionDecl>(Val: New);
452 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: FD->getDeclContext());
453
454 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
455 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()))
456 if (auto *PVD = dyn_cast<ParmVarDecl>(Val: DRE->getDecl())) {
457 Sema::ContextRAII SavedContext(S, FD);
458 LocalInstantiationScope Local(S);
459 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
460 Local.InstantiatedLocal(
461 D: PVD, Inst: FD->getParamDecl(i: PVD->getFunctionScopeIndex()));
462 return S.SubstExpr(E, TemplateArgs);
463 }
464 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
465 FD->isCXXInstanceMember());
466 return S.SubstExpr(E, TemplateArgs);
467 };
468
469 // Substitute a single OpenMP clause, which is a potentially-evaluated
470 // full-expression.
471 auto &&Subst = [&SubstExpr, &S](Expr *E) {
472 EnterExpressionEvaluationContext Evaluated(
473 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
474 ExprResult Res = SubstExpr(E);
475 if (Res.isInvalid())
476 return Res;
477 return S.ActOnFinishFullExpr(Expr: Res.get(), DiscardedValue: false);
478 };
479
480 ExprResult VariantFuncRef;
481 if (Expr *E = Attr.getVariantFuncRef()) {
482 // Do not mark function as is used to prevent its emission if this is the
483 // only place where it is used.
484 EnterExpressionEvaluationContext Unevaluated(
485 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
486 VariantFuncRef = Subst(E);
487 }
488
489 // Copy the template version of the OMPTraitInfo and run substitute on all
490 // score and condition expressiosn.
491 OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo();
492 TI = *Attr.getTraitInfos();
493
494 // Try to substitute template parameters in score and condition expressions.
495 auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
496 if (E) {
497 EnterExpressionEvaluationContext Unevaluated(
498 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
499 ExprResult ER = Subst(E);
500 if (ER.isUsable())
501 E = ER.get();
502 else
503 return true;
504 }
505 return false;
506 };
507 if (TI.anyScoreOrCondition(Cond: SubstScoreOrConditionExpr))
508 return;
509
510 Expr *E = VariantFuncRef.get();
511
512 // Check function/variant ref for `omp declare variant` but not for `omp
513 // begin declare variant` (which use implicit attributes).
514 std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
515 S.OpenMP().checkOpenMPDeclareVariantFunction(
516 DG: S.ConvertDeclToDeclGroup(Ptr: New), VariantRef: E, TI, NumAppendArgs: Attr.appendArgs_size(),
517 SR: Attr.getRange());
518
519 if (!DeclVarData)
520 return;
521
522 E = DeclVarData->second;
523 FD = DeclVarData->first;
524
525 if (auto *VariantDRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts())) {
526 if (auto *VariantFD = dyn_cast<FunctionDecl>(Val: VariantDRE->getDecl())) {
527 if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
528 if (!VariantFTD->isThisDeclarationADefinition())
529 return;
530 Sema::TentativeAnalysisScope Trap(S);
531 const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy(
532 Context&: S.Context, Args: TemplateArgs.getInnermost());
533
534 auto *SubstFD = S.InstantiateFunctionDeclaration(FTD: VariantFTD, Args: TAL,
535 Loc: New->getLocation());
536 if (!SubstFD)
537 return;
538 QualType NewType = S.Context.mergeFunctionTypes(
539 SubstFD->getType(), FD->getType(),
540 /* OfBlockPointer */ false,
541 /* Unqualified */ false, /* AllowCXX */ true);
542 if (NewType.isNull())
543 return;
544 S.InstantiateFunctionDefinition(
545 PointOfInstantiation: New->getLocation(), Function: SubstFD, /* Recursive */ true,
546 /* DefinitionRequired */ false, /* AtEndOfTU */ false);
547 SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
548 E = DeclRefExpr::Create(Context: S.Context, QualifierLoc: NestedNameSpecifierLoc(),
549 TemplateKWLoc: SourceLocation(), D: SubstFD,
550 /* RefersToEnclosingVariableOrCapture */ false,
551 /* NameLoc */ SubstFD->getLocation(),
552 T: SubstFD->getType(), VK: ExprValueKind::VK_PRValue);
553 }
554 }
555 }
556
557 SmallVector<Expr *, 8> NothingExprs;
558 SmallVector<Expr *, 8> NeedDevicePtrExprs;
559 SmallVector<Expr *, 8> NeedDeviceAddrExprs;
560 SmallVector<OMPInteropInfo, 4> AppendArgs;
561
562 for (Expr *E : Attr.adjustArgsNothing()) {
563 ExprResult ER = Subst(E);
564 if (ER.isInvalid())
565 continue;
566 NothingExprs.push_back(Elt: ER.get());
567 }
568 for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
569 ExprResult ER = Subst(E);
570 if (ER.isInvalid())
571 continue;
572 NeedDevicePtrExprs.push_back(Elt: ER.get());
573 }
574 for (Expr *E : Attr.adjustArgsNeedDeviceAddr()) {
575 ExprResult ER = Subst(E);
576 if (ER.isInvalid())
577 continue;
578 NeedDeviceAddrExprs.push_back(Elt: ER.get());
579 }
580 for (OMPInteropInfo &II : Attr.appendArgs()) {
581 OMPInteropInfo Info(II.IsTarget, II.IsTargetSync);
582 Info.HasPreferAttrs = II.HasPreferAttrs;
583 for (const OMPInteropPref &P : II.Prefs) {
584 Expr *SubstFr = nullptr;
585 if (P.Fr) {
586 ExprResult ER = Subst(P.Fr);
587 if (ER.isInvalid())
588 continue;
589 SubstFr = ER.get();
590 }
591 llvm::SmallVector<Expr *, 2> SubstAttrs;
592 for (Expr *A : P.Attrs) {
593 ExprResult ER = Subst(A);
594 if (!ER.isInvalid())
595 SubstAttrs.push_back(Elt: ER.get());
596 }
597 Info.Prefs.emplace_back(Args&: SubstFr, Args: std::move(SubstAttrs));
598 }
599 AppendArgs.push_back(Elt: Info);
600 }
601
602 S.OpenMP().ActOnOpenMPDeclareVariantDirective(
603 FD, VariantRef: E, TI, AdjustArgsNothing: NothingExprs, AdjustArgsNeedDevicePtr: NeedDevicePtrExprs, AdjustArgsNeedDeviceAddr: NeedDeviceAddrExprs,
604 AppendArgs, AdjustArgsLoc: SourceLocation(), AppendArgsLoc: SourceLocation(), SR: Attr.getRange());
605}
606
607static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
608 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
609 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
610 // Both min and max expression are constant expressions.
611 EnterExpressionEvaluationContext Unevaluated(
612 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
613
614 ExprResult Result = S.SubstExpr(E: Attr.getMin(), TemplateArgs);
615 if (Result.isInvalid())
616 return;
617 Expr *MinExpr = Result.getAs<Expr>();
618
619 Result = S.SubstExpr(E: Attr.getMax(), TemplateArgs);
620 if (Result.isInvalid())
621 return;
622 Expr *MaxExpr = Result.getAs<Expr>();
623
624 S.AMDGPU().addAMDGPUFlatWorkGroupSizeAttr(D: New, CI: Attr, Min: MinExpr, Max: MaxExpr);
625}
626
627static void instantiateDependentReqdWorkGroupSizeAttr(
628 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
629 const ReqdWorkGroupSizeAttr &Attr, Decl *New) {
630 // Both min and max expression are constant expressions.
631 EnterExpressionEvaluationContext Unevaluated(
632 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
633
634 ExprResult Result = S.SubstExpr(E: Attr.getXDim(), TemplateArgs);
635 if (Result.isInvalid())
636 return;
637 Expr *X = Result.getAs<Expr>();
638
639 Result = S.SubstExpr(E: Attr.getYDim(), TemplateArgs);
640 if (Result.isInvalid())
641 return;
642 Expr *Y = Result.getAs<Expr>();
643
644 Result = S.SubstExpr(E: Attr.getZDim(), TemplateArgs);
645 if (Result.isInvalid())
646 return;
647 Expr *Z = Result.getAs<Expr>();
648
649 ASTContext &Context = S.getASTContext();
650 New->addAttr(A: ::new (Context) ReqdWorkGroupSizeAttr(Context, Attr, X, Y, Z));
651}
652
653ExplicitSpecifier Sema::instantiateExplicitSpecifier(
654 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) {
655 if (!ES.getExpr())
656 return ES;
657 Expr *OldCond = ES.getExpr();
658 Expr *Cond = nullptr;
659 {
660 EnterExpressionEvaluationContext Unevaluated(
661 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
662 ExprResult SubstResult = SubstExpr(E: OldCond, TemplateArgs);
663 if (SubstResult.isInvalid()) {
664 return ExplicitSpecifier::Invalid();
665 }
666 Cond = SubstResult.get();
667 }
668 ExplicitSpecifier Result(Cond, ES.getKind());
669 if (!Cond->isTypeDependent())
670 tryResolveExplicitSpecifier(ExplicitSpec&: Result);
671 return Result;
672}
673
674static void instantiateDependentAMDGPUWavesPerEUAttr(
675 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
676 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
677 // Both min and max expression are constant expressions.
678 EnterExpressionEvaluationContext Unevaluated(
679 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
680
681 ExprResult Result = S.SubstExpr(E: Attr.getMin(), TemplateArgs);
682 if (Result.isInvalid())
683 return;
684 Expr *MinExpr = Result.getAs<Expr>();
685
686 Expr *MaxExpr = nullptr;
687 if (auto Max = Attr.getMax()) {
688 Result = S.SubstExpr(E: Max, TemplateArgs);
689 if (Result.isInvalid())
690 return;
691 MaxExpr = Result.getAs<Expr>();
692 }
693
694 S.AMDGPU().addAMDGPUWavesPerEUAttr(D: New, CI: Attr, Min: MinExpr, Max: MaxExpr);
695}
696
697static void instantiateDependentAMDGPUMaxNumWorkGroupsAttr(
698 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
699 const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New) {
700 EnterExpressionEvaluationContext Unevaluated(
701 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
702
703 Expr *XExpr = nullptr;
704 Expr *YExpr = nullptr;
705 Expr *ZExpr = nullptr;
706
707 if (Attr.getMaxNumWorkGroupsX()) {
708 ExprResult ResultX = S.SubstExpr(E: Attr.getMaxNumWorkGroupsX(), TemplateArgs);
709 if (ResultX.isUsable())
710 XExpr = ResultX.getAs<Expr>();
711 }
712
713 if (Attr.getMaxNumWorkGroupsY()) {
714 ExprResult ResultY = S.SubstExpr(E: Attr.getMaxNumWorkGroupsY(), TemplateArgs);
715 if (ResultY.isUsable())
716 YExpr = ResultY.getAs<Expr>();
717 }
718
719 if (Attr.getMaxNumWorkGroupsZ()) {
720 ExprResult ResultZ = S.SubstExpr(E: Attr.getMaxNumWorkGroupsZ(), TemplateArgs);
721 if (ResultZ.isUsable())
722 ZExpr = ResultZ.getAs<Expr>();
723 }
724
725 if (XExpr)
726 S.AMDGPU().addAMDGPUMaxNumWorkGroupsAttr(D: New, CI: Attr, XExpr, YExpr, ZExpr);
727}
728
729static void instantiateDependentCUDAClusterDimsAttr(
730 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
731 const CUDAClusterDimsAttr &Attr, Decl *New) {
732 EnterExpressionEvaluationContext Unevaluated(
733 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
734
735 auto SubstElt = [&S, &TemplateArgs](Expr *E) {
736 return E ? S.SubstExpr(E, TemplateArgs).get() : nullptr;
737 };
738
739 Expr *XExpr = SubstElt(Attr.getX());
740 Expr *YExpr = SubstElt(Attr.getY());
741 Expr *ZExpr = SubstElt(Attr.getZ());
742
743 S.addClusterDimsAttr(D: New, CI: Attr, X: XExpr, Y: YExpr, Z: ZExpr);
744}
745
746// This doesn't take any template parameters, but we have a custom action that
747// needs to happen when the kernel itself is instantiated. We need to run the
748// ItaniumMangler to mark the names required to name this kernel.
749static void instantiateDependentSYCLKernelAttr(
750 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
751 const SYCLKernelAttr &Attr, Decl *New) {
752 New->addAttr(A: Attr.clone(C&: S.getASTContext()));
753}
754
755/// Determine whether the attribute A might be relevant to the declaration D.
756/// If not, we can skip instantiating it. The attribute may or may not have
757/// been instantiated yet.
758static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
759 // 'preferred_name' is only relevant to the matching specialization of the
760 // template.
761 if (const auto *PNA = dyn_cast<PreferredNameAttr>(Val: A)) {
762 QualType T = PNA->getTypedefType();
763 const auto *RD = cast<CXXRecordDecl>(Val: D);
764 if (!T->isDependentType() && !RD->isDependentContext() &&
765 !declaresSameEntity(D1: T->getAsCXXRecordDecl(), D2: RD))
766 return false;
767 for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
768 if (S.Context.hasSameType(T1: ExistingPNA->getTypedefType(),
769 T2: PNA->getTypedefType()))
770 return false;
771 return true;
772 }
773
774 if (const auto *BA = dyn_cast<BuiltinAttr>(Val: A)) {
775 const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D);
776 switch (BA->getID()) {
777 case Builtin::BIforward:
778 // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
779 // type and returns an lvalue reference type. The library implementation
780 // will produce an error in this case; don't get in its way.
781 if (FD && FD->getNumParams() >= 1 &&
782 FD->getParamDecl(i: 0)->getType()->isRValueReferenceType() &&
783 FD->getReturnType()->isLValueReferenceType()) {
784 return false;
785 }
786 [[fallthrough]];
787 case Builtin::BImove:
788 case Builtin::BImove_if_noexcept:
789 // HACK: Super-old versions of libc++ (3.1 and earlier) provide
790 // std::forward and std::move overloads that sometimes return by value
791 // instead of by reference when building in C++98 mode. Don't treat such
792 // cases as builtins.
793 if (FD && !FD->getReturnType()->isReferenceType())
794 return false;
795 break;
796 }
797 }
798
799 return true;
800}
801
802static void instantiateDependentHLSLParamModifierAttr(
803 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
804 const HLSLParamModifierAttr *Attr, const Decl *Old, Decl *New) {
805 ParmVarDecl *NewParm = cast<ParmVarDecl>(Val: New);
806 NewParm->addAttr(A: Attr->clone(C&: S.getASTContext()));
807
808 // If this is groupshared don't change the type because it will assert
809 // below. In this case we might have already produced an error but we
810 // must produce one here again because of all the ways templates can
811 // be used.
812 if (const auto *RT = NewParm->getType()->getAs<LValueReferenceType>()) {
813 if (RT->getPointeeType().getAddressSpace() == LangAS::hlsl_groupshared) {
814 S.Diag(Loc: Attr->getLoc(), DiagID: diag::err_hlsl_attr_incompatible)
815 << Attr << "'groupshared'";
816 return;
817 }
818 }
819
820 const Type *OldParmTy = cast<ParmVarDecl>(Val: Old)->getType().getTypePtr();
821 if (OldParmTy->isDependentType() && Attr->isAnyOut())
822 NewParm->setType(S.HLSL().getInoutParameterType(Ty: NewParm->getType()));
823
824 assert(
825 (!Attr->isAnyOut() || (NewParm->getType().isRestrictQualified() &&
826 NewParm->getType()->isReferenceType())) &&
827 "out or inout parameter type must be a reference and restrict qualified");
828}
829
830static void instantiateDependentMallocSpanAttr(Sema &S,
831 const MallocSpanAttr *Attr,
832 Decl *New) {
833 QualType RT = getFunctionOrMethodResultType(D: New);
834 if (!S.CheckSpanLikeType(CI: *Attr, Ty: RT))
835 New->addAttr(A: Attr->clone(C&: S.getASTContext()));
836}
837
838void Sema::InstantiateAttrsForDecl(
839 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
840 Decl *New, LateInstantiatedAttrVec *LateAttrs,
841 LocalInstantiationScope *OuterMostScope) {
842 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: New)) {
843 // FIXME: This function is called multiple times for the same template
844 // specialization. We should only instantiate attributes that were added
845 // since the previous instantiation.
846 for (const auto *TmplAttr : Tmpl->attrs()) {
847 if (!isRelevantAttr(S&: *this, D: New, A: TmplAttr))
848 continue;
849
850 // FIXME: If any of the special case versions from InstantiateAttrs become
851 // applicable to template declaration, we'll need to add them here.
852 CXXThisScopeRAII ThisScope(
853 *this, dyn_cast_or_null<CXXRecordDecl>(Val: ND->getDeclContext()),
854 Qualifiers(), ND->isCXXInstanceMember());
855
856 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
857 At: TmplAttr, C&: Context, S&: *this, TemplateArgs);
858 if (NewAttr && isRelevantAttr(S&: *this, D: New, A: NewAttr) &&
859 checkInstantiatedThreadSafetyAttrs(D: New, A: NewAttr))
860 New->addAttr(A: NewAttr);
861 }
862 }
863}
864
865static Sema::RetainOwnershipKind
866attrToRetainOwnershipKind(const Attr *A) {
867 switch (A->getKind()) {
868 case clang::attr::CFConsumed:
869 return Sema::RetainOwnershipKind::CF;
870 case clang::attr::OSConsumed:
871 return Sema::RetainOwnershipKind::OS;
872 case clang::attr::NSConsumed:
873 return Sema::RetainOwnershipKind::NS;
874 default:
875 llvm_unreachable("Wrong argument supplied");
876 }
877}
878
879// Implementation is down with the rest of the OpenACC Decl instantiations.
880static void instantiateDependentOpenACCRoutineDeclAttr(
881 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
882 const OpenACCRoutineDeclAttr *OldAttr, const Decl *Old, Decl *New);
883
884void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
885 const Decl *Tmpl, Decl *New,
886 LateInstantiatedAttrVec *LateAttrs,
887 LocalInstantiationScope *OuterMostScope) {
888 for (const auto *TmplAttr : Tmpl->attrs()) {
889 if (!isRelevantAttr(S&: *this, D: New, A: TmplAttr))
890 continue;
891
892 // FIXME: This should be generalized to more than just the AlignedAttr.
893 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(Val: TmplAttr);
894 if (Aligned && Aligned->isAlignmentDependent()) {
895 instantiateDependentAlignedAttr(S&: *this, TemplateArgs, Aligned, New);
896 continue;
897 }
898
899 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(Val: TmplAttr)) {
900 instantiateDependentAssumeAlignedAttr(S&: *this, TemplateArgs, Aligned: AssumeAligned, New);
901 continue;
902 }
903
904 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(Val: TmplAttr)) {
905 instantiateDependentAlignValueAttr(S&: *this, TemplateArgs, Aligned: AlignValue, New);
906 continue;
907 }
908
909 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(Val: TmplAttr)) {
910 instantiateDependentAllocAlignAttr(S&: *this, TemplateArgs, Align: AllocAlign, New);
911 continue;
912 }
913
914 if (const auto *Annotate = dyn_cast<AnnotateAttr>(Val: TmplAttr)) {
915 instantiateDependentAnnotationAttr(S&: *this, TemplateArgs, Attr: Annotate, New);
916 continue;
917 }
918
919 if (auto *Constructor = dyn_cast<ConstructorAttr>(Val: TmplAttr)) {
920 sharedInstantiateConstructorDestructorAttr(S&: *this, TemplateArgs,
921 A: Constructor, New, C&: Context);
922 continue;
923 }
924
925 if (auto *Destructor = dyn_cast<DestructorAttr>(Val: TmplAttr)) {
926 sharedInstantiateConstructorDestructorAttr(S&: *this, TemplateArgs,
927 A: Destructor, New, C&: Context);
928 continue;
929 }
930
931 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(Val: TmplAttr)) {
932 instantiateDependentEnableIfAttr(S&: *this, TemplateArgs, EIA: EnableIf, Tmpl,
933 New: cast<FunctionDecl>(Val: New));
934 continue;
935 }
936
937 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(Val: TmplAttr)) {
938 instantiateDependentDiagnoseIfAttr(S&: *this, TemplateArgs, DIA: DiagnoseIf, Tmpl,
939 New: cast<FunctionDecl>(Val: New));
940 continue;
941 }
942
943 if (const auto *CUDALaunchBounds =
944 dyn_cast<CUDALaunchBoundsAttr>(Val: TmplAttr)) {
945 instantiateDependentCUDALaunchBoundsAttr(S&: *this, TemplateArgs,
946 Attr: *CUDALaunchBounds, New);
947 continue;
948 }
949
950 if (const auto *Mode = dyn_cast<ModeAttr>(Val: TmplAttr)) {
951 instantiateDependentModeAttr(S&: *this, TemplateArgs, Attr: *Mode, New);
952 continue;
953 }
954
955 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(Val: TmplAttr)) {
956 instantiateOMPDeclareSimdDeclAttr(S&: *this, TemplateArgs, Attr: *OMPAttr, New);
957 continue;
958 }
959
960 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(Val: TmplAttr)) {
961 instantiateOMPDeclareVariantAttr(S&: *this, TemplateArgs, Attr: *OMPAttr, New);
962 continue;
963 }
964
965 if (const auto *ReqdWorkGroupSize =
966 dyn_cast<ReqdWorkGroupSizeAttr>(Val: TmplAttr)) {
967 instantiateDependentReqdWorkGroupSizeAttr(S&: *this, TemplateArgs,
968 Attr: *ReqdWorkGroupSize, New);
969 }
970
971 if (const auto *AMDGPUFlatWorkGroupSize =
972 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(Val: TmplAttr)) {
973 instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
974 S&: *this, TemplateArgs, Attr: *AMDGPUFlatWorkGroupSize, New);
975 }
976
977 if (const auto *AMDGPUFlatWorkGroupSize =
978 dyn_cast<AMDGPUWavesPerEUAttr>(Val: TmplAttr)) {
979 instantiateDependentAMDGPUWavesPerEUAttr(S&: *this, TemplateArgs,
980 Attr: *AMDGPUFlatWorkGroupSize, New);
981 }
982
983 if (const auto *AMDGPUMaxNumWorkGroups =
984 dyn_cast<AMDGPUMaxNumWorkGroupsAttr>(Val: TmplAttr)) {
985 instantiateDependentAMDGPUMaxNumWorkGroupsAttr(
986 S&: *this, TemplateArgs, Attr: *AMDGPUMaxNumWorkGroups, New);
987 }
988
989 if (const auto *CUDAClusterDims = dyn_cast<CUDAClusterDimsAttr>(Val: TmplAttr)) {
990 instantiateDependentCUDAClusterDimsAttr(S&: *this, TemplateArgs,
991 Attr: *CUDAClusterDims, New);
992 }
993
994 if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(Val: TmplAttr)) {
995 instantiateDependentHLSLParamModifierAttr(S&: *this, TemplateArgs, Attr: ParamAttr,
996 Old: Tmpl, New);
997 continue;
998 }
999
1000 if (const auto *RoutineAttr = dyn_cast<OpenACCRoutineDeclAttr>(Val: TmplAttr)) {
1001 instantiateDependentOpenACCRoutineDeclAttr(S&: *this, TemplateArgs,
1002 OldAttr: RoutineAttr, Old: Tmpl, New);
1003 continue;
1004 }
1005
1006 // Existing DLL attribute on the instantiation takes precedence.
1007 if (TmplAttr->getKind() == attr::DLLExport ||
1008 TmplAttr->getKind() == attr::DLLImport) {
1009 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
1010 continue;
1011 }
1012 }
1013
1014 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(Val: TmplAttr)) {
1015 Swift().AddParameterABIAttr(D: New, CI: *ABIAttr, abi: ABIAttr->getABI());
1016 continue;
1017 }
1018
1019 if (isa<NSConsumedAttr>(Val: TmplAttr) || isa<OSConsumedAttr>(Val: TmplAttr) ||
1020 isa<CFConsumedAttr>(Val: TmplAttr)) {
1021 ObjC().AddXConsumedAttr(D: New, CI: *TmplAttr,
1022 K: attrToRetainOwnershipKind(A: TmplAttr),
1023 /*template instantiation=*/IsTemplateInstantiation: true);
1024 continue;
1025 }
1026
1027 if (auto *A = dyn_cast<PointerAttr>(Val: TmplAttr)) {
1028 if (!New->hasAttr<PointerAttr>())
1029 New->addAttr(A: A->clone(C&: Context));
1030 continue;
1031 }
1032
1033 if (auto *A = dyn_cast<OwnerAttr>(Val: TmplAttr)) {
1034 if (!New->hasAttr<OwnerAttr>())
1035 New->addAttr(A: A->clone(C&: Context));
1036 continue;
1037 }
1038
1039 if (auto *A = dyn_cast<SYCLKernelAttr>(Val: TmplAttr)) {
1040 instantiateDependentSYCLKernelAttr(S&: *this, TemplateArgs, Attr: *A, New);
1041 continue;
1042 }
1043
1044 if (auto *A = dyn_cast<CUDAGridConstantAttr>(Val: TmplAttr)) {
1045 if (!New->hasAttr<CUDAGridConstantAttr>())
1046 New->addAttr(A: A->clone(C&: Context));
1047 continue;
1048 }
1049
1050 if (auto *A = dyn_cast<MallocSpanAttr>(Val: TmplAttr)) {
1051 instantiateDependentMallocSpanAttr(S&: *this, Attr: A, New);
1052 continue;
1053 }
1054
1055 if (auto *A = dyn_cast<CleanupAttr>(Val: TmplAttr)) {
1056 if (!New->hasAttr<CleanupAttr>()) {
1057 auto *NewAttr = A->clone(C&: Context);
1058 NewAttr->setArgLoc(A->getArgLoc());
1059 New->addAttr(A: NewAttr);
1060 }
1061 continue;
1062 }
1063
1064 assert(!TmplAttr->isPackExpansion());
1065 if (TmplAttr->isLateParsed() && LateAttrs) {
1066 // Late parsed attributes must be instantiated and attached after the
1067 // enclosing class has been instantiated. See Sema::InstantiateClass.
1068 LocalInstantiationScope *Saved = nullptr;
1069 if (CurrentInstantiationScope)
1070 Saved = CurrentInstantiationScope->cloneScopes(Outermost: OuterMostScope);
1071 LateAttrs->push_back(Elt: LateInstantiatedAttribute(TmplAttr, Saved, New));
1072 } else {
1073 // Allow 'this' within late-parsed attributes.
1074 auto *ND = cast<NamedDecl>(Val: New);
1075 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: ND->getDeclContext());
1076 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
1077 ND->isCXXInstanceMember());
1078
1079 Attr *NewAttr = sema::instantiateTemplateAttribute(At: TmplAttr, C&: Context,
1080 S&: *this, TemplateArgs);
1081 if (NewAttr && isRelevantAttr(S&: *this, D: New, A: TmplAttr) &&
1082 checkInstantiatedThreadSafetyAttrs(D: New, A: NewAttr))
1083 New->addAttr(A: NewAttr);
1084 }
1085 }
1086}
1087
1088void Sema::updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst) {
1089 for (const auto *Attr : Pattern->attrs()) {
1090 if (auto *A = dyn_cast<StrictFPAttr>(Val: Attr)) {
1091 if (!Inst->hasAttr<StrictFPAttr>())
1092 Inst->addAttr(A: A->clone(C&: getASTContext()));
1093 continue;
1094 }
1095 }
1096}
1097
1098/// Get the previous declaration of a declaration for the purposes of template
1099/// instantiation. If this finds a previous declaration, then the previous
1100/// declaration of the instantiation of D should be an instantiation of the
1101/// result of this function.
1102template<typename DeclT>
1103static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
1104 DeclT *Result = D->getPreviousDecl();
1105
1106 // If the declaration is within a class, and the previous declaration was
1107 // merged from a different definition of that class, then we don't have a
1108 // previous declaration for the purpose of template instantiation.
1109 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
1110 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
1111 return nullptr;
1112
1113 return Result;
1114}
1115
1116Decl *
1117TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
1118 llvm_unreachable("Translation units cannot be instantiated");
1119}
1120
1121Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
1122 llvm_unreachable("HLSL buffer declarations cannot be instantiated");
1123}
1124
1125Decl *TemplateDeclInstantiator::VisitHLSLRootSignatureDecl(
1126 HLSLRootSignatureDecl *Decl) {
1127 llvm_unreachable("HLSL root signature declarations cannot be instantiated");
1128}
1129
1130Decl *
1131TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
1132 llvm_unreachable("pragma comment cannot be instantiated");
1133}
1134
1135Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
1136 PragmaDetectMismatchDecl *D) {
1137 llvm_unreachable("pragma comment cannot be instantiated");
1138}
1139
1140Decl *
1141TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
1142 llvm_unreachable("extern \"C\" context cannot be instantiated");
1143}
1144
1145Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
1146 llvm_unreachable("GUID declaration cannot be instantiated");
1147}
1148
1149Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
1150 UnnamedGlobalConstantDecl *D) {
1151 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
1152}
1153
1154Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
1155 TemplateParamObjectDecl *D) {
1156 llvm_unreachable("template parameter objects cannot be instantiated");
1157}
1158
1159Decl *
1160TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
1161 LabelDecl *Inst = LabelDecl::Create(C&: SemaRef.Context, DC: Owner, IdentL: D->getLocation(),
1162 II: D->getIdentifier());
1163 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: D, New: Inst, LateAttrs, OuterMostScope: StartingScope);
1164 Owner->addDecl(D: Inst);
1165 return Inst;
1166}
1167
1168Decl *
1169TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
1170 llvm_unreachable("Namespaces cannot be instantiated");
1171}
1172
1173namespace {
1174class OpenACCDeclClauseInstantiator final
1175 : public OpenACCClauseVisitor<OpenACCDeclClauseInstantiator> {
1176 Sema &SemaRef;
1177 const MultiLevelTemplateArgumentList &MLTAL;
1178 ArrayRef<OpenACCClause *> ExistingClauses;
1179 SemaOpenACC::OpenACCParsedClause &ParsedClause;
1180 OpenACCClause *NewClause = nullptr;
1181
1182public:
1183 OpenACCDeclClauseInstantiator(Sema &S,
1184 const MultiLevelTemplateArgumentList &MLTAL,
1185 ArrayRef<OpenACCClause *> ExistingClauses,
1186 SemaOpenACC::OpenACCParsedClause &ParsedClause)
1187 : SemaRef(S), MLTAL(MLTAL), ExistingClauses(ExistingClauses),
1188 ParsedClause(ParsedClause) {}
1189
1190 OpenACCClause *CreatedClause() { return NewClause; }
1191#define VISIT_CLAUSE(CLAUSE_NAME) \
1192 void Visit##CLAUSE_NAME##Clause(const OpenACC##CLAUSE_NAME##Clause &Clause);
1193#include "clang/Basic/OpenACCClauses.def"
1194
1195 llvm::SmallVector<Expr *> VisitVarList(ArrayRef<Expr *> VarList) {
1196 llvm::SmallVector<Expr *> InstantiatedVarList;
1197 for (Expr *CurVar : VarList) {
1198 ExprResult Res = SemaRef.SubstExpr(E: CurVar, TemplateArgs: MLTAL);
1199
1200 if (!Res.isUsable())
1201 continue;
1202
1203 Res = SemaRef.OpenACC().ActOnVar(DK: ParsedClause.getDirectiveKind(),
1204 CK: ParsedClause.getClauseKind(), VarExpr: Res.get());
1205
1206 if (Res.isUsable())
1207 InstantiatedVarList.push_back(Elt: Res.get());
1208 }
1209 return InstantiatedVarList;
1210 }
1211};
1212
1213#define CLAUSE_NOT_ON_DECLS(CLAUSE_NAME) \
1214 void OpenACCDeclClauseInstantiator::Visit##CLAUSE_NAME##Clause( \
1215 const OpenACC##CLAUSE_NAME##Clause &) { \
1216 llvm_unreachable("Clause type invalid on declaration construct, or " \
1217 "instantiation not implemented"); \
1218 }
1219
1220CLAUSE_NOT_ON_DECLS(Auto)
1221CLAUSE_NOT_ON_DECLS(Async)
1222CLAUSE_NOT_ON_DECLS(Attach)
1223CLAUSE_NOT_ON_DECLS(Collapse)
1224CLAUSE_NOT_ON_DECLS(Default)
1225CLAUSE_NOT_ON_DECLS(DefaultAsync)
1226CLAUSE_NOT_ON_DECLS(Delete)
1227CLAUSE_NOT_ON_DECLS(Detach)
1228CLAUSE_NOT_ON_DECLS(Device)
1229CLAUSE_NOT_ON_DECLS(DeviceNum)
1230CLAUSE_NOT_ON_DECLS(Finalize)
1231CLAUSE_NOT_ON_DECLS(FirstPrivate)
1232CLAUSE_NOT_ON_DECLS(Host)
1233CLAUSE_NOT_ON_DECLS(If)
1234CLAUSE_NOT_ON_DECLS(IfPresent)
1235CLAUSE_NOT_ON_DECLS(Independent)
1236CLAUSE_NOT_ON_DECLS(NoCreate)
1237CLAUSE_NOT_ON_DECLS(NumGangs)
1238CLAUSE_NOT_ON_DECLS(NumWorkers)
1239CLAUSE_NOT_ON_DECLS(Private)
1240CLAUSE_NOT_ON_DECLS(Reduction)
1241CLAUSE_NOT_ON_DECLS(Self)
1242CLAUSE_NOT_ON_DECLS(Tile)
1243CLAUSE_NOT_ON_DECLS(UseDevice)
1244CLAUSE_NOT_ON_DECLS(VectorLength)
1245CLAUSE_NOT_ON_DECLS(Wait)
1246#undef CLAUSE_NOT_ON_DECLS
1247
1248void OpenACCDeclClauseInstantiator::VisitGangClause(
1249 const OpenACCGangClause &C) {
1250 llvm::SmallVector<OpenACCGangKind> TransformedGangKinds;
1251 llvm::SmallVector<Expr *> TransformedIntExprs;
1252 assert(C.getNumExprs() <= 1 &&
1253 "Only 1 expression allowed on gang clause in routine");
1254
1255 if (C.getNumExprs() > 0) {
1256 assert(C.getExpr(0).first == OpenACCGangKind::Dim &&
1257 "Only dim allowed on routine");
1258 ExprResult ER =
1259 SemaRef.SubstExpr(E: const_cast<Expr *>(C.getExpr(I: 0).second), TemplateArgs: MLTAL);
1260 if (ER.isUsable()) {
1261 ER = SemaRef.OpenACC().CheckGangExpr(ExistingClauses,
1262 DK: ParsedClause.getDirectiveKind(),
1263 GK: C.getExpr(I: 0).first, E: ER.get());
1264 if (ER.isUsable()) {
1265 TransformedGangKinds.push_back(Elt: OpenACCGangKind::Dim);
1266 TransformedIntExprs.push_back(Elt: ER.get());
1267 }
1268 }
1269 }
1270
1271 NewClause = SemaRef.OpenACC().CheckGangClause(
1272 DirKind: ParsedClause.getDirectiveKind(), ExistingClauses,
1273 BeginLoc: ParsedClause.getBeginLoc(), LParenLoc: ParsedClause.getLParenLoc(),
1274 GangKinds: TransformedGangKinds, IntExprs: TransformedIntExprs, EndLoc: ParsedClause.getEndLoc());
1275}
1276
1277void OpenACCDeclClauseInstantiator::VisitSeqClause(const OpenACCSeqClause &C) {
1278 NewClause = OpenACCSeqClause::Create(Ctx: SemaRef.getASTContext(),
1279 BeginLoc: ParsedClause.getBeginLoc(),
1280 EndLoc: ParsedClause.getEndLoc());
1281}
1282void OpenACCDeclClauseInstantiator::VisitNoHostClause(
1283 const OpenACCNoHostClause &C) {
1284 NewClause = OpenACCNoHostClause::Create(Ctx: SemaRef.getASTContext(),
1285 BeginLoc: ParsedClause.getBeginLoc(),
1286 EndLoc: ParsedClause.getEndLoc());
1287}
1288
1289void OpenACCDeclClauseInstantiator::VisitDeviceTypeClause(
1290 const OpenACCDeviceTypeClause &C) {
1291 // Nothing to transform here, just create a new version of 'C'.
1292 NewClause = OpenACCDeviceTypeClause::Create(
1293 C: SemaRef.getASTContext(), K: C.getClauseKind(), BeginLoc: ParsedClause.getBeginLoc(),
1294 LParenLoc: ParsedClause.getLParenLoc(), Archs: C.getArchitectures(),
1295 EndLoc: ParsedClause.getEndLoc());
1296}
1297
1298void OpenACCDeclClauseInstantiator::VisitWorkerClause(
1299 const OpenACCWorkerClause &C) {
1300 assert(!C.hasIntExpr() && "Int Expr not allowed on routine 'worker' clause");
1301 NewClause = OpenACCWorkerClause::Create(Ctx: SemaRef.getASTContext(),
1302 BeginLoc: ParsedClause.getBeginLoc(), LParenLoc: {},
1303 IntExpr: nullptr, EndLoc: ParsedClause.getEndLoc());
1304}
1305
1306void OpenACCDeclClauseInstantiator::VisitVectorClause(
1307 const OpenACCVectorClause &C) {
1308 assert(!C.hasIntExpr() && "Int Expr not allowed on routine 'vector' clause");
1309 NewClause = OpenACCVectorClause::Create(Ctx: SemaRef.getASTContext(),
1310 BeginLoc: ParsedClause.getBeginLoc(), LParenLoc: {},
1311 IntExpr: nullptr, EndLoc: ParsedClause.getEndLoc());
1312}
1313
1314void OpenACCDeclClauseInstantiator::VisitCopyClause(
1315 const OpenACCCopyClause &C) {
1316 ParsedClause.setVarListDetails(VarList: VisitVarList(VarList: C.getVarList()),
1317 ModKind: C.getModifierList());
1318 if (SemaRef.OpenACC().CheckDeclareClause(Clause&: ParsedClause, Mods: C.getModifierList()))
1319 return;
1320 NewClause = OpenACCCopyClause::Create(
1321 C: SemaRef.getASTContext(), Spelling: ParsedClause.getClauseKind(),
1322 BeginLoc: ParsedClause.getBeginLoc(), LParenLoc: ParsedClause.getLParenLoc(),
1323 Mods: ParsedClause.getModifierList(), VarList: ParsedClause.getVarList(),
1324 EndLoc: ParsedClause.getEndLoc());
1325}
1326
1327void OpenACCDeclClauseInstantiator::VisitLinkClause(
1328 const OpenACCLinkClause &C) {
1329 ParsedClause.setVarListDetails(
1330 VarList: SemaRef.OpenACC().CheckLinkClauseVarList(VarExpr: VisitVarList(VarList: C.getVarList())),
1331 ModKind: OpenACCModifierKind::Invalid);
1332
1333 if (SemaRef.OpenACC().CheckDeclareClause(Clause&: ParsedClause,
1334 Mods: OpenACCModifierKind::Invalid))
1335 return;
1336
1337 NewClause = OpenACCLinkClause::Create(
1338 C: SemaRef.getASTContext(), BeginLoc: ParsedClause.getBeginLoc(),
1339 LParenLoc: ParsedClause.getLParenLoc(), VarList: ParsedClause.getVarList(),
1340 EndLoc: ParsedClause.getEndLoc());
1341}
1342
1343void OpenACCDeclClauseInstantiator::VisitDeviceResidentClause(
1344 const OpenACCDeviceResidentClause &C) {
1345 ParsedClause.setVarListDetails(VarList: VisitVarList(VarList: C.getVarList()),
1346 ModKind: OpenACCModifierKind::Invalid);
1347 if (SemaRef.OpenACC().CheckDeclareClause(Clause&: ParsedClause,
1348 Mods: OpenACCModifierKind::Invalid))
1349 return;
1350 NewClause = OpenACCDeviceResidentClause::Create(
1351 C: SemaRef.getASTContext(), BeginLoc: ParsedClause.getBeginLoc(),
1352 LParenLoc: ParsedClause.getLParenLoc(), VarList: ParsedClause.getVarList(),
1353 EndLoc: ParsedClause.getEndLoc());
1354}
1355
1356void OpenACCDeclClauseInstantiator::VisitCopyInClause(
1357 const OpenACCCopyInClause &C) {
1358 ParsedClause.setVarListDetails(VarList: VisitVarList(VarList: C.getVarList()),
1359 ModKind: C.getModifierList());
1360
1361 if (SemaRef.OpenACC().CheckDeclareClause(Clause&: ParsedClause, Mods: C.getModifierList()))
1362 return;
1363 NewClause = OpenACCCopyInClause::Create(
1364 C: SemaRef.getASTContext(), Spelling: ParsedClause.getClauseKind(),
1365 BeginLoc: ParsedClause.getBeginLoc(), LParenLoc: ParsedClause.getLParenLoc(),
1366 Mods: ParsedClause.getModifierList(), VarList: ParsedClause.getVarList(),
1367 EndLoc: ParsedClause.getEndLoc());
1368}
1369void OpenACCDeclClauseInstantiator::VisitCopyOutClause(
1370 const OpenACCCopyOutClause &C) {
1371 ParsedClause.setVarListDetails(VarList: VisitVarList(VarList: C.getVarList()),
1372 ModKind: C.getModifierList());
1373
1374 if (SemaRef.OpenACC().CheckDeclareClause(Clause&: ParsedClause, Mods: C.getModifierList()))
1375 return;
1376 NewClause = OpenACCCopyOutClause::Create(
1377 C: SemaRef.getASTContext(), Spelling: ParsedClause.getClauseKind(),
1378 BeginLoc: ParsedClause.getBeginLoc(), LParenLoc: ParsedClause.getLParenLoc(),
1379 Mods: ParsedClause.getModifierList(), VarList: ParsedClause.getVarList(),
1380 EndLoc: ParsedClause.getEndLoc());
1381}
1382void OpenACCDeclClauseInstantiator::VisitCreateClause(
1383 const OpenACCCreateClause &C) {
1384 ParsedClause.setVarListDetails(VarList: VisitVarList(VarList: C.getVarList()),
1385 ModKind: C.getModifierList());
1386
1387 if (SemaRef.OpenACC().CheckDeclareClause(Clause&: ParsedClause, Mods: C.getModifierList()))
1388 return;
1389 NewClause = OpenACCCreateClause::Create(
1390 C: SemaRef.getASTContext(), Spelling: ParsedClause.getClauseKind(),
1391 BeginLoc: ParsedClause.getBeginLoc(), LParenLoc: ParsedClause.getLParenLoc(),
1392 Mods: ParsedClause.getModifierList(), VarList: ParsedClause.getVarList(),
1393 EndLoc: ParsedClause.getEndLoc());
1394}
1395void OpenACCDeclClauseInstantiator::VisitPresentClause(
1396 const OpenACCPresentClause &C) {
1397 ParsedClause.setVarListDetails(VarList: VisitVarList(VarList: C.getVarList()),
1398 ModKind: OpenACCModifierKind::Invalid);
1399 if (SemaRef.OpenACC().CheckDeclareClause(Clause&: ParsedClause,
1400 Mods: OpenACCModifierKind::Invalid))
1401 return;
1402 NewClause = OpenACCPresentClause::Create(
1403 C: SemaRef.getASTContext(), BeginLoc: ParsedClause.getBeginLoc(),
1404 LParenLoc: ParsedClause.getLParenLoc(), VarList: ParsedClause.getVarList(),
1405 EndLoc: ParsedClause.getEndLoc());
1406}
1407void OpenACCDeclClauseInstantiator::VisitDevicePtrClause(
1408 const OpenACCDevicePtrClause &C) {
1409 llvm::SmallVector<Expr *> VarList = VisitVarList(VarList: C.getVarList());
1410 // Ensure each var is a pointer type.
1411 llvm::erase_if(C&: VarList, P: [&](Expr *E) {
1412 return SemaRef.OpenACC().CheckVarIsPointerType(ClauseKind: OpenACCClauseKind::DevicePtr,
1413 VarExpr: E);
1414 });
1415 ParsedClause.setVarListDetails(VarList, ModKind: OpenACCModifierKind::Invalid);
1416 if (SemaRef.OpenACC().CheckDeclareClause(Clause&: ParsedClause,
1417 Mods: OpenACCModifierKind::Invalid))
1418 return;
1419 NewClause = OpenACCDevicePtrClause::Create(
1420 C: SemaRef.getASTContext(), BeginLoc: ParsedClause.getBeginLoc(),
1421 LParenLoc: ParsedClause.getLParenLoc(), VarList: ParsedClause.getVarList(),
1422 EndLoc: ParsedClause.getEndLoc());
1423}
1424
1425void OpenACCDeclClauseInstantiator::VisitBindClause(
1426 const OpenACCBindClause &C) {
1427 // Nothing to instantiate, we support only string literal or identifier.
1428 if (C.isStringArgument())
1429 NewClause = OpenACCBindClause::Create(
1430 C: SemaRef.getASTContext(), BeginLoc: ParsedClause.getBeginLoc(),
1431 LParenLoc: ParsedClause.getLParenLoc(), SL: C.getStringArgument(),
1432 EndLoc: ParsedClause.getEndLoc());
1433 else
1434 NewClause = OpenACCBindClause::Create(
1435 C: SemaRef.getASTContext(), BeginLoc: ParsedClause.getBeginLoc(),
1436 LParenLoc: ParsedClause.getLParenLoc(), ID: C.getIdentifierArgument(),
1437 EndLoc: ParsedClause.getEndLoc());
1438}
1439
1440llvm::SmallVector<OpenACCClause *> InstantiateOpenACCClauseList(
1441 Sema &S, const MultiLevelTemplateArgumentList &MLTAL,
1442 OpenACCDirectiveKind DK, ArrayRef<const OpenACCClause *> ClauseList) {
1443 llvm::SmallVector<OpenACCClause *> TransformedClauses;
1444
1445 for (const auto *Clause : ClauseList) {
1446 SemaOpenACC::OpenACCParsedClause ParsedClause(DK, Clause->getClauseKind(),
1447 Clause->getBeginLoc());
1448 ParsedClause.setEndLoc(Clause->getEndLoc());
1449 if (const auto *WithParms = dyn_cast<OpenACCClauseWithParams>(Val: Clause))
1450 ParsedClause.setLParenLoc(WithParms->getLParenLoc());
1451
1452 OpenACCDeclClauseInstantiator Instantiator{S, MLTAL, TransformedClauses,
1453 ParsedClause};
1454 Instantiator.Visit(C: Clause);
1455 if (Instantiator.CreatedClause())
1456 TransformedClauses.push_back(Elt: Instantiator.CreatedClause());
1457 }
1458 return TransformedClauses;
1459}
1460
1461} // namespace
1462
1463static void instantiateDependentOpenACCRoutineDeclAttr(
1464 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
1465 const OpenACCRoutineDeclAttr *OldAttr, const Decl *OldDecl, Decl *NewDecl) {
1466 OpenACCRoutineDeclAttr *A =
1467 OpenACCRoutineDeclAttr::Create(Ctx&: S.getASTContext(), Range: OldAttr->getLocation());
1468
1469 if (!OldAttr->Clauses.empty()) {
1470 llvm::SmallVector<OpenACCClause *> TransformedClauses =
1471 InstantiateOpenACCClauseList(
1472 S, MLTAL: TemplateArgs, DK: OpenACCDirectiveKind::Routine, ClauseList: OldAttr->Clauses);
1473 A->Clauses.assign(in_start: TransformedClauses.begin(), in_end: TransformedClauses.end());
1474 }
1475
1476 // We don't end up having to do any magic-static or bind checking here, since
1477 // the first phase should have caught this, since we always apply to the
1478 // functiondecl.
1479 NewDecl->addAttr(A);
1480}
1481
1482Decl *TemplateDeclInstantiator::VisitOpenACCDeclareDecl(OpenACCDeclareDecl *D) {
1483 SemaRef.OpenACC().ActOnConstruct(K: D->getDirectiveKind(), DirLoc: D->getBeginLoc());
1484 llvm::SmallVector<OpenACCClause *> TransformedClauses =
1485 InstantiateOpenACCClauseList(S&: SemaRef, MLTAL: TemplateArgs, DK: D->getDirectiveKind(),
1486 ClauseList: D->clauses());
1487
1488 if (SemaRef.OpenACC().ActOnStartDeclDirective(
1489 K: D->getDirectiveKind(), StartLoc: D->getBeginLoc(), Clauses: TransformedClauses))
1490 return nullptr;
1491
1492 DeclGroupRef Res = SemaRef.OpenACC().ActOnEndDeclDirective(
1493 K: D->getDirectiveKind(), StartLoc: D->getBeginLoc(), DirLoc: D->getDirectiveLoc(), LParenLoc: {}, RParenLoc: {},
1494 EndLoc: D->getEndLoc(), Clauses: TransformedClauses);
1495
1496 if (Res.isNull())
1497 return nullptr;
1498
1499 return Res.getSingleDecl();
1500}
1501
1502Decl *TemplateDeclInstantiator::VisitOpenACCRoutineDecl(OpenACCRoutineDecl *D) {
1503 SemaRef.OpenACC().ActOnConstruct(K: D->getDirectiveKind(), DirLoc: D->getBeginLoc());
1504 llvm::SmallVector<OpenACCClause *> TransformedClauses =
1505 InstantiateOpenACCClauseList(S&: SemaRef, MLTAL: TemplateArgs, DK: D->getDirectiveKind(),
1506 ClauseList: D->clauses());
1507
1508 ExprResult FuncRef;
1509 if (D->getFunctionReference()) {
1510 FuncRef = SemaRef.SubstCXXIdExpr(E: D->getFunctionReference(), TemplateArgs);
1511 if (FuncRef.isUsable())
1512 FuncRef = SemaRef.OpenACC().ActOnRoutineName(RoutineName: FuncRef.get());
1513 // We don't return early here, we leave the construct in the AST, even if
1514 // the function decl is empty.
1515 }
1516
1517 if (SemaRef.OpenACC().ActOnStartDeclDirective(
1518 K: D->getDirectiveKind(), StartLoc: D->getBeginLoc(), Clauses: TransformedClauses))
1519 return nullptr;
1520
1521 DeclGroupRef Res = SemaRef.OpenACC().ActOnEndRoutineDeclDirective(
1522 StartLoc: D->getBeginLoc(), DirLoc: D->getDirectiveLoc(), LParenLoc: D->getLParenLoc(), ReferencedFunc: FuncRef.get(),
1523 RParenLoc: D->getRParenLoc(), Clauses: TransformedClauses, EndLoc: D->getEndLoc(), NextDecl: nullptr);
1524
1525 if (Res.isNull())
1526 return nullptr;
1527
1528 return Res.getSingleDecl();
1529}
1530
1531Decl *
1532TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1533 NamespaceAliasDecl *Inst
1534 = NamespaceAliasDecl::Create(C&: SemaRef.Context, DC: Owner,
1535 NamespaceLoc: D->getNamespaceLoc(),
1536 AliasLoc: D->getAliasLoc(),
1537 Alias: D->getIdentifier(),
1538 QualifierLoc: D->getQualifierLoc(),
1539 IdentLoc: D->getTargetNameLoc(),
1540 Namespace: D->getNamespace());
1541 Owner->addDecl(D: Inst);
1542 return Inst;
1543}
1544
1545Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
1546 bool IsTypeAlias) {
1547 bool Invalid = false;
1548 TypeSourceInfo *TSI = D->getTypeSourceInfo();
1549 if (TSI->getType()->isInstantiationDependentType() ||
1550 TSI->getType()->isVariablyModifiedType()) {
1551 TSI = SemaRef.SubstType(T: TSI, TemplateArgs, Loc: D->getLocation(),
1552 Entity: D->getDeclName());
1553 if (!TSI) {
1554 Invalid = true;
1555 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T: SemaRef.Context.IntTy);
1556 }
1557 } else {
1558 SemaRef.MarkDeclarationsReferencedInType(Loc: D->getLocation(), T: TSI->getType());
1559 }
1560
1561 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
1562 // libstdc++ relies upon this bug in its implementation of common_type. If we
1563 // happen to be processing that implementation, fake up the g++ ?:
1564 // semantics. See LWG issue 2141 for more information on the bug. The bugs
1565 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
1566 if (SemaRef.getPreprocessor().NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2014'04'22)) {
1567 const DecltypeType *DT = TSI->getType()->getAs<DecltypeType>();
1568 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext());
1569 if (DT && RD && isa<ConditionalOperator>(Val: DT->getUnderlyingExpr()) &&
1570 DT->isReferenceType() &&
1571 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
1572 RD->getIdentifier() && RD->getIdentifier()->isStr(Str: "common_type") &&
1573 D->getIdentifier() && D->getIdentifier()->isStr(Str: "type") &&
1574 SemaRef.getSourceManager().isInSystemHeader(Loc: D->getBeginLoc()))
1575 // Fold it to the (non-reference) type which g++ would have produced.
1576 TSI = SemaRef.Context.getTrivialTypeSourceInfo(
1577 T: TSI->getType().getNonReferenceType());
1578 }
1579
1580 // Create the new typedef
1581 TypedefNameDecl *Typedef;
1582 if (IsTypeAlias)
1583 Typedef = TypeAliasDecl::Create(C&: SemaRef.Context, DC: Owner, StartLoc: D->getBeginLoc(),
1584 IdLoc: D->getLocation(), Id: D->getIdentifier(), TInfo: TSI);
1585 else
1586 Typedef = TypedefDecl::Create(C&: SemaRef.Context, DC: Owner, StartLoc: D->getBeginLoc(),
1587 IdLoc: D->getLocation(), Id: D->getIdentifier(), TInfo: TSI);
1588 if (Invalid)
1589 Typedef->setInvalidDecl();
1590
1591 // If the old typedef was the name for linkage purposes of an anonymous
1592 // tag decl, re-establish that relationship for the new typedef.
1593 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1594 TagDecl *oldTag = oldTagType->getDecl();
1595 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1596 TagDecl *newTag = TSI->getType()->castAs<TagType>()->getDecl();
1597 assert(!newTag->hasNameForLinkage());
1598 newTag->setTypedefNameForAnonDecl(Typedef);
1599 }
1600 }
1601
1602 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
1603 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), D: Prev,
1604 TemplateArgs);
1605 if (!InstPrev)
1606 return nullptr;
1607
1608 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(Val: InstPrev);
1609
1610 // If the typedef types are not identical, reject them.
1611 SemaRef.isIncompatibleTypedef(Old: InstPrevTypedef, New: Typedef);
1612
1613 Typedef->setPreviousDecl(InstPrevTypedef);
1614 }
1615
1616 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: D, New: Typedef);
1617
1618 if (D->getUnderlyingType()->getAs<DependentNameType>())
1619 SemaRef.inferGslPointerAttribute(TD: Typedef);
1620
1621 Typedef->setAccess(D->getAccess());
1622 Typedef->setReferenced(D->isReferenced());
1623
1624 return Typedef;
1625}
1626
1627Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1628 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1629 if (Typedef)
1630 Owner->addDecl(D: Typedef);
1631 return Typedef;
1632}
1633
1634Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1635 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1636 if (Typedef)
1637 Owner->addDecl(D: Typedef);
1638 return Typedef;
1639}
1640
1641Decl *TemplateDeclInstantiator::InstantiateTypeAliasTemplateDecl(
1642 TypeAliasTemplateDecl *D) {
1643 // Create a local instantiation scope for this type alias template, which
1644 // will contain the instantiations of the template parameters.
1645 LocalInstantiationScope Scope(SemaRef);
1646
1647 TemplateParameterList *TempParams = D->getTemplateParameters();
1648 TemplateParameterList *InstParams = SubstTemplateParams(List: TempParams);
1649 if (!InstParams)
1650 return nullptr;
1651
1652 // FIXME: This is a hack for instantiating lambdas in the pattern of the
1653 // alias. We are not really instantiating the alias at its template level,
1654 // that only happens in CheckTemplateId, this is only for outer templates
1655 // which contain it. In getTemplateInstantiationArgs, the template arguments
1656 // used here would be used for collating the template arguments needed to
1657 // instantiate the lambda. Pass an empty argument list, so this workaround
1658 // doesn't get confused if there is an outer alias being instantiated.
1659 Sema::InstantiatingTemplate InstTemplate(SemaRef, D->getBeginLoc(), D,
1660 ArrayRef<TemplateArgument>());
1661 if (InstTemplate.isInvalid())
1662 return nullptr;
1663
1664 TypeAliasDecl *Pattern = D->getTemplatedDecl();
1665 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1666 if (getPreviousDeclForInstantiation<TypedefNameDecl>(D: Pattern)) {
1667 DeclContext::lookup_result Found = Owner->lookup(Name: Pattern->getDeclName());
1668 if (!Found.empty()) {
1669 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Val: Found.front());
1670 }
1671 }
1672
1673 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1674 Val: InstantiateTypedefNameDecl(D: Pattern, /*IsTypeAlias=*/true));
1675 if (!AliasInst)
1676 return nullptr;
1677
1678 TypeAliasTemplateDecl *Inst
1679 = TypeAliasTemplateDecl::Create(C&: SemaRef.Context, DC: Owner, L: D->getLocation(),
1680 Name: D->getDeclName(), Params: InstParams, Decl: AliasInst);
1681 AliasInst->setDescribedAliasTemplate(Inst);
1682 if (PrevAliasTemplate)
1683 Inst->setPreviousDecl(PrevAliasTemplate);
1684
1685 Inst->setAccess(D->getAccess());
1686
1687 if (!PrevAliasTemplate)
1688 Inst->setInstantiatedFromMemberTemplate(D);
1689
1690 return Inst;
1691}
1692
1693Decl *
1694TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1695 Decl *Inst = InstantiateTypeAliasTemplateDecl(D);
1696 if (Inst)
1697 Owner->addDecl(D: Inst);
1698
1699 return Inst;
1700}
1701
1702Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1703 auto *NewBD = BindingDecl::Create(C&: SemaRef.Context, DC: Owner, IdLoc: D->getLocation(),
1704 Id: D->getIdentifier(), T: D->getType());
1705 NewBD->setReferenced(D->isReferenced());
1706 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: NewBD);
1707
1708 return NewBD;
1709}
1710
1711Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1712 // Transform the bindings first.
1713 // The transformed DD will have all of the concrete BindingDecls.
1714 SmallVector<BindingDecl*, 16> NewBindings;
1715 BindingDecl *OldBindingPack = nullptr;
1716 for (auto *OldBD : D->bindings()) {
1717 Expr *BindingExpr = OldBD->getBinding();
1718 if (isa_and_present<FunctionParmPackExpr>(Val: BindingExpr)) {
1719 // We have a resolved pack.
1720 assert(!OldBindingPack && "no more than one pack is allowed");
1721 OldBindingPack = OldBD;
1722 }
1723 NewBindings.push_back(Elt: cast<BindingDecl>(Val: VisitBindingDecl(D: OldBD)));
1724 }
1725 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1726
1727 auto *NewDD = cast_if_present<DecompositionDecl>(
1728 Val: VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, Bindings: &NewBindingArray));
1729
1730 if (!NewDD || NewDD->isInvalidDecl()) {
1731 for (auto *NewBD : NewBindings)
1732 NewBD->setInvalidDecl();
1733 } else if (OldBindingPack) {
1734 // Mark the bindings in the pack as instantiated.
1735 auto Bindings = NewDD->bindings();
1736 BindingDecl *NewBindingPack = *llvm::find_if(
1737 Range&: Bindings, P: [](BindingDecl *D) -> bool { return D->isParameterPack(); });
1738 assert(NewBindingPack != nullptr && "new bindings should also have a pack");
1739 llvm::ArrayRef<BindingDecl *> OldDecls =
1740 OldBindingPack->getBindingPackDecls();
1741 llvm::ArrayRef<BindingDecl *> NewDecls =
1742 NewBindingPack->getBindingPackDecls();
1743 assert(OldDecls.size() == NewDecls.size());
1744 for (unsigned I = 0; I < OldDecls.size(); I++)
1745 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D: OldDecls[I],
1746 Inst: NewDecls[I]);
1747 }
1748
1749 return NewDD;
1750}
1751
1752Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
1753 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1754}
1755
1756Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
1757 bool InstantiatingVarTemplate,
1758 ArrayRef<BindingDecl*> *Bindings) {
1759
1760 // Do substitution on the type of the declaration
1761 TypeSourceInfo *TSI = SemaRef.SubstType(
1762 T: D->getTypeSourceInfo(), TemplateArgs, Loc: D->getTypeSpecStartLoc(),
1763 Entity: D->getDeclName(), /*AllowDeducedTST*/ true);
1764 bool Invalid = false;
1765 if (!TSI) {
1766 if (!InstantiatingVarTemplate)
1767 return nullptr;
1768 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T: SemaRef.Context.IntTy,
1769 Loc: D->getLocation());
1770 Invalid = true;
1771 } else if (TSI->getType()->isFunctionType()) {
1772 SemaRef.Diag(Loc: D->getLocation(), DiagID: diag::err_variable_instantiates_to_function)
1773 << D->isStaticDataMember() << TSI->getType();
1774 if (!InstantiatingVarTemplate)
1775 return nullptr;
1776 Invalid = true;
1777 }
1778
1779 DeclContext *DC = Owner;
1780 if (D->isLocalExternDecl())
1781 SemaRef.adjustContextForLocalExternDecl(DC);
1782
1783 // Build the instantiated declaration.
1784 VarDecl *Var;
1785 if (Bindings)
1786 Var = DecompositionDecl::Create(
1787 C&: SemaRef.Context, DC, StartLoc: D->getInnerLocStart(), LSquareLoc: D->getLocation(),
1788 RSquareLoc: D->getEndLoc(), T: TSI->getType(), TInfo: TSI, S: D->getStorageClass(), Bindings: *Bindings);
1789 else
1790 Var = VarDecl::Create(C&: SemaRef.Context, DC, StartLoc: D->getInnerLocStart(),
1791 IdLoc: D->getLocation(), Id: D->getIdentifier(), T: TSI->getType(),
1792 TInfo: TSI, S: D->getStorageClass());
1793
1794 // In ARC, infer 'retaining' for variables of retainable type.
1795 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1796 SemaRef.ObjC().inferObjCARCLifetime(decl: Var))
1797 Var->setInvalidDecl();
1798
1799 if (SemaRef.getLangOpts().OpenCL)
1800 SemaRef.deduceOpenCLAddressSpace(decl: Var);
1801
1802 // Substitute the nested name specifier, if any.
1803 if (SubstQualifier(OldDecl: D, NewDecl: Var))
1804 return nullptr;
1805
1806 SemaRef.BuildVariableInstantiation(NewVar: Var, OldVar: D, TemplateArgs, LateAttrs, Owner,
1807 StartingScope, InstantiatingVarTemplate);
1808 if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1809 QualType RT;
1810 if (auto *F = dyn_cast<FunctionDecl>(Val: DC))
1811 RT = F->getReturnType();
1812 else if (isa<BlockDecl>(Val: DC))
1813 RT = cast<FunctionType>(Val&: SemaRef.getCurBlock()->FunctionType)
1814 ->getReturnType();
1815 else
1816 llvm_unreachable("Unknown context type");
1817
1818 // This is the last chance we have of checking copy elision eligibility
1819 // for functions in dependent contexts. The sema actions for building
1820 // the return statement during template instantiation will have no effect
1821 // regarding copy elision, since NRVO propagation runs on the scope exit
1822 // actions, and these are not run on instantiation.
1823 // This might run through some VarDecls which were returned from non-taken
1824 // 'if constexpr' branches, and these will end up being constructed on the
1825 // return slot even if they will never be returned, as a sort of accidental
1826 // 'optimization'. Notably, functions with 'auto' return types won't have it
1827 // deduced by this point. Coupled with the limitation described
1828 // previously, this makes it very hard to support copy elision for these.
1829 Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(VD: Var);
1830 bool NRVO = SemaRef.getCopyElisionCandidate(Info, ReturnType: RT) != nullptr;
1831 Var->setNRVOVariable(NRVO);
1832 }
1833
1834 Var->setImplicit(D->isImplicit());
1835
1836 if (Var->isStaticLocal())
1837 SemaRef.CheckStaticLocalForDllExport(VD: Var);
1838
1839 if (Var->getTLSKind())
1840 SemaRef.CheckThreadLocalForLargeAlignment(VD: Var);
1841
1842 if (SemaRef.getLangOpts().OpenACC)
1843 SemaRef.OpenACC().ActOnVariableDeclarator(VD: Var);
1844
1845 if (Invalid)
1846 Var->setInvalidDecl();
1847
1848 return Var;
1849}
1850
1851Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1852 AccessSpecDecl* AD
1853 = AccessSpecDecl::Create(C&: SemaRef.Context, AS: D->getAccess(), DC: Owner,
1854 ASLoc: D->getAccessSpecifierLoc(), ColonLoc: D->getColonLoc());
1855 Owner->addHiddenDecl(D: AD);
1856 return AD;
1857}
1858
1859Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1860 bool Invalid = false;
1861 TypeSourceInfo *TSI = D->getTypeSourceInfo();
1862 if (TSI->getType()->isInstantiationDependentType() ||
1863 TSI->getType()->isVariablyModifiedType()) {
1864 TSI = SemaRef.SubstType(T: TSI, TemplateArgs, Loc: D->getLocation(),
1865 Entity: D->getDeclName());
1866 if (!TSI) {
1867 TSI = D->getTypeSourceInfo();
1868 Invalid = true;
1869 } else if (TSI->getType()->isFunctionType()) {
1870 // C++ [temp.arg.type]p3:
1871 // If a declaration acquires a function type through a type
1872 // dependent on a template-parameter and this causes a
1873 // declaration that does not use the syntactic form of a
1874 // function declarator to have function type, the program is
1875 // ill-formed.
1876 SemaRef.Diag(Loc: D->getLocation(), DiagID: diag::err_field_instantiates_to_function)
1877 << TSI->getType();
1878 Invalid = true;
1879 }
1880 } else {
1881 SemaRef.MarkDeclarationsReferencedInType(Loc: D->getLocation(), T: TSI->getType());
1882 }
1883
1884 Expr *BitWidth = D->getBitWidth();
1885 if (Invalid)
1886 BitWidth = nullptr;
1887 else if (BitWidth) {
1888 // The bit-width expression is a constant expression.
1889 EnterExpressionEvaluationContext Unevaluated(
1890 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1891
1892 ExprResult InstantiatedBitWidth
1893 = SemaRef.SubstExpr(E: BitWidth, TemplateArgs);
1894 if (InstantiatedBitWidth.isInvalid()) {
1895 Invalid = true;
1896 BitWidth = nullptr;
1897 } else
1898 BitWidth = InstantiatedBitWidth.getAs<Expr>();
1899 }
1900
1901 FieldDecl *Field = SemaRef.CheckFieldDecl(
1902 Name: D->getDeclName(), T: TSI->getType(), TInfo: TSI, Record: cast<RecordDecl>(Val: Owner),
1903 Loc: D->getLocation(), Mutable: D->isMutable(), BitfieldWidth: BitWidth, InitStyle: D->getInClassInitStyle(),
1904 TSSL: D->getInnerLocStart(), AS: D->getAccess(), PrevDecl: nullptr);
1905 if (!Field) {
1906 cast<Decl>(Val: Owner)->setInvalidDecl();
1907 return nullptr;
1908 }
1909
1910 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: D, New: Field, LateAttrs, OuterMostScope: StartingScope);
1911
1912 if (Field->hasAttrs())
1913 SemaRef.CheckAlignasUnderalignment(D: Field);
1914
1915 if (Invalid)
1916 Field->setInvalidDecl();
1917
1918 if (!Field->getDeclName() || Field->isPlaceholderVar(LangOpts: SemaRef.getLangOpts())) {
1919 // Keep track of where this decl came from.
1920 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Inst: Field, Tmpl: D);
1921 }
1922 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Val: Field->getDeclContext())) {
1923 if (Parent->isAnonymousStructOrUnion() &&
1924 Parent->getRedeclContext()->isFunctionOrMethod())
1925 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: Field);
1926 }
1927
1928 Field->setImplicit(D->isImplicit());
1929 Field->setAccess(D->getAccess());
1930 Owner->addDecl(D: Field);
1931
1932 return Field;
1933}
1934
1935Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1936 bool Invalid = false;
1937 TypeSourceInfo *TSI = D->getTypeSourceInfo();
1938
1939 if (TSI->getType()->isVariablyModifiedType()) {
1940 SemaRef.Diag(Loc: D->getLocation(), DiagID: diag::err_property_is_variably_modified)
1941 << D;
1942 Invalid = true;
1943 } else if (TSI->getType()->isInstantiationDependentType()) {
1944 TSI = SemaRef.SubstType(T: TSI, TemplateArgs, Loc: D->getLocation(),
1945 Entity: D->getDeclName());
1946 if (!TSI) {
1947 TSI = D->getTypeSourceInfo();
1948 Invalid = true;
1949 } else if (TSI->getType()->isFunctionType()) {
1950 // C++ [temp.arg.type]p3:
1951 // If a declaration acquires a function type through a type
1952 // dependent on a template-parameter and this causes a
1953 // declaration that does not use the syntactic form of a
1954 // function declarator to have function type, the program is
1955 // ill-formed.
1956 SemaRef.Diag(Loc: D->getLocation(), DiagID: diag::err_field_instantiates_to_function)
1957 << TSI->getType();
1958 Invalid = true;
1959 }
1960 } else {
1961 SemaRef.MarkDeclarationsReferencedInType(Loc: D->getLocation(), T: TSI->getType());
1962 }
1963
1964 MSPropertyDecl *Property = MSPropertyDecl::Create(
1965 C&: SemaRef.Context, DC: Owner, L: D->getLocation(), N: D->getDeclName(),
1966 T: TSI->getType(), TInfo: TSI, StartL: D->getBeginLoc(), Getter: D->getGetterId(),
1967 Setter: D->getSetterId());
1968
1969 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: D, New: Property, LateAttrs,
1970 OuterMostScope: StartingScope);
1971
1972 if (Invalid)
1973 Property->setInvalidDecl();
1974
1975 Property->setAccess(D->getAccess());
1976 Owner->addDecl(D: Property);
1977
1978 return Property;
1979}
1980
1981Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1982 NamedDecl **NamedChain =
1983 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1984
1985 int i = 0;
1986 for (auto *PI : D->chain()) {
1987 NamedDecl *Next = SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), D: PI,
1988 TemplateArgs);
1989 if (!Next)
1990 return nullptr;
1991
1992 NamedChain[i++] = Next;
1993 }
1994
1995 QualType T = cast<FieldDecl>(Val: NamedChain[i-1])->getType();
1996 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1997 C&: SemaRef.Context, DC: Owner, L: D->getLocation(), Id: D->getIdentifier(), T,
1998 CH: {NamedChain, D->getChainingSize()});
1999
2000 for (const auto *Attr : D->attrs())
2001 IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context));
2002
2003 IndirectField->setImplicit(D->isImplicit());
2004 IndirectField->setAccess(D->getAccess());
2005 Owner->addDecl(D: IndirectField);
2006 return IndirectField;
2007}
2008
2009static std::optional<TemplateName>
2010LookupFriendTemplateName(Sema &SemaRef, NestedNameSpecifierLoc QualifierLoc,
2011 DeclarationName Name, SourceLocation NameLoc,
2012 bool HasTemplateKeyword, bool RequireClassTemplate) {
2013 if (!QualifierLoc)
2014 return TemplateName();
2015
2016 CXXScopeSpec SS;
2017 SS.Adopt(Other: QualifierLoc);
2018
2019 DeclContext *DC = SemaRef.computeDeclContext(SS, /*EnteringContext=*/true);
2020 if (!DC) {
2021 if (QualifierLoc.getNestedNameSpecifier().isDependent())
2022 return TemplateName();
2023 return std::nullopt;
2024 }
2025
2026 bool IsDependentContext = DC->isDependentContext();
2027 if (!IsDependentContext && SemaRef.RequireCompleteDeclContext(SS, DC))
2028 return std::nullopt;
2029
2030 LookupResult Result(SemaRef, Name, NameLoc, Sema::LookupOrdinaryName,
2031 SemaRef.forRedeclarationInCurContext());
2032 if (!SemaRef.LookupQualifiedName(R&: Result, LookupCtx: DC)) {
2033 if (RequireClassTemplate && !IsDependentContext) {
2034 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_no_member_template)
2035 << Name << DC << QualifierLoc.getSourceRange();
2036 return std::nullopt;
2037 }
2038 return TemplateName();
2039 }
2040
2041 if (Result.isAmbiguous())
2042 return std::nullopt;
2043
2044 auto *CTD = Result.getAsSingle<ClassTemplateDecl>();
2045 if (!CTD) {
2046 if (RequireClassTemplate && !IsDependentContext) {
2047 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
2048 SemaRef.Diag(
2049 Loc: Result.getRepresentativeDecl()->getUnderlyingDecl()->getLocation(),
2050 DiagID: diag::note_previous_definition);
2051 return std::nullopt;
2052 }
2053 return TemplateName();
2054 }
2055
2056 auto *FoundUsingShadow =
2057 dyn_cast<UsingShadowDecl>(Val: Result.getRepresentativeDecl());
2058
2059 return SemaRef.Context.getQualifiedTemplateName(
2060 Qualifier: QualifierLoc.getNestedNameSpecifier(), TemplateKeyword: HasTemplateKeyword,
2061 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(CTD));
2062}
2063
2064TypeSourceInfo *
2065Sema::SubstFriendType(TypeSourceInfo *TSI,
2066 const MultiLevelTemplateArgumentList &TemplateArgs,
2067 SourceLocation Loc, DeclarationName Entity) {
2068 TemplateSpecializationTypeLoc TSTL =
2069 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>();
2070 NestedNameSpecifierLoc QualifierLoc =
2071 TSTL ? TSTL.getQualifierLoc() : NestedNameSpecifierLoc();
2072 if (!TSTL || !QualifierLoc ||
2073 !QualifierLoc.getNestedNameSpecifier().isDependent())
2074 return SubstType(T: TSI, TemplateArgs, Loc, Entity);
2075
2076 const auto *FriendTST = TSTL.getTypePtr();
2077 auto *FriendCTD = dyn_cast_or_null<ClassTemplateDecl>(
2078 Val: FriendTST->getTemplateName().getAsTemplateDecl());
2079 if (!FriendCTD)
2080 return SubstType(T: TSI, TemplateArgs, Loc, Entity);
2081
2082 QualifierLoc = SubstNestedNameSpecifierLoc(NNS: QualifierLoc, TemplateArgs);
2083 if (!QualifierLoc)
2084 return nullptr;
2085
2086 std::optional<TemplateName> InstTemplate = LookupFriendTemplateName(
2087 SemaRef&: *this, QualifierLoc, Name: FriendCTD->getDeclName(), NameLoc: TSTL.getTemplateNameLoc(),
2088 HasTemplateKeyword: TSTL.getTemplateKeywordLoc().isValid(),
2089 /*RequireClassTemplate=*/false);
2090 if (!InstTemplate)
2091 return nullptr;
2092 if (InstTemplate->isNull())
2093 return SubstType(T: TSI, TemplateArgs, Loc, Entity);
2094
2095 SmallVector<TemplateArgumentLoc, 4> FriendArgLocs;
2096 for (unsigned I = 0, N = TSTL.getNumArgs(); I != N; ++I)
2097 FriendArgLocs.push_back(Elt: TSTL.getArgLoc(i: I));
2098
2099 TemplateArgumentListInfo InstArgs(TSTL.getLAngleLoc(), TSTL.getRAngleLoc());
2100 if (SubstTemplateArguments(Args: FriendArgLocs, TemplateArgs, Outputs&: InstArgs))
2101 return nullptr;
2102
2103 QualType InstTy =
2104 CheckTemplateIdType(Keyword: FriendTST->getKeyword(), Template: *InstTemplate,
2105 TemplateLoc: TSTL.getTemplateNameLoc(), TemplateArgs&: InstArgs,
2106 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
2107 if (InstTy.isNull())
2108 return nullptr;
2109
2110 TypeLocBuilder TLB;
2111 TLB.push<TemplateSpecializationTypeLoc>(T: InstTy).set(
2112 ElaboratedKeywordLoc: TSTL.getElaboratedKeywordLoc(), QualifierLoc,
2113 TemplateKeywordLoc: TSTL.getTemplateKeywordLoc(), NameLoc: TSTL.getTemplateNameLoc(), TAL: InstArgs);
2114 return TLB.getTypeSourceInfo(Context, T: InstTy);
2115}
2116
2117struct SubstitutedFriend {
2118 TypeSourceInfo *TypeInfo = nullptr;
2119 TemplateName Template;
2120
2121 bool empty() const { return !TypeInfo && Template.isNull(); }
2122};
2123
2124static std::optional<SubstitutedFriend>
2125SubstFriendTemplateType(Sema &SemaRef, TypeSourceInfo *TSI,
2126 TemplateName FriendTemplate,
2127 const MultiLevelTemplateArgumentList &TemplateArgs,
2128 SourceLocation Loc, DeclarationName Entity) {
2129 NestedNameSpecifierLoc QualifierLoc = TSI->getTypeLoc().getPrefix();
2130 NestedNameSpecifierLoc InstQualifierLoc = QualifierLoc;
2131 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier().isDependent()) {
2132 InstQualifierLoc =
2133 SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc, TemplateArgs);
2134 if (!InstQualifierLoc ||
2135 SemaRef.CheckDependentFriend(Loc, NNSLoc: InstQualifierLoc, /*TPLs=*/{},
2136 /*IsInstantiation=*/true))
2137 return std::nullopt;
2138 }
2139
2140 TemplateName InstFriendTemplate;
2141 if (!FriendTemplate.isNull()) {
2142 auto DNTL = TSI->getTypeLoc().getAs<DependentNameTypeLoc>();
2143 assert(DNTL && "friend class template must have a dependent name type");
2144
2145 std::optional<TemplateName> InstTemplate = LookupFriendTemplateName(
2146 SemaRef, QualifierLoc: InstQualifierLoc, Name: DNTL.getTypePtr()->getIdentifier(),
2147 NameLoc: DNTL.getNameLoc(), /*HasTemplateKeyword=*/false,
2148 /*RequireClassTemplate=*/true);
2149 if (!InstTemplate)
2150 return std::nullopt;
2151 if (!InstTemplate->isNull())
2152 return SubstitutedFriend{.TypeInfo: nullptr, .Template: *InstTemplate};
2153
2154 auto *DTN = FriendTemplate.getAsDependentTemplateName();
2155 assert(DTN && "unresolved friend template must have a dependent name");
2156 InstFriendTemplate = SemaRef.Context.getDependentTemplateName(
2157 Name: {InstQualifierLoc.getNestedNameSpecifier(), DTN->getName(),
2158 DTN->hasTemplateKeyword()});
2159 }
2160
2161 TypeSourceInfo *InstType =
2162 SemaRef.SubstFriendType(TSI, TemplateArgs, Loc, Entity);
2163 if (!InstType)
2164 return std::nullopt;
2165 return SubstitutedFriend{.TypeInfo: InstType, .Template: InstFriendTemplate};
2166}
2167
2168bool TemplateDeclInstantiator::InstantiateFriendPackExpansion(FriendDecl *D) {
2169 TypeSourceInfo *TSI = D->getFriendType();
2170 assert(TSI && "friend pack expansion must name a type");
2171
2172 const auto *FTD = dyn_cast<FriendTemplateDecl>(Val: D);
2173 ArrayRef<TemplateParameterList *> TPLs;
2174 if (FTD)
2175 TPLs = FTD->getTemplateParameterLists();
2176
2177 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2178 SemaRef.collectUnexpandedParameterPacks(TL: TSI->getTypeLoc(), Unexpanded);
2179 assert(!Unexpanded.empty() && "Pack expansion without packs");
2180
2181 bool ShouldExpand = true;
2182 bool RetainExpansion = false;
2183 UnsignedOrNone NumExpansions = std::nullopt;
2184 if (SemaRef.CheckParameterPacksForExpansion(
2185 EllipsisLoc: D->getEllipsisLoc(), PatternRange: D->getSourceRange(), Unexpanded, TemplateArgs,
2186 /*FailOnPackProducingTemplates=*/true, ShouldExpand, RetainExpansion,
2187 NumExpansions))
2188 return true;
2189
2190 assert(!RetainExpansion &&
2191 "should never retain an expansion for a friend declaration");
2192
2193 if (!ShouldExpand)
2194 return false;
2195
2196 for (unsigned I = 0; I != *NumExpansions; I++) {
2197 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
2198 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
2199 SmallVector<TemplateParameterList *, 1> InstTPLs;
2200 if (SubstTemplateParameterLists(TPLs, InstTPLs))
2201 return true;
2202
2203 std::optional<SubstitutedFriend> InstFriend;
2204 if (FTD)
2205 InstFriend = SubstFriendTemplateType(
2206 SemaRef, TSI, FriendTemplate: FTD->getFriendTemplateName(), TemplateArgs,
2207 Loc: D->getEllipsisLoc(), Entity: DeclarationName());
2208 else if (TypeSourceInfo *InstType = SemaRef.SubstFriendType(
2209 TSI, TemplateArgs, Loc: D->getEllipsisLoc(), Entity: DeclarationName()))
2210 InstFriend = SubstitutedFriend{.TypeInfo: InstType, .Template: {}};
2211 if (!InstFriend || InstFriend->empty())
2212 return true;
2213
2214 FriendDecl *FD;
2215 if (FTD) {
2216 FriendDecl::FriendUnion ToFriend =
2217 InstFriend->TypeInfo ? FriendDecl::FriendUnion(InstFriend->TypeInfo)
2218 : FriendDecl::FriendUnion();
2219 FD = FriendTemplateDecl::Create(Context&: SemaRef.Context, DC: Owner, Loc: D->getLocation(),
2220 Friend: ToFriend, FriendLoc: D->getFriendLoc(), FriendTPLists: InstTPLs,
2221 /*EllipsisLoc=*/{}, Template: InstFriend->Template);
2222 } else {
2223 assert(InstTPLs.empty() && "unexpected template parameter lists");
2224 assert(InstFriend->Template.isNull() &&
2225 "non-template friend resolved to a class template");
2226 FD = FriendDecl::Create(C&: SemaRef.Context, DC: Owner, L: D->getLocation(),
2227 Friend: InstFriend->TypeInfo, FriendL: D->getFriendLoc());
2228 }
2229
2230 FD->setAccess(AS_public);
2231 Owner->addDecl(D: FD);
2232 }
2233
2234 return true;
2235}
2236
2237Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
2238 if (TypeSourceInfo *Ty = D->getFriendType()) {
2239 if (D->isPackExpansion() && InstantiateFriendPackExpansion(D))
2240 return nullptr;
2241
2242 TypeSourceInfo *InstTy = SemaRef.SubstFriendType(
2243 TSI: Ty, TemplateArgs, Loc: D->getLocation(), Entity: DeclarationName());
2244 if (!InstTy)
2245 return nullptr;
2246
2247 FriendDecl *FD = FriendDecl::Create(
2248 C&: SemaRef.Context, DC: Owner, L: D->getLocation(), Friend: InstTy, FriendL: D->getFriendLoc());
2249 FD->setAccess(AS_public);
2250 Owner->addDecl(D: FD);
2251 return FD;
2252 }
2253
2254 NamedDecl *ND = D->getFriendDecl();
2255 assert(ND && "friend decl must be a decl or a type!");
2256
2257 // All of the Visit implementations for the various potential friend
2258 // declarations have to be carefully written to work for friend
2259 // objects, with the most important detail being that the target
2260 // decl should almost certainly not be placed in Owner.
2261 Decl *NewND = Visit(D: ND);
2262 if (!NewND) return nullptr;
2263
2264 FriendDecl *FD =
2265 FriendDecl::Create(C&: SemaRef.Context, DC: Owner, L: D->getLocation(),
2266 Friend: cast<NamedDecl>(Val: NewND), FriendL: D->getFriendLoc());
2267 FD->setAccess(AS_public);
2268 Owner->addDecl(D: FD);
2269 return FD;
2270}
2271
2272Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
2273 Expr *AssertExpr = D->getAssertExpr();
2274
2275 // The expression in a static assertion is a constant expression.
2276 EnterExpressionEvaluationContext Unevaluated(
2277 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2278
2279 ExprResult InstantiatedAssertExpr
2280 = SemaRef.SubstExpr(E: AssertExpr, TemplateArgs);
2281 if (InstantiatedAssertExpr.isInvalid())
2282 return nullptr;
2283
2284 ExprResult InstantiatedMessageExpr =
2285 SemaRef.SubstExpr(E: D->getMessage(), TemplateArgs);
2286 if (InstantiatedMessageExpr.isInvalid())
2287 return nullptr;
2288
2289 return SemaRef.BuildStaticAssertDeclaration(
2290 StaticAssertLoc: D->getLocation(), AssertExpr: InstantiatedAssertExpr.get(),
2291 AssertMessageExpr: InstantiatedMessageExpr.get(), RParenLoc: D->getRParenLoc(), Failed: D->isFailed());
2292}
2293
2294Decl *TemplateDeclInstantiator::VisitExplicitInstantiationDecl(
2295 ExplicitInstantiationDecl *D) {
2296 // ExplicitInstantiationDecl is a source-info-only node and should not
2297 // appear inside a template pattern. Nothing to instantiate.
2298 llvm_unreachable("ExplicitInstantiationDecl should not be instantiated");
2299}
2300
2301Decl *TemplateDeclInstantiator::VisitCXXExpansionStmtDecl(
2302 CXXExpansionStmtDecl *OldESD) {
2303 Decl *Index = VisitNonTypeTemplateParmDecl(D: OldESD->getIndexTemplateParm());
2304 CXXExpansionStmtDecl *NewESD = SemaRef.BuildCXXExpansionStmtDecl(
2305 Ctx: Owner, TemplateKWLoc: OldESD->getBeginLoc(), NTTP: cast<NonTypeTemplateParmDecl>(Val: Index));
2306 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D: OldESD, Inst: NewESD);
2307
2308 // If this was already expanded, only instantiate the expansion and
2309 // don't touch the unexpanded expansion statement.
2310 if (CXXExpansionStmtInstantiation *OldInst = OldESD->getInstantiations()) {
2311 StmtResult NewInst = SemaRef.SubstStmt(S: OldInst, TemplateArgs);
2312 if (NewInst.isInvalid())
2313 return nullptr;
2314
2315 NewESD->setInstantiations(NewInst.getAs<CXXExpansionStmtInstantiation>());
2316 NewESD->setExpansionPattern(OldESD->getExpansionPattern());
2317 return NewESD;
2318 }
2319
2320 // Enter the scope of this expansion statement; don't do this if we've
2321 // already expanded it, as in that case we no longer want to treat its
2322 // content as dependent.
2323 Sema::ContextRAII Context(SemaRef, NewESD, /*NewThis=*/false);
2324
2325 StmtResult Expansion =
2326 SemaRef.SubstStmt(S: OldESD->getExpansionPattern(), TemplateArgs);
2327 if (Expansion.isInvalid())
2328 return nullptr;
2329
2330 // The code that handles CXXExpansionStmtPattern takes care of calling
2331 // setInstantiation() on the ESD if there was an expansion.
2332 NewESD->setExpansionPattern(cast<CXXExpansionStmtPattern>(Val: Expansion.get()));
2333 return NewESD;
2334}
2335
2336Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
2337 EnumDecl *PrevDecl = nullptr;
2338 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2339 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(Loc: D->getLocation(),
2340 D: PatternPrev,
2341 TemplateArgs);
2342 if (!Prev) return nullptr;
2343 PrevDecl = cast<EnumDecl>(Val: Prev);
2344 }
2345
2346 EnumDecl *Enum =
2347 EnumDecl::Create(C&: SemaRef.Context, DC: Owner, StartLoc: D->getBeginLoc(),
2348 IdLoc: D->getLocation(), Id: D->getIdentifier(), PrevDecl,
2349 IsScoped: D->isScoped(), IsScopedUsingClassTag: D->isScopedUsingClassTag(), IsFixed: D->isFixed());
2350 if (D->isFixed()) {
2351 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
2352 // If we have type source information for the underlying type, it means it
2353 // has been explicitly set by the user. Perform substitution on it before
2354 // moving on.
2355 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
2356 TypeSourceInfo *NewTI = SemaRef.SubstType(T: TI, TemplateArgs, Loc: UnderlyingLoc,
2357 Entity: DeclarationName());
2358 if (!NewTI || SemaRef.CheckEnumUnderlyingType(TI: NewTI))
2359 Enum->setIntegerType(SemaRef.Context.IntTy);
2360 else {
2361 // If the underlying type is atomic, we need to adjust the type before
2362 // continuing. See C23 6.7.3.3p5 and Sema::ActOnTag(). FIXME: same as
2363 // within ActOnTag(), it would be nice to have an easy way to get a
2364 // derived TypeSourceInfo which strips qualifiers including the weird
2365 // ones like _Atomic where it forms a different type.
2366 if (NewTI->getType()->isAtomicType())
2367 Enum->setIntegerType(NewTI->getType().getAtomicUnqualifiedType());
2368 else
2369 Enum->setIntegerTypeSourceInfo(NewTI);
2370 }
2371
2372 // C++23 [conv.prom]p4
2373 // if integral promotion can be applied to its underlying type, a prvalue
2374 // of an unscoped enumeration type whose underlying type is fixed can also
2375 // be converted to a prvalue of the promoted underlying type.
2376 //
2377 // FIXME: that logic is already implemented in ActOnEnumBody, factor out
2378 // into (Re)BuildEnumBody.
2379 QualType UnderlyingType = Enum->getIntegerType();
2380 Enum->setPromotionType(
2381 SemaRef.Context.isPromotableIntegerType(T: UnderlyingType)
2382 ? SemaRef.Context.getPromotedIntegerType(PromotableType: UnderlyingType)
2383 : UnderlyingType);
2384 } else {
2385 assert(!D->getIntegerType()->isDependentType()
2386 && "Dependent type without type source info");
2387 Enum->setIntegerType(D->getIntegerType());
2388 }
2389 }
2390
2391 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: D, New: Enum);
2392
2393 Enum->setInstantiationOfMemberEnum(ED: D, TSK: TSK_ImplicitInstantiation);
2394 Enum->setAccess(D->getAccess());
2395 // Forward the mangling number from the template to the instantiated decl.
2396 SemaRef.Context.setManglingNumber(ND: Enum, Number: SemaRef.Context.getManglingNumber(ND: D));
2397 // See if the old tag was defined along with a declarator.
2398 // If it did, mark the new tag as being associated with that declarator.
2399 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(TD: D))
2400 SemaRef.Context.addDeclaratorForUnnamedTagDecl(TD: Enum, DD);
2401 // See if the old tag was defined along with a typedef.
2402 // If it did, mark the new tag as being associated with that typedef.
2403 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(TD: D))
2404 SemaRef.Context.addTypedefNameForUnnamedTagDecl(TD: Enum, TND);
2405 if (SubstQualifier(OldDecl: D, NewDecl: Enum)) return nullptr;
2406 Owner->addDecl(D: Enum);
2407
2408 EnumDecl *Def = D->getDefinition();
2409 if (Def && Def != D) {
2410 // If this is an out-of-line definition of an enum member template, check
2411 // that the underlying types match in the instantiation of both
2412 // declarations.
2413 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
2414 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
2415 QualType DefnUnderlying =
2416 SemaRef.SubstType(T: TI->getType(), TemplateArgs,
2417 Loc: UnderlyingLoc, Entity: DeclarationName());
2418 SemaRef.CheckEnumRedeclaration(EnumLoc: Def->getLocation(), IsScoped: Def->isScoped(),
2419 EnumUnderlyingTy: DefnUnderlying, /*IsFixed=*/true, Prev: Enum);
2420 }
2421 }
2422
2423 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2424 // specialization causes the implicit instantiation of the declarations, but
2425 // not the definitions of scoped member enumerations.
2426 //
2427 // DR1484 clarifies that enumeration definitions inside a template
2428 // declaration aren't considered entities that can be separately instantiated
2429 // from the rest of the entity they are declared inside.
2430 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
2431 // Prevent redundant instantiation of the enumerator-definition if the
2432 // definition has already been instantiated due to a prior
2433 // opaque-enum-declaration.
2434 if (PrevDecl == nullptr) {
2435 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: Enum);
2436 InstantiateEnumDefinition(Enum, Pattern: Def);
2437 }
2438 }
2439
2440 return Enum;
2441}
2442
2443void TemplateDeclInstantiator::InstantiateEnumDefinition(
2444 EnumDecl *Enum, EnumDecl *Pattern) {
2445 Enum->startDefinition();
2446
2447 // Update the location to refer to the definition.
2448 Enum->setLocation(Pattern->getLocation());
2449
2450 SmallVector<Decl*, 4> Enumerators;
2451
2452 EnumConstantDecl *LastEnumConst = nullptr;
2453 for (auto *EC : Pattern->enumerators()) {
2454 // The specified value for the enumerator.
2455 ExprResult Value((Expr *)nullptr);
2456 if (Expr *UninstValue = EC->getInitExpr()) {
2457 // The enumerator's value expression is a constant expression.
2458 EnterExpressionEvaluationContext Unevaluated(
2459 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2460
2461 Value = SemaRef.SubstExpr(E: UninstValue, TemplateArgs);
2462 }
2463
2464 // Drop the initial value and continue.
2465 bool isInvalid = false;
2466 if (Value.isInvalid()) {
2467 Value = nullptr;
2468 isInvalid = true;
2469 }
2470
2471 EnumConstantDecl *EnumConst
2472 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
2473 IdLoc: EC->getLocation(), Id: EC->getIdentifier(),
2474 val: Value.get());
2475
2476 if (isInvalid) {
2477 if (EnumConst)
2478 EnumConst->setInvalidDecl();
2479 Enum->setInvalidDecl();
2480 }
2481
2482 if (EnumConst) {
2483 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: EC, New: EnumConst);
2484
2485 EnumConst->setAccess(Enum->getAccess());
2486 Enum->addDecl(D: EnumConst);
2487 Enumerators.push_back(Elt: EnumConst);
2488 LastEnumConst = EnumConst;
2489
2490 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
2491 !Enum->isScoped()) {
2492 // If the enumeration is within a function or method, record the enum
2493 // constant as a local.
2494 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D: EC, Inst: EnumConst);
2495 }
2496 }
2497 }
2498
2499 SemaRef.ActOnEnumBody(EnumLoc: Enum->getLocation(), BraceRange: Enum->getBraceRange(), EnumDecl: Enum,
2500 Elements: Enumerators, S: nullptr, Attr: ParsedAttributesView());
2501}
2502
2503Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
2504 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
2505}
2506
2507Decl *
2508TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2509 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
2510}
2511
2512Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2513 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2514
2515 // Create a local instantiation scope for this class template, which
2516 // will contain the instantiations of the template parameters.
2517 LocalInstantiationScope Scope(SemaRef);
2518 TemplateParameterList *TempParams = D->getTemplateParameters();
2519 TemplateParameterList *InstParams = SubstTemplateParams(List: TempParams);
2520 if (!InstParams)
2521 return nullptr;
2522
2523 CXXRecordDecl *Pattern = D->getTemplatedDecl();
2524
2525 // Instantiate the qualifier. We have to do this first in case
2526 // we're a friend declaration, because if we are then we need to put
2527 // the new declaration in the appropriate context.
2528 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
2529 if (QualifierLoc) {
2530 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc,
2531 TemplateArgs);
2532 if (!QualifierLoc)
2533 return nullptr;
2534 }
2535
2536 CXXRecordDecl *PrevDecl = nullptr;
2537 ClassTemplateDecl *PrevClassTemplate = nullptr;
2538
2539 if (!isFriend && getPreviousDeclForInstantiation(D: Pattern)) {
2540 DeclContext::lookup_result Found = Owner->lookup(Name: Pattern->getDeclName());
2541 if (!Found.empty()) {
2542 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Val: Found.front());
2543 if (PrevClassTemplate)
2544 PrevDecl = PrevClassTemplate->getTemplatedDecl();
2545 }
2546 }
2547
2548 // If this isn't a friend, then it's a member template, in which
2549 // case we just want to build the instantiation in the
2550 // specialization. If it is a friend, we want to build it in
2551 // the appropriate context.
2552 DeclContext *DC = Owner;
2553 if (isFriend) {
2554 if (QualifierLoc) {
2555 CXXScopeSpec SS;
2556 SS.Adopt(Other: QualifierLoc);
2557 DC = SemaRef.computeDeclContext(SS);
2558 if (!DC) return nullptr;
2559 } else {
2560 DC = SemaRef.FindInstantiatedContext(Loc: Pattern->getLocation(),
2561 DC: Pattern->getDeclContext(),
2562 TemplateArgs);
2563 }
2564
2565 // Look for a previous declaration of the template in the owning
2566 // context.
2567 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
2568 Sema::LookupOrdinaryName,
2569 SemaRef.forRedeclarationInCurContext());
2570 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
2571
2572 if (R.isSingleResult()) {
2573 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
2574 if (PrevClassTemplate)
2575 PrevDecl = PrevClassTemplate->getTemplatedDecl();
2576 }
2577
2578 if (!PrevClassTemplate && QualifierLoc) {
2579 SemaRef.Diag(Loc: Pattern->getLocation(), DiagID: diag::err_not_tag_in_scope)
2580 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
2581 << QualifierLoc.getSourceRange();
2582 return nullptr;
2583 }
2584 }
2585
2586 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
2587 C: SemaRef.Context, TK: Pattern->getTagKind(), DC, StartLoc: Pattern->getBeginLoc(),
2588 IdLoc: Pattern->getLocation(), Id: Pattern->getIdentifier(), PrevDecl);
2589 if (QualifierLoc)
2590 RecordInst->setQualifierInfo(QualifierLoc);
2591
2592 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Tmpl: Pattern, New: RecordInst, LateAttrs,
2593 OuterMostScope: StartingScope);
2594
2595 ClassTemplateDecl *Inst
2596 = ClassTemplateDecl::Create(C&: SemaRef.Context, DC, L: D->getLocation(),
2597 Name: D->getIdentifier(), Params: InstParams, Decl: RecordInst);
2598 RecordInst->setDescribedClassTemplate(Inst);
2599
2600 if (isFriend) {
2601 assert(!Owner->isDependentContext());
2602 Inst->setLexicalDeclContext(Owner);
2603 RecordInst->setLexicalDeclContext(Owner);
2604 Inst->setObjectOfFriendDecl();
2605
2606 if (PrevClassTemplate) {
2607 Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
2608 const ClassTemplateDecl *MostRecentPrevCT =
2609 PrevClassTemplate->getMostRecentDecl();
2610 TemplateParameterList *PrevParams =
2611 MostRecentPrevCT->getTemplateParameters();
2612
2613 // Make sure the parameter lists match.
2614 if (!SemaRef.TemplateParameterListsAreEqual(
2615 NewInstFrom: RecordInst, New: InstParams, OldInstFrom: MostRecentPrevCT->getTemplatedDecl(),
2616 Old: PrevParams, Complain: true, Kind: Sema::TPL_TemplateMatch))
2617 return nullptr;
2618
2619 // Do some additional validation, then merge default arguments
2620 // from the existing declarations.
2621 if (SemaRef.CheckTemplateParameterList(NewParams: InstParams, OldParams: PrevParams,
2622 TPC: Sema::TPC_Other))
2623 return nullptr;
2624
2625 Inst->setAccess(PrevClassTemplate->getAccess());
2626 } else {
2627 Inst->setAccess(D->getAccess());
2628 }
2629
2630 Inst->setObjectOfFriendDecl();
2631 // TODO: do we want to track the instantiation progeny of this
2632 // friend target decl?
2633 } else {
2634 Inst->setAccess(D->getAccess());
2635 if (!PrevClassTemplate)
2636 Inst->setInstantiatedFromMemberTemplate(D);
2637 }
2638
2639 Inst->setPreviousDecl(PrevClassTemplate);
2640
2641 // Finish handling of friends.
2642 if (isFriend) {
2643 DC->makeDeclVisibleInContext(D: Inst);
2644 return Inst;
2645 }
2646
2647 if (D->isOutOfLine()) {
2648 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
2649 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
2650 }
2651
2652 Owner->addDecl(D: Inst);
2653
2654 if (!PrevClassTemplate) {
2655 // Queue up any out-of-line partial specializations of this member
2656 // class template; the client will force their instantiation once
2657 // the enclosing class has been instantiated.
2658 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2659 D->getPartialSpecializations(PS&: PartialSpecs);
2660 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
2661 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
2662 OutOfLinePartialSpecs.push_back(Elt: std::make_pair(x&: Inst, y&: PartialSpecs[I]));
2663 }
2664
2665 return Inst;
2666}
2667
2668Decl *
2669TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
2670 ClassTemplatePartialSpecializationDecl *D) {
2671 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2672
2673 // Lookup the already-instantiated declaration in the instantiation
2674 // of the class template and return that.
2675 DeclContext::lookup_result Found
2676 = Owner->lookup(Name: ClassTemplate->getDeclName());
2677 if (Found.empty())
2678 return nullptr;
2679
2680 ClassTemplateDecl *InstClassTemplate
2681 = dyn_cast<ClassTemplateDecl>(Val: Found.front());
2682 if (!InstClassTemplate)
2683 return nullptr;
2684
2685 if (ClassTemplatePartialSpecializationDecl *Result
2686 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
2687 return Result;
2688
2689 return InstantiateClassTemplatePartialSpecialization(ClassTemplate: InstClassTemplate, PartialSpec: D);
2690}
2691
2692Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
2693 assert(D->getTemplatedDecl()->isStaticDataMember() &&
2694 "Only static data member templates are allowed.");
2695
2696 // Create a local instantiation scope for this variable template, which
2697 // will contain the instantiations of the template parameters.
2698 LocalInstantiationScope Scope(SemaRef);
2699 TemplateParameterList *TempParams = D->getTemplateParameters();
2700 TemplateParameterList *InstParams = SubstTemplateParams(List: TempParams);
2701 if (!InstParams)
2702 return nullptr;
2703
2704 VarDecl *Pattern = D->getTemplatedDecl();
2705 VarTemplateDecl *PrevVarTemplate = nullptr;
2706
2707 if (getPreviousDeclForInstantiation(D: Pattern)) {
2708 DeclContext::lookup_result Found = Owner->lookup(Name: Pattern->getDeclName());
2709 if (!Found.empty())
2710 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Val: Found.front());
2711 }
2712
2713 VarDecl *VarInst =
2714 cast_or_null<VarDecl>(Val: VisitVarDecl(D: Pattern,
2715 /*InstantiatingVarTemplate=*/true));
2716 if (!VarInst) return nullptr;
2717
2718 DeclContext *DC = Owner;
2719
2720 VarTemplateDecl *Inst = VarTemplateDecl::Create(
2721 C&: SemaRef.Context, DC, L: D->getLocation(), Name: D->getIdentifier(), Params: InstParams,
2722 Decl: VarInst);
2723 VarInst->setDescribedVarTemplate(Inst);
2724 Inst->setPreviousDecl(PrevVarTemplate);
2725
2726 Inst->setAccess(D->getAccess());
2727 if (!PrevVarTemplate)
2728 Inst->setInstantiatedFromMemberTemplate(D);
2729
2730 if (D->isOutOfLine()) {
2731 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
2732 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
2733 }
2734
2735 Owner->addDecl(D: Inst);
2736 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Tmpl: D, New: Inst, LateAttrs,
2737 OuterMostScope: StartingScope);
2738
2739 if (!PrevVarTemplate) {
2740 // Queue up any out-of-line partial specializations of this member
2741 // variable template; the client will force their instantiation once
2742 // the enclosing class has been instantiated.
2743 SmallVector<VarTemplatePartialSpecializationDecl *, 1> PartialSpecs;
2744 D->getPartialSpecializations(PS&: PartialSpecs);
2745 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
2746 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
2747 OutOfLineVarPartialSpecs.push_back(
2748 Elt: std::make_pair(x&: Inst, y&: PartialSpecs[I]));
2749 }
2750
2751 return Inst;
2752}
2753
2754Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
2755 VarTemplatePartialSpecializationDecl *D) {
2756 assert(D->isStaticDataMember() &&
2757 "Only static data member templates are allowed.");
2758
2759 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2760
2761 // Lookup the already-instantiated declaration and return that.
2762 DeclContext::lookup_result Found = Owner->lookup(Name: VarTemplate->getDeclName());
2763 assert(!Found.empty() && "Instantiation found nothing?");
2764
2765 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Val: Found.front());
2766 assert(InstVarTemplate && "Instantiation did not find a variable template?");
2767
2768 if (VarTemplatePartialSpecializationDecl *Result =
2769 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
2770 return Result;
2771
2772 return InstantiateVarTemplatePartialSpecialization(VarTemplate: InstVarTemplate, PartialSpec: D);
2773}
2774
2775Decl *
2776TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2777 // Create a local instantiation scope for this function template, which
2778 // will contain the instantiations of the template parameters and then get
2779 // merged with the local instantiation scope for the function template
2780 // itself.
2781 LocalInstantiationScope Scope(SemaRef);
2782 llvm::SaveAndRestore RAII(EvaluateConstraints, false);
2783
2784 TemplateParameterList *TempParams = D->getTemplateParameters();
2785 TemplateParameterList *InstParams = SubstTemplateParams(List: TempParams);
2786 if (!InstParams)
2787 return nullptr;
2788
2789 FunctionDecl *Instantiated = nullptr;
2790 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(Val: D->getTemplatedDecl()))
2791 Instantiated = cast_or_null<FunctionDecl>(Val: VisitCXXMethodDecl(D: DMethod,
2792 TemplateParams: InstParams));
2793 else
2794 Instantiated = cast_or_null<FunctionDecl>(Val: VisitFunctionDecl(
2795 D: D->getTemplatedDecl(),
2796 TemplateParams: InstParams));
2797
2798 if (!Instantiated)
2799 return nullptr;
2800
2801 // Link the instantiated function template declaration to the function
2802 // template from which it was instantiated.
2803 FunctionTemplateDecl *InstTemplate
2804 = Instantiated->getDescribedFunctionTemplate();
2805 InstTemplate->setAccess(D->getAccess());
2806 assert(InstTemplate &&
2807 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
2808
2809 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
2810
2811 // Link the instantiation back to the pattern *unless* this is a
2812 // non-definition friend declaration.
2813 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
2814 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
2815 InstTemplate->setInstantiatedFromMemberTemplate(D);
2816
2817 // Make declarations visible in the appropriate context.
2818 if (!isFriend) {
2819 Owner->addDecl(D: InstTemplate);
2820 } else if (InstTemplate->getDeclContext()->isRecord() &&
2821 !getPreviousDeclForInstantiation(D) &&
2822 isa<CXXMethodDecl>(Val: InstTemplate->getTemplatedDecl())) {
2823 SemaRef.CheckFriendAccess(D: InstTemplate);
2824 }
2825
2826 return InstTemplate;
2827}
2828
2829Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
2830 CXXRecordDecl *PrevDecl = nullptr;
2831 if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2832 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(Loc: D->getLocation(),
2833 D: PatternPrev,
2834 TemplateArgs);
2835 if (!Prev) return nullptr;
2836 PrevDecl = cast<CXXRecordDecl>(Val: Prev);
2837 }
2838
2839 CXXRecordDecl *Record = nullptr;
2840 bool IsInjectedClassName = D->isInjectedClassName();
2841 if (D->isLambda())
2842 Record = CXXRecordDecl::CreateLambda(
2843 C: SemaRef.Context, DC: Owner, Info: D->getLambdaTypeInfo(), Loc: D->getLocation(),
2844 DependencyKind: D->getLambdaDependencyKind(), IsGeneric: D->isGenericLambda(),
2845 CaptureDefault: D->getLambdaCaptureDefault());
2846 else
2847 Record = CXXRecordDecl::Create(C: SemaRef.Context, TK: D->getTagKind(), DC: Owner,
2848 StartLoc: D->getBeginLoc(), IdLoc: D->getLocation(),
2849 Id: D->getIdentifier(), PrevDecl);
2850
2851 Record->setImplicit(D->isImplicit());
2852
2853 // Substitute the nested name specifier, if any.
2854 if (SubstQualifier(OldDecl: D, NewDecl: Record))
2855 return nullptr;
2856
2857 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Tmpl: D, New: Record, LateAttrs,
2858 OuterMostScope: StartingScope);
2859
2860 // FIXME: Check against AS_none is an ugly hack to work around the issue that
2861 // the tag decls introduced by friend class declarations don't have an access
2862 // specifier. Remove once this area of the code gets sorted out.
2863 if (D->getAccess() != AS_none)
2864 Record->setAccess(D->getAccess());
2865 if (!IsInjectedClassName)
2866 Record->setInstantiationOfMemberClass(RD: D, TSK: TSK_ImplicitInstantiation);
2867
2868 // If the original function was part of a friend declaration,
2869 // inherit its namespace state.
2870 if (D->getFriendObjectKind())
2871 Record->setObjectOfFriendDecl();
2872
2873 // Make sure that anonymous structs and unions are recorded.
2874 if (D->isAnonymousStructOrUnion())
2875 Record->setAnonymousStructOrUnion(true);
2876
2877 if (D->isLocalClass())
2878 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: Record);
2879
2880 // Forward the mangling number from the template to the instantiated decl.
2881 SemaRef.Context.setManglingNumber(ND: Record,
2882 Number: SemaRef.Context.getManglingNumber(ND: D));
2883
2884 // See if the old tag was defined along with a declarator.
2885 // If it did, mark the new tag as being associated with that declarator.
2886 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(TD: D))
2887 SemaRef.Context.addDeclaratorForUnnamedTagDecl(TD: Record, DD);
2888
2889 // See if the old tag was defined along with a typedef.
2890 // If it did, mark the new tag as being associated with that typedef.
2891 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(TD: D))
2892 SemaRef.Context.addTypedefNameForUnnamedTagDecl(TD: Record, TND);
2893
2894 Owner->addDecl(D: Record);
2895
2896 // DR1484 clarifies that the members of a local class are instantiated as part
2897 // of the instantiation of their enclosing entity.
2898 if (D->isCompleteDefinition() && D->isLocalClass()) {
2899 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef,
2900 /*AtEndOfTU=*/false);
2901
2902 SemaRef.InstantiateClass(PointOfInstantiation: D->getLocation(), Instantiation: Record, Pattern: D, TemplateArgs,
2903 TSK: TSK_ImplicitInstantiation,
2904 /*Complain=*/true);
2905
2906 // For nested local classes, we will instantiate the members when we
2907 // reach the end of the outermost (non-nested) local class.
2908 if (!D->isCXXClassMember())
2909 SemaRef.InstantiateClassMembers(PointOfInstantiation: D->getLocation(), Instantiation: Record, TemplateArgs,
2910 TSK: TSK_ImplicitInstantiation);
2911
2912 // This class may have local implicit instantiations that need to be
2913 // performed within this scope.
2914 LocalInstantiations.perform();
2915 }
2916
2917 SemaRef.DiagnoseUnusedNestedTypedefs(D: Record);
2918
2919 if (IsInjectedClassName)
2920 assert(Record->isInjectedClassName() && "Broken injected-class-name");
2921
2922 return Record;
2923}
2924
2925/// Adjust the given function type for an instantiation of the
2926/// given declaration, to cope with modifications to the function's type that
2927/// aren't reflected in the type-source information.
2928///
2929/// \param D The declaration we're instantiating.
2930/// \param TInfo The already-instantiated type.
2931static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
2932 FunctionDecl *D,
2933 TypeSourceInfo *TInfo) {
2934 const FunctionProtoType *OrigFunc
2935 = D->getType()->castAs<FunctionProtoType>();
2936 const FunctionProtoType *NewFunc
2937 = TInfo->getType()->castAs<FunctionProtoType>();
2938 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2939 return TInfo->getType();
2940
2941 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2942 NewEPI.ExtInfo = OrigFunc->getExtInfo();
2943 return Context.getFunctionType(ResultTy: NewFunc->getReturnType(),
2944 Args: NewFunc->getParamTypes(), EPI: NewEPI);
2945}
2946
2947/// Normal class members are of more specific types and therefore
2948/// don't make it here. This function serves three purposes:
2949/// 1) instantiating function templates
2950/// 2) substituting friend and local function declarations
2951/// 3) substituting deduction guide declarations for nested class templates
2952Decl *TemplateDeclInstantiator::VisitFunctionDecl(
2953 FunctionDecl *D, TemplateParameterList *TemplateParams,
2954 RewriteKind FunctionRewriteKind) {
2955 // Check whether there is already a function template specialization for
2956 // this declaration.
2957 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2958 bool isFriend;
2959 if (FunctionTemplate)
2960 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2961 else
2962 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2963
2964 // Friend function defined withing class template may stop being function
2965 // definition during AST merges from different modules, in this case decl
2966 // with function body should be used for instantiation.
2967 if (ExternalASTSource *Source = SemaRef.Context.getExternalSource()) {
2968 if (isFriend && Source->wasThisDeclarationADefinition(FD: D)) {
2969 const FunctionDecl *Defn = nullptr;
2970 if (D->hasBody(Definition&: Defn)) {
2971 D = const_cast<FunctionDecl *>(Defn);
2972 FunctionTemplate = Defn->getDescribedFunctionTemplate();
2973 }
2974 }
2975 }
2976
2977 if (FunctionTemplate && !TemplateParams) {
2978 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2979
2980 void *InsertPos = nullptr;
2981 FunctionDecl *SpecFunc
2982 = FunctionTemplate->findSpecialization(Args: Innermost, InsertPos);
2983
2984 // If we already have a function template specialization, return it.
2985 if (SpecFunc)
2986 return SpecFunc;
2987 }
2988
2989 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2990 Owner->isFunctionOrMethod() ||
2991 !(isa<Decl>(Val: Owner) &&
2992 cast<Decl>(Val: Owner)->isDefinedOutsideFunctionOrMethod());
2993 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2994
2995 ExplicitSpecifier InstantiatedExplicitSpecifier;
2996 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(Val: D)) {
2997 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2998 TemplateArgs, ES: DGuide->getExplicitSpecifier());
2999 if (InstantiatedExplicitSpecifier.isInvalid())
3000 return nullptr;
3001 }
3002
3003 SmallVector<ParmVarDecl *, 4> Params;
3004 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
3005 if (!TInfo)
3006 return nullptr;
3007 QualType T = adjustFunctionTypeForInstantiation(Context&: SemaRef.Context, D, TInfo);
3008
3009 if (TemplateParams && TemplateParams->size()) {
3010 auto *LastParam =
3011 dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->asArray().back());
3012 if (LastParam && LastParam->isImplicit() &&
3013 LastParam->hasTypeConstraint()) {
3014 // In abbreviated templates, the type-constraints of invented template
3015 // type parameters are instantiated with the function type, invalidating
3016 // the TemplateParameterList which relied on the template type parameter
3017 // not having a type constraint. Recreate the TemplateParameterList with
3018 // the updated parameter list.
3019 TemplateParams = TemplateParameterList::Create(
3020 C: SemaRef.Context, TemplateLoc: TemplateParams->getTemplateLoc(),
3021 LAngleLoc: TemplateParams->getLAngleLoc(), Params: TemplateParams->asArray(),
3022 RAngleLoc: TemplateParams->getRAngleLoc(), RequiresClause: TemplateParams->getRequiresClause());
3023 }
3024 }
3025
3026 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
3027 if (QualifierLoc) {
3028 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc,
3029 TemplateArgs);
3030 if (!QualifierLoc)
3031 return nullptr;
3032 }
3033 if (isFriend &&
3034 (FunctionTemplate || !D->getTemplateParameterLists().empty()) &&
3035 D->getQualifier().isDependent() &&
3036 SemaRef.CheckDependentFriend(Loc: D->getLocation(), NNSLoc: QualifierLoc,
3037 /*TPLs=*/{}, /*IsInstantiation=*/true))
3038 return nullptr;
3039
3040 AssociatedConstraint TrailingRequiresClause = D->getTrailingRequiresClause();
3041
3042 // If we're instantiating a local function declaration, put the result
3043 // in the enclosing namespace; otherwise we need to find the instantiated
3044 // context.
3045 DeclContext *DC;
3046 if (D->isLocalExternDecl()) {
3047 DC = Owner;
3048 SemaRef.adjustContextForLocalExternDecl(DC);
3049 } else if (isFriend && QualifierLoc) {
3050 CXXScopeSpec SS;
3051 SS.Adopt(Other: QualifierLoc);
3052 DC = SemaRef.computeDeclContext(SS);
3053 if (!DC) return nullptr;
3054 } else {
3055 DC = SemaRef.FindInstantiatedContext(Loc: D->getLocation(), DC: D->getDeclContext(),
3056 TemplateArgs);
3057 }
3058
3059 DeclarationNameInfo NameInfo
3060 = SemaRef.SubstDeclarationNameInfo(NameInfo: D->getNameInfo(), TemplateArgs);
3061
3062 if (FunctionRewriteKind != RewriteKind::None)
3063 adjustForRewrite(RK: FunctionRewriteKind, Orig: D, T, TInfo, NameInfo);
3064
3065 FunctionDecl *Function;
3066 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(Val: D)) {
3067 Function = CXXDeductionGuideDecl::Create(
3068 C&: SemaRef.Context, DC, StartLoc: D->getInnerLocStart(),
3069 ES: InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
3070 EndLocation: D->getSourceRange().getEnd(), Ctor: DGuide->getCorrespondingConstructor(),
3071 Kind: DGuide->getDeductionCandidateKind(), TrailingRequiresClause,
3072 SourceDG: DGuide->getSourceDeductionGuide(),
3073 SK: DGuide->getSourceDeductionGuideKind());
3074 Function->setAccess(D->getAccess());
3075 } else {
3076 Function = FunctionDecl::Create(
3077 C&: SemaRef.Context, DC, StartLoc: D->getInnerLocStart(), NameInfo, T, TInfo,
3078 SC: D->getCanonicalDecl()->getStorageClass(), UsesFPIntrin: D->UsesFPIntrin(),
3079 isInlineSpecified: D->isInlineSpecified(), hasWrittenPrototype: D->hasWrittenPrototype(), ConstexprKind: D->getConstexprKind(),
3080 TrailingRequiresClause);
3081 Function->setFriendConstraintRefersToEnclosingTemplate(
3082 D->FriendConstraintRefersToEnclosingTemplate());
3083 Function->setRangeEnd(D->getSourceRange().getEnd());
3084 }
3085
3086 if (D->isInlined())
3087 Function->setImplicitlyInline();
3088
3089 if (QualifierLoc)
3090 Function->setQualifierInfo(QualifierLoc);
3091
3092 if (D->isLocalExternDecl())
3093 Function->setLocalExternDecl();
3094
3095 DeclContext *LexicalDC = Owner;
3096 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
3097 assert(D->getDeclContext()->isFileContext());
3098 LexicalDC = D->getDeclContext();
3099 }
3100 else if (D->isLocalExternDecl()) {
3101 LexicalDC = SemaRef.CurContext;
3102 }
3103
3104 Function->setIsDestroyingOperatorDelete(D->isDestroyingOperatorDelete());
3105 Function->setIsTypeAwareOperatorNewOrDelete(
3106 D->isTypeAwareOperatorNewOrDelete());
3107 Function->setLexicalDeclContext(LexicalDC);
3108
3109 // Attach the parameters
3110 for (unsigned P = 0; P < Params.size(); ++P)
3111 if (Params[P])
3112 Params[P]->setOwningFunction(Function);
3113 Function->setParams(Params);
3114
3115 if (TrailingRequiresClause)
3116 Function->setTrailingRequiresClause(TrailingRequiresClause);
3117
3118 if (TemplateParams) {
3119 // Our resulting instantiation is actually a function template, since we
3120 // are substituting only the outer template parameters. For example, given
3121 //
3122 // template<typename T>
3123 // struct X {
3124 // template<typename U> friend void f(T, U);
3125 // };
3126 //
3127 // X<int> x;
3128 //
3129 // We are instantiating the friend function template "f" within X<int>,
3130 // which means substituting int for T, but leaving "f" as a friend function
3131 // template.
3132 // Build the function template itself.
3133 FunctionTemplate = FunctionTemplateDecl::Create(C&: SemaRef.Context, DC,
3134 L: Function->getLocation(),
3135 Name: Function->getDeclName(),
3136 Params: TemplateParams, Decl: Function);
3137 Function->setDescribedFunctionTemplate(FunctionTemplate);
3138
3139 FunctionTemplate->setLexicalDeclContext(LexicalDC);
3140
3141 if (isFriend && D->isThisDeclarationADefinition()) {
3142 FunctionTemplate->setInstantiatedFromMemberTemplate(
3143 D->getDescribedFunctionTemplate());
3144 }
3145 } else if (FunctionTemplate &&
3146 SemaRef.CodeSynthesisContexts.back().Kind !=
3147 Sema::CodeSynthesisContext::BuildingDeductionGuides) {
3148 // Record this function template specialization.
3149 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
3150 Function->setFunctionTemplateSpecialization(Template: FunctionTemplate,
3151 TemplateArgs: TemplateArgumentList::CreateCopy(Context&: SemaRef.Context,
3152 Args: Innermost),
3153 /*InsertPos=*/nullptr);
3154 } else if (FunctionRewriteKind == RewriteKind::None) {
3155 if (isFriend && D->isThisDeclarationADefinition()) {
3156 // Do not connect the friend to the template unless it's actually a
3157 // definition. We don't want non-template functions to be marked as being
3158 // template instantiations.
3159 Function->setInstantiationOfMemberFunction(FD: D, TSK: TSK_ImplicitInstantiation);
3160 } else if (!isFriend) {
3161 // If this is not a function template, and this is not a friend (that is,
3162 // this is a locally declared function), save the instantiation
3163 // relationship for the purposes of constraint instantiation.
3164 Function->setInstantiatedFromDecl(D);
3165 }
3166 }
3167
3168 if (isFriend) {
3169 Function->setObjectOfFriendDecl();
3170 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
3171 FT->setObjectOfFriendDecl();
3172 }
3173
3174 if (InitFunctionInstantiation(New: Function, Tmpl: D))
3175 Function->setInvalidDecl();
3176
3177 bool IsExplicitSpecialization = false;
3178
3179 LookupResult Previous(
3180 SemaRef, Function->getDeclName(), SourceLocation(),
3181 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3182 : Sema::LookupOrdinaryName,
3183 D->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
3184 : SemaRef.forRedeclarationInCurContext());
3185
3186 if (DependentFunctionTemplateSpecializationInfo *DFTSI =
3187 D->getDependentSpecializationInfo()) {
3188 assert(isFriend && "dependent specialization info on "
3189 "non-member non-friend function?");
3190
3191 // Instantiate the explicit template arguments.
3192 TemplateArgumentListInfo ExplicitArgs;
3193 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
3194 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
3195 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
3196 if (SemaRef.SubstTemplateArguments(Args: ArgsWritten->arguments(), TemplateArgs,
3197 Outputs&: ExplicitArgs))
3198 return nullptr;
3199 }
3200
3201 // Map the candidates for the primary template to their instantiations.
3202 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
3203 if (NamedDecl *ND =
3204 SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), D: FTD, TemplateArgs))
3205 Previous.addDecl(D: ND);
3206 else
3207 return nullptr;
3208 }
3209
3210 if (SemaRef.CheckFunctionTemplateSpecialization(
3211 FD: Function,
3212 ExplicitTemplateArgs: DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
3213 Previous))
3214 Function->setInvalidDecl();
3215
3216 IsExplicitSpecialization = true;
3217 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
3218 D->getTemplateSpecializationArgsAsWritten()) {
3219 // The name of this function was written as a template-id.
3220 SemaRef.LookupQualifiedName(R&: Previous, LookupCtx: DC);
3221
3222 // Instantiate the explicit template arguments.
3223 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
3224 ArgsWritten->getRAngleLoc());
3225 if (SemaRef.SubstTemplateArguments(Args: ArgsWritten->arguments(), TemplateArgs,
3226 Outputs&: ExplicitArgs))
3227 return nullptr;
3228
3229 if (SemaRef.CheckFunctionTemplateSpecialization(FD: Function,
3230 ExplicitTemplateArgs: &ExplicitArgs,
3231 Previous))
3232 Function->setInvalidDecl();
3233
3234 IsExplicitSpecialization = true;
3235 } else if (TemplateParams || !FunctionTemplate) {
3236 // Look only into the namespace where the friend would be declared to
3237 // find a previous declaration. This is the innermost enclosing namespace,
3238 // as described in ActOnFriendFunctionDecl.
3239 SemaRef.LookupQualifiedName(R&: Previous, LookupCtx: DC->getRedeclContext());
3240
3241 // In C++, the previous declaration we find might be a tag type
3242 // (class or enum). In this case, the new declaration will hide the
3243 // tag type. Note that this does not apply if we're declaring a
3244 // typedef (C++ [dcl.typedef]p4).
3245 if (Previous.isSingleTagDecl())
3246 Previous.clear();
3247
3248 // Filter out previous declarations that don't match the scope. The only
3249 // effect this has is to remove declarations found in inline namespaces
3250 // for friend declarations with unqualified names.
3251 if (isFriend && !QualifierLoc) {
3252 SemaRef.FilterLookupForScope(R&: Previous, Ctx: DC, /*Scope=*/ S: nullptr,
3253 /*ConsiderLinkage=*/ true,
3254 AllowInlineNamespace: QualifierLoc.hasQualifier());
3255 }
3256 }
3257
3258 // Per [temp.inst], default arguments in function declarations at local scope
3259 // are instantiated along with the enclosing declaration. For example:
3260 //
3261 // template<typename T>
3262 // void ft() {
3263 // void f(int = []{ return T::value; }());
3264 // }
3265 // template void ft<int>(); // error: type 'int' cannot be used prior
3266 // to '::' because it has no members
3267 //
3268 // The error is issued during instantiation of ft<int>() because substitution
3269 // into the default argument fails; the default argument is instantiated even
3270 // though it is never used.
3271 if (Function->isLocalExternDecl()) {
3272 for (ParmVarDecl *PVD : Function->parameters()) {
3273 if (!PVD->hasDefaultArg())
3274 continue;
3275 if (SemaRef.SubstDefaultArgument(Loc: D->getInnerLocStart(), Param: PVD, TemplateArgs)) {
3276 // If substitution fails, the default argument is set to a
3277 // RecoveryExpr that wraps the uninstantiated default argument so
3278 // that downstream diagnostics are omitted.
3279 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
3280 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
3281 Begin: UninstExpr->getBeginLoc(), End: UninstExpr->getEndLoc(),
3282 SubExprs: { UninstExpr }, T: UninstExpr->getType());
3283 if (ErrorResult.isUsable())
3284 PVD->setDefaultArg(ErrorResult.get());
3285 }
3286 }
3287 }
3288
3289 SemaRef.CheckFunctionDeclaration(/*Scope*/ S: nullptr, NewFD: Function, Previous,
3290 IsMemberSpecialization: IsExplicitSpecialization,
3291 DeclIsDefn: Function->isThisDeclarationADefinition());
3292
3293 // Check the template parameter list against the previous declaration. The
3294 // goal here is to pick up default arguments added since the friend was
3295 // declared; we know the template parameter lists match, since otherwise
3296 // we would not have picked this template as the previous declaration.
3297 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
3298 SemaRef.CheckTemplateParameterList(
3299 NewParams: TemplateParams,
3300 OldParams: FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
3301 TPC: Function->isThisDeclarationADefinition()
3302 ? Sema::TPC_FriendFunctionTemplateDefinition
3303 : Sema::TPC_FriendFunctionTemplate);
3304 }
3305
3306 // If we're introducing a friend definition after the first use, trigger
3307 // instantiation.
3308 // FIXME: If this is a friend function template definition, we should check
3309 // to see if any specializations have been used.
3310 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(CheckUsedAttr: false)) {
3311 if (MemberSpecializationInfo *MSInfo =
3312 Function->getMemberSpecializationInfo()) {
3313 if (MSInfo->getPointOfInstantiation().isInvalid()) {
3314 SourceLocation Loc = D->getLocation(); // FIXME
3315 MSInfo->setPointOfInstantiation(Loc);
3316 SemaRef.PendingLocalImplicitInstantiations.emplace_back(args&: Function, args&: Loc);
3317 }
3318 }
3319 }
3320
3321 if (D->isExplicitlyDefaulted()) {
3322 if (SubstDefaultedFunction(New: Function, Tmpl: D))
3323 return nullptr;
3324 }
3325 if (D->isDeleted())
3326 SemaRef.SetDeclDeleted(dcl: Function, DelLoc: D->getLocation(), Message: D->getDeletedMessage());
3327
3328 NamedDecl *PrincipalDecl =
3329 (TemplateParams ? cast<NamedDecl>(Val: FunctionTemplate) : Function);
3330
3331 // If this declaration lives in a different context from its lexical context,
3332 // add it to the corresponding lookup table.
3333 if (isFriend ||
3334 (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
3335 DC->makeDeclVisibleInContext(D: PrincipalDecl);
3336
3337 if (Function->isOverloadedOperator() && !DC->isRecord() &&
3338 PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
3339 PrincipalDecl->setNonMemberOperator();
3340
3341 return Function;
3342}
3343
3344Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
3345 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
3346 RewriteKind FunctionRewriteKind) {
3347 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
3348 if (FunctionTemplate && !TemplateParams) {
3349 // We are creating a function template specialization from a function
3350 // template. Check whether there is already a function template
3351 // specialization for this particular set of template arguments.
3352 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
3353
3354 void *InsertPos = nullptr;
3355 FunctionDecl *SpecFunc
3356 = FunctionTemplate->findSpecialization(Args: Innermost, InsertPos);
3357
3358 // If we already have a function template specialization, return it.
3359 if (SpecFunc)
3360 return SpecFunc;
3361 }
3362
3363 bool isFriend;
3364 if (FunctionTemplate)
3365 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
3366 else
3367 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
3368
3369 bool MergeWithParentScope = (TemplateParams != nullptr) ||
3370 !(isa<Decl>(Val: Owner) &&
3371 cast<Decl>(Val: Owner)->isDefinedOutsideFunctionOrMethod());
3372 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
3373
3374 Sema::LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
3375 SemaRef, D, TemplateArgs, Scope);
3376
3377 // Instantiate enclosing template arguments for friends.
3378 SmallVector<TemplateParameterList *, 4> TempParamLists;
3379 ArrayRef<TemplateParameterList *> TPLs = D->getTemplateParameterLists();
3380 if (isFriend && !TPLs.empty()) {
3381 TempParamLists.resize(N: TPLs.size());
3382 for (unsigned I = 0; I != TPLs.size(); ++I) {
3383 TemplateParameterList *InstParams = SubstTemplateParams(List: TPLs[I]);
3384 if (!InstParams)
3385 return nullptr;
3386 TempParamLists[I] = InstParams;
3387 }
3388 }
3389
3390 auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(Function: D);
3391 // deduction guides need this
3392 const bool CouldInstantiate =
3393 InstantiatedExplicitSpecifier.getExpr() == nullptr ||
3394 !InstantiatedExplicitSpecifier.getExpr()->isValueDependent();
3395
3396 // Delay the instantiation of the explicit-specifier until after the
3397 // constraints are checked during template argument deduction.
3398 if (CouldInstantiate ||
3399 SemaRef.CodeSynthesisContexts.back().Kind !=
3400 Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution) {
3401 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
3402 TemplateArgs, ES: InstantiatedExplicitSpecifier);
3403
3404 if (InstantiatedExplicitSpecifier.isInvalid())
3405 return nullptr;
3406 } else {
3407 InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved);
3408 }
3409
3410 // Implicit destructors/constructors created for local classes in
3411 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
3412 // Unfortunately there isn't enough context in those functions to
3413 // conditionally populate the TSI without breaking non-template related use
3414 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
3415 // a proper transformation.
3416 if (isLambdaMethod(DC: D) && !D->getTypeSourceInfo() &&
3417 isa<CXXConstructorDecl, CXXDestructorDecl>(Val: D)) {
3418 TypeSourceInfo *TSI =
3419 SemaRef.Context.getTrivialTypeSourceInfo(T: D->getType());
3420 D->setTypeSourceInfo(TSI);
3421 }
3422
3423 SmallVector<ParmVarDecl *, 4> Params;
3424 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
3425 if (!TInfo)
3426 return nullptr;
3427 QualType T = adjustFunctionTypeForInstantiation(Context&: SemaRef.Context, D, TInfo);
3428
3429 if (TemplateParams && TemplateParams->size()) {
3430 auto *LastParam =
3431 dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->asArray().back());
3432 if (LastParam && LastParam->isImplicit() &&
3433 LastParam->hasTypeConstraint()) {
3434 // In abbreviated templates, the type-constraints of invented template
3435 // type parameters are instantiated with the function type, invalidating
3436 // the TemplateParameterList which relied on the template type parameter
3437 // not having a type constraint. Recreate the TemplateParameterList with
3438 // the updated parameter list.
3439 TemplateParams = TemplateParameterList::Create(
3440 C: SemaRef.Context, TemplateLoc: TemplateParams->getTemplateLoc(),
3441 LAngleLoc: TemplateParams->getLAngleLoc(), Params: TemplateParams->asArray(),
3442 RAngleLoc: TemplateParams->getRAngleLoc(), RequiresClause: TemplateParams->getRequiresClause());
3443 }
3444 }
3445
3446 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
3447 if (QualifierLoc) {
3448 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc,
3449 TemplateArgs);
3450 if (!QualifierLoc)
3451 return nullptr;
3452 }
3453 if (isFriend &&
3454 (FunctionTemplate || !D->getTemplateParameterLists().empty()) &&
3455 D->getQualifier().isDependent() &&
3456 SemaRef.CheckDependentFriend(Loc: D->getLocation(), NNSLoc: QualifierLoc,
3457 /*TPLs=*/{}, /*IsInstantiation=*/true))
3458 return nullptr;
3459
3460 DeclContext *DC = Owner;
3461 if (isFriend) {
3462 if (QualifierLoc && !QualifierLoc.getNestedNameSpecifier().isDependent()) {
3463 CXXScopeSpec SS;
3464 SS.Adopt(Other: QualifierLoc);
3465 DC = SemaRef.computeDeclContext(SS);
3466
3467 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
3468 return nullptr;
3469 } else if (!QualifierLoc) {
3470 DC = SemaRef.FindInstantiatedContext(Loc: D->getLocation(),
3471 DC: D->getDeclContext(),
3472 TemplateArgs);
3473 }
3474 if (!DC) return nullptr;
3475 }
3476
3477 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
3478 AssociatedConstraint TrailingRequiresClause = D->getTrailingRequiresClause();
3479
3480 DeclarationNameInfo NameInfo
3481 = SemaRef.SubstDeclarationNameInfo(NameInfo: D->getNameInfo(), TemplateArgs);
3482
3483 // Check if the substitution of template args failed
3484 // leading to an empty DeclarationNameInfo.
3485 if (!NameInfo.getName())
3486 return nullptr;
3487
3488 if (FunctionRewriteKind != RewriteKind::None)
3489 adjustForRewrite(RK: FunctionRewriteKind, Orig: D, T, TInfo, NameInfo);
3490
3491 // Build the instantiated method declaration.
3492 CXXMethodDecl *Method = nullptr;
3493
3494 SourceLocation StartLoc = D->getInnerLocStart();
3495 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: D)) {
3496 Method = CXXConstructorDecl::Create(
3497 C&: SemaRef.Context, RD: Record, StartLoc, NameInfo, T, TInfo,
3498 ES: InstantiatedExplicitSpecifier, UsesFPIntrin: Constructor->UsesFPIntrin(),
3499 isInline: Constructor->isInlineSpecified(), isImplicitlyDeclared: false,
3500 ConstexprKind: Constructor->getConstexprKind(), Inherited: InheritedConstructor(),
3501 TrailingRequiresClause);
3502 Method->setRangeEnd(Constructor->getEndLoc());
3503 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: D)) {
3504 Method = CXXDestructorDecl::Create(
3505 C&: SemaRef.Context, RD: Record, StartLoc, NameInfo, T, TInfo,
3506 UsesFPIntrin: Destructor->UsesFPIntrin(), isInline: Destructor->isInlineSpecified(), isImplicitlyDeclared: false,
3507 ConstexprKind: Destructor->getConstexprKind(), TrailingRequiresClause);
3508 Method->setIneligibleOrNotSelected(true);
3509 Method->setRangeEnd(Destructor->getEndLoc());
3510 Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
3511
3512 Ty: SemaRef.Context.getCanonicalTagType(TD: Record)));
3513 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: D)) {
3514 Method = CXXConversionDecl::Create(
3515 C&: SemaRef.Context, RD: Record, StartLoc, NameInfo, T, TInfo,
3516 UsesFPIntrin: Conversion->UsesFPIntrin(), isInline: Conversion->isInlineSpecified(),
3517 ES: InstantiatedExplicitSpecifier, ConstexprKind: Conversion->getConstexprKind(),
3518 EndLocation: Conversion->getEndLoc(), TrailingRequiresClause);
3519 } else {
3520 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
3521 Method = CXXMethodDecl::Create(
3522 C&: SemaRef.Context, RD: Record, StartLoc, NameInfo, T, TInfo, SC,
3523 UsesFPIntrin: D->UsesFPIntrin(), isInline: D->isInlineSpecified(), ConstexprKind: D->getConstexprKind(),
3524 EndLocation: D->getEndLoc(), TrailingRequiresClause);
3525 }
3526
3527 if (D->isInlined())
3528 Method->setImplicitlyInline();
3529
3530 if (QualifierLoc)
3531 Method->setQualifierInfo(QualifierLoc);
3532
3533 if (TemplateParams) {
3534 // Our resulting instantiation is actually a function template, since we
3535 // are substituting only the outer template parameters. For example, given
3536 //
3537 // template<typename T>
3538 // struct X {
3539 // template<typename U> void f(T, U);
3540 // };
3541 //
3542 // X<int> x;
3543 //
3544 // We are instantiating the member template "f" within X<int>, which means
3545 // substituting int for T, but leaving "f" as a member function template.
3546 // Build the function template itself.
3547 FunctionTemplate = FunctionTemplateDecl::Create(C&: SemaRef.Context, DC: Record,
3548 L: Method->getLocation(),
3549 Name: Method->getDeclName(),
3550 Params: TemplateParams, Decl: Method);
3551 if (isFriend) {
3552 FunctionTemplate->setLexicalDeclContext(Owner);
3553 FunctionTemplate->setObjectOfFriendDecl();
3554 } else if (D->isOutOfLine())
3555 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
3556 Method->setDescribedFunctionTemplate(FunctionTemplate);
3557 } else if (FunctionTemplate) {
3558 // Record this function template specialization.
3559 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
3560 Method->setFunctionTemplateSpecialization(Template: FunctionTemplate,
3561 TemplateArgs: TemplateArgumentList::CreateCopy(Context&: SemaRef.Context,
3562 Args: Innermost),
3563 /*InsertPos=*/nullptr);
3564 } else if (!isFriend && FunctionRewriteKind == RewriteKind::None) {
3565 // Record that this is an instantiation of a member function.
3566 Method->setInstantiationOfMemberFunction(FD: D, TSK: TSK_ImplicitInstantiation);
3567 }
3568
3569 // If we are instantiating a member function defined
3570 // out-of-line, the instantiation will have the same lexical
3571 // context (which will be a namespace scope) as the template.
3572 if (isFriend) {
3573 if (!TempParamLists.empty())
3574 Method->setTemplateParameterListsInfo(Context&: SemaRef.Context, TPLists: TempParamLists);
3575
3576 Method->setLexicalDeclContext(Owner);
3577 Method->setObjectOfFriendDecl();
3578 } else if (D->isOutOfLine())
3579 Method->setLexicalDeclContext(D->getLexicalDeclContext());
3580
3581 // Attach the parameters
3582 for (unsigned P = 0; P < Params.size(); ++P)
3583 Params[P]->setOwningFunction(Method);
3584 Method->setParams(Params);
3585
3586 if (InitMethodInstantiation(New: Method, Tmpl: D))
3587 Method->setInvalidDecl();
3588
3589 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
3590 RedeclarationKind::ForExternalRedeclaration);
3591
3592 bool IsExplicitSpecialization = false;
3593
3594 // If the name of this function was written as a template-id, instantiate
3595 // the explicit template arguments.
3596 if (DependentFunctionTemplateSpecializationInfo *DFTSI =
3597 D->getDependentSpecializationInfo()) {
3598 // Instantiate the explicit template arguments.
3599 TemplateArgumentListInfo ExplicitArgs;
3600 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
3601 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
3602 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
3603 if (SemaRef.SubstTemplateArguments(Args: ArgsWritten->arguments(), TemplateArgs,
3604 Outputs&: ExplicitArgs))
3605 return nullptr;
3606 }
3607
3608 // Map the candidates for the primary template to their instantiations.
3609 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
3610 if (NamedDecl *ND =
3611 SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), D: FTD, TemplateArgs))
3612 Previous.addDecl(D: ND);
3613 else
3614 return nullptr;
3615 }
3616
3617 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier().isDependent()) {
3618 if (SemaRef.CheckDependentFunctionTemplateSpecialization(
3619 FD: Method,
3620 ExplicitTemplateArgs: DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
3621 Previous))
3622 Method->setInvalidDecl();
3623 } else {
3624 if (Previous.empty())
3625 SemaRef.LookupQualifiedName(R&: Previous, LookupCtx: DC);
3626 if (SemaRef.CheckFunctionTemplateSpecialization(
3627 FD: Method,
3628 ExplicitTemplateArgs: DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
3629 Previous))
3630 Method->setInvalidDecl();
3631 IsExplicitSpecialization = true;
3632 }
3633 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
3634 D->getTemplateSpecializationArgsAsWritten()) {
3635 SemaRef.LookupQualifiedName(R&: Previous, LookupCtx: DC);
3636
3637 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
3638 ArgsWritten->getRAngleLoc());
3639
3640 if (SemaRef.SubstTemplateArguments(Args: ArgsWritten->arguments(), TemplateArgs,
3641 Outputs&: ExplicitArgs))
3642 return nullptr;
3643
3644 if (SemaRef.CheckFunctionTemplateSpecialization(FD: Method,
3645 ExplicitTemplateArgs: &ExplicitArgs,
3646 Previous))
3647 Method->setInvalidDecl();
3648
3649 IsExplicitSpecialization = true;
3650 } else if (!FunctionTemplate || TemplateParams || isFriend) {
3651 SemaRef.LookupQualifiedName(R&: Previous, LookupCtx: Record);
3652
3653 // In C++, the previous declaration we find might be a tag type
3654 // (class or enum). In this case, the new declaration will hide the
3655 // tag type. Note that this does not apply if we're declaring a
3656 // typedef (C++ [dcl.typedef]p4).
3657 if (Previous.isSingleTagDecl())
3658 Previous.clear();
3659 }
3660
3661 // Per [temp.inst], default arguments in member functions of local classes
3662 // are instantiated along with the member function declaration. For example:
3663 //
3664 // template<typename T>
3665 // void ft() {
3666 // struct lc {
3667 // int operator()(int p = []{ return T::value; }());
3668 // };
3669 // }
3670 // template void ft<int>(); // error: type 'int' cannot be used prior
3671 // to '::'because it has no members
3672 //
3673 // The error is issued during instantiation of ft<int>()::lc::operator()
3674 // because substitution into the default argument fails; the default argument
3675 // is instantiated even though it is never used.
3676 if (D->isInLocalScopeForInstantiation()) {
3677 for (unsigned P = 0; P < Params.size(); ++P) {
3678 if (!Params[P]->hasDefaultArg())
3679 continue;
3680 if (SemaRef.SubstDefaultArgument(Loc: StartLoc, Param: Params[P], TemplateArgs)) {
3681 // If substitution fails, the default argument is set to a
3682 // RecoveryExpr that wraps the uninstantiated default argument so
3683 // that downstream diagnostics are omitted.
3684 Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
3685 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
3686 Begin: UninstExpr->getBeginLoc(), End: UninstExpr->getEndLoc(),
3687 SubExprs: { UninstExpr }, T: UninstExpr->getType());
3688 if (ErrorResult.isUsable())
3689 Params[P]->setDefaultArg(ErrorResult.get());
3690 }
3691 }
3692 }
3693
3694 SemaRef.CheckFunctionDeclaration(S: nullptr, NewFD: Method, Previous,
3695 IsMemberSpecialization: IsExplicitSpecialization,
3696 DeclIsDefn: Method->isThisDeclarationADefinition());
3697
3698 if (D->isPureVirtual())
3699 SemaRef.CheckPureMethod(Method, InitRange: SourceRange());
3700
3701 // Propagate access. For a non-friend declaration, the access is
3702 // whatever we're propagating from. For a friend, it should be the
3703 // previous declaration we just found.
3704 if (isFriend && Method->getPreviousDecl())
3705 Method->setAccess(Method->getPreviousDecl()->getAccess());
3706 else
3707 Method->setAccess(D->getAccess());
3708 if (FunctionTemplate)
3709 FunctionTemplate->setAccess(Method->getAccess());
3710
3711 SemaRef.CheckOverrideControl(D: Method);
3712
3713 // If a function is defined as defaulted or deleted, mark it as such now.
3714 if (D->isExplicitlyDefaulted()) {
3715 if (SubstDefaultedFunction(New: Method, Tmpl: D))
3716 return nullptr;
3717 }
3718 if (D->isDeletedAsWritten())
3719 SemaRef.SetDeclDeleted(dcl: Method, DelLoc: Method->getLocation(),
3720 Message: D->getDeletedMessage());
3721
3722 // If this is an explicit specialization, mark the implicitly-instantiated
3723 // template specialization as being an explicit specialization too.
3724 // FIXME: Is this necessary?
3725 if (IsExplicitSpecialization && !isFriend)
3726 SemaRef.CompleteMemberSpecialization(Member: Method, Previous);
3727
3728 // If the method is a special member function, we need to mark it as
3729 // ineligible so that Owner->addDecl() won't mark the class as non trivial.
3730 // At the end of the class instantiation, we calculate eligibility again and
3731 // then we adjust trivility if needed.
3732 // We need this check to happen only after the method parameters are set,
3733 // because being e.g. a copy constructor depends on the instantiated
3734 // arguments.
3735 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method)) {
3736 if (Constructor->isDefaultConstructor() ||
3737 Constructor->isCopyOrMoveConstructor())
3738 Method->setIneligibleOrNotSelected(true);
3739 } else if (Method->isCopyAssignmentOperator() ||
3740 Method->isMoveAssignmentOperator()) {
3741 Method->setIneligibleOrNotSelected(true);
3742 }
3743
3744 // If there's a function template, let our caller handle it.
3745 if (FunctionTemplate) {
3746 // do nothing
3747
3748 // Don't hide a (potentially) valid declaration with an invalid one.
3749 } else if (Method->isInvalidDecl() && !Previous.empty()) {
3750 // do nothing
3751
3752 // Otherwise, check access to friends and make them visible.
3753 } else if (isFriend) {
3754 // We only need to re-check access for methods which we didn't
3755 // manage to match during parsing.
3756 if (!D->getPreviousDecl())
3757 SemaRef.CheckFriendAccess(D: Method);
3758
3759 Record->makeDeclVisibleInContext(D: Method);
3760
3761 // Otherwise, add the declaration. We don't need to do this for
3762 // class-scope specializations because we'll have matched them with
3763 // the appropriate template.
3764 } else {
3765 Owner->addDecl(D: Method);
3766 }
3767
3768 // PR17480: Honor the used attribute to instantiate member function
3769 // definitions
3770 if (Method->hasAttr<UsedAttr>()) {
3771 if (const auto *A = dyn_cast<CXXRecordDecl>(Val: Owner)) {
3772 SourceLocation Loc;
3773 if (const MemberSpecializationInfo *MSInfo =
3774 A->getMemberSpecializationInfo())
3775 Loc = MSInfo->getPointOfInstantiation();
3776 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: A))
3777 Loc = Spec->getPointOfInstantiation();
3778 SemaRef.MarkFunctionReferenced(Loc, Func: Method);
3779 }
3780 }
3781
3782 return Method;
3783}
3784
3785Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3786 return VisitCXXMethodDecl(D);
3787}
3788
3789Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3790 return VisitCXXMethodDecl(D);
3791}
3792
3793Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
3794 return VisitCXXMethodDecl(D);
3795}
3796
3797Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
3798 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
3799 NumExpansions: std::nullopt,
3800 /*ExpectParameterPack=*/false);
3801}
3802
3803Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
3804 TemplateTypeParmDecl *D) {
3805 assert(D->getTypeForDecl()->isTemplateTypeParmType());
3806
3807 UnsignedOrNone NumExpanded = std::nullopt;
3808
3809 if (const TypeConstraint *TC = D->getTypeConstraint()) {
3810 if (D->isPackExpansion() && !D->getNumExpansionParameters()) {
3811 assert(TC->getTemplateArgsAsWritten() &&
3812 "type parameter can only be an expansion when explicit arguments "
3813 "are specified");
3814 // The template type parameter pack's type is a pack expansion of types.
3815 // Determine whether we need to expand this parameter pack into separate
3816 // types.
3817 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3818 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
3819 SemaRef.collectUnexpandedParameterPacks(Arg: ArgLoc, Unexpanded);
3820
3821 // Determine whether the set of unexpanded parameter packs can and should
3822 // be expanded.
3823 bool Expand = true;
3824 bool RetainExpansion = false;
3825 if (SemaRef.CheckParameterPacksForExpansion(
3826 EllipsisLoc: cast<CXXFoldExpr>(Val: TC->getImmediatelyDeclaredConstraint())
3827 ->getEllipsisLoc(),
3828 PatternRange: SourceRange(TC->getConceptNameLoc(),
3829 TC->hasExplicitTemplateArgs()
3830 ? TC->getTemplateArgsAsWritten()->getRAngleLoc()
3831 : TC->getConceptNameInfo().getEndLoc()),
3832 Unexpanded, TemplateArgs, /*FailOnPackProducingTemplates=*/true,
3833 ShouldExpand&: Expand, RetainExpansion, NumExpansions&: NumExpanded))
3834 return nullptr;
3835 }
3836 }
3837
3838 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
3839 C: SemaRef.Context, DC: Owner, KeyLoc: D->getBeginLoc(), NameLoc: D->getLocation(),
3840 D: D->getDepth() - (TemplateArgs.retainInnerDepths()
3841 ? 0
3842 : TemplateArgs.getNumSubstitutedLevels()),
3843 P: D->getIndex(), Id: D->getIdentifier(), Typename: D->wasDeclaredWithTypename(),
3844 ParameterPack: D->isParameterPack(), HasTypeConstraint: D->hasTypeConstraint(), NumExpanded);
3845
3846 Inst->setAccess(AS_public);
3847 Inst->setImplicit(D->isImplicit());
3848 if (auto *TC = D->getTypeConstraint()) {
3849 if (!D->isImplicit()) {
3850 // Invented template parameter type constraints will be instantiated
3851 // with the corresponding auto-typed parameter as it might reference
3852 // other parameters.
3853 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
3854 EvaluateConstraint: EvaluateConstraints))
3855 return nullptr;
3856 }
3857 }
3858 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3859 TemplateArgumentLoc Output;
3860 if (!SemaRef.SubstTemplateArgument(Input: D->getDefaultArgument(), TemplateArgs,
3861 Output))
3862 Inst->setDefaultArgument(C: SemaRef.getASTContext(), DefArg: Output);
3863 }
3864
3865 // Introduce this template parameter's instantiation into the instantiation
3866 // scope.
3867 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3868
3869 return Inst;
3870}
3871
3872Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
3873 NonTypeTemplateParmDecl *D) {
3874 // Substitute into the type of the non-type template parameter.
3875 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
3876 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
3877 SmallVector<QualType, 4> ExpandedParameterPackTypes;
3878 bool IsExpandedParameterPack = false;
3879 TypeSourceInfo *TSI;
3880 QualType T;
3881 bool Invalid = false;
3882
3883 if (D->isExpandedParameterPack()) {
3884 // The non-type template parameter pack is an already-expanded pack
3885 // expansion of types. Substitute into each of the expanded types.
3886 ExpandedParameterPackTypes.reserve(N: D->getNumExpansionTypes());
3887 ExpandedParameterPackTypesAsWritten.reserve(N: D->getNumExpansionTypes());
3888 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
3889 TypeSourceInfo *NewTSI =
3890 SemaRef.SubstType(T: D->getExpansionTypeSourceInfo(I), TemplateArgs,
3891 Loc: D->getLocation(), Entity: D->getDeclName());
3892 if (!NewTSI)
3893 return nullptr;
3894
3895 QualType NewT =
3896 SemaRef.CheckNonTypeTemplateParameterType(TSI&: NewTSI, Loc: D->getLocation());
3897 if (NewT.isNull())
3898 return nullptr;
3899
3900 ExpandedParameterPackTypesAsWritten.push_back(Elt: NewTSI);
3901 ExpandedParameterPackTypes.push_back(Elt: NewT);
3902 }
3903
3904 IsExpandedParameterPack = true;
3905 TSI = D->getTypeSourceInfo();
3906 T = TSI->getType();
3907 } else if (D->isPackExpansion()) {
3908 // The non-type template parameter pack's type is a pack expansion of types.
3909 // Determine whether we need to expand this parameter pack into separate
3910 // types.
3911 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
3912 TypeLoc Pattern = Expansion.getPatternLoc();
3913 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3914 SemaRef.collectUnexpandedParameterPacks(TL: Pattern, Unexpanded);
3915
3916 // Determine whether the set of unexpanded parameter packs can and should
3917 // be expanded.
3918 bool Expand = true;
3919 bool RetainExpansion = false;
3920 UnsignedOrNone OrigNumExpansions =
3921 Expansion.getTypePtr()->getNumExpansions();
3922 UnsignedOrNone NumExpansions = OrigNumExpansions;
3923 if (SemaRef.CheckParameterPacksForExpansion(
3924 EllipsisLoc: Expansion.getEllipsisLoc(), PatternRange: Pattern.getSourceRange(), Unexpanded,
3925 TemplateArgs, /*FailOnPackProducingTemplates=*/true, ShouldExpand&: Expand,
3926 RetainExpansion, NumExpansions))
3927 return nullptr;
3928
3929 if (Expand) {
3930 for (unsigned I = 0; I != *NumExpansions; ++I) {
3931 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
3932 TypeSourceInfo *NewTSI = SemaRef.SubstType(
3933 TL: Pattern, TemplateArgs, Loc: D->getLocation(), Entity: D->getDeclName());
3934 if (!NewTSI)
3935 return nullptr;
3936
3937 QualType NewT =
3938 SemaRef.CheckNonTypeTemplateParameterType(TSI&: NewTSI, Loc: D->getLocation());
3939 if (NewT.isNull())
3940 return nullptr;
3941
3942 ExpandedParameterPackTypesAsWritten.push_back(Elt: NewTSI);
3943 ExpandedParameterPackTypes.push_back(Elt: NewT);
3944 }
3945
3946 // Note that we have an expanded parameter pack. The "type" of this
3947 // expanded parameter pack is the original expansion type, but callers
3948 // will end up using the expanded parameter pack types for type-checking.
3949 IsExpandedParameterPack = true;
3950 TSI = D->getTypeSourceInfo();
3951 T = TSI->getType();
3952 } else {
3953 // We cannot fully expand the pack expansion now, so substitute into the
3954 // pattern and create a new pack expansion type.
3955 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, std::nullopt);
3956 TypeSourceInfo *NewPattern = SemaRef.SubstType(TL: Pattern, TemplateArgs,
3957 Loc: D->getLocation(),
3958 Entity: D->getDeclName());
3959 if (!NewPattern)
3960 return nullptr;
3961
3962 SemaRef.CheckNonTypeTemplateParameterType(TSI&: NewPattern, Loc: D->getLocation());
3963 TSI = SemaRef.CheckPackExpansion(Pattern: NewPattern, EllipsisLoc: Expansion.getEllipsisLoc(),
3964 NumExpansions);
3965 if (!TSI)
3966 return nullptr;
3967
3968 T = TSI->getType();
3969 }
3970 } else {
3971 // Simple case: substitution into a parameter that is not a parameter pack.
3972 TSI = SemaRef.SubstType(T: D->getTypeSourceInfo(), TemplateArgs,
3973 Loc: D->getLocation(), Entity: D->getDeclName());
3974 if (!TSI)
3975 return nullptr;
3976
3977 // Check that this type is acceptable for a non-type template parameter.
3978 T = SemaRef.CheckNonTypeTemplateParameterType(TSI, Loc: D->getLocation());
3979 if (T.isNull()) {
3980 T = SemaRef.Context.IntTy;
3981 Invalid = true;
3982 }
3983 }
3984
3985 NonTypeTemplateParmDecl *Param;
3986 if (IsExpandedParameterPack)
3987 Param = NonTypeTemplateParmDecl::Create(
3988 C: SemaRef.Context, DC: Owner, StartLoc: D->getInnerLocStart(), IdLoc: D->getLocation(),
3989 D: D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3990 P: D->getPosition(), Id: D->getIdentifier(), T, TInfo: TSI,
3991 ExpandedTypes: ExpandedParameterPackTypes, ExpandedTInfos: ExpandedParameterPackTypesAsWritten);
3992 else
3993 Param = NonTypeTemplateParmDecl::Create(
3994 C: SemaRef.Context, DC: Owner, StartLoc: D->getInnerLocStart(), IdLoc: D->getLocation(),
3995 D: D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3996 P: D->getPosition(), Id: D->getIdentifier(), T, ParameterPack: D->isParameterPack(), TInfo: TSI);
3997
3998 if (AutoTypeLoc AutoLoc = TSI->getTypeLoc().getContainedAutoTypeLoc())
3999 if (AutoLoc.isConstrained()) {
4000 SourceLocation EllipsisLoc;
4001 if (IsExpandedParameterPack)
4002 EllipsisLoc =
4003 TSI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
4004 else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
4005 Val: D->getPlaceholderTypeConstraint()))
4006 EllipsisLoc = Constraint->getEllipsisLoc();
4007 // Note: We attach the uninstantiated constriant here, so that it can be
4008 // instantiated relative to the top level, like all our other
4009 // constraints.
4010 if (SemaRef.AttachTypeConstraint(TL: AutoLoc, /*NewConstrainedParm=*/Param,
4011 /*OrigConstrainedParm=*/D, EllipsisLoc))
4012 Invalid = true;
4013 }
4014
4015 Param->setAccess(AS_public);
4016 Param->setImplicit(D->isImplicit());
4017 if (Invalid)
4018 Param->setInvalidDecl();
4019
4020 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
4021 EnterExpressionEvaluationContext ConstantEvaluated(
4022 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4023 TemplateArgumentLoc Result;
4024 if (!SemaRef.SubstTemplateArgument(Input: D->getDefaultArgument(), TemplateArgs,
4025 Output&: Result))
4026 Param->setDefaultArgument(C: SemaRef.Context, DefArg: Result);
4027 }
4028
4029 // Introduce this template parameter's instantiation into the instantiation
4030 // scope.
4031 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: Param);
4032 return Param;
4033}
4034
4035static void collectUnexpandedParameterPacks(
4036 Sema &S,
4037 TemplateParameterList *Params,
4038 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
4039 for (const auto &P : *Params) {
4040 if (P->isTemplateParameterPack())
4041 continue;
4042 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P))
4043 S.collectUnexpandedParameterPacks(TL: NTTP->getTypeSourceInfo()->getTypeLoc(),
4044 Unexpanded);
4045 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: P))
4046 collectUnexpandedParameterPacks(S, Params: TTP->getTemplateParameters(),
4047 Unexpanded);
4048 }
4049}
4050
4051Decl *
4052TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
4053 TemplateTemplateParmDecl *D) {
4054 // Instantiate the template parameter list of the template template parameter.
4055 TemplateParameterList *TempParams = D->getTemplateParameters();
4056 TemplateParameterList *InstParams;
4057 SmallVector<TemplateParameterList*, 8> ExpandedParams;
4058
4059 bool IsExpandedParameterPack = false;
4060
4061 if (D->isExpandedParameterPack()) {
4062 // The template template parameter pack is an already-expanded pack
4063 // expansion of template parameters. Substitute into each of the expanded
4064 // parameters.
4065 ExpandedParams.reserve(N: D->getNumExpansionTemplateParameters());
4066 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
4067 I != N; ++I) {
4068 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
4069 TemplateParameterList *Expansion =
4070 SubstTemplateParams(List: D->getExpansionTemplateParameters(I));
4071 if (!Expansion)
4072 return nullptr;
4073 ExpandedParams.push_back(Elt: Expansion);
4074 }
4075
4076 IsExpandedParameterPack = true;
4077 InstParams = TempParams;
4078 } else if (D->isPackExpansion()) {
4079 // The template template parameter pack expands to a pack of template
4080 // template parameters. Determine whether we need to expand this parameter
4081 // pack into separate parameters.
4082 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4083 collectUnexpandedParameterPacks(S&: SemaRef, Params: D->getTemplateParameters(),
4084 Unexpanded);
4085
4086 // Determine whether the set of unexpanded parameter packs can and should
4087 // be expanded.
4088 bool Expand = true;
4089 bool RetainExpansion = false;
4090 UnsignedOrNone NumExpansions = std::nullopt;
4091 if (SemaRef.CheckParameterPacksForExpansion(
4092 EllipsisLoc: D->getLocation(), PatternRange: TempParams->getSourceRange(), Unexpanded,
4093 TemplateArgs, /*FailOnPackProducingTemplates=*/true, ShouldExpand&: Expand,
4094 RetainExpansion, NumExpansions))
4095 return nullptr;
4096
4097 if (Expand) {
4098 for (unsigned I = 0; I != *NumExpansions; ++I) {
4099 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
4100 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
4101 TemplateParameterList *Expansion = SubstTemplateParams(List: TempParams);
4102 if (!Expansion)
4103 return nullptr;
4104 ExpandedParams.push_back(Elt: Expansion);
4105 }
4106
4107 // Note that we have an expanded parameter pack. The "type" of this
4108 // expanded parameter pack is the original expansion type, but callers
4109 // will end up using the expanded parameter pack types for type-checking.
4110 IsExpandedParameterPack = true;
4111 }
4112
4113 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, std::nullopt);
4114
4115 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
4116 InstParams = SubstTemplateParams(List: TempParams);
4117 if (!InstParams)
4118 return nullptr;
4119 } else {
4120 // Perform the actual substitution of template parameters within a new,
4121 // local instantiation scope.
4122 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
4123 InstParams = SubstTemplateParams(List: TempParams);
4124 if (!InstParams)
4125 return nullptr;
4126 }
4127
4128 // Build the template template parameter.
4129 TemplateTemplateParmDecl *Param;
4130 if (IsExpandedParameterPack)
4131 Param = TemplateTemplateParmDecl::Create(
4132 C: SemaRef.Context, DC: Owner, L: D->getLocation(),
4133 D: D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
4134 P: D->getPosition(), Id: D->getIdentifier(), ParameterKind: D->templateParameterKind(),
4135 Typename: D->wasDeclaredWithTypename(), Params: InstParams, Expansions: ExpandedParams);
4136 else
4137 Param = TemplateTemplateParmDecl::Create(
4138 C: SemaRef.Context, DC: Owner, L: D->getLocation(),
4139 D: D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
4140 P: D->getPosition(), ParameterPack: D->isParameterPack(), Id: D->getIdentifier(),
4141 ParameterKind: D->templateParameterKind(), Typename: D->wasDeclaredWithTypename(), Params: InstParams);
4142 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
4143 const TemplateArgumentLoc &A = D->getDefaultArgument();
4144 NestedNameSpecifierLoc QualifierLoc = A.getTemplateQualifierLoc();
4145 // FIXME: Pass in the template keyword location.
4146 TemplateName TName = SemaRef.SubstTemplateName(
4147 TemplateKWLoc: A.getTemplateKWLoc(), QualifierLoc, Name: A.getArgument().getAsTemplate(),
4148 NameLoc: A.getTemplateNameLoc(), TemplateArgs);
4149 if (!TName.isNull())
4150 Param->setDefaultArgument(
4151 C: SemaRef.Context,
4152 DefArg: TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
4153 A.getTemplateKWLoc(), QualifierLoc,
4154 A.getTemplateNameLoc()));
4155 }
4156 Param->setAccess(AS_public);
4157 Param->setImplicit(D->isImplicit());
4158
4159 // Introduce this template parameter's instantiation into the instantiation
4160 // scope.
4161 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: Param);
4162
4163 return Param;
4164}
4165
4166Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
4167 // Using directives are never dependent (and never contain any types or
4168 // expressions), so they require no explicit instantiation work.
4169
4170 UsingDirectiveDecl *Inst
4171 = UsingDirectiveDecl::Create(C&: SemaRef.Context, DC: Owner, UsingLoc: D->getLocation(),
4172 NamespaceLoc: D->getNamespaceKeyLocation(),
4173 QualifierLoc: D->getQualifierLoc(),
4174 IdentLoc: D->getIdentLocation(),
4175 Nominated: D->getNominatedNamespace(),
4176 CommonAncestor: D->getCommonAncestor());
4177
4178 // Add the using directive to its declaration context
4179 // only if this is not a function or method.
4180 if (!Owner->isFunctionOrMethod())
4181 Owner->addDecl(D: Inst);
4182
4183 return Inst;
4184}
4185
4186Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D,
4187 BaseUsingDecl *Inst,
4188 LookupResult *Lookup) {
4189
4190 bool isFunctionScope = Owner->isFunctionOrMethod();
4191
4192 for (auto *Shadow : D->shadows()) {
4193 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
4194 // reconstruct it in the case where it matters. Hm, can we extract it from
4195 // the DeclSpec when parsing and save it in the UsingDecl itself?
4196 NamedDecl *OldTarget = Shadow->getTargetDecl();
4197 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Val: Shadow))
4198 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
4199 OldTarget = BaseShadow;
4200
4201 NamedDecl *InstTarget = nullptr;
4202 if (auto *EmptyD =
4203 dyn_cast<UnresolvedUsingIfExistsDecl>(Val: Shadow->getTargetDecl())) {
4204 InstTarget = UnresolvedUsingIfExistsDecl::Create(
4205 Ctx&: SemaRef.Context, DC: Owner, Loc: EmptyD->getLocation(), Name: EmptyD->getDeclName());
4206 } else {
4207 InstTarget = cast_or_null<NamedDecl>(Val: SemaRef.FindInstantiatedDecl(
4208 Loc: Shadow->getLocation(), D: OldTarget, TemplateArgs));
4209 }
4210 if (!InstTarget)
4211 return nullptr;
4212
4213 UsingShadowDecl *PrevDecl = nullptr;
4214 if (Lookup &&
4215 SemaRef.CheckUsingShadowDecl(BUD: Inst, Target: InstTarget, PreviousDecls: *Lookup, PrevShadow&: PrevDecl))
4216 continue;
4217
4218 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(D: Shadow))
4219 PrevDecl = cast_or_null<UsingShadowDecl>(Val: SemaRef.FindInstantiatedDecl(
4220 Loc: Shadow->getLocation(), D: OldPrev, TemplateArgs));
4221
4222 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
4223 /*Scope*/ S: nullptr, BUD: Inst, Target: InstTarget, PrevDecl);
4224 SemaRef.Context.setInstantiatedFromUsingShadowDecl(Inst: InstShadow, Pattern: Shadow);
4225
4226 if (isFunctionScope)
4227 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D: Shadow, Inst: InstShadow);
4228 }
4229
4230 return Inst;
4231}
4232
4233Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
4234
4235 // The nested name specifier may be dependent, for example
4236 // template <typename T> struct t {
4237 // struct s1 { T f1(); };
4238 // struct s2 : s1 { using s1::f1; };
4239 // };
4240 // template struct t<int>;
4241 // Here, in using s1::f1, s1 refers to t<T>::s1;
4242 // we need to substitute for t<int>::s1.
4243 NestedNameSpecifierLoc QualifierLoc
4244 = SemaRef.SubstNestedNameSpecifierLoc(NNS: D->getQualifierLoc(),
4245 TemplateArgs);
4246 if (!QualifierLoc)
4247 return nullptr;
4248
4249 // For an inheriting constructor declaration, the name of the using
4250 // declaration is the name of a constructor in this class, not in the
4251 // base class.
4252 DeclarationNameInfo NameInfo = D->getNameInfo();
4253 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
4254 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: SemaRef.CurContext))
4255 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
4256 Ty: SemaRef.Context.getCanonicalTagType(TD: RD)));
4257
4258 // We only need to do redeclaration lookups if we're in a class scope (in
4259 // fact, it's not really even possible in non-class scopes).
4260 bool CheckRedeclaration = Owner->isRecord();
4261 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
4262 RedeclarationKind::ForVisibleRedeclaration);
4263
4264 UsingDecl *NewUD = UsingDecl::Create(C&: SemaRef.Context, DC: Owner,
4265 UsingL: D->getUsingLoc(),
4266 QualifierLoc,
4267 NameInfo,
4268 HasTypenameKeyword: D->hasTypename());
4269
4270 CXXScopeSpec SS;
4271 SS.Adopt(Other: QualifierLoc);
4272 if (CheckRedeclaration) {
4273 Prev.setHideTags(false);
4274 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: Owner);
4275
4276 // Check for invalid redeclarations.
4277 if (SemaRef.CheckUsingDeclRedeclaration(UsingLoc: D->getUsingLoc(),
4278 HasTypenameKeyword: D->hasTypename(), SS,
4279 NameLoc: D->getLocation(), Previous: Prev))
4280 NewUD->setInvalidDecl();
4281 }
4282
4283 if (!NewUD->isInvalidDecl() &&
4284 SemaRef.CheckUsingDeclQualifier(UsingLoc: D->getUsingLoc(), HasTypename: D->hasTypename(), SS,
4285 NameInfo, NameLoc: D->getLocation(), R: nullptr, UD: D))
4286 NewUD->setInvalidDecl();
4287
4288 SemaRef.Context.setInstantiatedFromUsingDecl(Inst: NewUD, Pattern: D);
4289 NewUD->setAccess(D->getAccess());
4290 Owner->addDecl(D: NewUD);
4291
4292 // Don't process the shadow decls for an invalid decl.
4293 if (NewUD->isInvalidDecl())
4294 return NewUD;
4295
4296 // If the using scope was dependent, or we had dependent bases, we need to
4297 // recheck the inheritance
4298 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
4299 SemaRef.CheckInheritingConstructorUsingDecl(UD: NewUD);
4300
4301 return VisitBaseUsingDecls(D, Inst: NewUD, Lookup: CheckRedeclaration ? &Prev : nullptr);
4302}
4303
4304Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
4305 // Cannot be a dependent type, but still could be an instantiation
4306 EnumDecl *EnumD = cast_or_null<EnumDecl>(Val: SemaRef.FindInstantiatedDecl(
4307 Loc: D->getLocation(), D: D->getEnumDecl(), TemplateArgs));
4308
4309 if (SemaRef.RequireCompleteEnumDecl(D: EnumD, L: EnumD->getLocation()))
4310 return nullptr;
4311
4312 TypeSourceInfo *TSI = SemaRef.SubstType(T: D->getEnumType(), TemplateArgs,
4313 Loc: D->getLocation(), Entity: D->getDeclName());
4314
4315 if (!TSI)
4316 return nullptr;
4317
4318 UsingEnumDecl *NewUD =
4319 UsingEnumDecl::Create(C&: SemaRef.Context, DC: Owner, UsingL: D->getUsingLoc(),
4320 EnumL: D->getEnumLoc(), NameL: D->getLocation(), EnumType: TSI);
4321
4322 SemaRef.Context.setInstantiatedFromUsingEnumDecl(Inst: NewUD, Pattern: D);
4323 NewUD->setAccess(D->getAccess());
4324 Owner->addDecl(D: NewUD);
4325
4326 // Don't process the shadow decls for an invalid decl.
4327 if (NewUD->isInvalidDecl())
4328 return NewUD;
4329
4330 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
4331 // cannot be dependent, and will therefore have been checked during template
4332 // definition.
4333
4334 return VisitBaseUsingDecls(D, Inst: NewUD, Lookup: nullptr);
4335}
4336
4337Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
4338 // Ignore these; we handle them in bulk when processing the UsingDecl.
4339 return nullptr;
4340}
4341
4342Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
4343 ConstructorUsingShadowDecl *D) {
4344 // Ignore these; we handle them in bulk when processing the UsingDecl.
4345 return nullptr;
4346}
4347
4348template <typename T>
4349Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
4350 T *D, bool InstantiatingPackElement) {
4351 // If this is a pack expansion, expand it now.
4352 if (D->isPackExpansion() && !InstantiatingPackElement) {
4353 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4354 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
4355 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
4356
4357 // Determine whether the set of unexpanded parameter packs can and should
4358 // be expanded.
4359 bool Expand = true;
4360 bool RetainExpansion = false;
4361 UnsignedOrNone NumExpansions = std::nullopt;
4362 if (SemaRef.CheckParameterPacksForExpansion(
4363 EllipsisLoc: D->getEllipsisLoc(), PatternRange: D->getSourceRange(), Unexpanded, TemplateArgs,
4364 /*FailOnPackProducingTemplates=*/true, ShouldExpand&: Expand, RetainExpansion,
4365 NumExpansions))
4366 return nullptr;
4367
4368 // This declaration cannot appear within a function template signature,
4369 // so we can't have a partial argument list for a parameter pack.
4370 assert(!RetainExpansion &&
4371 "should never need to retain an expansion for UsingPackDecl");
4372
4373 if (!Expand) {
4374 // We cannot fully expand the pack expansion now, so substitute into the
4375 // pattern and create a new pack expansion.
4376 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, std::nullopt);
4377 return instantiateUnresolvedUsingDecl(D, true);
4378 }
4379
4380 // Within a function, we don't have any normal way to check for conflicts
4381 // between shadow declarations from different using declarations in the
4382 // same pack expansion, but this is always ill-formed because all expansions
4383 // must produce (conflicting) enumerators.
4384 //
4385 // Sadly we can't just reject this in the template definition because it
4386 // could be valid if the pack is empty or has exactly one expansion.
4387 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
4388 SemaRef.Diag(D->getEllipsisLoc(),
4389 diag::err_using_decl_redeclaration_expansion);
4390 return nullptr;
4391 }
4392
4393 // Instantiate the slices of this pack and build a UsingPackDecl.
4394 SmallVector<NamedDecl*, 8> Expansions;
4395 for (unsigned I = 0; I != *NumExpansions; ++I) {
4396 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
4397 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
4398 if (!Slice)
4399 return nullptr;
4400 // Note that we can still get unresolved using declarations here, if we
4401 // had arguments for all packs but the pattern also contained other
4402 // template arguments (this only happens during partial substitution, eg
4403 // into the body of a generic lambda in a function template).
4404 Expansions.push_back(Elt: cast<NamedDecl>(Val: Slice));
4405 }
4406
4407 auto *NewD = SemaRef.BuildUsingPackDecl(InstantiatedFrom: D, Expansions);
4408 if (isDeclWithinFunction(D))
4409 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: NewD);
4410 return NewD;
4411 }
4412
4413 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
4414 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
4415
4416 NestedNameSpecifierLoc QualifierLoc
4417 = SemaRef.SubstNestedNameSpecifierLoc(NNS: D->getQualifierLoc(),
4418 TemplateArgs);
4419 if (!QualifierLoc)
4420 return nullptr;
4421
4422 CXXScopeSpec SS;
4423 SS.Adopt(Other: QualifierLoc);
4424
4425 DeclarationNameInfo NameInfo
4426 = SemaRef.SubstDeclarationNameInfo(NameInfo: D->getNameInfo(), TemplateArgs);
4427
4428 // Produce a pack expansion only if we're not instantiating a particular
4429 // slice of a pack expansion.
4430 bool InstantiatingSlice =
4431 D->getEllipsisLoc().isValid() && SemaRef.ArgPackSubstIndex;
4432 SourceLocation EllipsisLoc =
4433 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
4434
4435 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
4436 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
4437 /*Scope*/ S: nullptr, AS: D->getAccess(), UsingLoc: D->getUsingLoc(),
4438 /*HasTypename*/ HasTypenameKeyword: TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
4439 AttrList: ParsedAttributesView(),
4440 /*IsInstantiation*/ true, IsUsingIfExists);
4441 if (UD) {
4442 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: D, New: UD);
4443 SemaRef.Context.setInstantiatedFromUsingDecl(Inst: UD, Pattern: D);
4444 }
4445
4446 return UD;
4447}
4448
4449Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
4450 UnresolvedUsingTypenameDecl *D) {
4451 return instantiateUnresolvedUsingDecl(D);
4452}
4453
4454Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
4455 UnresolvedUsingValueDecl *D) {
4456 return instantiateUnresolvedUsingDecl(D);
4457}
4458
4459Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
4460 UnresolvedUsingIfExistsDecl *D) {
4461 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
4462}
4463
4464Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
4465 SmallVector<NamedDecl*, 8> Expansions;
4466 for (auto *UD : D->expansions()) {
4467 if (NamedDecl *NewUD =
4468 SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), D: UD, TemplateArgs))
4469 Expansions.push_back(Elt: NewUD);
4470 else
4471 return nullptr;
4472 }
4473
4474 auto *NewD = SemaRef.BuildUsingPackDecl(InstantiatedFrom: D, Expansions);
4475 if (isDeclWithinFunction(D))
4476 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: NewD);
4477 return NewD;
4478}
4479
4480Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
4481 OMPThreadPrivateDecl *D) {
4482 SmallVector<Expr *, 5> Vars;
4483 for (auto *I : D->varlist()) {
4484 Expr *Var = SemaRef.SubstExpr(E: I, TemplateArgs).get();
4485 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
4486 Vars.push_back(Elt: Var);
4487 }
4488
4489 OMPThreadPrivateDecl *TD =
4490 SemaRef.OpenMP().CheckOMPThreadPrivateDecl(Loc: D->getLocation(), VarList: Vars);
4491
4492 TD->setAccess(AS_public);
4493 Owner->addDecl(D: TD);
4494
4495 return TD;
4496}
4497
4498Decl *
4499TemplateDeclInstantiator::VisitOMPGroupPrivateDecl(OMPGroupPrivateDecl *D) {
4500 SmallVector<Expr *, 5> Vars;
4501 for (auto *I : D->varlist()) {
4502 Expr *Var = SemaRef.SubstExpr(E: I, TemplateArgs).get();
4503 assert(isa<DeclRefExpr>(Var) && "groupprivate arg is not a DeclRefExpr");
4504 Vars.push_back(Elt: Var);
4505 }
4506
4507 OMPGroupPrivateDecl *TD =
4508 SemaRef.OpenMP().CheckOMPGroupPrivateDecl(Loc: D->getLocation(), VarList: Vars);
4509
4510 TD->setAccess(AS_public);
4511 Owner->addDecl(D: TD);
4512
4513 return TD;
4514}
4515
4516Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
4517 SmallVector<Expr *, 5> Vars;
4518 for (auto *I : D->varlist()) {
4519 Expr *Var = SemaRef.SubstExpr(E: I, TemplateArgs).get();
4520 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
4521 Vars.push_back(Elt: Var);
4522 }
4523 SmallVector<OMPClause *, 4> Clauses;
4524 // Copy map clauses from the original mapper.
4525 for (OMPClause *C : D->clauselists()) {
4526 OMPClause *IC = nullptr;
4527 if (auto *AC = dyn_cast<OMPAllocatorClause>(Val: C)) {
4528 ExprResult NewE = SemaRef.SubstExpr(E: AC->getAllocator(), TemplateArgs);
4529 if (!NewE.isUsable())
4530 continue;
4531 IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause(
4532 Allocator: NewE.get(), StartLoc: AC->getBeginLoc(), LParenLoc: AC->getLParenLoc(), EndLoc: AC->getEndLoc());
4533 } else if (auto *AC = dyn_cast<OMPAlignClause>(Val: C)) {
4534 ExprResult NewE = SemaRef.SubstExpr(E: AC->getAlignment(), TemplateArgs);
4535 if (!NewE.isUsable())
4536 continue;
4537 IC = SemaRef.OpenMP().ActOnOpenMPAlignClause(
4538 Alignment: NewE.get(), StartLoc: AC->getBeginLoc(), LParenLoc: AC->getLParenLoc(), EndLoc: AC->getEndLoc());
4539 // If align clause value ends up being invalid, this can end up null.
4540 if (!IC)
4541 continue;
4542 }
4543 Clauses.push_back(Elt: IC);
4544 }
4545
4546 Sema::DeclGroupPtrTy Res = SemaRef.OpenMP().ActOnOpenMPAllocateDirective(
4547 Loc: D->getLocation(), VarList: Vars, Clauses, Owner);
4548 if (Res.get().isNull())
4549 return nullptr;
4550 return Res.get().getSingleDecl();
4551}
4552
4553Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
4554 llvm_unreachable(
4555 "Requires directive cannot be instantiated within a dependent context");
4556}
4557
4558Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
4559 OMPDeclareReductionDecl *D) {
4560 // Instantiate type and check if it is allowed.
4561 const bool RequiresInstantiation =
4562 D->getType()->isDependentType() ||
4563 D->getType()->isInstantiationDependentType() ||
4564 D->getType()->containsUnexpandedParameterPack();
4565 QualType SubstReductionType;
4566 if (RequiresInstantiation) {
4567 SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType(
4568 TyLoc: D->getLocation(),
4569 ParsedType: ParsedType::make(P: SemaRef.SubstType(
4570 T: D->getType(), TemplateArgs, Loc: D->getLocation(), Entity: DeclarationName())));
4571 } else {
4572 SubstReductionType = D->getType();
4573 }
4574 if (SubstReductionType.isNull())
4575 return nullptr;
4576 Expr *Combiner = D->getCombiner();
4577 Expr *Init = D->getInitializer();
4578 bool IsCorrect = true;
4579 // Create instantiated copy.
4580 std::pair<QualType, SourceLocation> ReductionTypes[] = {
4581 std::make_pair(x&: SubstReductionType, y: D->getLocation())};
4582 auto *PrevDeclInScope = D->getPrevDeclInScope();
4583 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
4584 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
4585 Val: cast<Decl *>(Val&: *SemaRef.CurrentInstantiationScope->findInstantiationOf(
4586 D: PrevDeclInScope)));
4587 }
4588 auto DRD = SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveStart(
4589 /*S=*/nullptr, DC: Owner, Name: D->getDeclName(), ReductionTypes, AS: D->getAccess(),
4590 PrevDeclInScope);
4591 auto *NewDRD = cast<OMPDeclareReductionDecl>(Val: DRD.get().getSingleDecl());
4592 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: NewDRD);
4593 Expr *SubstCombiner = nullptr;
4594 Expr *SubstInitializer = nullptr;
4595 // Combiners instantiation sequence.
4596 if (Combiner) {
4597 SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerStart(
4598 /*S=*/nullptr, D: NewDRD);
4599 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4600 D: cast<DeclRefExpr>(Val: D->getCombinerIn())->getDecl(),
4601 Inst: cast<DeclRefExpr>(Val: NewDRD->getCombinerIn())->getDecl());
4602 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4603 D: cast<DeclRefExpr>(Val: D->getCombinerOut())->getDecl(),
4604 Inst: cast<DeclRefExpr>(Val: NewDRD->getCombinerOut())->getDecl());
4605 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: Owner);
4606 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
4607 ThisContext);
4608 SubstCombiner = SemaRef.SubstExpr(E: Combiner, TemplateArgs).get();
4609 SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerEnd(D: NewDRD,
4610 Combiner: SubstCombiner);
4611 }
4612 // Initializers instantiation sequence.
4613 if (Init) {
4614 VarDecl *OmpPrivParm =
4615 SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerStart(
4616 /*S=*/nullptr, D: NewDRD);
4617 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4618 D: cast<DeclRefExpr>(Val: D->getInitOrig())->getDecl(),
4619 Inst: cast<DeclRefExpr>(Val: NewDRD->getInitOrig())->getDecl());
4620 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4621 D: cast<DeclRefExpr>(Val: D->getInitPriv())->getDecl(),
4622 Inst: cast<DeclRefExpr>(Val: NewDRD->getInitPriv())->getDecl());
4623 if (D->getInitializerKind() == OMPDeclareReductionInitKind::Call) {
4624 SubstInitializer = SemaRef.SubstExpr(E: Init, TemplateArgs).get();
4625 } else {
4626 auto *OldPrivParm =
4627 cast<VarDecl>(Val: cast<DeclRefExpr>(Val: D->getInitPriv())->getDecl());
4628 IsCorrect = IsCorrect && OldPrivParm->hasInit();
4629 if (IsCorrect)
4630 SemaRef.InstantiateVariableInitializer(Var: OmpPrivParm, OldVar: OldPrivParm,
4631 TemplateArgs);
4632 }
4633 SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerEnd(
4634 D: NewDRD, Initializer: SubstInitializer, OmpPrivParm);
4635 }
4636 IsCorrect = IsCorrect && SubstCombiner &&
4637 (!Init ||
4638 (D->getInitializerKind() == OMPDeclareReductionInitKind::Call &&
4639 SubstInitializer) ||
4640 (D->getInitializerKind() != OMPDeclareReductionInitKind::Call &&
4641 !SubstInitializer));
4642
4643 (void)SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveEnd(
4644 /*S=*/nullptr, DeclReductions: DRD, IsValid: IsCorrect && !D->isInvalidDecl());
4645
4646 return NewDRD;
4647}
4648
4649Decl *
4650TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
4651 // Instantiate type and check if it is allowed.
4652 const bool RequiresInstantiation =
4653 D->getType()->isDependentType() ||
4654 D->getType()->isInstantiationDependentType() ||
4655 D->getType()->containsUnexpandedParameterPack();
4656 QualType SubstMapperTy;
4657 DeclarationName VN = D->getVarName();
4658 if (RequiresInstantiation) {
4659 SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType(
4660 TyLoc: D->getLocation(),
4661 ParsedType: ParsedType::make(P: SemaRef.SubstType(T: D->getType(), TemplateArgs,
4662 Loc: D->getLocation(), Entity: VN)));
4663 } else {
4664 SubstMapperTy = D->getType();
4665 }
4666 if (SubstMapperTy.isNull())
4667 return nullptr;
4668 // Create an instantiated copy of mapper.
4669 auto *PrevDeclInScope = D->getPrevDeclInScope();
4670 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
4671 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
4672 Val: cast<Decl *>(Val&: *SemaRef.CurrentInstantiationScope->findInstantiationOf(
4673 D: PrevDeclInScope)));
4674 }
4675 bool IsCorrect = true;
4676 SmallVector<OMPClause *, 6> Clauses;
4677 // Instantiate the mapper variable.
4678 DeclarationNameInfo DirName;
4679 SemaRef.OpenMP().StartOpenMPDSABlock(K: llvm::omp::OMPD_declare_mapper, DirName,
4680 /*S=*/CurScope: nullptr,
4681 Loc: (*D->clauselist_begin())->getBeginLoc());
4682 ExprResult MapperVarRef =
4683 SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirectiveVarDecl(
4684 /*S=*/nullptr, MapperType: SubstMapperTy, StartLoc: D->getLocation(), VN);
4685 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4686 D: cast<DeclRefExpr>(Val: D->getMapperVarRef())->getDecl(),
4687 Inst: cast<DeclRefExpr>(Val: MapperVarRef.get())->getDecl());
4688 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: Owner);
4689 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
4690 ThisContext);
4691 // Instantiate map clauses.
4692 for (OMPClause *C : D->clauselists()) {
4693 auto *OldC = cast<OMPMapClause>(Val: C);
4694 SmallVector<Expr *, 4> NewVars;
4695 for (Expr *OE : OldC->varlist()) {
4696 Expr *NE = SemaRef.SubstExpr(E: OE, TemplateArgs).get();
4697 if (!NE) {
4698 IsCorrect = false;
4699 break;
4700 }
4701 NewVars.push_back(Elt: NE);
4702 }
4703 if (!IsCorrect)
4704 break;
4705 NestedNameSpecifierLoc NewQualifierLoc =
4706 SemaRef.SubstNestedNameSpecifierLoc(NNS: OldC->getMapperQualifierLoc(),
4707 TemplateArgs);
4708 CXXScopeSpec SS;
4709 SS.Adopt(Other: NewQualifierLoc);
4710 DeclarationNameInfo NewNameInfo =
4711 SemaRef.SubstDeclarationNameInfo(NameInfo: OldC->getMapperIdInfo(), TemplateArgs);
4712 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
4713 OldC->getEndLoc());
4714 OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause(
4715 IteratorModifier: OldC->getIteratorModifier(), MapTypeModifiers: OldC->getMapTypeModifiers(),
4716 MapTypeModifiersLoc: OldC->getMapTypeModifiersLoc(), MapperIdScopeSpec&: SS, MapperId&: NewNameInfo, MapType: OldC->getMapType(),
4717 IsMapTypeImplicit: OldC->isImplicitMapType(), MapLoc: OldC->getMapLoc(), ColonLoc: OldC->getColonLoc(),
4718 VarList: NewVars, Locs);
4719 Clauses.push_back(Elt: NewC);
4720 }
4721 SemaRef.OpenMP().EndOpenMPDSABlock(CurDirective: nullptr);
4722 if (!IsCorrect)
4723 return nullptr;
4724 Sema::DeclGroupPtrTy DG = SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirective(
4725 /*S=*/nullptr, DC: Owner, Name: D->getDeclName(), MapperType: SubstMapperTy, StartLoc: D->getLocation(),
4726 VN, AS: D->getAccess(), MapperVarRef: MapperVarRef.get(), Clauses, PrevDeclInScope);
4727 Decl *NewDMD = DG.get().getSingleDecl();
4728 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: NewDMD);
4729 return NewDMD;
4730}
4731
4732Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
4733 OMPCapturedExprDecl * /*D*/) {
4734 llvm_unreachable("Should not be met in templates");
4735}
4736
4737Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
4738 return VisitFunctionDecl(D, TemplateParams: nullptr);
4739}
4740
4741Decl *
4742TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
4743 Decl *Inst = VisitFunctionDecl(D, TemplateParams: nullptr);
4744 if (Inst && !D->getDescribedFunctionTemplate())
4745 Owner->addDecl(D: Inst);
4746 return Inst;
4747}
4748
4749Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
4750 return VisitCXXMethodDecl(D, TemplateParams: nullptr);
4751}
4752
4753Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
4754 llvm_unreachable("There are only CXXRecordDecls in C++");
4755}
4756
4757Decl *
4758TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
4759 ClassTemplateSpecializationDecl *D) {
4760 // As a MS extension, we permit class-scope explicit specialization
4761 // of member class templates.
4762 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
4763 assert(ClassTemplate->getDeclContext()->isRecord() &&
4764 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
4765 "can only instantiate an explicit specialization "
4766 "for a member class template");
4767
4768 // Lookup the already-instantiated declaration in the instantiation
4769 // of the class template.
4770 ClassTemplateDecl *InstClassTemplate =
4771 cast_or_null<ClassTemplateDecl>(Val: SemaRef.FindInstantiatedDecl(
4772 Loc: D->getLocation(), D: ClassTemplate, TemplateArgs));
4773 if (!InstClassTemplate)
4774 return nullptr;
4775
4776 // Substitute into the template arguments of the class template explicit
4777 // specialization.
4778 TemplateArgumentListInfo InstTemplateArgs;
4779 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4780 D->getTemplateArgsAsWritten()) {
4781 InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4782 InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4783
4784 if (SemaRef.SubstTemplateArguments(Args: TemplateArgsInfo->arguments(),
4785 TemplateArgs, Outputs&: InstTemplateArgs))
4786 return nullptr;
4787 }
4788
4789 // Check that the template argument list is well-formed for this
4790 // class template.
4791 Sema::CheckTemplateArgumentInfo CTAI;
4792 if (SemaRef.CheckTemplateArgumentList(
4793 Template: InstClassTemplate, TemplateLoc: D->getLocation(), TemplateArgs&: InstTemplateArgs,
4794 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4795 /*UpdateArgsWithConversions=*/true))
4796 return nullptr;
4797
4798 // Figure out where to insert this class template explicit specialization
4799 // in the member template's set of class template explicit specializations.
4800 void *InsertPos = nullptr;
4801 ClassTemplateSpecializationDecl *PrevDecl =
4802 InstClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
4803
4804 // Check whether we've already seen a conflicting instantiation of this
4805 // declaration (for instance, if there was a prior implicit instantiation).
4806 bool Ignored;
4807 if (PrevDecl &&
4808 SemaRef.CheckSpecializationInstantiationRedecl(NewLoc: D->getLocation(),
4809 ActOnExplicitInstantiationNewTSK: D->getSpecializationKind(),
4810 PrevDecl,
4811 PrevTSK: PrevDecl->getSpecializationKind(),
4812 PrevPtOfInstantiation: PrevDecl->getPointOfInstantiation(),
4813 SuppressNew&: Ignored))
4814 return nullptr;
4815
4816 // If PrevDecl was a definition and D is also a definition, diagnose.
4817 // This happens in cases like:
4818 //
4819 // template<typename T, typename U>
4820 // struct Outer {
4821 // template<typename X> struct Inner;
4822 // template<> struct Inner<T> {};
4823 // template<> struct Inner<U> {};
4824 // };
4825 //
4826 // Outer<int, int> outer; // error: the explicit specializations of Inner
4827 // // have the same signature.
4828 if (PrevDecl && PrevDecl->getDefinition() &&
4829 D->isThisDeclarationADefinition()) {
4830 SemaRef.Diag(Loc: D->getLocation(), DiagID: diag::err_redefinition) << PrevDecl;
4831 SemaRef.Diag(Loc: PrevDecl->getDefinition()->getLocation(),
4832 DiagID: diag::note_previous_definition);
4833 return nullptr;
4834 }
4835
4836 // Create the class template partial specialization declaration.
4837 ClassTemplateSpecializationDecl *InstD =
4838 ClassTemplateSpecializationDecl::Create(
4839 Context&: SemaRef.Context, TK: D->getTagKind(), DC: Owner, StartLoc: D->getBeginLoc(),
4840 IdLoc: D->getLocation(), SpecializedTemplate: InstClassTemplate, Args: CTAI.CanonicalConverted,
4841 StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
4842 InstD->setTemplateArgsAsWritten(InstTemplateArgs);
4843
4844 // Add this partial specialization to the set of class template partial
4845 // specializations.
4846 if (!PrevDecl)
4847 InstClassTemplate->AddSpecialization(D: InstD, InsertPos);
4848
4849 // Substitute the nested name specifier, if any.
4850 if (SubstQualifier(OldDecl: D, NewDecl: InstD))
4851 return nullptr;
4852
4853 InstD->setAccess(D->getAccess());
4854 InstD->setInstantiationOfMemberClass(RD: D, TSK: TSK_ImplicitInstantiation);
4855 InstD->setSpecializationKind(D->getSpecializationKind());
4856 InstD->setExternKeywordLoc(D->getExternKeywordLoc());
4857 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
4858
4859 Owner->addDecl(D: InstD);
4860
4861 // Instantiate the members of the class-scope explicit specialization eagerly.
4862 // We don't have support for lazy instantiation of an explicit specialization
4863 // yet, and MSVC eagerly instantiates in this case.
4864 // FIXME: This is wrong in standard C++.
4865 if (D->isThisDeclarationADefinition() &&
4866 SemaRef.InstantiateClass(PointOfInstantiation: D->getLocation(), Instantiation: InstD, Pattern: D, TemplateArgs,
4867 TSK: TSK_ImplicitInstantiation,
4868 /*Complain=*/true))
4869 return nullptr;
4870
4871 return InstD;
4872}
4873
4874Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
4875 VarTemplateSpecializationDecl *D) {
4876
4877 TemplateArgumentListInfo VarTemplateArgsInfo;
4878 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
4879 assert(VarTemplate &&
4880 "A template specialization without specialized template?");
4881
4882 VarTemplateDecl *InstVarTemplate =
4883 cast_or_null<VarTemplateDecl>(Val: SemaRef.FindInstantiatedDecl(
4884 Loc: D->getLocation(), D: VarTemplate, TemplateArgs));
4885 if (!InstVarTemplate)
4886 return nullptr;
4887
4888 // Substitute the current template arguments.
4889 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4890 D->getTemplateArgsAsWritten()) {
4891 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4892 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4893
4894 if (SemaRef.SubstTemplateArguments(Args: TemplateArgsInfo->arguments(),
4895 TemplateArgs, Outputs&: VarTemplateArgsInfo))
4896 return nullptr;
4897 }
4898
4899 // Check that the template argument list is well-formed for this template.
4900 Sema::CheckTemplateArgumentInfo CTAI;
4901 if (SemaRef.CheckTemplateArgumentList(
4902 Template: InstVarTemplate, TemplateLoc: D->getLocation(), TemplateArgs&: VarTemplateArgsInfo,
4903 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4904 /*UpdateArgsWithConversions=*/true))
4905 return nullptr;
4906
4907 // Check whether we've already seen a declaration of this specialization.
4908 void *InsertPos = nullptr;
4909 VarTemplateSpecializationDecl *PrevDecl =
4910 InstVarTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
4911
4912 // Check whether we've already seen a conflicting instantiation of this
4913 // declaration (for instance, if there was a prior implicit instantiation).
4914 bool Ignored;
4915 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
4916 NewLoc: D->getLocation(), ActOnExplicitInstantiationNewTSK: D->getSpecializationKind(), PrevDecl,
4917 PrevTSK: PrevDecl->getSpecializationKind(),
4918 PrevPtOfInstantiation: PrevDecl->getPointOfInstantiation(), SuppressNew&: Ignored))
4919 return nullptr;
4920
4921 if (VarTemplateSpecializationDecl *VTSD = VisitVarTemplateSpecializationDecl(
4922 VarTemplate: InstVarTemplate, FromVar: D, Converted: CTAI.CanonicalConverted, PrevDecl)) {
4923 VTSD->setTemplateArgsAsWritten(VarTemplateArgsInfo);
4924 return VTSD;
4925 }
4926 return nullptr;
4927}
4928
4929VarTemplateSpecializationDecl *
4930TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
4931 VarTemplateDecl *VarTemplate, VarDecl *D,
4932 ArrayRef<TemplateArgument> Converted,
4933 VarTemplateSpecializationDecl *PrevDecl) {
4934
4935 // Do substitution on the type of the declaration
4936 TypeSourceInfo *TSI =
4937 SemaRef.SubstType(T: D->getTypeSourceInfo(), TemplateArgs,
4938 Loc: D->getTypeSpecStartLoc(), Entity: D->getDeclName());
4939 if (!TSI)
4940 return nullptr;
4941
4942 if (TSI->getType()->isFunctionType()) {
4943 SemaRef.Diag(Loc: D->getLocation(), DiagID: diag::err_variable_instantiates_to_function)
4944 << D->isStaticDataMember() << TSI->getType();
4945 return nullptr;
4946 }
4947
4948 // Build the instantiated declaration
4949 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
4950 Context&: SemaRef.Context, DC: Owner, StartLoc: D->getInnerLocStart(), IdLoc: D->getLocation(),
4951 SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI, S: D->getStorageClass(), Args: Converted);
4952 if (!PrevDecl) {
4953 void *InsertPos = nullptr;
4954 VarTemplate->findSpecialization(Args: Converted, InsertPos);
4955 VarTemplate->AddSpecialization(D: Var, InsertPos);
4956 }
4957
4958 if (SemaRef.getLangOpts().OpenCL)
4959 SemaRef.deduceOpenCLAddressSpace(decl: Var);
4960
4961 // Substitute the nested name specifier, if any.
4962 if (SubstQualifier(OldDecl: D, NewDecl: Var))
4963 return nullptr;
4964
4965 SemaRef.BuildVariableInstantiation(NewVar: Var, OldVar: D, TemplateArgs, LateAttrs, Owner,
4966 StartingScope, InstantiatingVarTemplate: false, PrevVTSD: PrevDecl);
4967
4968 return Var;
4969}
4970
4971Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
4972 llvm_unreachable("@defs is not supported in Objective-C++");
4973}
4974
4975Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
4976 ArrayRef<TemplateParameterList *> FriendTPLs = D->getTemplateParameterLists();
4977
4978 TypeSourceInfo *FriendTSI = D->getFriendType();
4979 if (FriendTSI && D->isPackExpansion() && InstantiateFriendPackExpansion(D))
4980 return nullptr;
4981
4982 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
4983 SmallVector<TemplateParameterList *, 1> InstTPLs;
4984 if (SubstTemplateParameterLists(TPLs: FriendTPLs, InstTPLs))
4985 return nullptr;
4986
4987 FriendDecl::FriendUnion ToFriend;
4988 TemplateName ToTemplate;
4989 if (FriendTSI) {
4990 std::optional<SubstitutedFriend> Substituted = SubstFriendTemplateType(
4991 SemaRef, TSI: FriendTSI, FriendTemplate: D->getFriendTemplateName(), TemplateArgs,
4992 Loc: D->getLocation(), Entity: DeclarationName());
4993 if (!Substituted || Substituted->empty())
4994 return nullptr;
4995 ToFriend = Substituted->TypeInfo;
4996 ToTemplate = Substituted->Template;
4997 } else if (!D->getFriendTemplateName().isNull()) {
4998 if (auto *InstTemplate =
4999 cast_or_null<TemplateDecl>(Val: Visit(D: D->getFriendDecl())))
5000 ToTemplate = TemplateName(InstTemplate);
5001 else
5002 return nullptr;
5003 } else {
5004 if (auto *InstFriendDecl =
5005 cast_or_null<NamedDecl>(Val: Visit(D: D->getFriendDecl())))
5006 ToFriend = InstFriendDecl;
5007 else
5008 return nullptr;
5009 }
5010
5011 FriendTemplateDecl *InstFriend = FriendTemplateDecl::Create(
5012 Context&: SemaRef.Context, DC: Owner, Loc: D->getLocation(), Friend: ToFriend, FriendLoc: D->getFriendLoc(),
5013 FriendTPLists: InstTPLs, /*EllipsisLoc=*/{}, Template: ToTemplate);
5014
5015 InstFriend->setAccess(AS_public);
5016 Owner->addDecl(D: InstFriend);
5017 return InstFriend;
5018}
5019
5020Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
5021 llvm_unreachable("Concept definitions cannot reside inside a template");
5022}
5023
5024Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
5025 ImplicitConceptSpecializationDecl *D) {
5026 llvm_unreachable("Concept specializations cannot reside inside a template");
5027}
5028
5029Decl *
5030TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
5031 return RequiresExprBodyDecl::Create(C&: SemaRef.Context, DC: D->getDeclContext(),
5032 StartLoc: D->getBeginLoc());
5033}
5034
5035Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
5036 llvm_unreachable("Unexpected decl");
5037}
5038
5039Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
5040 const MultiLevelTemplateArgumentList &TemplateArgs) {
5041 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
5042 if (D->isInvalidDecl())
5043 return nullptr;
5044
5045 Decl *SubstD;
5046 runWithSufficientStackSpace(Loc: D->getLocation(), Fn: [&] {
5047 SubstD = Instantiator.Visit(D);
5048 });
5049 return SubstD;
5050}
5051
5052void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
5053 FunctionDecl *Orig, QualType &T,
5054 TypeSourceInfo *&TInfo,
5055 DeclarationNameInfo &NameInfo) {
5056 assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual);
5057
5058 // C++2a [class.compare.default]p3:
5059 // the return type is replaced with bool
5060 auto *FPT = T->castAs<FunctionProtoType>();
5061 T = SemaRef.Context.getFunctionType(
5062 ResultTy: SemaRef.Context.BoolTy, Args: FPT->getParamTypes(), EPI: FPT->getExtProtoInfo());
5063
5064 // Update the return type in the source info too. The most straightforward
5065 // way is to create new TypeSourceInfo for the new type. Use the location of
5066 // the '= default' as the location of the new type.
5067 //
5068 // FIXME: Set the correct return type when we initially transform the type,
5069 // rather than delaying it to now.
5070 TypeSourceInfo *NewTInfo =
5071 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Orig->getEndLoc());
5072 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
5073 assert(OldLoc && "type of function is not a function type?");
5074 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
5075 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
5076 NewLoc.setParam(i: I, VD: OldLoc.getParam(i: I));
5077 TInfo = NewTInfo;
5078
5079 // and the declarator-id is replaced with operator==
5080 NameInfo.setName(
5081 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual));
5082}
5083
5084FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
5085 FunctionDecl *Spaceship) {
5086 if (Spaceship->isInvalidDecl())
5087 return nullptr;
5088
5089 // C++2a [class.compare.default]p3:
5090 // an == operator function is declared implicitly [...] with the same
5091 // access and function-definition and in the same class scope as the
5092 // three-way comparison operator function
5093 MultiLevelTemplateArgumentList NoTemplateArgs;
5094 NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite);
5095 NoTemplateArgs.addOuterRetainedLevels(Num: RD->getTemplateDepth());
5096 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
5097 Decl *R;
5098 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Spaceship)) {
5099 R = Instantiator.VisitCXXMethodDecl(
5100 D: MD, /*TemplateParams=*/nullptr,
5101 FunctionRewriteKind: TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
5102 } else {
5103 assert(Spaceship->getFriendObjectKind() &&
5104 "defaulted spaceship is neither a member nor a friend");
5105
5106 R = Instantiator.VisitFunctionDecl(
5107 D: Spaceship, /*TemplateParams=*/nullptr,
5108 FunctionRewriteKind: TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
5109 if (!R)
5110 return nullptr;
5111
5112 FriendDecl *FD =
5113 FriendDecl::Create(C&: Context, DC: RD, L: Spaceship->getLocation(),
5114 Friend: cast<NamedDecl>(Val: R), FriendL: Spaceship->getBeginLoc());
5115 FD->setAccess(AS_public);
5116 RD->addDecl(D: FD);
5117 }
5118 return cast_or_null<FunctionDecl>(Val: R);
5119}
5120
5121/// Instantiates a nested template parameter list in the current
5122/// instantiation context.
5123///
5124/// \param L The parameter list to instantiate
5125///
5126/// \returns NULL if there was an error
5127TemplateParameterList *
5128TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
5129 // Get errors for all the parameters before bailing out.
5130 bool Invalid = false;
5131
5132 unsigned N = L->size();
5133 typedef SmallVector<NamedDecl *, 8> ParamVector;
5134 ParamVector Params;
5135 Params.reserve(N);
5136 for (auto &P : *L) {
5137 NamedDecl *D = cast_or_null<NamedDecl>(Val: Visit(D: P));
5138 Params.push_back(Elt: D);
5139 Invalid = Invalid || !D || D->isInvalidDecl();
5140 }
5141
5142 // Clean up if we had an error.
5143 if (Invalid)
5144 return nullptr;
5145
5146 Expr *InstRequiresClause = L->getRequiresClause();
5147 if (InstRequiresClause && EvaluateConstraints) {
5148 ExprResult E =
5149 SemaRef.SubstConstraintExpr(E: InstRequiresClause, TemplateArgs);
5150 if (E.isInvalid())
5151 return nullptr;
5152 InstRequiresClause = E.get();
5153 }
5154
5155 TemplateParameterList *InstL
5156 = TemplateParameterList::Create(C: SemaRef.Context, TemplateLoc: L->getTemplateLoc(),
5157 LAngleLoc: L->getLAngleLoc(), Params,
5158 RAngleLoc: L->getRAngleLoc(), RequiresClause: InstRequiresClause);
5159 return InstL;
5160}
5161
5162bool TemplateDeclInstantiator::SubstTemplateParameterLists(
5163 ArrayRef<TemplateParameterList *> TPLs,
5164 SmallVectorImpl<TemplateParameterList *> &InstTPLs) {
5165 llvm::SaveAndRestore RAII(EvaluateConstraints, false);
5166 for (TemplateParameterList *L : TPLs) {
5167 TemplateParameterList *InstParams = SubstTemplateParams(L);
5168 if (!InstParams)
5169 return true;
5170
5171 if (Expr *RequiresClause = L->getRequiresClause()) {
5172 ExprResult InstRequiresClause =
5173 SemaRef.SubstConstraintExprWithoutSatisfaction(E: RequiresClause,
5174 TemplateArgs);
5175 if (!InstRequiresClause.isUsable())
5176 return true;
5177
5178 InstParams = TemplateParameterList::Create(
5179 C: SemaRef.Context, TemplateLoc: InstParams->getTemplateLoc(),
5180 LAngleLoc: InstParams->getLAngleLoc(), Params: InstParams->asArray(),
5181 RAngleLoc: InstParams->getRAngleLoc(), RequiresClause: InstRequiresClause.get());
5182 }
5183
5184 InstTPLs.push_back(Elt: InstParams);
5185 }
5186 return false;
5187}
5188
5189TemplateParameterList *
5190Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
5191 const MultiLevelTemplateArgumentList &TemplateArgs,
5192 bool EvaluateConstraints) {
5193 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
5194 Instantiator.setEvaluateConstraints(EvaluateConstraints);
5195 return Instantiator.SubstTemplateParams(L: Params);
5196}
5197
5198/// Instantiate the declaration of a class template partial
5199/// specialization.
5200///
5201/// \param ClassTemplate the (instantiated) class template that is partially
5202// specialized by the instantiation of \p PartialSpec.
5203///
5204/// \param PartialSpec the (uninstantiated) class template partial
5205/// specialization that we are instantiating.
5206///
5207/// \returns The instantiated partial specialization, if successful; otherwise,
5208/// NULL to indicate an error.
5209ClassTemplatePartialSpecializationDecl *
5210TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
5211 ClassTemplateDecl *ClassTemplate,
5212 ClassTemplatePartialSpecializationDecl *PartialSpec) {
5213 // Create a local instantiation scope for this class template partial
5214 // specialization, which will contain the instantiations of the template
5215 // parameters.
5216 LocalInstantiationScope Scope(SemaRef);
5217
5218 // Substitute into the template parameters of the class template partial
5219 // specialization.
5220 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
5221 TemplateParameterList *InstParams = SubstTemplateParams(L: TempParams);
5222 if (!InstParams)
5223 return nullptr;
5224
5225 // Substitute into the template arguments of the class template partial
5226 // specialization.
5227 const ASTTemplateArgumentListInfo *TemplArgInfo
5228 = PartialSpec->getTemplateArgsAsWritten();
5229 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
5230 TemplArgInfo->RAngleLoc);
5231 if (SemaRef.SubstTemplateArguments(Args: TemplArgInfo->arguments(), TemplateArgs,
5232 Outputs&: InstTemplateArgs))
5233 return nullptr;
5234
5235 // Check that the template argument list is well-formed for this
5236 // class template.
5237 Sema::CheckTemplateArgumentInfo CTAI;
5238 if (SemaRef.CheckTemplateArgumentList(
5239 Template: ClassTemplate, TemplateLoc: PartialSpec->getLocation(), TemplateArgs&: InstTemplateArgs,
5240 /*DefaultArgs=*/{},
5241 /*PartialTemplateArgs=*/false, CTAI))
5242 return nullptr;
5243
5244 // Check these arguments are valid for a template partial specialization.
5245 if (SemaRef.CheckTemplatePartialSpecializationArgs(
5246 Loc: PartialSpec->getLocation(), PrimaryTemplate: ClassTemplate, NumExplicitArgs: InstTemplateArgs.size(),
5247 Args: CTAI.CanonicalConverted))
5248 return nullptr;
5249
5250 // Figure out where to insert this class template partial specialization
5251 // in the member template's set of class template partial specializations.
5252 void *InsertPos = nullptr;
5253 ClassTemplateSpecializationDecl *PrevDecl =
5254 ClassTemplate->findPartialSpecialization(Args: CTAI.CanonicalConverted,
5255 TPL: InstParams, InsertPos);
5256
5257 // Create the class template partial specialization declaration.
5258 ClassTemplatePartialSpecializationDecl *InstPartialSpec =
5259 ClassTemplatePartialSpecializationDecl::Create(
5260 Context&: SemaRef.Context, TK: PartialSpec->getTagKind(), DC: Owner,
5261 StartLoc: PartialSpec->getBeginLoc(), IdLoc: PartialSpec->getLocation(), Params: InstParams,
5262 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted,
5263 /*CanonInjectedTST=*/CanQualType(),
5264 /*PrevDecl=*/nullptr);
5265
5266 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
5267
5268 // Substitute the nested name specifier, if any.
5269 if (SubstQualifier(OldDecl: PartialSpec, NewDecl: InstPartialSpec))
5270 return nullptr;
5271
5272 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
5273
5274 if (PrevDecl) {
5275 // We've already seen a partial specialization with the same template
5276 // parameters and template arguments. This can happen, for example, when
5277 // substituting the outer template arguments ends up causing two
5278 // class template partial specializations of a member class template
5279 // to have identical forms, e.g.,
5280 //
5281 // template<typename T, typename U>
5282 // struct Outer {
5283 // template<typename X, typename Y> struct Inner;
5284 // template<typename Y> struct Inner<T, Y>;
5285 // template<typename Y> struct Inner<U, Y>;
5286 // };
5287 //
5288 // Outer<int, int> outer; // error: the partial specializations of Inner
5289 // // have the same signature.
5290 SemaRef.Diag(Loc: InstPartialSpec->getLocation(),
5291 DiagID: diag::err_partial_spec_redeclared)
5292 << InstPartialSpec;
5293 SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_prev_partial_spec_here)
5294 << SemaRef.Context.getCanonicalTagType(TD: PrevDecl);
5295 return nullptr;
5296 }
5297
5298 // Check the completed partial specialization.
5299 SemaRef.CheckTemplatePartialSpecialization(Partial: InstPartialSpec);
5300
5301 // Add this partial specialization to the set of class template partial
5302 // specializations.
5303 ClassTemplate->AddPartialSpecialization(D: InstPartialSpec,
5304 /*InsertPos=*/nullptr);
5305 return InstPartialSpec;
5306}
5307
5308/// Instantiate the declaration of a variable template partial
5309/// specialization.
5310///
5311/// \param VarTemplate the (instantiated) variable template that is partially
5312/// specialized by the instantiation of \p PartialSpec.
5313///
5314/// \param PartialSpec the (uninstantiated) variable template partial
5315/// specialization that we are instantiating.
5316///
5317/// \returns The instantiated partial specialization, if successful; otherwise,
5318/// NULL to indicate an error.
5319VarTemplatePartialSpecializationDecl *
5320TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
5321 VarTemplateDecl *VarTemplate,
5322 VarTemplatePartialSpecializationDecl *PartialSpec) {
5323 // Create a local instantiation scope for this variable template partial
5324 // specialization, which will contain the instantiations of the template
5325 // parameters.
5326 LocalInstantiationScope Scope(SemaRef);
5327
5328 // Substitute into the template parameters of the variable template partial
5329 // specialization.
5330 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
5331 TemplateParameterList *InstParams = SubstTemplateParams(L: TempParams);
5332 if (!InstParams)
5333 return nullptr;
5334
5335 // Substitute into the template arguments of the variable template partial
5336 // specialization.
5337 const ASTTemplateArgumentListInfo *TemplArgInfo
5338 = PartialSpec->getTemplateArgsAsWritten();
5339 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
5340 TemplArgInfo->RAngleLoc);
5341 if (SemaRef.SubstTemplateArguments(Args: TemplArgInfo->arguments(), TemplateArgs,
5342 Outputs&: InstTemplateArgs))
5343 return nullptr;
5344
5345 // Check that the template argument list is well-formed for this
5346 // class template.
5347 Sema::CheckTemplateArgumentInfo CTAI;
5348 if (SemaRef.CheckTemplateArgumentList(Template: VarTemplate, TemplateLoc: PartialSpec->getLocation(),
5349 TemplateArgs&: InstTemplateArgs, /*DefaultArgs=*/{},
5350 /*PartialTemplateArgs=*/false, CTAI))
5351 return nullptr;
5352
5353 // Check these arguments are valid for a template partial specialization.
5354 if (SemaRef.CheckTemplatePartialSpecializationArgs(
5355 Loc: PartialSpec->getLocation(), PrimaryTemplate: VarTemplate, NumExplicitArgs: InstTemplateArgs.size(),
5356 Args: CTAI.CanonicalConverted))
5357 return nullptr;
5358
5359 // Figure out where to insert this variable template partial specialization
5360 // in the member template's set of variable template partial specializations.
5361 void *InsertPos = nullptr;
5362 VarTemplateSpecializationDecl *PrevDecl =
5363 VarTemplate->findPartialSpecialization(Args: CTAI.CanonicalConverted,
5364 TPL: InstParams, InsertPos);
5365
5366 // Do substitution on the type of the declaration
5367 TypeSourceInfo *TSI = SemaRef.SubstType(
5368 T: PartialSpec->getTypeSourceInfo(), TemplateArgs,
5369 Loc: PartialSpec->getTypeSpecStartLoc(), Entity: PartialSpec->getDeclName());
5370 if (!TSI)
5371 return nullptr;
5372
5373 if (TSI->getType()->isFunctionType()) {
5374 SemaRef.Diag(Loc: PartialSpec->getLocation(),
5375 DiagID: diag::err_variable_instantiates_to_function)
5376 << PartialSpec->isStaticDataMember() << TSI->getType();
5377 return nullptr;
5378 }
5379
5380 // Create the variable template partial specialization declaration.
5381 VarTemplatePartialSpecializationDecl *InstPartialSpec =
5382 VarTemplatePartialSpecializationDecl::Create(
5383 Context&: SemaRef.Context, DC: Owner, StartLoc: PartialSpec->getInnerLocStart(),
5384 IdLoc: PartialSpec->getLocation(), Params: InstParams, SpecializedTemplate: VarTemplate, T: TSI->getType(),
5385 TInfo: TSI, S: PartialSpec->getStorageClass(), Args: CTAI.CanonicalConverted);
5386
5387 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
5388
5389 // Substitute the nested name specifier, if any.
5390 if (SubstQualifier(OldDecl: PartialSpec, NewDecl: InstPartialSpec))
5391 return nullptr;
5392
5393 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
5394
5395 if (PrevDecl) {
5396 // We've already seen a partial specialization with the same template
5397 // parameters and template arguments. This can happen, for example, when
5398 // substituting the outer template arguments ends up causing two
5399 // variable template partial specializations of a member variable template
5400 // to have identical forms, e.g.,
5401 //
5402 // template<typename T, typename U>
5403 // struct Outer {
5404 // template<typename X, typename Y> pair<X,Y> p;
5405 // template<typename Y> pair<T, Y> p;
5406 // template<typename Y> pair<U, Y> p;
5407 // };
5408 //
5409 // Outer<int, int> outer; // error: the partial specializations of Inner
5410 // // have the same signature.
5411 SemaRef.Diag(Loc: PartialSpec->getLocation(),
5412 DiagID: diag::err_var_partial_spec_redeclared)
5413 << InstPartialSpec;
5414 SemaRef.Diag(Loc: PrevDecl->getLocation(),
5415 DiagID: diag::note_var_prev_partial_spec_here);
5416 return nullptr;
5417 }
5418 // Check the completed partial specialization.
5419 SemaRef.CheckTemplatePartialSpecialization(Partial: InstPartialSpec);
5420
5421 // Add this partial specialization to the set of variable template partial
5422 // specializations. The instantiation of the initializer is not necessary.
5423 VarTemplate->AddPartialSpecialization(D: InstPartialSpec, /*InsertPos=*/nullptr);
5424
5425 SemaRef.BuildVariableInstantiation(NewVar: InstPartialSpec, OldVar: PartialSpec, TemplateArgs,
5426 LateAttrs, Owner, StartingScope);
5427
5428 return InstPartialSpec;
5429}
5430
5431TypeSourceInfo *TemplateDeclInstantiator::SubstFunctionType(
5432 FunctionDecl *D, SmallVectorImpl<ParmVarDecl *> &Params) {
5433 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
5434 assert(OldTInfo && "substituting function without type source info");
5435 assert(Params.empty() && "parameter vector is non-empty at start");
5436
5437 CXXRecordDecl *ThisContext = nullptr;
5438 Qualifiers ThisTypeQuals;
5439 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
5440 ThisContext = cast<CXXRecordDecl>(Val: Owner);
5441 ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
5442 }
5443
5444 TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
5445 T: OldTInfo, TemplateArgs, Loc: D->getTypeSpecStartLoc(), Entity: D->getDeclName(),
5446 ThisContext, ThisTypeQuals, EvaluateConstraints);
5447 if (!NewTInfo)
5448 return nullptr;
5449
5450 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
5451 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
5452 if (NewTInfo != OldTInfo) {
5453 // Get parameters from the new type info.
5454 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
5455 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
5456 unsigned NewIdx = 0;
5457 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
5458 OldIdx != NumOldParams; ++OldIdx) {
5459 ParmVarDecl *OldParam = OldProtoLoc.getParam(i: OldIdx);
5460 if (!OldParam)
5461 return nullptr;
5462
5463 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
5464
5465 UnsignedOrNone NumArgumentsInExpansion = std::nullopt;
5466 if (OldParam->isParameterPack())
5467 NumArgumentsInExpansion =
5468 SemaRef.getNumArgumentsInExpansion(T: OldParam->getType(),
5469 TemplateArgs);
5470 if (!NumArgumentsInExpansion) {
5471 // Simple case: normal parameter, or a parameter pack that's
5472 // instantiated to a (still-dependent) parameter pack.
5473 ParmVarDecl *NewParam = NewProtoLoc.getParam(i: NewIdx++);
5474 Params.push_back(Elt: NewParam);
5475 Scope->InstantiatedLocal(D: OldParam, Inst: NewParam);
5476 } else {
5477 // Parameter pack expansion: make the instantiation an argument pack.
5478 Scope->MakeInstantiatedLocalArgPack(D: OldParam);
5479 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
5480 ParmVarDecl *NewParam = NewProtoLoc.getParam(i: NewIdx++);
5481 Params.push_back(Elt: NewParam);
5482 Scope->InstantiatedLocalPackArg(D: OldParam, Inst: NewParam);
5483 }
5484 }
5485 }
5486 } else {
5487 // The function type itself was not dependent and therefore no
5488 // substitution occurred. However, we still need to instantiate
5489 // the function parameters themselves.
5490 const FunctionProtoType *OldProto =
5491 cast<FunctionProtoType>(Val: OldProtoLoc.getType());
5492 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
5493 ++i) {
5494 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
5495 if (!OldParam) {
5496 Params.push_back(Elt: SemaRef.BuildParmVarDeclForTypedef(
5497 DC: D, Loc: D->getLocation(), T: OldProto->getParamType(i)));
5498 continue;
5499 }
5500
5501 ParmVarDecl *Parm = SemaRef.SubstParmVarDecl(
5502 D: OldParam, TemplateArgs, /*indexAdjustment=*/0,
5503 /*NumExpansions=*/std::nullopt,
5504 /*ExpectParameterPack=*/false, EvaluateConstraints);
5505 if (!Parm)
5506 return nullptr;
5507 Params.push_back(Elt: Parm);
5508 }
5509 }
5510 } else {
5511 // If the type of this function, after ignoring parentheses, is not
5512 // *directly* a function type, then we're instantiating a function that
5513 // was declared via a typedef or with attributes, e.g.,
5514 //
5515 // typedef int functype(int, int);
5516 // functype func;
5517 // int __cdecl meth(int, int);
5518 //
5519 // In this case, we'll just go instantiate the ParmVarDecls that we
5520 // synthesized in the method declaration.
5521 SmallVector<QualType, 4> ParamTypes;
5522 Sema::ExtParameterInfoBuilder ExtParamInfos;
5523 if (SemaRef.SubstParmTypes(Loc: D->getLocation(), Params: D->parameters(), ExtParamInfos: nullptr,
5524 TemplateArgs, ParamTypes, OutParams: &Params,
5525 ParamInfos&: ExtParamInfos))
5526 return nullptr;
5527 }
5528
5529 return NewTInfo;
5530}
5531
5532void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
5533 const FunctionDecl *PatternDecl,
5534 LocalInstantiationScope &Scope) {
5535 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: getFunctionScopes().back());
5536
5537 for (auto *decl : PatternDecl->decls()) {
5538 if (!isa<VarDecl>(Val: decl) || isa<ParmVarDecl>(Val: decl))
5539 continue;
5540
5541 VarDecl *VD = cast<VarDecl>(Val: decl);
5542 IdentifierInfo *II = VD->getIdentifier();
5543
5544 auto it = llvm::find_if(Range: Function->decls(), P: [&](Decl *inst) {
5545 VarDecl *InstVD = dyn_cast<VarDecl>(Val: inst);
5546 return InstVD && InstVD->isLocalVarDecl() &&
5547 InstVD->getIdentifier() == II;
5548 });
5549
5550 if (it == Function->decls().end())
5551 continue;
5552
5553 Scope.InstantiatedLocal(D: VD, Inst: *it);
5554 LSI->addCapture(Var: cast<VarDecl>(Val: *it), /*isBlock=*/false, /*isByref=*/false,
5555 /*isNested=*/false, Loc: VD->getLocation(), EllipsisLoc: SourceLocation(),
5556 CaptureType: VD->getType(), /*Invalid=*/false);
5557 }
5558}
5559
5560bool Sema::addInstantiatedParametersToScope(
5561 FunctionDecl *Function, const FunctionDecl *PatternDecl,
5562 LocalInstantiationScope &Scope,
5563 const MultiLevelTemplateArgumentList &TemplateArgs) {
5564 unsigned FParamIdx = 0;
5565 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
5566 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(i: I);
5567 if (!PatternParam->isParameterPack()) {
5568 // Simple case: not a parameter pack.
5569 assert(FParamIdx < Function->getNumParams());
5570 ParmVarDecl *FunctionParam = Function->getParamDecl(i: FParamIdx);
5571 FunctionParam->setDeclName(PatternParam->getDeclName());
5572 // If the parameter's type is not dependent, update it to match the type
5573 // in the pattern. They can differ in top-level cv-qualifiers, and we want
5574 // the pattern's type here. If the type is dependent, they can't differ,
5575 // per core issue 1668. Substitute into the type from the pattern, in case
5576 // it's instantiation-dependent.
5577 // FIXME: Updating the type to work around this is at best fragile.
5578 if (!PatternDecl->getType()->isDependentType()) {
5579 QualType T = SubstType(T: PatternParam->getType(), TemplateArgs,
5580 Loc: FunctionParam->getLocation(),
5581 Entity: FunctionParam->getDeclName());
5582 if (T.isNull())
5583 return true;
5584 FunctionParam->setType(T);
5585 }
5586
5587 Scope.InstantiatedLocal(D: PatternParam, Inst: FunctionParam);
5588 ++FParamIdx;
5589 continue;
5590 }
5591
5592 // Expand the parameter pack.
5593 Scope.MakeInstantiatedLocalArgPack(D: PatternParam);
5594 UnsignedOrNone NumArgumentsInExpansion =
5595 getNumArgumentsInExpansion(T: PatternParam->getType(), TemplateArgs);
5596 if (NumArgumentsInExpansion) {
5597 QualType PatternType =
5598 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
5599 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
5600 ParmVarDecl *FunctionParam = Function->getParamDecl(i: FParamIdx);
5601 FunctionParam->setDeclName(PatternParam->getDeclName());
5602 if (!PatternDecl->getType()->isDependentType()) {
5603 Sema::ArgPackSubstIndexRAII SubstIndex(*this, Arg);
5604 QualType T =
5605 SubstType(T: PatternType, TemplateArgs, Loc: FunctionParam->getLocation(),
5606 Entity: FunctionParam->getDeclName());
5607 if (T.isNull())
5608 return true;
5609 FunctionParam->setType(T);
5610 }
5611
5612 Scope.InstantiatedLocalPackArg(D: PatternParam, Inst: FunctionParam);
5613 ++FParamIdx;
5614 }
5615 }
5616 }
5617
5618 return false;
5619}
5620
5621bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
5622 ParmVarDecl *Param) {
5623 assert(Param->hasUninstantiatedDefaultArg());
5624
5625 // FIXME: We don't track member specialization info for non-defining
5626 // friend declarations, so we will not be able to later find the function
5627 // pattern. As a workaround, don't instantiate the default argument in this
5628 // case. This is correct per the standard and only an issue for recovery
5629 // purposes. [dcl.fct.default]p4:
5630 // if a friend declaration D specifies a default argument expression,
5631 // that declaration shall be a definition.
5632 if (FD->getFriendObjectKind() != Decl::FOK_None &&
5633 !FD->getTemplateInstantiationPattern())
5634 return true;
5635
5636 // Instantiate the expression.
5637 //
5638 // FIXME: Pass in a correct Pattern argument, otherwise
5639 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
5640 //
5641 // template<typename T>
5642 // struct A {
5643 // static int FooImpl();
5644 //
5645 // template<typename Tp>
5646 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
5647 // // template argument list [[T], [Tp]], should be [[Tp]].
5648 // friend A<Tp> Foo(int a);
5649 // };
5650 //
5651 // template<typename T>
5652 // A<T> Foo(int a = A<T>::FooImpl());
5653 MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
5654 D: FD, DC: FD->getLexicalDeclContext(),
5655 /*Final=*/false, /*Innermost=*/std::nullopt,
5656 /*RelativeToPrimary=*/true, /*Pattern=*/nullptr,
5657 /*ForConstraintInstantiation=*/false, /*SkipForSpecialization=*/false,
5658 /*ForDefaultArgumentSubstitution=*/true);
5659
5660 if (SubstDefaultArgument(Loc: CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
5661 return true;
5662
5663 if (ASTMutationListener *L = getASTMutationListener())
5664 L->DefaultArgumentInstantiated(D: Param);
5665
5666 return false;
5667}
5668
5669void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
5670 FunctionDecl *Decl) {
5671 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
5672 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
5673 return;
5674
5675 RecursiveInstGuard AlreadyInstantiating(
5676 *this, Decl, RecursiveInstGuard::Kind::ExceptionSpec);
5677 if (AlreadyInstantiating) {
5678 // This exception specification indirectly depends on itself. Reject.
5679 // FIXME: Corresponding rule in the standard?
5680 Diag(Loc: PointOfInstantiation, DiagID: diag::err_exception_spec_cycle) << Decl;
5681 UpdateExceptionSpec(FD: Decl, ESI: EST_None);
5682 return;
5683 }
5684
5685 NonSFINAEContext _(*this);
5686 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
5687 InstantiatingTemplate::ExceptionSpecification());
5688 if (Inst.isInvalid()) {
5689 // We hit the instantiation depth limit. Clear the exception specification
5690 // so that our callers don't have to cope with EST_Uninstantiated.
5691 UpdateExceptionSpec(FD: Decl, ESI: EST_None);
5692 return;
5693 }
5694
5695 // Enter the scope of this instantiation. We don't use
5696 // PushDeclContext because we don't have a scope.
5697 Sema::ContextRAII savedContext(*this, Decl);
5698 LocalInstantiationScope Scope(*this);
5699
5700 MultiLevelTemplateArgumentList TemplateArgs =
5701 getTemplateInstantiationArgs(D: Decl, DC: Decl->getLexicalDeclContext(),
5702 /*Final=*/false, /*Innermost=*/std::nullopt,
5703 /*RelativeToPrimary*/ true);
5704
5705 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
5706 // here, because for a non-defining friend declaration in a class template,
5707 // we don't store enough information to map back to the friend declaration in
5708 // the template.
5709 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
5710 if (addInstantiatedParametersToScope(Function: Decl, PatternDecl: Template, Scope, TemplateArgs)) {
5711 UpdateExceptionSpec(FD: Decl, ESI: EST_None);
5712 return;
5713 }
5714
5715 // The noexcept specification could reference any lambda captures. Ensure
5716 // those are added to the LocalInstantiationScope.
5717 LambdaScopeForCallOperatorInstantiationRAII PushLambdaCaptures(
5718 *this, Decl, TemplateArgs, Scope,
5719 /*ShouldAddDeclsFromParentScope=*/false);
5720
5721 SubstExceptionSpec(New: Decl, Proto: Template->getType()->castAs<FunctionProtoType>(),
5722 Args: TemplateArgs);
5723}
5724
5725/// Initializes the common fields of an instantiation function
5726/// declaration (New) from the corresponding fields of its template (Tmpl).
5727///
5728/// \returns true if there was an error
5729bool
5730TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
5731 FunctionDecl *Tmpl) {
5732 New->setImplicit(Tmpl->isImplicit());
5733
5734 // Forward the mangling number from the template to the instantiated decl.
5735 SemaRef.Context.setManglingNumber(ND: New,
5736 Number: SemaRef.Context.getManglingNumber(ND: Tmpl));
5737
5738 // If we are performing substituting explicitly-specified template arguments
5739 // or deduced template arguments into a function template and we reach this
5740 // point, we are now past the point where SFINAE applies and have committed
5741 // to keeping the new function template specialization. We therefore
5742 // convert the active template instantiation for the function template
5743 // into a template instantiation for this specific function template
5744 // specialization, which is not a SFINAE context, so that we diagnose any
5745 // further errors in the declaration itself.
5746 //
5747 // FIXME: This is a hack.
5748 typedef Sema::CodeSynthesisContext ActiveInstType;
5749 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
5750 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
5751 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
5752 if (isa<FunctionTemplateDecl>(Val: ActiveInst.Entity)) {
5753 SemaRef.CurrentSFINAEContext = nullptr;
5754 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
5755 ActiveInst.Entity = New;
5756 }
5757 }
5758
5759 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
5760 assert(Proto && "Function template without prototype?");
5761
5762 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
5763 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5764
5765 // DR1330: In C++11, defer instantiation of a non-trivial
5766 // exception specification.
5767 // DR1484: Local classes and their members are instantiated along with the
5768 // containing function.
5769 if (SemaRef.getLangOpts().CPlusPlus11 &&
5770 EPI.ExceptionSpec.Type != EST_None &&
5771 EPI.ExceptionSpec.Type != EST_DynamicNone &&
5772 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
5773 !Tmpl->isInLocalScopeForInstantiation()) {
5774 FunctionDecl *ExceptionSpecTemplate = Tmpl;
5775 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
5776 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
5777 ExceptionSpecificationType NewEST = EST_Uninstantiated;
5778 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
5779 NewEST = EST_Unevaluated;
5780
5781 // Mark the function has having an uninstantiated exception specification.
5782 const FunctionProtoType *NewProto
5783 = New->getType()->getAs<FunctionProtoType>();
5784 assert(NewProto && "Template instantiation without function prototype?");
5785 EPI = NewProto->getExtProtoInfo();
5786 EPI.ExceptionSpec.Type = NewEST;
5787 EPI.ExceptionSpec.SourceDecl = New;
5788 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
5789 New->setType(SemaRef.Context.getFunctionType(
5790 ResultTy: NewProto->getReturnType(), Args: NewProto->getParamTypes(), EPI));
5791 } else {
5792 Sema::ContextRAII SwitchContext(SemaRef, New);
5793 SemaRef.SubstExceptionSpec(New, Proto, Args: TemplateArgs);
5794 }
5795 }
5796
5797 // Get the definition. Leaves the variable unchanged if undefined.
5798 const FunctionDecl *Definition = Tmpl;
5799 Tmpl->isDefined(Definition);
5800
5801 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: Definition, New,
5802 LateAttrs, OuterMostScope: StartingScope);
5803
5804 SemaRef.inferLifetimeBoundAttribute(FD: New);
5805
5806 return false;
5807}
5808
5809/// Initializes common fields of an instantiated method
5810/// declaration (New) from the corresponding fields of its template
5811/// (Tmpl).
5812///
5813/// \returns true if there was an error
5814bool
5815TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
5816 CXXMethodDecl *Tmpl) {
5817 if (InitFunctionInstantiation(New, Tmpl))
5818 return true;
5819
5820 if (isa<CXXDestructorDecl>(Val: New) && SemaRef.getLangOpts().CPlusPlus11)
5821 SemaRef.AdjustDestructorExceptionSpec(Destructor: cast<CXXDestructorDecl>(Val: New));
5822
5823 New->setAccess(Tmpl->getAccess());
5824 if (Tmpl->isVirtualAsWritten())
5825 New->setVirtualAsWritten(true);
5826
5827 // FIXME: New needs a pointer to Tmpl
5828 return false;
5829}
5830
5831bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
5832 FunctionDecl *Tmpl) {
5833 // Transfer across any unqualified lookups.
5834 if (auto *DFI = Tmpl->getDefaultedOrDeletedInfo()) {
5835 SmallVector<DeclAccessPair, 32> Lookups;
5836 Lookups.reserve(N: DFI->getUnqualifiedLookups().size());
5837 bool AnyChanged = false;
5838 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
5839 NamedDecl *D = SemaRef.FindInstantiatedDecl(Loc: New->getLocation(),
5840 D: DA.getDecl(), TemplateArgs);
5841 if (!D)
5842 return true;
5843 AnyChanged |= (D != DA.getDecl());
5844 Lookups.push_back(Elt: DeclAccessPair::make(D, AS: DA.getAccess()));
5845 }
5846
5847 New->setDefaultedOrDeletedInfo(
5848 AnyChanged ? FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
5849 Context&: SemaRef.Context, Lookups, FPFeatures: DFI->getFPFeatures(),
5850 DeletedMessage: DFI->getDeletedMessage())
5851 : DFI);
5852 }
5853
5854 SemaRef.SetDeclDefaulted(dcl: New, DefaultLoc: Tmpl->getLocation());
5855 return false;
5856}
5857
5858FunctionDecl *Sema::InstantiateFunctionDeclaration(
5859 FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
5860 SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC) {
5861 FunctionDecl *FD = FTD->getTemplatedDecl();
5862
5863 InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC);
5864 if (Inst.isInvalid())
5865 return nullptr;
5866
5867 ContextRAII SavedContext(*this, FD);
5868 MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
5869 /*Final=*/false);
5870
5871 return cast_or_null<FunctionDecl>(Val: SubstDecl(D: FD, Owner: FD->getParent(), TemplateArgs: MArgs));
5872}
5873
5874void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
5875 FunctionDecl *Function,
5876 bool Recursive,
5877 bool DefinitionRequired,
5878 bool AtEndOfTU) {
5879 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Val: Function))
5880 return;
5881
5882 // Never instantiate an explicit specialization except if it is a class scope
5883 // explicit specialization.
5884 TemplateSpecializationKind TSK =
5885 Function->getTemplateSpecializationKindForInstantiation();
5886 if (TSK == TSK_ExplicitSpecialization)
5887 return;
5888
5889 // Never implicitly instantiate a builtin; we don't actually need a function
5890 // body.
5891 if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
5892 !DefinitionRequired)
5893 return;
5894
5895 // Don't instantiate a definition if we already have one.
5896 const FunctionDecl *ExistingDefn = nullptr;
5897 if (Function->isDefined(Definition&: ExistingDefn,
5898 /*CheckForPendingFriendDefinition=*/true)) {
5899 if (ExistingDefn->isThisDeclarationADefinition())
5900 return;
5901
5902 // If we're asked to instantiate a function whose body comes from an
5903 // instantiated friend declaration, attach the instantiated body to the
5904 // corresponding declaration of the function.
5905 assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition());
5906 Function = const_cast<FunctionDecl*>(ExistingDefn);
5907 }
5908
5909#ifndef NDEBUG
5910 RecursiveInstGuard AlreadyInstantiating(*this, Function,
5911 RecursiveInstGuard::Kind::Template);
5912 assert(!AlreadyInstantiating && "should have been caught by caller");
5913#endif
5914
5915 // Find the function body that we'll be substituting.
5916 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
5917 assert(PatternDecl && "instantiating a non-template");
5918
5919 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
5920 Stmt *Pattern = nullptr;
5921 if (PatternDef) {
5922 Pattern = PatternDef->getBody(Definition&: PatternDef);
5923 PatternDecl = PatternDef;
5924 if (PatternDef->willHaveBody())
5925 PatternDef = nullptr;
5926 }
5927
5928 // True is the template definition is unreachable, otherwise false.
5929 bool Unreachable = false;
5930 // FIXME: We need to track the instantiation stack in order to know which
5931 // definitions should be visible within this instantiation.
5932 if (DiagnoseUninstantiableTemplate(
5933 PointOfInstantiation, Instantiation: Function,
5934 InstantiatedFromMember: Function->getInstantiatedFromMemberFunction(), Pattern: PatternDecl,
5935 PatternDef, TSK,
5936 /*Complain*/ DefinitionRequired, Unreachable: &Unreachable)) {
5937 if (DefinitionRequired)
5938 Function->setInvalidDecl();
5939 else if (TSK == TSK_ExplicitInstantiationDefinition ||
5940 (Function->isConstexpr() && !Recursive)) {
5941 // Try again at the end of the translation unit (at which point a
5942 // definition will be required).
5943 assert(!Recursive);
5944 Function->setInstantiationIsPending(true);
5945 PendingInstantiations.emplace_back(args&: Function, args&: PointOfInstantiation);
5946
5947 if (llvm::isTimeTraceVerbose()) {
5948 llvm::timeTraceAddInstantEvent(Name: "DeferInstantiation", Detail: [&] {
5949 std::string Name;
5950 llvm::raw_string_ostream OS(Name);
5951 Function->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
5952 /*Qualified=*/true);
5953 return Name;
5954 });
5955 }
5956 } else if (TSK == TSK_ImplicitInstantiation) {
5957 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5958 !getSourceManager().isInSystemHeader(Loc: PatternDecl->getBeginLoc())) {
5959 Diag(Loc: PointOfInstantiation, DiagID: diag::warn_func_template_missing)
5960 << Function;
5961 if (Unreachable) {
5962 // FIXME: would be nice to mention which module the function template
5963 // comes from.
5964 Diag(Loc: PatternDecl->getLocation(),
5965 DiagID: diag::note_unreachable_template_decl);
5966 } else {
5967 Diag(Loc: PatternDecl->getLocation(), DiagID: diag::note_forward_template_decl);
5968 if (getLangOpts().CPlusPlus11)
5969 Diag(Loc: PointOfInstantiation, DiagID: diag::note_inst_declaration_hint)
5970 << Function;
5971 }
5972 }
5973 }
5974
5975 return;
5976 }
5977
5978 // Postpone late parsed template instantiations.
5979 if (PatternDecl->isLateTemplateParsed() &&
5980 !LateTemplateParser) {
5981 Function->setInstantiationIsPending(true);
5982 LateParsedInstantiations.push_back(
5983 Elt: std::make_pair(x&: Function, y&: PointOfInstantiation));
5984 return;
5985 }
5986
5987 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
5988 llvm::TimeTraceMetadata M;
5989 llvm::raw_string_ostream OS(M.Detail);
5990 Function->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
5991 /*Qualified=*/true);
5992 if (llvm::isTimeTraceVerbose()) {
5993 auto Loc = SourceMgr.getExpansionLoc(Loc: Function->getLocation());
5994 M.File = SourceMgr.getFilename(SpellingLoc: Loc);
5995 M.Line = SourceMgr.getExpansionLineNumber(Loc);
5996 }
5997 return M;
5998 });
5999
6000 // If we're performing recursive template instantiation, create our own
6001 // queue of pending implicit instantiations that we will instantiate later,
6002 // while we're still within our own instantiation context.
6003 // This has to happen before LateTemplateParser below is called, so that
6004 // it marks vtables used in late parsed templates as used.
6005 GlobalEagerInstantiationScope GlobalInstantiations(*this,
6006 /*Enabled=*/Recursive,
6007 /*AtEndOfTU=*/AtEndOfTU);
6008 LocalEagerInstantiationScope LocalInstantiations(*this,
6009 /*AtEndOfTU=*/AtEndOfTU);
6010
6011 // Call the LateTemplateParser callback if there is a need to late parse
6012 // a templated function definition.
6013 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
6014 LateTemplateParser) {
6015 // FIXME: Optimize to allow individual templates to be deserialized.
6016 if (PatternDecl->isFromASTFile())
6017 ExternalSource->ReadLateParsedTemplates(LPTMap&: LateParsedTemplateMap);
6018
6019 auto LPTIter = LateParsedTemplateMap.find(Key: PatternDecl);
6020 assert(LPTIter != LateParsedTemplateMap.end() &&
6021 "missing LateParsedTemplate");
6022 LateTemplateParser(OpaqueParser, *LPTIter->second);
6023 Pattern = PatternDecl->getBody(Definition&: PatternDecl);
6024 updateAttrsForLateParsedTemplate(Pattern: PatternDecl, Inst: Function);
6025 }
6026
6027 // Note, we should never try to instantiate a deleted function template.
6028 assert((Pattern || PatternDecl->isDefaulted() ||
6029 PatternDecl->hasSkippedBody()) &&
6030 "unexpected kind of function template definition");
6031
6032 // C++1y [temp.explicit]p10:
6033 // Except for inline functions, declarations with types deduced from their
6034 // initializer or return value, and class template specializations, other
6035 // explicit instantiation declarations have the effect of suppressing the
6036 // implicit instantiation of the entity to which they refer.
6037 if (TSK == TSK_ExplicitInstantiationDeclaration &&
6038 !PatternDecl->isInlined() &&
6039 !PatternDecl->getReturnType()->getContainedAutoType())
6040 return;
6041
6042 if (PatternDecl->isInlined()) {
6043 // Function, and all later redeclarations of it (from imported modules,
6044 // for instance), are now implicitly inline.
6045 for (auto *D = Function->getMostRecentDecl(); /**/;
6046 D = D->getPreviousDecl()) {
6047 D->setImplicitlyInline();
6048 if (D == Function)
6049 break;
6050 }
6051 }
6052
6053 NonSFINAEContext _(*this);
6054 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
6055 if (Inst.isInvalid())
6056 return;
6057 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
6058 "instantiating function definition");
6059
6060 // The instantiation is visible here, even if it was first declared in an
6061 // unimported module.
6062 Function->setVisibleDespiteOwningModule();
6063
6064 // Copy the source locations from the pattern.
6065 Function->setLocation(PatternDecl->getLocation());
6066 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
6067 Function->setRangeEnd(PatternDecl->getEndLoc());
6068 // Let the instantiation use the Pattern's DeclarationNameLoc, due to the
6069 // following awkwardness:
6070 //
6071 // 1. There are out-of-tree users of getNameInfo().getSourceRange(), who
6072 // expect the source range of the instantiated declaration to be set to
6073 // point to the definition.
6074 //
6075 // 2. That getNameInfo().getSourceRange() might return the TypeLocInfo's
6076 // location it tracked.
6077 //
6078 // 3. Function might come from an (implicit) declaration, while the pattern
6079 // comes from a definition. In these cases, we need the PatternDecl's source
6080 // location.
6081 //
6082 // To that end, we need to more or less tweak the DeclarationNameLoc. However,
6083 // we can't blindly copy the DeclarationNameLoc from the PatternDecl to the
6084 // function, since it contains associated TypeLocs that should have already
6085 // been transformed. So, we rebuild the TypeLoc for that purpose. Technically,
6086 // we should create a new function declaration and assign everything we need,
6087 // but InstantiateFunctionDefinition updates the declaration in place.
6088 auto NameLocPointsToPattern = [&] {
6089 DeclarationNameInfo PatternName = PatternDecl->getNameInfo();
6090 DeclarationNameLoc PatternNameLoc = PatternName.getInfo();
6091 switch (PatternName.getName().getNameKind()) {
6092 case DeclarationName::CXXConstructorName:
6093 case DeclarationName::CXXDestructorName:
6094 case DeclarationName::CXXConversionFunctionName:
6095 break;
6096 default:
6097 // Cases where DeclarationNameLoc doesn't matter, as it merely contains a
6098 // source range.
6099 return PatternNameLoc;
6100 }
6101
6102 TypeSourceInfo *TSI = Function->getNameInfo().getNamedTypeInfo();
6103 // TSI might be null if the function is named by a constructor template id.
6104 // E.g. S<T>() {} for class template S with a template parameter T.
6105 if (!TSI) {
6106 // We don't care about the DeclarationName of the instantiated function,
6107 // but only the DeclarationNameLoc. So if the TypeLoc is absent, we do
6108 // nothing.
6109 return PatternNameLoc;
6110 }
6111
6112 QualType InstT = TSI->getType();
6113 // We want to use a TypeLoc that reflects the transformed type while
6114 // preserving the source location from the pattern.
6115 TypeLocBuilder TLB;
6116 TypeSourceInfo *PatternTSI = PatternName.getNamedTypeInfo();
6117 assert(PatternTSI && "Pattern is supposed to have an associated TSI");
6118 // FIXME: PatternTSI is not trivial. We should copy the source location
6119 // along the TypeLoc chain. However a trivial TypeLoc is sufficient for
6120 // getNameInfo().getSourceRange().
6121 TLB.pushTrivial(Context, T: InstT, Loc: PatternTSI->getTypeLoc().getBeginLoc());
6122 return DeclarationNameLoc::makeNamedTypeLoc(
6123 TInfo: TLB.getTypeSourceInfo(Context, T: InstT));
6124 };
6125 Function->setDeclarationNameLoc(NameLocPointsToPattern());
6126
6127 EnterExpressionEvaluationContextForFunction EvalContext(
6128 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Function);
6129
6130 Qualifiers ThisTypeQuals;
6131 CXXRecordDecl *ThisContext = nullptr;
6132 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
6133 ThisContext = Method->getParent();
6134 ThisTypeQuals = Method->getMethodQualifiers();
6135 }
6136 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals);
6137
6138 // Introduce a new scope where local variable instantiations will be
6139 // recorded, unless we're actually a member function within a local
6140 // class, in which case we need to merge our results with the parent
6141 // scope (of the enclosing function). The exception is instantiating
6142 // a function template specialization, since the template to be
6143 // instantiated already has references to locals properly substituted.
6144 bool MergeWithParentScope = false;
6145 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Val: Function->getDeclContext()))
6146 MergeWithParentScope =
6147 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
6148
6149 LocalInstantiationScope Scope(*this, MergeWithParentScope);
6150 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
6151 // Special members might get their TypeSourceInfo set up w.r.t the
6152 // PatternDecl context, in which case parameters could still be pointing
6153 // back to the original class, make sure arguments are bound to the
6154 // instantiated record instead.
6155 assert(PatternDecl->isDefaulted() &&
6156 "Special member needs to be defaulted");
6157 auto PatternSM = PatternDecl->getDefaultedFunctionKind().asSpecialMember();
6158 if (!(PatternSM == CXXSpecialMemberKind::CopyConstructor ||
6159 PatternSM == CXXSpecialMemberKind::CopyAssignment ||
6160 PatternSM == CXXSpecialMemberKind::MoveConstructor ||
6161 PatternSM == CXXSpecialMemberKind::MoveAssignment))
6162 return;
6163
6164 auto *NewRec = dyn_cast<CXXRecordDecl>(Val: Function->getDeclContext());
6165 const auto *PatternRec =
6166 dyn_cast<CXXRecordDecl>(Val: PatternDecl->getDeclContext());
6167 if (!NewRec || !PatternRec)
6168 return;
6169 if (!PatternRec->isLambda())
6170 return;
6171
6172 struct SpecialMemberTypeInfoRebuilder
6173 : TreeTransform<SpecialMemberTypeInfoRebuilder> {
6174 using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>;
6175 const CXXRecordDecl *OldDecl;
6176 CXXRecordDecl *NewDecl;
6177
6178 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
6179 CXXRecordDecl *N)
6180 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
6181
6182 bool TransformExceptionSpec(SourceLocation Loc,
6183 FunctionProtoType::ExceptionSpecInfo &ESI,
6184 SmallVectorImpl<QualType> &Exceptions,
6185 bool &Changed) {
6186 return false;
6187 }
6188
6189 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
6190 const RecordType *T = TL.getTypePtr();
6191 RecordDecl *Record = cast_or_null<RecordDecl>(
6192 Val: getDerived().TransformDecl(Loc: TL.getNameLoc(), D: T->getDecl()));
6193 if (Record != OldDecl)
6194 return Base::TransformRecordType(TLB, TL);
6195
6196 // FIXME: transform the rest of the record type.
6197 QualType Result = getDerived().RebuildTagType(
6198 Keyword: ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt, Tag: NewDecl);
6199 if (Result.isNull())
6200 return QualType();
6201
6202 TagTypeLoc NewTL = TLB.push<RecordTypeLoc>(T: Result);
6203 NewTL.setElaboratedKeywordLoc(SourceLocation());
6204 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6205 NewTL.setNameLoc(TL.getNameLoc());
6206 return Result;
6207 }
6208 } IR{*this, PatternRec, NewRec};
6209
6210 TypeSourceInfo *NewSI = IR.TransformType(TSI: Function->getTypeSourceInfo());
6211 assert(NewSI && "Type Transform failed?");
6212 Function->setType(NewSI->getType());
6213 Function->setTypeSourceInfo(NewSI);
6214
6215 ParmVarDecl *Parm = Function->getParamDecl(i: 0);
6216 TypeSourceInfo *NewParmSI = IR.TransformType(TSI: Parm->getTypeSourceInfo());
6217 assert(NewParmSI && "Type transformation failed.");
6218 Parm->setType(NewParmSI->getType());
6219 Parm->setTypeSourceInfo(NewParmSI);
6220 };
6221
6222 if (PatternDecl->isDefaulted()) {
6223 RebuildTypeSourceInfoForDefaultSpecialMembers();
6224 SetDeclDefaulted(dcl: Function, DefaultLoc: PatternDecl->getLocation());
6225 } else {
6226 DeclContext *DC = Function->getLexicalDeclContext();
6227 std::optional<ArrayRef<TemplateArgument>> Innermost;
6228 if (auto *Primary = Function->getPrimaryTemplate();
6229 Primary &&
6230 !isGenericLambdaCallOperatorOrStaticInvokerSpecialization(DC: Function) &&
6231 Function->getTemplateSpecializationKind() !=
6232 TSK_ExplicitSpecialization) {
6233 auto It = llvm::find_if(Range: Primary->redecls(),
6234 P: [](const RedeclarableTemplateDecl *RTD) {
6235 return cast<FunctionTemplateDecl>(Val: RTD)
6236 ->isCompatibleWithDefinition();
6237 });
6238 assert(It != Primary->redecls().end() &&
6239 "Should't get here without a definition");
6240 if (FunctionDecl *Def = cast<FunctionTemplateDecl>(Val: *It)
6241 ->getTemplatedDecl()
6242 ->getDefinition())
6243 DC = Def->getLexicalDeclContext();
6244 else
6245 DC = (*It)->getLexicalDeclContext();
6246 Innermost.emplace(args: Function->getTemplateSpecializationArgs()->asArray());
6247 }
6248 MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
6249 D: Function, DC, /*Final=*/false, Innermost, RelativeToPrimary: false, Pattern: PatternDecl);
6250
6251 // Substitute into the qualifier; we can get a substitution failure here
6252 // through evil use of alias templates.
6253 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
6254 // of the) lexical context of the pattern?
6255 SubstQualifier(SemaRef&: *this, OldDecl: PatternDecl, NewDecl: Function, TemplateArgs);
6256
6257 ActOnStartOfFunctionDef(S: nullptr, D: Function);
6258
6259 // Enter the scope of this instantiation. We don't use
6260 // PushDeclContext because we don't have a scope.
6261 Sema::ContextRAII savedContext(*this, Function);
6262
6263 FPFeaturesStateRAII SavedFPFeatures(*this);
6264 CurFPFeatures = FPOptions(getLangOpts());
6265 FpPragmaStack.CurrentValue = FPOptionsOverride();
6266
6267 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
6268 TemplateArgs))
6269 return;
6270
6271 StmtResult Body;
6272 if (PatternDecl->hasSkippedBody()) {
6273 ActOnSkippedFunctionBody(Decl: Function);
6274 Body = nullptr;
6275 } else {
6276 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Val: Function)) {
6277 // If this is a constructor, instantiate the member initializers.
6278 InstantiateMemInitializers(New: Ctor, Tmpl: cast<CXXConstructorDecl>(Val: PatternDecl),
6279 TemplateArgs);
6280
6281 // If this is an MS ABI dllexport default constructor, instantiate any
6282 // default arguments.
6283 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6284 Ctor->isDefaultConstructor()) {
6285 if (DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>())
6286 BuildCtorClosureDefaultArgs(Loc: Attr->getLocation(), Ctor);
6287 }
6288 }
6289
6290 // Instantiate the function body.
6291 Body = SubstStmt(S: Pattern, TemplateArgs);
6292
6293 if (Body.isInvalid())
6294 Function->setInvalidDecl();
6295 }
6296 // FIXME: finishing the function body while in an expression evaluation
6297 // context seems wrong. Investigate more.
6298 ActOnFinishFunctionBody(Decl: Function, Body: Body.get(), /*IsInstantiation=*/true);
6299
6300 inferLifetimeBoundAttribute(FD: Function);
6301
6302 checkReferenceToTULocalFromOtherTU(FD: Function, PointOfInstantiation);
6303
6304 if (PatternDecl->isDependentContext())
6305 PerformDependentDiagnostics(Pattern: PatternDecl, TemplateArgs);
6306
6307 if (auto *Listener = getASTMutationListener())
6308 Listener->FunctionDefinitionInstantiated(D: Function);
6309
6310 savedContext.pop();
6311 }
6312
6313 // We never need to emit the code for a lambda in unevaluated context.
6314 // We also can't mangle a lambda in the require clause of a function template
6315 // during constraint checking as the MSI ABI would need to mangle the (not yet
6316 // specialized) enclosing declaration
6317 // FIXME: Should we try to skip this for non-lambda functions too?
6318 bool ShouldSkipCG = [&] {
6319 auto *RD = dyn_cast<CXXRecordDecl>(Val: Function->getParent());
6320 if (!RD || !RD->isLambda())
6321 return false;
6322
6323 return llvm::any_of(Range&: ExprEvalContexts, P: [](auto &Context) {
6324 return Context.isUnevaluated() || Context.isImmediateFunctionContext();
6325 });
6326 }();
6327 if (!ShouldSkipCG) {
6328 DeclGroupRef DG(Function);
6329 Consumer.HandleTopLevelDecl(D: DG);
6330 }
6331
6332 // This class may have local implicit instantiations that need to be
6333 // instantiation within this scope.
6334 LocalInstantiations.perform();
6335 Scope.Exit();
6336 GlobalInstantiations.perform();
6337}
6338
6339VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
6340 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
6341 const TemplateArgumentList *PartialSpecArgs,
6342 SmallVectorImpl<TemplateArgument> &Converted,
6343 SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
6344 LocalInstantiationScope *StartingScope) {
6345 if (FromVar->isInvalidDecl())
6346 return nullptr;
6347
6348 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
6349 if (Inst.isInvalid())
6350 return nullptr;
6351
6352 // Instantiate the first declaration of the variable template: for a partial
6353 // specialization of a static data member template, the first declaration may
6354 // or may not be the declaration in the class; if it's in the class, we want
6355 // to instantiate a member in the class (a declaration), and if it's outside,
6356 // we want to instantiate a definition.
6357 //
6358 // If we're instantiating an explicitly-specialized member template or member
6359 // partial specialization, don't do this. The member specialization completely
6360 // replaces the original declaration in this case.
6361 bool IsMemberSpec = false;
6362 MultiLevelTemplateArgumentList MultiLevelList;
6363 if (auto *PartialSpec =
6364 dyn_cast<VarTemplatePartialSpecializationDecl>(Val: FromVar)) {
6365 assert(PartialSpecArgs);
6366 IsMemberSpec = PartialSpec->isMemberSpecialization();
6367 MultiLevelList.addOuterTemplateArguments(
6368 AssociatedDecl: PartialSpec, Args: PartialSpecArgs->asArray(), /*Final=*/false);
6369 } else {
6370 assert(VarTemplate == FromVar->getDescribedVarTemplate());
6371 IsMemberSpec = VarTemplate->isMemberSpecialization();
6372 MultiLevelList.addOuterTemplateArguments(AssociatedDecl: VarTemplate, Args: Converted,
6373 /*Final=*/false);
6374 }
6375 if (!IsMemberSpec)
6376 FromVar = FromVar->getFirstDecl();
6377
6378 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
6379 MultiLevelList);
6380
6381 // TODO: Set LateAttrs and StartingScope ...
6382
6383 return Instantiator.VisitVarTemplateSpecializationDecl(VarTemplate, D: FromVar,
6384 Converted);
6385}
6386
6387VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
6388 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
6389 const MultiLevelTemplateArgumentList &TemplateArgs) {
6390 assert(PatternDecl->isThisDeclarationADefinition() &&
6391 "don't have a definition to instantiate from");
6392
6393 // Do substitution on the type of the declaration
6394 TypeSourceInfo *TSI =
6395 SubstType(T: PatternDecl->getTypeSourceInfo(), TemplateArgs,
6396 Loc: PatternDecl->getTypeSpecStartLoc(), Entity: PatternDecl->getDeclName());
6397 if (!TSI)
6398 return nullptr;
6399
6400 // Update the type of this variable template specialization.
6401 VarSpec->setType(TSI->getType());
6402
6403 // Convert the declaration into a definition now.
6404 VarSpec->setCompleteDefinition();
6405
6406 // Instantiate the initializer.
6407 InstantiateVariableInitializer(Var: VarSpec, OldVar: PatternDecl, TemplateArgs);
6408
6409 if (getLangOpts().OpenCL)
6410 deduceOpenCLAddressSpace(decl: VarSpec);
6411
6412 return VarSpec;
6413}
6414
6415void Sema::BuildVariableInstantiation(
6416 VarDecl *NewVar, VarDecl *OldVar,
6417 const MultiLevelTemplateArgumentList &TemplateArgs,
6418 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
6419 LocalInstantiationScope *StartingScope,
6420 bool InstantiatingVarTemplate,
6421 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
6422 // Instantiating a partial specialization to produce a partial
6423 // specialization.
6424 bool InstantiatingVarTemplatePartialSpec =
6425 isa<VarTemplatePartialSpecializationDecl>(Val: OldVar) &&
6426 isa<VarTemplatePartialSpecializationDecl>(Val: NewVar);
6427 // Instantiating from a variable template (or partial specialization) to
6428 // produce a variable template specialization.
6429 bool InstantiatingSpecFromTemplate =
6430 isa<VarTemplateSpecializationDecl>(Val: NewVar) &&
6431 (OldVar->getDescribedVarTemplate() ||
6432 isa<VarTemplatePartialSpecializationDecl>(Val: OldVar));
6433
6434 // If we are instantiating a local extern declaration, the
6435 // instantiation belongs lexically to the containing function.
6436 // If we are instantiating a static data member defined
6437 // out-of-line, the instantiation will have the same lexical
6438 // context (which will be a namespace scope) as the template.
6439 if (OldVar->isLocalExternDecl()) {
6440 NewVar->setLocalExternDecl();
6441 NewVar->setLexicalDeclContext(Owner);
6442 } else if (OldVar->isOutOfLine())
6443 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
6444 NewVar->setTSCSpec(OldVar->getTSCSpec());
6445 NewVar->setInitStyle(OldVar->getInitStyle());
6446 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
6447 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
6448 NewVar->setConstexpr(OldVar->isConstexpr());
6449 NewVar->setInitCapture(OldVar->isInitCapture());
6450 NewVar->setPreviousDeclInSameBlockScope(
6451 OldVar->isPreviousDeclInSameBlockScope());
6452 NewVar->setAccess(OldVar->getAccess());
6453
6454 if (!OldVar->isStaticDataMember()) {
6455 if (OldVar->isUsed(CheckUsedAttr: false))
6456 NewVar->setIsUsed();
6457 NewVar->setReferenced(OldVar->isReferenced());
6458 }
6459
6460 InstantiateAttrs(TemplateArgs, Tmpl: OldVar, New: NewVar, LateAttrs, OuterMostScope: StartingScope);
6461
6462 LookupResult Previous(
6463 *this, NewVar->getDeclName(), NewVar->getLocation(),
6464 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
6465 : Sema::LookupOrdinaryName,
6466 NewVar->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
6467 : forRedeclarationInCurContext());
6468
6469 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
6470 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
6471 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
6472 // We have a previous declaration. Use that one, so we merge with the
6473 // right type.
6474 if (NamedDecl *NewPrev = FindInstantiatedDecl(
6475 Loc: NewVar->getLocation(), D: OldVar->getPreviousDecl(), TemplateArgs))
6476 Previous.addDecl(D: NewPrev);
6477 } else if (!isa<VarTemplateSpecializationDecl>(Val: NewVar) &&
6478 OldVar->hasLinkage()) {
6479 LookupQualifiedName(R&: Previous, LookupCtx: NewVar->getDeclContext(), InUnqualifiedLookup: false);
6480 } else if (PrevDeclForVarTemplateSpecialization) {
6481 Previous.addDecl(D: PrevDeclForVarTemplateSpecialization);
6482 }
6483 CheckVariableDeclaration(NewVD: NewVar, Previous);
6484
6485 if (!InstantiatingVarTemplate) {
6486 NewVar->getLexicalDeclContext()->addHiddenDecl(D: NewVar);
6487 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
6488 NewVar->getDeclContext()->makeDeclVisibleInContext(D: NewVar);
6489 }
6490
6491 if (!OldVar->isOutOfLine()) {
6492 if (NewVar->getDeclContext()->isFunctionOrMethod())
6493 CurrentInstantiationScope->InstantiatedLocal(D: OldVar, Inst: NewVar);
6494 }
6495
6496 // Link instantiations of static data members back to the template from
6497 // which they were instantiated.
6498 //
6499 // Don't do this when instantiating a template (we link the template itself
6500 // back in that case) nor when instantiating a static data member template
6501 // (that's not a member specialization).
6502 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
6503 !InstantiatingSpecFromTemplate)
6504 NewVar->setInstantiationOfStaticDataMember(VD: OldVar,
6505 TSK: TSK_ImplicitInstantiation);
6506
6507 // If the pattern is an (in-class) explicit specialization, then the result
6508 // is also an explicit specialization.
6509 if (VarTemplateSpecializationDecl *OldVTSD =
6510 dyn_cast<VarTemplateSpecializationDecl>(Val: OldVar)) {
6511 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
6512 !isa<VarTemplatePartialSpecializationDecl>(Val: OldVTSD))
6513 cast<VarTemplateSpecializationDecl>(Val: NewVar)->setSpecializationKind(
6514 TSK_ExplicitSpecialization);
6515 }
6516
6517 // Forward the mangling number from the template to the instantiated decl.
6518 Context.setManglingNumber(ND: NewVar, Number: Context.getManglingNumber(ND: OldVar));
6519 Context.setStaticLocalNumber(VD: NewVar, Number: Context.getStaticLocalNumber(VD: OldVar));
6520
6521 // Figure out whether to eagerly instantiate the initializer.
6522 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
6523 // We're producing a template. Don't instantiate the initializer yet.
6524 } else if (NewVar->getType()->isUndeducedType()) {
6525 // We need the type to complete the declaration of the variable.
6526 InstantiateVariableInitializer(Var: NewVar, OldVar, TemplateArgs);
6527 } else if (InstantiatingSpecFromTemplate ||
6528 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
6529 !NewVar->isThisDeclarationADefinition())) {
6530 // Delay instantiation of the initializer for variable template
6531 // specializations or inline static data members until a definition of the
6532 // variable is needed.
6533 } else {
6534 InstantiateVariableInitializer(Var: NewVar, OldVar, TemplateArgs);
6535 }
6536
6537 // Diagnose unused local variables with dependent types, where the diagnostic
6538 // will have been deferred.
6539 if (!NewVar->isInvalidDecl() &&
6540 NewVar->getDeclContext()->isFunctionOrMethod() &&
6541 OldVar->getType()->isDependentType())
6542 DiagnoseUnusedDecl(ND: NewVar);
6543}
6544
6545void Sema::InstantiateVariableInitializer(
6546 VarDecl *Var, VarDecl *OldVar,
6547 const MultiLevelTemplateArgumentList &TemplateArgs) {
6548 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
6549 L->VariableDefinitionInstantiated(D: Var);
6550
6551 // We propagate the 'inline' flag with the initializer, because it
6552 // would otherwise imply that the variable is a definition for a
6553 // non-static data member.
6554 if (OldVar->isInlineSpecified())
6555 Var->setInlineSpecified();
6556 else if (OldVar->isInline())
6557 Var->setImplicitlyInline();
6558
6559 ContextRAII SwitchContext(*this, Var->getDeclContext());
6560
6561 EnterExpressionEvaluationContext Evaluated(
6562 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var,
6563 ExpressionEvaluationContextRecord::EK_VariableInit);
6564 currentEvaluationContext().InLifetimeExtendingContext =
6565 parentEvaluationContext().InLifetimeExtendingContext;
6566 currentEvaluationContext().RebuildDefaultArgOrDefaultInit =
6567 parentEvaluationContext().RebuildDefaultArgOrDefaultInit;
6568
6569 // Set DeclForInitializer for this variable so DiagIfReachable can properly
6570 // suppress runtime diagnostics for constexpr/static member variables
6571 currentEvaluationContext().DeclForInitializer = Var;
6572
6573 if (OldVar->getInit()) {
6574 // Instantiate the initializer.
6575 ExprResult Init =
6576 SubstInitializer(E: OldVar->getInit(), TemplateArgs,
6577 CXXDirectInit: OldVar->getInitStyle() == VarDecl::CallInit);
6578
6579 if (!Init.isInvalid()) {
6580 Expr *InitExpr = Init.get();
6581
6582 if (Var->hasAttr<DLLImportAttr>() &&
6583 (!InitExpr || !InitExpr->isConstantInitializer(Ctx&: getASTContext()))) {
6584 // Do not dynamically initialize dllimport variables.
6585 } else if (InitExpr) {
6586 bool DirectInit = OldVar->isDirectInit();
6587 AddInitializerToDecl(dcl: Var, init: InitExpr, DirectInit);
6588 } else
6589 ActOnUninitializedDecl(dcl: Var);
6590 } else {
6591 // FIXME: Not too happy about invalidating the declaration
6592 // because of a bogus initializer.
6593 Var->setInvalidDecl();
6594 }
6595 } else {
6596 // `inline` variables are a definition and declaration all in one; we won't
6597 // pick up an initializer from anywhere else.
6598 if (Var->isStaticDataMember() && !Var->isInline()) {
6599 if (!Var->isOutOfLine())
6600 return;
6601
6602 // If the declaration inside the class had an initializer, don't add
6603 // another one to the out-of-line definition.
6604 if (OldVar->getFirstDecl()->hasInit())
6605 return;
6606 }
6607
6608 // We'll add an initializer to a for-range declaration later.
6609 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
6610 return;
6611
6612 ActOnUninitializedDecl(dcl: Var);
6613 }
6614
6615 if (getLangOpts().CUDA)
6616 CUDA().checkAllowedInitializer(VD: Var);
6617}
6618
6619void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
6620 VarDecl *Var, bool Recursive,
6621 bool DefinitionRequired, bool AtEndOfTU) {
6622 if (Var->isInvalidDecl())
6623 return;
6624
6625 // Never instantiate an explicitly-specialized entity.
6626 TemplateSpecializationKind TSK =
6627 Var->getTemplateSpecializationKindForInstantiation();
6628 if (TSK == TSK_ExplicitSpecialization)
6629 return;
6630
6631 RecursiveInstGuard AlreadyInstantiating(*this, Var,
6632 RecursiveInstGuard::Kind::Template);
6633 if (AlreadyInstantiating)
6634 return;
6635
6636 // Find the pattern and the arguments to substitute into it.
6637 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
6638 assert(PatternDecl && "no pattern for templated variable");
6639 MultiLevelTemplateArgumentList TemplateArgs =
6640 getTemplateInstantiationArgs(D: Var);
6641
6642 VarTemplateSpecializationDecl *VarSpec =
6643 dyn_cast<VarTemplateSpecializationDecl>(Val: Var);
6644 if (VarSpec) {
6645 // If this is a static data member template, there might be an
6646 // uninstantiated initializer on the declaration. If so, instantiate
6647 // it now.
6648 //
6649 // FIXME: This largely duplicates what we would do below. The difference
6650 // is that along this path we may instantiate an initializer from an
6651 // in-class declaration of the template and instantiate the definition
6652 // from a separate out-of-class definition.
6653 if (PatternDecl->isStaticDataMember() &&
6654 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
6655 !Var->hasInit()) {
6656 // FIXME: Factor out the duplicated instantiation context setup/tear down
6657 // code here.
6658 NonSFINAEContext _(*this);
6659 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
6660 if (Inst.isInvalid())
6661 return;
6662 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
6663 "instantiating variable initializer");
6664
6665 // The instantiation is visible here, even if it was first declared in an
6666 // unimported module.
6667 Var->setVisibleDespiteOwningModule();
6668
6669 // If we're performing recursive template instantiation, create our own
6670 // queue of pending implicit instantiations that we will instantiate
6671 // later, while we're still within our own instantiation context.
6672 GlobalEagerInstantiationScope GlobalInstantiations(
6673 *this,
6674 /*Enabled=*/Recursive, /*AtEndOfTU=*/AtEndOfTU);
6675 LocalInstantiationScope Local(*this);
6676 LocalEagerInstantiationScope LocalInstantiations(*this,
6677 /*AtEndOfTU=*/AtEndOfTU);
6678
6679 // Enter the scope of this instantiation. We don't use
6680 // PushDeclContext because we don't have a scope.
6681 ContextRAII PreviousContext(*this, Var->getDeclContext());
6682 InstantiateVariableInitializer(Var, OldVar: PatternDecl, TemplateArgs);
6683 PreviousContext.pop();
6684
6685 // This variable may have local implicit instantiations that need to be
6686 // instantiated within this scope.
6687 LocalInstantiations.perform();
6688 Local.Exit();
6689 GlobalInstantiations.perform();
6690 }
6691 } else {
6692 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
6693 "not a static data member?");
6694 }
6695
6696 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
6697
6698 // If we don't have a definition of the variable template, we won't perform
6699 // any instantiation. Rather, we rely on the user to instantiate this
6700 // definition (or provide a specialization for it) in another translation
6701 // unit.
6702 if (!Def && !DefinitionRequired) {
6703 if (TSK == TSK_ExplicitInstantiationDefinition) {
6704 PendingInstantiations.emplace_back(args&: Var, args&: PointOfInstantiation);
6705 } else if (TSK == TSK_ImplicitInstantiation) {
6706 // Warn about missing definition at the end of translation unit.
6707 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
6708 !getSourceManager().isInSystemHeader(Loc: PatternDecl->getBeginLoc())) {
6709 Diag(Loc: PointOfInstantiation, DiagID: diag::warn_var_template_missing)
6710 << Var;
6711 Diag(Loc: PatternDecl->getLocation(), DiagID: diag::note_forward_template_decl);
6712 if (getLangOpts().CPlusPlus11)
6713 Diag(Loc: PointOfInstantiation, DiagID: diag::note_inst_declaration_hint) << Var;
6714 }
6715 return;
6716 }
6717 }
6718
6719 // FIXME: We need to track the instantiation stack in order to know which
6720 // definitions should be visible within this instantiation.
6721 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
6722 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation: Var,
6723 /*InstantiatedFromMember*/false,
6724 Pattern: PatternDecl, PatternDef: Def, TSK,
6725 /*Complain*/DefinitionRequired))
6726 return;
6727
6728 // C++11 [temp.explicit]p10:
6729 // Except for inline functions, const variables of literal types, variables
6730 // of reference types, [...] explicit instantiation declarations
6731 // have the effect of suppressing the implicit instantiation of the entity
6732 // to which they refer.
6733 //
6734 // FIXME: That's not exactly the same as "might be usable in constant
6735 // expressions", which only allows constexpr variables and const integral
6736 // types, not arbitrary const literal types.
6737 if (TSK == TSK_ExplicitInstantiationDeclaration &&
6738 !Var->mightBeUsableInConstantExpressions(C: getASTContext()))
6739 return;
6740
6741 // Make sure to pass the instantiated variable to the consumer at the end.
6742 struct PassToConsumerRAII {
6743 ASTConsumer &Consumer;
6744 VarDecl *Var;
6745
6746 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
6747 : Consumer(Consumer), Var(Var) { }
6748
6749 ~PassToConsumerRAII() {
6750 Consumer.HandleCXXStaticMemberVarInstantiation(D: Var);
6751 }
6752 } PassToConsumerRAII(Consumer, Var);
6753
6754 // If we already have a definition, we're done.
6755 if (VarDecl *Def = Var->getDefinition()) {
6756 // We may be explicitly instantiating something we've already implicitly
6757 // instantiated.
6758 Def->setTemplateSpecializationKind(TSK: Var->getTemplateSpecializationKind(),
6759 PointOfInstantiation);
6760 return;
6761 }
6762
6763 NonSFINAEContext _(*this);
6764 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
6765 if (Inst.isInvalid())
6766 return;
6767 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
6768 "instantiating variable definition");
6769
6770 // If we're performing recursive template instantiation, create our own
6771 // queue of pending implicit instantiations that we will instantiate later,
6772 // while we're still within our own instantiation context.
6773 GlobalEagerInstantiationScope GlobalInstantiations(*this,
6774 /*Enabled=*/Recursive,
6775 /*AtEndOfTU=*/AtEndOfTU);
6776
6777 // Enter the scope of this instantiation. We don't use
6778 // PushDeclContext because we don't have a scope.
6779 ContextRAII PreviousContext(*this, Var->getDeclContext());
6780 LocalInstantiationScope Local(*this);
6781
6782 LocalEagerInstantiationScope LocalInstantiations(*this,
6783 /*AtEndOfTU=*/AtEndOfTU);
6784
6785 VarDecl *OldVar = Var;
6786 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
6787 // We're instantiating an inline static data member whose definition was
6788 // provided inside the class.
6789 InstantiateVariableInitializer(Var, OldVar: Def, TemplateArgs);
6790 } else if (!VarSpec) {
6791 Var = cast_or_null<VarDecl>(Val: SubstDecl(D: Def, Owner: Var->getDeclContext(),
6792 TemplateArgs));
6793 } else if (Var->isStaticDataMember() &&
6794 Var->getLexicalDeclContext()->isRecord()) {
6795 // We need to instantiate the definition of a static data member template,
6796 // and all we have is the in-class declaration of it. Instantiate a separate
6797 // declaration of the definition.
6798 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
6799 TemplateArgs);
6800
6801 TemplateArgumentListInfo TemplateArgInfo;
6802 if (const ASTTemplateArgumentListInfo *ArgInfo =
6803 VarSpec->getTemplateArgsAsWritten()) {
6804 TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
6805 TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
6806 for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
6807 TemplateArgInfo.addArgument(Loc: Arg);
6808 }
6809
6810 VarTemplateSpecializationDecl *VTSD =
6811 Instantiator.VisitVarTemplateSpecializationDecl(
6812 VarTemplate: VarSpec->getSpecializedTemplate(), D: Def,
6813 Converted: VarSpec->getTemplateArgs().asArray(), PrevDecl: VarSpec);
6814 Var = VTSD;
6815
6816 if (Var) {
6817 VTSD->setTemplateArgsAsWritten(TemplateArgInfo);
6818
6819 llvm::PointerUnion<VarTemplateDecl *,
6820 VarTemplatePartialSpecializationDecl *> PatternPtr =
6821 VarSpec->getSpecializedTemplateOrPartial();
6822 if (VarTemplatePartialSpecializationDecl *Partial =
6823 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
6824 cast<VarTemplateSpecializationDecl>(Val: Var)->setInstantiationOf(
6825 PartialSpec: Partial, TemplateArgs: &VarSpec->getTemplateInstantiationArgs());
6826
6827 // Attach the initializer.
6828 InstantiateVariableInitializer(Var, OldVar: Def, TemplateArgs);
6829 }
6830 } else
6831 // Complete the existing variable's definition with an appropriately
6832 // substituted type and initializer.
6833 Var = CompleteVarTemplateSpecializationDecl(VarSpec, PatternDecl: Def, TemplateArgs);
6834
6835 PreviousContext.pop();
6836
6837 if (Var) {
6838 PassToConsumerRAII.Var = Var;
6839 Var->setTemplateSpecializationKind(TSK: OldVar->getTemplateSpecializationKind(),
6840 PointOfInstantiation: OldVar->getPointOfInstantiation());
6841 // Emit any deferred warnings for the variable's initializer
6842 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD: Var);
6843 }
6844
6845 // This variable may have local implicit instantiations that need to be
6846 // instantiated within this scope.
6847 LocalInstantiations.perform();
6848 Local.Exit();
6849 GlobalInstantiations.perform();
6850}
6851
6852void
6853Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
6854 const CXXConstructorDecl *Tmpl,
6855 const MultiLevelTemplateArgumentList &TemplateArgs) {
6856
6857 SmallVector<CXXCtorInitializer*, 4> NewInits;
6858 bool AnyErrors = Tmpl->isInvalidDecl();
6859
6860 // Instantiate all the initializers.
6861 for (const auto *Init : Tmpl->inits()) {
6862 // Only instantiate written initializers, let Sema re-construct implicit
6863 // ones.
6864 if (!Init->isWritten())
6865 continue;
6866
6867 SourceLocation EllipsisLoc;
6868
6869 if (Init->isPackExpansion()) {
6870 // This is a pack expansion. We should expand it now.
6871 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
6872 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
6873 collectUnexpandedParameterPacks(TL: BaseTL, Unexpanded);
6874 collectUnexpandedParameterPacks(E: Init->getInit(), Unexpanded);
6875 bool ShouldExpand = false;
6876 bool RetainExpansion = false;
6877 UnsignedOrNone NumExpansions = std::nullopt;
6878 if (CheckParameterPacksForExpansion(
6879 EllipsisLoc: Init->getEllipsisLoc(), PatternRange: BaseTL.getSourceRange(), Unexpanded,
6880 TemplateArgs, /*FailOnPackProducingTemplates=*/true, ShouldExpand,
6881 RetainExpansion, NumExpansions)) {
6882 AnyErrors = true;
6883 New->setInvalidDecl();
6884 continue;
6885 }
6886 assert(ShouldExpand && "Partial instantiation of base initializer?");
6887
6888 // Loop over all of the arguments in the argument pack(s),
6889 for (unsigned I = 0; I != *NumExpansions; ++I) {
6890 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
6891
6892 // Instantiate the initializer.
6893 ExprResult TempInit = SubstInitializer(E: Init->getInit(), TemplateArgs,
6894 /*CXXDirectInit=*/true);
6895 if (TempInit.isInvalid()) {
6896 AnyErrors = true;
6897 break;
6898 }
6899
6900 // Instantiate the base type.
6901 TypeSourceInfo *BaseTInfo = SubstType(T: Init->getTypeSourceInfo(),
6902 TemplateArgs,
6903 Loc: Init->getSourceLocation(),
6904 Entity: New->getDeclName());
6905 if (!BaseTInfo) {
6906 AnyErrors = true;
6907 break;
6908 }
6909
6910 // Build the initializer.
6911 MemInitResult NewInit = BuildBaseInitializer(BaseType: BaseTInfo->getType(),
6912 BaseTInfo, Init: TempInit.get(),
6913 ClassDecl: New->getParent(),
6914 EllipsisLoc: SourceLocation());
6915 if (NewInit.isInvalid()) {
6916 AnyErrors = true;
6917 break;
6918 }
6919
6920 NewInits.push_back(Elt: NewInit.get());
6921 }
6922
6923 continue;
6924 }
6925
6926 // Instantiate the initializer.
6927 ExprResult TempInit = SubstInitializer(E: Init->getInit(), TemplateArgs,
6928 /*CXXDirectInit=*/true);
6929 if (TempInit.isInvalid()) {
6930 AnyErrors = true;
6931 continue;
6932 }
6933
6934 MemInitResult NewInit;
6935 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
6936 TypeSourceInfo *TInfo = SubstType(T: Init->getTypeSourceInfo(),
6937 TemplateArgs,
6938 Loc: Init->getSourceLocation(),
6939 Entity: New->getDeclName());
6940 if (!TInfo) {
6941 AnyErrors = true;
6942 New->setInvalidDecl();
6943 continue;
6944 }
6945
6946 if (Init->isBaseInitializer())
6947 NewInit = BuildBaseInitializer(BaseType: TInfo->getType(), BaseTInfo: TInfo, Init: TempInit.get(),
6948 ClassDecl: New->getParent(), EllipsisLoc);
6949 else
6950 NewInit = BuildDelegatingInitializer(TInfo, Init: TempInit.get(),
6951 ClassDecl: cast<CXXRecordDecl>(Val: CurContext->getParent()));
6952 } else if (Init->isMemberInitializer()) {
6953 FieldDecl *Member = cast_or_null<FieldDecl>(Val: FindInstantiatedDecl(
6954 Loc: Init->getMemberLocation(),
6955 D: Init->getMember(),
6956 TemplateArgs));
6957 if (!Member) {
6958 AnyErrors = true;
6959 New->setInvalidDecl();
6960 continue;
6961 }
6962
6963 NewInit = BuildMemberInitializer(Member, Init: TempInit.get(),
6964 IdLoc: Init->getSourceLocation());
6965 } else if (Init->isIndirectMemberInitializer()) {
6966 IndirectFieldDecl *IndirectMember =
6967 cast_or_null<IndirectFieldDecl>(Val: FindInstantiatedDecl(
6968 Loc: Init->getMemberLocation(),
6969 D: Init->getIndirectMember(), TemplateArgs));
6970
6971 if (!IndirectMember) {
6972 AnyErrors = true;
6973 New->setInvalidDecl();
6974 continue;
6975 }
6976
6977 NewInit = BuildMemberInitializer(Member: IndirectMember, Init: TempInit.get(),
6978 IdLoc: Init->getSourceLocation());
6979 }
6980
6981 if (NewInit.isInvalid()) {
6982 AnyErrors = true;
6983 New->setInvalidDecl();
6984 } else {
6985 NewInits.push_back(Elt: NewInit.get());
6986 }
6987 }
6988
6989 // Assign all the initializers to the new constructor.
6990 ActOnMemInitializers(ConstructorDecl: New,
6991 /*FIXME: ColonLoc */
6992 ColonLoc: SourceLocation(),
6993 MemInits: NewInits,
6994 AnyErrors);
6995}
6996
6997// TODO: this could be templated if the various decl types used the
6998// same method name.
6999static bool isInstantiationOf(ClassTemplateDecl *Pattern,
7000 ClassTemplateDecl *Instance) {
7001 Pattern = Pattern->getCanonicalDecl();
7002
7003 do {
7004 Instance = Instance->getCanonicalDecl();
7005 if (Pattern == Instance) return true;
7006 Instance = Instance->getInstantiatedFromMemberTemplate();
7007 } while (Instance);
7008
7009 return false;
7010}
7011
7012static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
7013 FunctionTemplateDecl *Instance) {
7014 Pattern = Pattern->getCanonicalDecl();
7015
7016 do {
7017 Instance = Instance->getCanonicalDecl();
7018 if (Pattern == Instance) return true;
7019 Instance = Instance->getInstantiatedFromMemberTemplate();
7020 } while (Instance);
7021
7022 return false;
7023}
7024
7025static bool
7026isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
7027 ClassTemplatePartialSpecializationDecl *Instance) {
7028 Pattern
7029 = cast<ClassTemplatePartialSpecializationDecl>(Val: Pattern->getCanonicalDecl());
7030 do {
7031 Instance = cast<ClassTemplatePartialSpecializationDecl>(
7032 Val: Instance->getCanonicalDecl());
7033 if (Pattern == Instance)
7034 return true;
7035 Instance = Instance->getInstantiatedFromMember();
7036 } while (Instance);
7037
7038 return false;
7039}
7040
7041static bool isInstantiationOf(CXXRecordDecl *Pattern,
7042 CXXRecordDecl *Instance) {
7043 Pattern = Pattern->getCanonicalDecl();
7044
7045 do {
7046 Instance = Instance->getCanonicalDecl();
7047 if (Pattern == Instance) return true;
7048 Instance = Instance->getInstantiatedFromMemberClass();
7049 } while (Instance);
7050
7051 return false;
7052}
7053
7054static bool isInstantiationOf(FunctionDecl *Pattern,
7055 FunctionDecl *Instance) {
7056 Pattern = Pattern->getCanonicalDecl();
7057
7058 do {
7059 Instance = Instance->getCanonicalDecl();
7060 if (Pattern == Instance) return true;
7061 Instance = Instance->getInstantiatedFromMemberFunction();
7062 } while (Instance);
7063
7064 return false;
7065}
7066
7067static bool isInstantiationOf(EnumDecl *Pattern,
7068 EnumDecl *Instance) {
7069 Pattern = Pattern->getCanonicalDecl();
7070
7071 do {
7072 Instance = Instance->getCanonicalDecl();
7073 if (Pattern == Instance) return true;
7074 Instance = Instance->getInstantiatedFromMemberEnum();
7075 } while (Instance);
7076
7077 return false;
7078}
7079
7080static bool isInstantiationOf(UsingShadowDecl *Pattern,
7081 UsingShadowDecl *Instance,
7082 ASTContext &C) {
7083 return declaresSameEntity(D1: C.getInstantiatedFromUsingShadowDecl(Inst: Instance),
7084 D2: Pattern);
7085}
7086
7087static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
7088 ASTContext &C) {
7089 return declaresSameEntity(D1: C.getInstantiatedFromUsingDecl(Inst: Instance), D2: Pattern);
7090}
7091
7092template<typename T>
7093static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
7094 ASTContext &Ctx) {
7095 // An unresolved using declaration can instantiate to an unresolved using
7096 // declaration, or to a using declaration or a using declaration pack.
7097 //
7098 // Multiple declarations can claim to be instantiated from an unresolved
7099 // using declaration if it's a pack expansion. We want the UsingPackDecl
7100 // in that case, not the individual UsingDecls within the pack.
7101 bool OtherIsPackExpansion;
7102 NamedDecl *OtherFrom;
7103 if (auto *OtherUUD = dyn_cast<T>(Other)) {
7104 OtherIsPackExpansion = OtherUUD->isPackExpansion();
7105 OtherFrom = Ctx.getInstantiatedFromUsingDecl(Inst: OtherUUD);
7106 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Val: Other)) {
7107 OtherIsPackExpansion = true;
7108 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
7109 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Val: Other)) {
7110 OtherIsPackExpansion = false;
7111 OtherFrom = Ctx.getInstantiatedFromUsingDecl(Inst: OtherUD);
7112 } else {
7113 return false;
7114 }
7115 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
7116 declaresSameEntity(OtherFrom, Pattern);
7117}
7118
7119static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
7120 VarDecl *Instance) {
7121 assert(Instance->isStaticDataMember());
7122
7123 Pattern = Pattern->getCanonicalDecl();
7124
7125 do {
7126 Instance = Instance->getCanonicalDecl();
7127 if (Pattern == Instance) return true;
7128 Instance = Instance->getInstantiatedFromStaticDataMember();
7129 } while (Instance);
7130
7131 return false;
7132}
7133
7134// Other is the prospective instantiation
7135// D is the prospective pattern
7136static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
7137 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D))
7138 return isInstantiationOfUnresolvedUsingDecl(Pattern: UUD, Other, Ctx);
7139
7140 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: D))
7141 return isInstantiationOfUnresolvedUsingDecl(Pattern: UUD, Other, Ctx);
7142
7143 if (D->getKind() != Other->getKind())
7144 return false;
7145
7146 if (auto *Record = dyn_cast<CXXRecordDecl>(Val: Other))
7147 return isInstantiationOf(Pattern: cast<CXXRecordDecl>(Val: D), Instance: Record);
7148
7149 if (auto *Function = dyn_cast<FunctionDecl>(Val: Other))
7150 return isInstantiationOf(Pattern: cast<FunctionDecl>(Val: D), Instance: Function);
7151
7152 if (auto *Enum = dyn_cast<EnumDecl>(Val: Other))
7153 return isInstantiationOf(Pattern: cast<EnumDecl>(Val: D), Instance: Enum);
7154
7155 if (auto *Var = dyn_cast<VarDecl>(Val: Other))
7156 if (Var->isStaticDataMember())
7157 return isInstantiationOfStaticDataMember(Pattern: cast<VarDecl>(Val: D), Instance: Var);
7158
7159 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Val: Other))
7160 return isInstantiationOf(Pattern: cast<ClassTemplateDecl>(Val: D), Instance: Temp);
7161
7162 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Val: Other))
7163 return isInstantiationOf(Pattern: cast<FunctionTemplateDecl>(Val: D), Instance: Temp);
7164
7165 if (auto *PartialSpec =
7166 dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Other))
7167 return isInstantiationOf(Pattern: cast<ClassTemplatePartialSpecializationDecl>(Val: D),
7168 Instance: PartialSpec);
7169
7170 if (auto *Field = dyn_cast<FieldDecl>(Val: Other)) {
7171 if (!Field->getDeclName()) {
7172 // This is an unnamed field.
7173 return declaresSameEntity(D1: Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
7174 D2: cast<FieldDecl>(Val: D));
7175 }
7176 }
7177
7178 if (auto *Using = dyn_cast<UsingDecl>(Val: Other))
7179 return isInstantiationOf(Pattern: cast<UsingDecl>(Val: D), Instance: Using, C&: Ctx);
7180
7181 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: Other))
7182 return isInstantiationOf(Pattern: cast<UsingShadowDecl>(Val: D), Instance: Shadow, C&: Ctx);
7183
7184 return D->getDeclName() &&
7185 D->getDeclName() == cast<NamedDecl>(Val: Other)->getDeclName();
7186}
7187
7188template<typename ForwardIterator>
7189static NamedDecl *findInstantiationOf(ASTContext &Ctx,
7190 NamedDecl *D,
7191 ForwardIterator first,
7192 ForwardIterator last) {
7193 for (; first != last; ++first)
7194 if (isInstantiationOf(Ctx, D, *first))
7195 return cast<NamedDecl>(*first);
7196
7197 return nullptr;
7198}
7199
7200DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
7201 const MultiLevelTemplateArgumentList &TemplateArgs) {
7202 if (NamedDecl *D = dyn_cast<NamedDecl>(Val: DC)) {
7203 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, FindingInstantiatedContext: true);
7204 return cast_or_null<DeclContext>(Val: ID);
7205 } else return DC;
7206}
7207
7208/// Determine whether the given context is dependent on template parameters at
7209/// level \p Level or below.
7210///
7211/// Sometimes we only substitute an inner set of template arguments and leave
7212/// the outer templates alone. In such cases, contexts dependent only on the
7213/// outer levels are not effectively dependent.
7214static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
7215 if (!DC->isDependentContext())
7216 return false;
7217 if (!Level)
7218 return true;
7219 return cast<Decl>(Val: DC)->getTemplateDepth() > Level;
7220}
7221
7222NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7223 const MultiLevelTemplateArgumentList &TemplateArgs,
7224 bool FindingInstantiatedContext) {
7225 DeclContext *ParentDC = D->getDeclContext();
7226 // Determine whether our parent context depends on any of the template
7227 // arguments we're currently substituting.
7228 bool ParentDependsOnArgs = isDependentContextAtLevel(
7229 DC: ParentDC, Level: TemplateArgs.getNumRetainedOuterLevels());
7230 // FIXME: Parameters of pointer to functions (y below) that are themselves
7231 // parameters (p below) can have their ParentDC set to the translation-unit
7232 // - thus we can not consistently check if the ParentDC of such a parameter
7233 // is Dependent or/and a FunctionOrMethod.
7234 // For e.g. this code, during Template argument deduction tries to
7235 // find an instantiated decl for (T y) when the ParentDC for y is
7236 // the translation unit.
7237 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
7238 // float baz(float(*)()) { return 0.0; }
7239 // Foo(baz);
7240 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
7241 // it gets here, always has a FunctionOrMethod as its ParentDC??
7242 // For now:
7243 // - as long as we have a ParmVarDecl whose parent is non-dependent and
7244 // whose type is not instantiation dependent, do nothing to the decl
7245 // - otherwise find its instantiated decl.
7246 if (isa<ParmVarDecl>(Val: D) && !ParentDependsOnArgs &&
7247 !cast<ParmVarDecl>(Val: D)->getType()->isInstantiationDependentType())
7248 return D;
7249 if (isa<ParmVarDecl>(Val: D) || isa<NonTypeTemplateParmDecl>(Val: D) ||
7250 isa<TemplateTypeParmDecl>(Val: D) || isa<TemplateTemplateParmDecl>(Val: D) ||
7251 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
7252 isa<OMPDeclareReductionDecl>(Val: ParentDC) ||
7253 isa<OMPDeclareMapperDecl>(Val: ParentDC))) ||
7254 (isa<CXXRecordDecl>(Val: D) && cast<CXXRecordDecl>(Val: D)->isLambda() &&
7255 cast<CXXRecordDecl>(Val: D)->getTemplateDepth() >
7256 TemplateArgs.getNumRetainedOuterLevels())) {
7257 // D is a local of some kind. Look into the map of local
7258 // declarations to their instantiations.
7259 if (CurrentInstantiationScope) {
7260 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
7261 if (Decl *FD = Found->dyn_cast<Decl *>()) {
7262 if (auto *BD = dyn_cast<BindingDecl>(Val: FD);
7263 BD && BD->isParameterPack() && ArgPackSubstIndex) {
7264 return BD->getBindingPackDecls()[*ArgPackSubstIndex];
7265 }
7266 return cast<NamedDecl>(Val: FD);
7267 }
7268
7269 assert(ArgPackSubstIndex &&
7270 "found declaration pack but not pack expanding");
7271 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
7272 return cast<NamedDecl>(
7273 Val: (*cast<DeclArgumentPack *>(Val&: *Found))[*ArgPackSubstIndex]);
7274 }
7275 }
7276
7277 // If we're performing a partial substitution during template argument
7278 // deduction, we may not have values for template parameters yet. They
7279 // just map to themselves.
7280 if (isa<NonTypeTemplateParmDecl>(Val: D) || isa<TemplateTypeParmDecl>(Val: D) ||
7281 isa<TemplateTemplateParmDecl>(Val: D))
7282 return D;
7283
7284 if (D->isInvalidDecl())
7285 return nullptr;
7286
7287 // Normally this function only searches for already instantiated declaration
7288 // however we have to make an exclusion for local types used before
7289 // definition as in the code:
7290 //
7291 // template<typename T> void f1() {
7292 // void g1(struct x1);
7293 // struct x1 {};
7294 // }
7295 //
7296 // In this case instantiation of the type of 'g1' requires definition of
7297 // 'x1', which is defined later. Error recovery may produce an enum used
7298 // before definition. In these cases we need to instantiate relevant
7299 // declarations here.
7300 bool NeedInstantiate = false;
7301 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: D))
7302 NeedInstantiate = RD->isLocalClass();
7303 else if (isa<TypedefNameDecl>(Val: D) &&
7304 isa<CXXDeductionGuideDecl>(Val: D->getDeclContext()))
7305 NeedInstantiate = true;
7306 else
7307 NeedInstantiate = isa<EnumDecl>(Val: D);
7308 if (NeedInstantiate) {
7309 Decl *Inst = SubstDecl(D, Owner: CurContext, TemplateArgs);
7310 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
7311 return cast<TypeDecl>(Val: Inst);
7312 }
7313
7314 // If we didn't find the decl, then we must have a label decl that hasn't
7315 // been found yet. Lazily instantiate it and return it now.
7316 assert(isa<LabelDecl>(D));
7317
7318 Decl *Inst = SubstDecl(D, Owner: CurContext, TemplateArgs);
7319 assert(Inst && "Failed to instantiate label??");
7320
7321 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
7322 return cast<LabelDecl>(Val: Inst);
7323 }
7324
7325 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D)) {
7326 if (!Record->isDependentContext())
7327 return D;
7328
7329 // Determine whether this record is the "templated" declaration describing
7330 // a class template or class template specialization.
7331 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
7332 if (ClassTemplate)
7333 ClassTemplate = ClassTemplate->getCanonicalDecl();
7334 else if (ClassTemplateSpecializationDecl *Spec =
7335 dyn_cast<ClassTemplateSpecializationDecl>(Val: Record))
7336 ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl();
7337
7338 // Walk the current context to find either the record or an instantiation of
7339 // it.
7340 DeclContext *DC = CurContext;
7341 while (!DC->isFileContext()) {
7342 // If we're performing substitution while we're inside the template
7343 // definition, we'll find our own context. We're done.
7344 if (DC->Equals(DC: Record))
7345 return Record;
7346
7347 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(Val: DC)) {
7348 // Check whether we're in the process of instantiating a class template
7349 // specialization of the template we're mapping.
7350 if (ClassTemplateSpecializationDecl *InstSpec
7351 = dyn_cast<ClassTemplateSpecializationDecl>(Val: InstRecord)){
7352 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
7353 if (ClassTemplate && isInstantiationOf(Pattern: ClassTemplate, Instance: SpecTemplate))
7354 return InstRecord;
7355 }
7356
7357 // Check whether we're in the process of instantiating a member class.
7358 if (isInstantiationOf(Pattern: Record, Instance: InstRecord))
7359 return InstRecord;
7360 }
7361
7362 // Move to the outer template scope.
7363 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: DC)) {
7364 if (FD->getFriendObjectKind() &&
7365 FD->getNonTransparentDeclContext()->isFileContext()) {
7366 DC = FD->getLexicalDeclContext();
7367 continue;
7368 }
7369 // An implicit deduction guide acts as if it's within the class template
7370 // specialization described by its name and first N template params.
7371 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: FD);
7372 if (Guide && Guide->isImplicit()) {
7373 TemplateDecl *TD = Guide->getDeducedTemplate();
7374 // Convert the arguments to an "as-written" list.
7375 TemplateArgumentListInfo Args(Loc, Loc);
7376 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
7377 N: TD->getTemplateParameters()->size())) {
7378 ArrayRef<TemplateArgument> Unpacked(Arg);
7379 if (Arg.getKind() == TemplateArgument::Pack)
7380 Unpacked = Arg.pack_elements();
7381 for (TemplateArgument UnpackedArg : Unpacked)
7382 Args.addArgument(
7383 Loc: getTrivialTemplateArgumentLoc(Arg: UnpackedArg, NTTPType: QualType(), Loc));
7384 }
7385 QualType T = CheckTemplateIdType(
7386 Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(TD), TemplateLoc: Loc, TemplateArgs&: Args,
7387 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
7388 // We may get a non-null type with errors, in which case
7389 // `getAsCXXRecordDecl` will return `nullptr`. For instance, this
7390 // happens when one of the template arguments is an invalid
7391 // expression. We return early to avoid triggering the assertion
7392 // about the `CodeSynthesisContext`.
7393 if (T.isNull() || T->containsErrors())
7394 return nullptr;
7395 CXXRecordDecl *SubstRecord = T->getAsCXXRecordDecl();
7396
7397 if (!SubstRecord) {
7398 // T can be a dependent TemplateSpecializationType when performing a
7399 // substitution for building a deduction guide or for template
7400 // argument deduction in the process of rebuilding immediate
7401 // expressions. (Because the default argument that involves a lambda
7402 // is untransformed and thus could be dependent at this point.)
7403 assert(SemaRef.RebuildingImmediateInvocation ||
7404 CodeSynthesisContexts.back().Kind ==
7405 CodeSynthesisContext::BuildingDeductionGuides);
7406 // Return a nullptr as a sentinel value, we handle it properly in
7407 // the TemplateInstantiator::TransformInjectedClassNameType
7408 // override, which we transform it to a TemplateSpecializationType.
7409 return nullptr;
7410 }
7411 // Check that this template-id names the primary template and not a
7412 // partial or explicit specialization. (In the latter cases, it's
7413 // meaningless to attempt to find an instantiation of D within the
7414 // specialization.)
7415 // FIXME: The standard doesn't say what should happen here.
7416 if (FindingInstantiatedContext &&
7417 usesPartialOrExplicitSpecialization(
7418 Loc, ClassTemplateSpec: cast<ClassTemplateSpecializationDecl>(Val: SubstRecord))) {
7419 Diag(Loc, DiagID: diag::err_specialization_not_primary_template)
7420 << T << (SubstRecord->getTemplateSpecializationKind() ==
7421 TSK_ExplicitSpecialization);
7422 return nullptr;
7423 }
7424 DC = SubstRecord;
7425 continue;
7426 }
7427 }
7428
7429 DC = DC->getParent();
7430 }
7431
7432 // Fall through to deal with other dependent record types (e.g.,
7433 // anonymous unions in class templates).
7434 }
7435
7436 if (CurrentInstantiationScope) {
7437 if (auto Found = CurrentInstantiationScope->getInstantiationOfIfExists(D))
7438 if (auto *FD = dyn_cast<NamedDecl>(Val: cast<Decl *>(Val&: *Found)))
7439 return FD;
7440 }
7441
7442 if (!ParentDependsOnArgs)
7443 return D;
7444
7445 ParentDC = FindInstantiatedContext(Loc, DC: ParentDC, TemplateArgs);
7446 if (!ParentDC)
7447 return nullptr;
7448
7449 if (ParentDC != D->getDeclContext()) {
7450 // We performed some kind of instantiation in the parent context,
7451 // so now we need to look into the instantiated parent context to
7452 // find the instantiation of the declaration D.
7453
7454 // If our context used to be dependent, we may need to instantiate
7455 // it before performing lookup into that context.
7456 bool IsBeingInstantiated = false;
7457 if (auto *Spec = dyn_cast<CXXRecordDecl>(Val: ParentDC)) {
7458 if (!Spec->isDependentContext()) {
7459 if (Spec->isEntityBeingDefined())
7460 IsBeingInstantiated = true;
7461 else if (RequireCompleteType(Loc, T: Context.getCanonicalTagType(TD: Spec),
7462 DiagID: diag::err_incomplete_type))
7463 return nullptr;
7464
7465 ParentDC = Spec->getDefinitionOrSelf();
7466 }
7467 }
7468
7469 NamedDecl *Result = nullptr;
7470 // FIXME: If the name is a dependent name, this lookup won't necessarily
7471 // find it. Does that ever matter?
7472 if (auto Name = D->getDeclName()) {
7473 DeclarationNameInfo NameInfo(Name, D->getLocation());
7474 DeclarationNameInfo NewNameInfo =
7475 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
7476 Name = NewNameInfo.getName();
7477 if (!Name)
7478 return nullptr;
7479 DeclContext::lookup_result Found = ParentDC->lookup(Name);
7480
7481 Result = findInstantiationOf(Ctx&: Context, D, first: Found.begin(), last: Found.end());
7482 } else {
7483 // Since we don't have a name for the entity we're looking for,
7484 // our only option is to walk through all of the declarations to
7485 // find that name. This will occur in a few cases:
7486 //
7487 // - anonymous struct/union within a template
7488 // - unnamed class/struct/union/enum within a template
7489 //
7490 // FIXME: Find a better way to find these instantiations!
7491 Result = findInstantiationOf(Ctx&: Context, D,
7492 first: ParentDC->decls_begin(),
7493 last: ParentDC->decls_end());
7494 }
7495
7496 if (!Result) {
7497 if (isa<UsingShadowDecl>(Val: D)) {
7498 // UsingShadowDecls can instantiate to nothing because of using hiding.
7499 } else if (hasUncompilableErrorOccurred()) {
7500 // We've already complained about some ill-formed code, so most likely
7501 // this declaration failed to instantiate. There's no point in
7502 // complaining further, since this is normal in invalid code.
7503 // FIXME: Use more fine-grained 'invalid' tracking for this.
7504 } else if (IsBeingInstantiated) {
7505 // The class in which this member exists is currently being
7506 // instantiated, and we haven't gotten around to instantiating this
7507 // member yet. This can happen when the code uses forward declarations
7508 // of member classes, and introduces ordering dependencies via
7509 // template instantiation.
7510 Diag(Loc, DiagID: diag::err_member_not_yet_instantiated)
7511 << D->getDeclName()
7512 << Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: ParentDC));
7513 Diag(Loc: D->getLocation(), DiagID: diag::note_non_instantiated_member_here);
7514 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(Val: D)) {
7515 // This enumeration constant was found when the template was defined,
7516 // but can't be found in the instantiation. This can happen if an
7517 // unscoped enumeration member is explicitly specialized.
7518 EnumDecl *Enum = cast<EnumDecl>(Val: ED->getLexicalDeclContext());
7519 EnumDecl *Spec = cast<EnumDecl>(Val: FindInstantiatedDecl(Loc, D: Enum,
7520 TemplateArgs));
7521 assert(Spec->getTemplateSpecializationKind() ==
7522 TSK_ExplicitSpecialization);
7523 Diag(Loc, DiagID: diag::err_enumerator_does_not_exist)
7524 << D->getDeclName()
7525 << Context.getTypeDeclType(Decl: cast<TypeDecl>(Val: Spec->getDeclContext()));
7526 Diag(Loc: Spec->getLocation(), DiagID: diag::note_enum_specialized_here)
7527 << Context.getCanonicalTagType(TD: Spec);
7528 } else {
7529 // We should have found something, but didn't.
7530 llvm_unreachable("Unable to find instantiation of declaration!");
7531 }
7532 }
7533
7534 D = Result;
7535 }
7536
7537 return D;
7538}
7539
7540void Sema::PerformPendingInstantiations(bool LocalOnly, bool AtEndOfTU) {
7541 std::deque<PendingImplicitInstantiation> DelayedImplicitInstantiations;
7542 while (!PendingLocalImplicitInstantiations.empty() ||
7543 (!LocalOnly && !PendingInstantiations.empty())) {
7544 PendingImplicitInstantiation Inst;
7545
7546 bool LocalInstantiation = false;
7547 if (PendingLocalImplicitInstantiations.empty()) {
7548 Inst = PendingInstantiations.front();
7549 PendingInstantiations.pop_front();
7550 } else {
7551 Inst = PendingLocalImplicitInstantiations.front();
7552 PendingLocalImplicitInstantiations.pop_front();
7553 LocalInstantiation = true;
7554 }
7555
7556 // Instantiate function definitions
7557 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Inst.first)) {
7558 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
7559 TSK_ExplicitInstantiationDefinition;
7560 if (Function->isMultiVersion()) {
7561 getASTContext().forEachMultiversionedFunctionVersion(
7562 FD: Function,
7563 Pred: [this, Inst, DefinitionRequired, AtEndOfTU](FunctionDecl *CurFD) {
7564 InstantiateFunctionDefinition(/*FIXME:*/ PointOfInstantiation: Inst.second, Function: CurFD, Recursive: true,
7565 DefinitionRequired, AtEndOfTU);
7566 if (CurFD->isDefined())
7567 CurFD->setInstantiationIsPending(false);
7568 });
7569 } else {
7570 InstantiateFunctionDefinition(/*FIXME:*/ PointOfInstantiation: Inst.second, Function, Recursive: true,
7571 DefinitionRequired, AtEndOfTU);
7572 if (Function->isDefined())
7573 Function->setInstantiationIsPending(false);
7574 }
7575 // Definition of a PCH-ed template declaration may be available only in the TU.
7576 if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
7577 TUKind == TU_Prefix && Function->instantiationIsPending())
7578 DelayedImplicitInstantiations.push_back(x: Inst);
7579 else if (!AtEndOfTU && Function->instantiationIsPending() &&
7580 !LocalInstantiation)
7581 DelayedImplicitInstantiations.push_back(x: Inst);
7582 continue;
7583 }
7584
7585 // Instantiate variable definitions
7586 VarDecl *Var = cast<VarDecl>(Val: Inst.first);
7587
7588 assert((Var->isStaticDataMember() ||
7589 isa<VarTemplateSpecializationDecl>(Var)) &&
7590 "Not a static data member, nor a variable template"
7591 " specialization?");
7592
7593 // Don't try to instantiate declarations if the most recent redeclaration
7594 // is invalid.
7595 if (Var->getMostRecentDecl()->isInvalidDecl())
7596 continue;
7597
7598 // Check if the most recent declaration has changed the specialization kind
7599 // and removed the need for implicit instantiation.
7600 switch (Var->getMostRecentDecl()
7601 ->getTemplateSpecializationKindForInstantiation()) {
7602 case TSK_Undeclared:
7603 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
7604 case TSK_ExplicitInstantiationDeclaration:
7605 case TSK_ExplicitSpecialization:
7606 continue; // No longer need to instantiate this type.
7607 case TSK_ExplicitInstantiationDefinition:
7608 // We only need an instantiation if the pending instantiation *is* the
7609 // explicit instantiation.
7610 if (Var != Var->getMostRecentDecl())
7611 continue;
7612 break;
7613 case TSK_ImplicitInstantiation:
7614 break;
7615 }
7616
7617 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
7618 "instantiating variable definition");
7619 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
7620 TSK_ExplicitInstantiationDefinition;
7621
7622 // Instantiate static data member definitions or variable template
7623 // specializations.
7624 InstantiateVariableDefinition(/*FIXME:*/ PointOfInstantiation: Inst.second, Var, Recursive: true,
7625 DefinitionRequired, AtEndOfTU);
7626 }
7627
7628 if (!DelayedImplicitInstantiations.empty())
7629 PendingInstantiations.swap(x&: DelayedImplicitInstantiations);
7630}
7631
7632void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
7633 const MultiLevelTemplateArgumentList &TemplateArgs) {
7634 for (auto *DD : Pattern->ddiags()) {
7635 switch (DD->getKind()) {
7636 case DependentDiagnostic::Access:
7637 HandleDependentAccessCheck(DD: *DD, TemplateArgs);
7638 break;
7639 }
7640 }
7641}
7642