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