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

source code of clang/lib/Sema/SemaTemplateInstantiateDecl.cpp