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