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