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