clang 20.0.0git
SemaTemplateInstantiateDecl.cpp
Go to the documentation of this file.
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"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
21#include "clang/AST/TypeLoc.h"
26#include "clang/Sema/Lookup.h"
29#include "clang/Sema/SemaCUDA.h"
30#include "clang/Sema/SemaHLSL.h"
31#include "clang/Sema/SemaObjC.h"
34#include "clang/Sema/Template.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>(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(OldDecl->getQualifierLoc(),
69 TemplateArgs);
70
71 if (!NewQualifierLoc)
72 return true;
73
74 NewDecl->setQualifierInfo(NewQualifierLoc);
75 return false;
76}
77
79 DeclaratorDecl *NewDecl) {
80 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
81}
82
84 TagDecl *NewDecl) {
85 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
86}
87
88// Include attribute instantiation code.
89#include "clang/Sema/AttrTemplateInstantiate.inc"
90
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.
98 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
99 if (!Result.isInvalid())
100 S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
101 } else {
103 S.SubstType(Aligned->getAlignmentType(), TemplateArgs,
104 Aligned->getLocation(), DeclarationName())) {
105 if (!S.CheckAlignasTypeArgument(Aligned->getSpelling(), Result,
106 Aligned->getLocation(),
107 Result->getTypeLoc().getSourceRange()))
108 S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
109 }
110 }
111}
112
114 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
115 const AlignedAttr *Aligned, Decl *New) {
116 if (!Aligned->isPackExpansion()) {
117 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
118 return;
119 }
120
122 if (Aligned->isAlignmentExpr())
123 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
124 Unexpanded);
125 else
126 S.collectUnexpandedParameterPacks(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 std::optional<unsigned> NumExpansions;
133 // FIXME: Use the actual location of the ellipsis.
134 SourceLocation EllipsisLoc = Aligned->getLocation();
135 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
136 Unexpanded, TemplateArgs, Expand,
137 RetainExpansion, NumExpansions))
138 return;
139
140 if (!Expand) {
142 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
143 } else {
144 for (unsigned I = 0; I != *NumExpansions; ++I) {
146 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
147 }
148 }
149}
150
152 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
153 const AssumeAlignedAttr *Aligned, Decl *New) {
154 // The alignment expression is a constant expression.
157
158 Expr *E, *OE = nullptr;
159 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
160 if (Result.isInvalid())
161 return;
162 E = Result.getAs<Expr>();
163
164 if (Aligned->getOffset()) {
165 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
166 if (Result.isInvalid())
167 return;
168 OE = Result.getAs<Expr>();
169 }
170
171 S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
172}
173
175 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
176 const AlignValueAttr *Aligned, Decl *New) {
177 // The alignment expression is a constant expression.
180 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
181 if (!Result.isInvalid())
182 S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
183}
184
186 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
187 const AllocAlignAttr *Align, Decl *New) {
189 S.getASTContext(),
190 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
191 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
192 S.AddAllocAlignAttr(New, *Align, Param);
193}
194
196 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
197 const AnnotateAttr *Attr, Decl *New) {
200
201 // If the attribute has delayed arguments it will have to instantiate those
202 // and handle them as new arguments for the attribute.
203 bool HasDelayedArgs = Attr->delayedArgs_size();
204
205 ArrayRef<Expr *> ArgsToInstantiate =
206 HasDelayedArgs
207 ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
208 : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
209
211 if (S.SubstExprs(ArgsToInstantiate,
212 /*IsCall=*/false, TemplateArgs, Args))
213 return;
214
215 StringRef Str = Attr->getAnnotation();
216 if (HasDelayedArgs) {
217 if (Args.size() < 1) {
218 S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
219 << Attr << 1;
220 return;
221 }
222
223 if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
224 return;
225
227 ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
228 std::swap(Args, ActualArgs);
229 }
230 auto *AA = S.CreateAnnotationAttr(*Attr, Str, Args);
231 if (AA) {
232 New->addAttr(AA);
233 }
234}
235
237 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
238 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
239 Expr *Cond = nullptr;
240 {
241 Sema::ContextRAII SwitchContext(S, New);
244 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
245 if (Result.isInvalid())
246 return nullptr;
247 Cond = Result.getAs<Expr>();
248 }
249 if (!Cond->isTypeDependent()) {
251 if (Converted.isInvalid())
252 return nullptr;
253 Cond = Converted.get();
254 }
255
257 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
258 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
259 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
260 for (const auto &P : Diags)
261 S.Diag(P.first, P.second);
262 return nullptr;
263 }
264 return Cond;
265}
266
268 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
269 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
271 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
272
273 if (Cond)
274 New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
275 Cond, EIA->getMessage()));
276}
277
279 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
280 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
282 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
283
284 if (Cond)
285 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
286 S.getASTContext(), *DIA, Cond, DIA->getMessage(),
287 DIA->getDiagnosticType(), DIA->getArgDependent(), New));
288}
289
290// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
291// template A as the base and arguments from TemplateArgs.
293 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
294 const CUDALaunchBoundsAttr &Attr, Decl *New) {
295 // The alignment expression is a constant expression.
298
299 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
300 if (Result.isInvalid())
301 return;
302 Expr *MaxThreads = Result.getAs<Expr>();
303
304 Expr *MinBlocks = nullptr;
305 if (Attr.getMinBlocks()) {
306 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
307 if (Result.isInvalid())
308 return;
309 MinBlocks = Result.getAs<Expr>();
310 }
311
312 Expr *MaxBlocks = nullptr;
313 if (Attr.getMaxBlocks()) {
314 Result = S.SubstExpr(Attr.getMaxBlocks(), TemplateArgs);
315 if (Result.isInvalid())
316 return;
317 MaxBlocks = Result.getAs<Expr>();
318 }
319
320 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks, MaxBlocks);
321}
322
323static void
325 const MultiLevelTemplateArgumentList &TemplateArgs,
326 const ModeAttr &Attr, Decl *New) {
327 S.AddModeAttr(New, Attr, Attr.getMode(),
328 /*InInstantiation=*/true);
329}
330
331/// Instantiation of 'declare simd' attribute and its arguments.
333 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
334 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
335 // Allow 'this' in clauses with varlist.
336 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
337 New = FTD->getTemplatedDecl();
338 auto *FD = cast<FunctionDecl>(New);
339 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
340 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
341 SmallVector<unsigned, 4> LinModifiers;
342
343 auto SubstExpr = [&](Expr *E) -> ExprResult {
344 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
345 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
346 Sema::ContextRAII SavedContext(S, FD);
348 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
349 Local.InstantiatedLocal(
350 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
351 return S.SubstExpr(E, TemplateArgs);
352 }
353 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
354 FD->isCXXInstanceMember());
355 return S.SubstExpr(E, TemplateArgs);
356 };
357
358 // Substitute a single OpenMP clause, which is a potentially-evaluated
359 // full-expression.
360 auto Subst = [&](Expr *E) -> ExprResult {
363 ExprResult Res = SubstExpr(E);
364 if (Res.isInvalid())
365 return Res;
366 return S.ActOnFinishFullExpr(Res.get(), false);
367 };
368
369 ExprResult Simdlen;
370 if (auto *E = Attr.getSimdlen())
371 Simdlen = Subst(E);
372
373 if (Attr.uniforms_size() > 0) {
374 for(auto *E : Attr.uniforms()) {
375 ExprResult Inst = Subst(E);
376 if (Inst.isInvalid())
377 continue;
378 Uniforms.push_back(Inst.get());
379 }
380 }
381
382 auto AI = Attr.alignments_begin();
383 for (auto *E : Attr.aligneds()) {
384 ExprResult Inst = Subst(E);
385 if (Inst.isInvalid())
386 continue;
387 Aligneds.push_back(Inst.get());
388 Inst = ExprEmpty();
389 if (*AI)
390 Inst = S.SubstExpr(*AI, TemplateArgs);
391 Alignments.push_back(Inst.get());
392 ++AI;
393 }
394
395 auto SI = Attr.steps_begin();
396 for (auto *E : Attr.linears()) {
397 ExprResult Inst = Subst(E);
398 if (Inst.isInvalid())
399 continue;
400 Linears.push_back(Inst.get());
401 Inst = ExprEmpty();
402 if (*SI)
403 Inst = S.SubstExpr(*SI, TemplateArgs);
404 Steps.push_back(Inst.get());
405 ++SI;
406 }
407 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
409 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
410 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
411 Attr.getRange());
412}
413
414/// Instantiation of 'declare variant' attribute and its arguments.
416 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
417 const OMPDeclareVariantAttr &Attr, Decl *New) {
418 // Allow 'this' in clauses with varlist.
419 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
420 New = FTD->getTemplatedDecl();
421 auto *FD = cast<FunctionDecl>(New);
422 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
423
424 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
425 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
426 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
427 Sema::ContextRAII SavedContext(S, FD);
429 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
430 Local.InstantiatedLocal(
431 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
432 return S.SubstExpr(E, TemplateArgs);
433 }
434 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
435 FD->isCXXInstanceMember());
436 return S.SubstExpr(E, TemplateArgs);
437 };
438
439 // Substitute a single OpenMP clause, which is a potentially-evaluated
440 // full-expression.
441 auto &&Subst = [&SubstExpr, &S](Expr *E) {
444 ExprResult Res = SubstExpr(E);
445 if (Res.isInvalid())
446 return Res;
447 return S.ActOnFinishFullExpr(Res.get(), false);
448 };
449
450 ExprResult VariantFuncRef;
451 if (Expr *E = Attr.getVariantFuncRef()) {
452 // Do not mark function as is used to prevent its emission if this is the
453 // only place where it is used.
456 VariantFuncRef = Subst(E);
457 }
458
459 // Copy the template version of the OMPTraitInfo and run substitute on all
460 // score and condition expressiosn.
462 TI = *Attr.getTraitInfos();
463
464 // Try to substitute template parameters in score and condition expressions.
465 auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
466 if (E) {
469 ExprResult ER = Subst(E);
470 if (ER.isUsable())
471 E = ER.get();
472 else
473 return true;
474 }
475 return false;
476 };
477 if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
478 return;
479
480 Expr *E = VariantFuncRef.get();
481
482 // Check function/variant ref for `omp declare variant` but not for `omp
483 // begin declare variant` (which use implicit attributes).
484 std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
486 S.ConvertDeclToDeclGroup(New), E, TI, Attr.appendArgs_size(),
487 Attr.getRange());
488
489 if (!DeclVarData)
490 return;
491
492 E = DeclVarData->second;
493 FD = DeclVarData->first;
494
495 if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
496 if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
497 if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
498 if (!VariantFTD->isThisDeclarationADefinition())
499 return;
502 S.Context, TemplateArgs.getInnermost());
503
504 auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
505 New->getLocation());
506 if (!SubstFD)
507 return;
509 SubstFD->getType(), FD->getType(),
510 /* OfBlockPointer */ false,
511 /* Unqualified */ false, /* AllowCXX */ true);
512 if (NewType.isNull())
513 return;
515 New->getLocation(), SubstFD, /* Recursive */ true,
516 /* DefinitionRequired */ false, /* AtEndOfTU */ false);
517 SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
519 SourceLocation(), SubstFD,
520 /* RefersToEnclosingVariableOrCapture */ false,
521 /* NameLoc */ SubstFD->getLocation(),
522 SubstFD->getType(), ExprValueKind::VK_PRValue);
523 }
524 }
525 }
526
527 SmallVector<Expr *, 8> NothingExprs;
528 SmallVector<Expr *, 8> NeedDevicePtrExprs;
530
531 for (Expr *E : Attr.adjustArgsNothing()) {
532 ExprResult ER = Subst(E);
533 if (ER.isInvalid())
534 continue;
535 NothingExprs.push_back(ER.get());
536 }
537 for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
538 ExprResult ER = Subst(E);
539 if (ER.isInvalid())
540 continue;
541 NeedDevicePtrExprs.push_back(ER.get());
542 }
543 for (OMPInteropInfo &II : Attr.appendArgs()) {
544 // When prefer_type is implemented for append_args handle them here too.
545 AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
546 }
547
549 FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
551}
552
554 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
555 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
556 // Both min and max expression are constant expressions.
559
560 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
561 if (Result.isInvalid())
562 return;
563 Expr *MinExpr = Result.getAs<Expr>();
564
565 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
566 if (Result.isInvalid())
567 return;
568 Expr *MaxExpr = Result.getAs<Expr>();
569
570 S.AMDGPU().addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
571}
572
574 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) {
575 if (!ES.getExpr())
576 return ES;
577 Expr *OldCond = ES.getExpr();
578 Expr *Cond = nullptr;
579 {
582 ExprResult SubstResult = SubstExpr(OldCond, TemplateArgs);
583 if (SubstResult.isInvalid()) {
585 }
586 Cond = SubstResult.get();
587 }
588 ExplicitSpecifier Result(Cond, ES.getKind());
589 if (!Cond->isTypeDependent())
591 return Result;
592}
593
595 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
596 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
597 // Both min and max expression are constant expressions.
600
601 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
602 if (Result.isInvalid())
603 return;
604 Expr *MinExpr = Result.getAs<Expr>();
605
606 Expr *MaxExpr = nullptr;
607 if (auto Max = Attr.getMax()) {
608 Result = S.SubstExpr(Max, TemplateArgs);
609 if (Result.isInvalid())
610 return;
611 MaxExpr = Result.getAs<Expr>();
612 }
613
614 S.AMDGPU().addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
615}
616
618 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
619 const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New) {
622
623 ExprResult ResultX = S.SubstExpr(Attr.getMaxNumWorkGroupsX(), TemplateArgs);
624 if (!ResultX.isUsable())
625 return;
626 ExprResult ResultY = S.SubstExpr(Attr.getMaxNumWorkGroupsY(), TemplateArgs);
627 if (!ResultY.isUsable())
628 return;
629 ExprResult ResultZ = S.SubstExpr(Attr.getMaxNumWorkGroupsZ(), TemplateArgs);
630 if (!ResultZ.isUsable())
631 return;
632
633 Expr *XExpr = ResultX.getAs<Expr>();
634 Expr *YExpr = ResultY.getAs<Expr>();
635 Expr *ZExpr = ResultZ.getAs<Expr>();
636
637 S.AMDGPU().addAMDGPUMaxNumWorkGroupsAttr(New, Attr, XExpr, YExpr, ZExpr);
638}
639
640// This doesn't take any template parameters, but we have a custom action that
641// needs to happen when the kernel itself is instantiated. We need to run the
642// ItaniumMangler to mark the names required to name this kernel.
644 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
645 const SYCLKernelAttr &Attr, Decl *New) {
646 New->addAttr(Attr.clone(S.getASTContext()));
647}
648
649/// Determine whether the attribute A might be relevant to the declaration D.
650/// If not, we can skip instantiating it. The attribute may or may not have
651/// been instantiated yet.
652static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
653 // 'preferred_name' is only relevant to the matching specialization of the
654 // template.
655 if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
656 QualType T = PNA->getTypedefType();
657 const auto *RD = cast<CXXRecordDecl>(D);
658 if (!T->isDependentType() && !RD->isDependentContext() &&
660 return false;
661 for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
662 if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
663 PNA->getTypedefType()))
664 return false;
665 return true;
666 }
667
668 if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
669 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
670 switch (BA->getID()) {
671 case Builtin::BIforward:
672 // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
673 // type and returns an lvalue reference type. The library implementation
674 // will produce an error in this case; don't get in its way.
675 if (FD && FD->getNumParams() >= 1 &&
678 return false;
679 }
680 [[fallthrough]];
681 case Builtin::BImove:
682 case Builtin::BImove_if_noexcept:
683 // HACK: Super-old versions of libc++ (3.1 and earlier) provide
684 // std::forward and std::move overloads that sometimes return by value
685 // instead of by reference when building in C++98 mode. Don't treat such
686 // cases as builtins.
687 if (FD && !FD->getReturnType()->isReferenceType())
688 return false;
689 break;
690 }
691 }
692
693 return true;
694}
695
697 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
698 const HLSLParamModifierAttr *Attr, Decl *New) {
699 ParmVarDecl *P = cast<ParmVarDecl>(New);
700 P->addAttr(Attr->clone(S.getASTContext()));
701 P->setType(S.HLSL().getInoutParameterType(P->getType()));
702}
703
705 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
706 Decl *New, LateInstantiatedAttrVec *LateAttrs,
707 LocalInstantiationScope *OuterMostScope) {
708 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
709 // FIXME: This function is called multiple times for the same template
710 // specialization. We should only instantiate attributes that were added
711 // since the previous instantiation.
712 for (const auto *TmplAttr : Tmpl->attrs()) {
713 if (!isRelevantAttr(*this, New, TmplAttr))
714 continue;
715
716 // FIXME: If any of the special case versions from InstantiateAttrs become
717 // applicable to template declaration, we'll need to add them here.
718 CXXThisScopeRAII ThisScope(
719 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
720 Qualifiers(), ND->isCXXInstanceMember());
721
723 TmplAttr, Context, *this, TemplateArgs);
724 if (NewAttr && isRelevantAttr(*this, New, NewAttr))
725 New->addAttr(NewAttr);
726 }
727 }
728}
729
732 switch (A->getKind()) {
733 case clang::attr::CFConsumed:
735 case clang::attr::OSConsumed:
737 case clang::attr::NSConsumed:
739 default:
740 llvm_unreachable("Wrong argument supplied");
741 }
742}
743
745 const Decl *Tmpl, Decl *New,
746 LateInstantiatedAttrVec *LateAttrs,
747 LocalInstantiationScope *OuterMostScope) {
748 for (const auto *TmplAttr : Tmpl->attrs()) {
749 if (!isRelevantAttr(*this, New, TmplAttr))
750 continue;
751
752 // FIXME: This should be generalized to more than just the AlignedAttr.
753 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
754 if (Aligned && Aligned->isAlignmentDependent()) {
755 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
756 continue;
757 }
758
759 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
760 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
761 continue;
762 }
763
764 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
765 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
766 continue;
767 }
768
769 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
770 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
771 continue;
772 }
773
774 if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
775 instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
776 continue;
777 }
778
779 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
780 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
781 cast<FunctionDecl>(New));
782 continue;
783 }
784
785 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
786 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
787 cast<FunctionDecl>(New));
788 continue;
789 }
790
791 if (const auto *CUDALaunchBounds =
792 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
794 *CUDALaunchBounds, New);
795 continue;
796 }
797
798 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
799 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
800 continue;
801 }
802
803 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
804 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
805 continue;
806 }
807
808 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
809 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
810 continue;
811 }
812
813 if (const auto *AMDGPUFlatWorkGroupSize =
814 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
816 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
817 }
818
819 if (const auto *AMDGPUFlatWorkGroupSize =
820 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
822 *AMDGPUFlatWorkGroupSize, New);
823 }
824
825 if (const auto *AMDGPUMaxNumWorkGroups =
826 dyn_cast<AMDGPUMaxNumWorkGroupsAttr>(TmplAttr)) {
828 *this, TemplateArgs, *AMDGPUMaxNumWorkGroups, New);
829 }
830
831 if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(TmplAttr)) {
832 instantiateDependentHLSLParamModifierAttr(*this, TemplateArgs, ParamAttr,
833 New);
834 continue;
835 }
836
837 // Existing DLL attribute on the instantiation takes precedence.
838 if (TmplAttr->getKind() == attr::DLLExport ||
839 TmplAttr->getKind() == attr::DLLImport) {
840 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
841 continue;
842 }
843 }
844
845 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
846 Swift().AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
847 continue;
848 }
849
850 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
851 isa<CFConsumedAttr>(TmplAttr)) {
852 ObjC().AddXConsumedAttr(New, *TmplAttr,
854 /*template instantiation=*/true);
855 continue;
856 }
857
858 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
859 if (!New->hasAttr<PointerAttr>())
860 New->addAttr(A->clone(Context));
861 continue;
862 }
863
864 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
865 if (!New->hasAttr<OwnerAttr>())
866 New->addAttr(A->clone(Context));
867 continue;
868 }
869
870 if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
871 instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
872 continue;
873 }
874
875 if (auto *A = dyn_cast<CUDAGridConstantAttr>(TmplAttr)) {
876 if (!New->hasAttr<CUDAGridConstantAttr>())
877 New->addAttr(A->clone(Context));
878 continue;
879 }
880
881 assert(!TmplAttr->isPackExpansion());
882 if (TmplAttr->isLateParsed() && LateAttrs) {
883 // Late parsed attributes must be instantiated and attached after the
884 // enclosing class has been instantiated. See Sema::InstantiateClass.
885 LocalInstantiationScope *Saved = nullptr;
887 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
888 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
889 } else {
890 // Allow 'this' within late-parsed attributes.
891 auto *ND = cast<NamedDecl>(New);
892 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
893 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
894 ND->isCXXInstanceMember());
895
897 *this, TemplateArgs);
898 if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
899 New->addAttr(NewAttr);
900 }
901 }
902}
903
905 for (const auto *Attr : Pattern->attrs()) {
906 if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
907 if (!Inst->hasAttr<StrictFPAttr>())
908 Inst->addAttr(A->clone(getASTContext()));
909 continue;
910 }
911 }
912}
913
916 Ctor->isDefaultConstructor());
917 unsigned NumParams = Ctor->getNumParams();
918 if (NumParams == 0)
919 return;
920 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
921 if (!Attr)
922 return;
923 for (unsigned I = 0; I != NumParams; ++I) {
925 Ctor->getParamDecl(I));
927 }
928}
929
930/// Get the previous declaration of a declaration for the purposes of template
931/// instantiation. If this finds a previous declaration, then the previous
932/// declaration of the instantiation of D should be an instantiation of the
933/// result of this function.
934template<typename DeclT>
935static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
936 DeclT *Result = D->getPreviousDecl();
937
938 // If the declaration is within a class, and the previous declaration was
939 // merged from a different definition of that class, then we don't have a
940 // previous declaration for the purpose of template instantiation.
941 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
942 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
943 return nullptr;
944
945 return Result;
946}
947
948Decl *
949TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
950 llvm_unreachable("Translation units cannot be instantiated");
951}
952
953Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
954 llvm_unreachable("HLSL buffer declarations cannot be instantiated");
955}
956
957Decl *
958TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
959 llvm_unreachable("pragma comment cannot be instantiated");
960}
961
962Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
964 llvm_unreachable("pragma comment cannot be instantiated");
965}
966
967Decl *
968TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
969 llvm_unreachable("extern \"C\" context cannot be instantiated");
970}
971
972Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
973 llvm_unreachable("GUID declaration cannot be instantiated");
974}
975
976Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
978 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
979}
980
981Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
983 llvm_unreachable("template parameter objects cannot be instantiated");
984}
985
986Decl *
987TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
988 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
989 D->getIdentifier());
990 SemaRef.InstantiateAttrs(TemplateArgs, D, Inst, LateAttrs, StartingScope);
991 Owner->addDecl(Inst);
992 return Inst;
993}
994
995Decl *
996TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
997 llvm_unreachable("Namespaces cannot be instantiated");
998}
999
1000Decl *
1001TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1002 NamespaceAliasDecl *Inst
1003 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
1004 D->getNamespaceLoc(),
1005 D->getAliasLoc(),
1006 D->getIdentifier(),
1007 D->getQualifierLoc(),
1008 D->getTargetNameLoc(),
1009 D->getNamespace());
1010 Owner->addDecl(Inst);
1011 return Inst;
1012}
1013
1015 bool IsTypeAlias) {
1016 bool Invalid = false;
1017 TypeSourceInfo *DI = D->getTypeSourceInfo();
1020 DI = SemaRef.SubstType(DI, TemplateArgs,
1021 D->getLocation(), D->getDeclName());
1022 if (!DI) {
1023 Invalid = true;
1024 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
1025 }
1026 } else {
1028 }
1029
1030 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
1031 // libstdc++ relies upon this bug in its implementation of common_type. If we
1032 // happen to be processing that implementation, fake up the g++ ?:
1033 // semantics. See LWG issue 2141 for more information on the bug. The bugs
1034 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
1035 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
1036 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1037 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
1038 DT->isReferenceType() &&
1039 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
1040 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
1041 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
1043 // Fold it to the (non-reference) type which g++ would have produced.
1044 DI = SemaRef.Context.getTrivialTypeSourceInfo(
1046
1047 // Create the new typedef
1048 TypedefNameDecl *Typedef;
1049 if (IsTypeAlias)
1050 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1051 D->getLocation(), D->getIdentifier(), DI);
1052 else
1053 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1054 D->getLocation(), D->getIdentifier(), DI);
1055 if (Invalid)
1056 Typedef->setInvalidDecl();
1057
1058 // If the old typedef was the name for linkage purposes of an anonymous
1059 // tag decl, re-establish that relationship for the new typedef.
1060 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1061 TagDecl *oldTag = oldTagType->getDecl();
1062 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1063 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
1064 assert(!newTag->hasNameForLinkage());
1065 newTag->setTypedefNameForAnonDecl(Typedef);
1066 }
1067 }
1068
1070 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1071 TemplateArgs);
1072 if (!InstPrev)
1073 return nullptr;
1074
1075 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1076
1077 // If the typedef types are not identical, reject them.
1078 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1079
1080 Typedef->setPreviousDecl(InstPrevTypedef);
1081 }
1082
1083 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1084
1085 if (D->getUnderlyingType()->getAs<DependentNameType>())
1086 SemaRef.inferGslPointerAttribute(Typedef);
1087
1088 Typedef->setAccess(D->getAccess());
1089 Typedef->setReferenced(D->isReferenced());
1090
1091 return Typedef;
1092}
1093
1094Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1095 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1096 if (Typedef)
1097 Owner->addDecl(Typedef);
1098 return Typedef;
1099}
1100
1101Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1102 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1103 if (Typedef)
1104 Owner->addDecl(Typedef);
1105 return Typedef;
1106}
1107
1110 // Create a local instantiation scope for this type alias template, which
1111 // will contain the instantiations of the template parameters.
1113
1114 TemplateParameterList *TempParams = D->getTemplateParameters();
1115 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1116 if (!InstParams)
1117 return nullptr;
1118
1119 TypeAliasDecl *Pattern = D->getTemplatedDecl();
1120 Sema::InstantiatingTemplate InstTemplate(
1121 SemaRef, D->getBeginLoc(), D,
1122 D->getTemplateDepth() >= TemplateArgs.getNumLevels()
1124 : (TemplateArgs.begin() + TemplateArgs.getNumLevels() - 1 -
1126 ->Args);
1127 if (InstTemplate.isInvalid())
1128 return nullptr;
1129
1130 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1131 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
1133 if (!Found.empty()) {
1134 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1135 }
1136 }
1137
1138 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1139 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1140 if (!AliasInst)
1141 return nullptr;
1142
1145 D->getDeclName(), InstParams, AliasInst);
1146 AliasInst->setDescribedAliasTemplate(Inst);
1147 if (PrevAliasTemplate)
1148 Inst->setPreviousDecl(PrevAliasTemplate);
1149
1150 Inst->setAccess(D->getAccess());
1151
1152 if (!PrevAliasTemplate)
1154
1155 return Inst;
1156}
1157
1158Decl *
1159TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1161 if (Inst)
1162 Owner->addDecl(Inst);
1163
1164 return Inst;
1165}
1166
1167Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1168 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1169 D->getIdentifier());
1170 NewBD->setReferenced(D->isReferenced());
1172 return NewBD;
1173}
1174
1175Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1176 // Transform the bindings first.
1178 for (auto *OldBD : D->bindings())
1179 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1180 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1181
1182 auto *NewDD = cast_or_null<DecompositionDecl>(
1183 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1184
1185 if (!NewDD || NewDD->isInvalidDecl())
1186 for (auto *NewBD : NewBindings)
1187 NewBD->setInvalidDecl();
1188
1189 return NewDD;
1190}
1191
1193 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1194}
1195
1197 bool InstantiatingVarTemplate,
1199
1200 // Do substitution on the type of the declaration
1201 TypeSourceInfo *DI = SemaRef.SubstType(
1202 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1203 D->getDeclName(), /*AllowDeducedTST*/true);
1204 if (!DI)
1205 return nullptr;
1206
1207 if (DI->getType()->isFunctionType()) {
1208 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1209 << D->isStaticDataMember() << DI->getType();
1210 return nullptr;
1211 }
1212
1213 DeclContext *DC = Owner;
1214 if (D->isLocalExternDecl())
1216
1217 // Build the instantiated declaration.
1218 VarDecl *Var;
1219 if (Bindings)
1220 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1221 D->getLocation(), DI->getType(), DI,
1222 D->getStorageClass(), *Bindings);
1223 else
1224 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1225 D->getLocation(), D->getIdentifier(), DI->getType(),
1226 DI, D->getStorageClass());
1227
1228 // In ARC, infer 'retaining' for variables of retainable type.
1229 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1230 SemaRef.ObjC().inferObjCARCLifetime(Var))
1231 Var->setInvalidDecl();
1232
1233 if (SemaRef.getLangOpts().OpenCL)
1234 SemaRef.deduceOpenCLAddressSpace(Var);
1235
1236 // Substitute the nested name specifier, if any.
1237 if (SubstQualifier(D, Var))
1238 return nullptr;
1239
1240 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1241 StartingScope, InstantiatingVarTemplate);
1242 if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1243 QualType RT;
1244 if (auto *F = dyn_cast<FunctionDecl>(DC))
1245 RT = F->getReturnType();
1246 else if (isa<BlockDecl>(DC))
1247 RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1248 ->getReturnType();
1249 else
1250 llvm_unreachable("Unknown context type");
1251
1252 // This is the last chance we have of checking copy elision eligibility
1253 // for functions in dependent contexts. The sema actions for building
1254 // the return statement during template instantiation will have no effect
1255 // regarding copy elision, since NRVO propagation runs on the scope exit
1256 // actions, and these are not run on instantiation.
1257 // This might run through some VarDecls which were returned from non-taken
1258 // 'if constexpr' branches, and these will end up being constructed on the
1259 // return slot even if they will never be returned, as a sort of accidental
1260 // 'optimization'. Notably, functions with 'auto' return types won't have it
1261 // deduced by this point. Coupled with the limitation described
1262 // previously, this makes it very hard to support copy elision for these.
1263 Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1264 bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1265 Var->setNRVOVariable(NRVO);
1266 }
1267
1268 Var->setImplicit(D->isImplicit());
1269
1270 if (Var->isStaticLocal())
1271 SemaRef.CheckStaticLocalForDllExport(Var);
1272
1273 if (Var->getTLSKind())
1275
1276 return Var;
1277}
1278
1279Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1280 AccessSpecDecl* AD
1281 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1282 D->getAccessSpecifierLoc(), D->getColonLoc());
1283 Owner->addHiddenDecl(AD);
1284 return AD;
1285}
1286
1287Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1288 bool Invalid = false;
1289 TypeSourceInfo *DI = D->getTypeSourceInfo();
1292 DI = SemaRef.SubstType(DI, TemplateArgs,
1293 D->getLocation(), D->getDeclName());
1294 if (!DI) {
1295 DI = D->getTypeSourceInfo();
1296 Invalid = true;
1297 } else if (DI->getType()->isFunctionType()) {
1298 // C++ [temp.arg.type]p3:
1299 // If a declaration acquires a function type through a type
1300 // dependent on a template-parameter and this causes a
1301 // declaration that does not use the syntactic form of a
1302 // function declarator to have function type, the program is
1303 // ill-formed.
1304 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1305 << DI->getType();
1306 Invalid = true;
1307 }
1308 } else {
1310 }
1311
1312 Expr *BitWidth = D->getBitWidth();
1313 if (Invalid)
1314 BitWidth = nullptr;
1315 else if (BitWidth) {
1316 // The bit-width expression is a constant expression.
1319
1320 ExprResult InstantiatedBitWidth
1321 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1322 if (InstantiatedBitWidth.isInvalid()) {
1323 Invalid = true;
1324 BitWidth = nullptr;
1325 } else
1326 BitWidth = InstantiatedBitWidth.getAs<Expr>();
1327 }
1328
1329 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1330 DI->getType(), DI,
1331 cast<RecordDecl>(Owner),
1332 D->getLocation(),
1333 D->isMutable(),
1334 BitWidth,
1335 D->getInClassInitStyle(),
1336 D->getInnerLocStart(),
1337 D->getAccess(),
1338 nullptr);
1339 if (!Field) {
1340 cast<Decl>(Owner)->setInvalidDecl();
1341 return nullptr;
1342 }
1343
1344 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1345
1346 if (Field->hasAttrs())
1347 SemaRef.CheckAlignasUnderalignment(Field);
1348
1349 if (Invalid)
1350 Field->setInvalidDecl();
1351
1352 if (!Field->getDeclName() || Field->isPlaceholderVar(SemaRef.getLangOpts())) {
1353 // Keep track of where this decl came from.
1355 }
1356 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1357 if (Parent->isAnonymousStructOrUnion() &&
1358 Parent->getRedeclContext()->isFunctionOrMethod())
1360 }
1361
1362 Field->setImplicit(D->isImplicit());
1363 Field->setAccess(D->getAccess());
1364 Owner->addDecl(Field);
1365
1366 return Field;
1367}
1368
1369Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1370 bool Invalid = false;
1371 TypeSourceInfo *DI = D->getTypeSourceInfo();
1372
1373 if (DI->getType()->isVariablyModifiedType()) {
1374 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1375 << D;
1376 Invalid = true;
1377 } else if (DI->getType()->isInstantiationDependentType()) {
1378 DI = SemaRef.SubstType(DI, TemplateArgs,
1379 D->getLocation(), D->getDeclName());
1380 if (!DI) {
1381 DI = D->getTypeSourceInfo();
1382 Invalid = true;
1383 } else if (DI->getType()->isFunctionType()) {
1384 // C++ [temp.arg.type]p3:
1385 // If a declaration acquires a function type through a type
1386 // dependent on a template-parameter and this causes a
1387 // declaration that does not use the syntactic form of a
1388 // function declarator to have function type, the program is
1389 // ill-formed.
1390 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1391 << DI->getType();
1392 Invalid = true;
1393 }
1394 } else {
1396 }
1397
1399 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1400 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1401
1402 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1403 StartingScope);
1404
1405 if (Invalid)
1406 Property->setInvalidDecl();
1407
1408 Property->setAccess(D->getAccess());
1409 Owner->addDecl(Property);
1410
1411 return Property;
1412}
1413
1414Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1415 NamedDecl **NamedChain =
1416 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1417
1418 int i = 0;
1419 for (auto *PI : D->chain()) {
1420 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1421 TemplateArgs);
1422 if (!Next)
1423 return nullptr;
1424
1425 NamedChain[i++] = Next;
1426 }
1427
1428 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1430 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1431 {NamedChain, D->getChainingSize()});
1432
1433 for (const auto *Attr : D->attrs())
1434 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1435
1436 IndirectField->setImplicit(D->isImplicit());
1437 IndirectField->setAccess(D->getAccess());
1438 Owner->addDecl(IndirectField);
1439 return IndirectField;
1440}
1441
1442Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1443 // Handle friend type expressions by simply substituting template
1444 // parameters into the pattern type and checking the result.
1445 if (TypeSourceInfo *Ty = D->getFriendType()) {
1446 TypeSourceInfo *InstTy;
1447 // If this is an unsupported friend, don't bother substituting template
1448 // arguments into it. The actual type referred to won't be used by any
1449 // parts of Clang, and may not be valid for instantiating. Just use the
1450 // same info for the instantiated friend.
1451 if (D->isUnsupportedFriend()) {
1452 InstTy = Ty;
1453 } else {
1454 if (D->isPackExpansion()) {
1456 SemaRef.collectUnexpandedParameterPacks(Ty->getTypeLoc(), Unexpanded);
1457 assert(!Unexpanded.empty() && "Pack expansion without packs");
1458
1459 bool ShouldExpand = true;
1460 bool RetainExpansion = false;
1461 std::optional<unsigned> NumExpansions;
1463 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded,
1464 TemplateArgs, ShouldExpand, RetainExpansion, NumExpansions))
1465 return nullptr;
1466
1467 assert(!RetainExpansion &&
1468 "should never retain an expansion for a variadic friend decl");
1469
1470 if (ShouldExpand) {
1472 for (unsigned I = 0; I != *NumExpansions; I++) {
1473 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1474 TypeSourceInfo *TSI = SemaRef.SubstType(
1475 Ty, TemplateArgs, D->getEllipsisLoc(), DeclarationName());
1476 if (!TSI)
1477 return nullptr;
1478
1479 auto FD =
1480 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1481 TSI, D->getFriendLoc());
1482
1483 FD->setAccess(AS_public);
1484 Owner->addDecl(FD);
1485 Decls.push_back(FD);
1486 }
1487
1488 // Just drop this node; we have no use for it anymore.
1489 return nullptr;
1490 }
1491 }
1492
1493 InstTy = SemaRef.SubstType(Ty, TemplateArgs, D->getLocation(),
1494 DeclarationName());
1495 }
1496 if (!InstTy)
1497 return nullptr;
1498
1500 SemaRef.Context, Owner, D->getLocation(), InstTy, D->getFriendLoc());
1501 FD->setAccess(AS_public);
1502 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1503 Owner->addDecl(FD);
1504 return FD;
1505 }
1506
1507 NamedDecl *ND = D->getFriendDecl();
1508 assert(ND && "friend decl must be a decl or a type!");
1509
1510 // All of the Visit implementations for the various potential friend
1511 // declarations have to be carefully written to work for friend
1512 // objects, with the most important detail being that the target
1513 // decl should almost certainly not be placed in Owner.
1514 Decl *NewND = Visit(ND);
1515 if (!NewND) return nullptr;
1516
1517 FriendDecl *FD =
1518 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1519 cast<NamedDecl>(NewND), D->getFriendLoc());
1520 FD->setAccess(AS_public);
1521 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1522 Owner->addDecl(FD);
1523 return FD;
1524}
1525
1526Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1527 Expr *AssertExpr = D->getAssertExpr();
1528
1529 // The expression in a static assertion is a constant expression.
1532
1533 ExprResult InstantiatedAssertExpr
1534 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1535 if (InstantiatedAssertExpr.isInvalid())
1536 return nullptr;
1537
1538 ExprResult InstantiatedMessageExpr =
1539 SemaRef.SubstExpr(D->getMessage(), TemplateArgs);
1540 if (InstantiatedMessageExpr.isInvalid())
1541 return nullptr;
1542
1543 return SemaRef.BuildStaticAssertDeclaration(
1544 D->getLocation(), InstantiatedAssertExpr.get(),
1545 InstantiatedMessageExpr.get(), D->getRParenLoc(), D->isFailed());
1546}
1547
1548Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1549 EnumDecl *PrevDecl = nullptr;
1550 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1551 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1552 PatternPrev,
1553 TemplateArgs);
1554 if (!Prev) return nullptr;
1555 PrevDecl = cast<EnumDecl>(Prev);
1556 }
1557
1558 EnumDecl *Enum =
1559 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1560 D->getLocation(), D->getIdentifier(), PrevDecl,
1561 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1562 if (D->isFixed()) {
1563 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1564 // If we have type source information for the underlying type, it means it
1565 // has been explicitly set by the user. Perform substitution on it before
1566 // moving on.
1567 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1568 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1569 DeclarationName());
1570 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1571 Enum->setIntegerType(SemaRef.Context.IntTy);
1572 else
1573 Enum->setIntegerTypeSourceInfo(NewTI);
1574 } else {
1575 assert(!D->getIntegerType()->isDependentType()
1576 && "Dependent type without type source info");
1577 Enum->setIntegerType(D->getIntegerType());
1578 }
1579 }
1580
1581 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1582
1583 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1584 Enum->setAccess(D->getAccess());
1585 // Forward the mangling number from the template to the instantiated decl.
1587 // See if the old tag was defined along with a declarator.
1588 // If it did, mark the new tag as being associated with that declarator.
1591 // See if the old tag was defined along with a typedef.
1592 // If it did, mark the new tag as being associated with that typedef.
1595 if (SubstQualifier(D, Enum)) return nullptr;
1596 Owner->addDecl(Enum);
1597
1598 EnumDecl *Def = D->getDefinition();
1599 if (Def && Def != D) {
1600 // If this is an out-of-line definition of an enum member template, check
1601 // that the underlying types match in the instantiation of both
1602 // declarations.
1603 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1604 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1605 QualType DefnUnderlying =
1606 SemaRef.SubstType(TI->getType(), TemplateArgs,
1607 UnderlyingLoc, DeclarationName());
1608 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1609 DefnUnderlying, /*IsFixed=*/true, Enum);
1610 }
1611 }
1612
1613 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1614 // specialization causes the implicit instantiation of the declarations, but
1615 // not the definitions of scoped member enumerations.
1616 //
1617 // DR1484 clarifies that enumeration definitions inside of a template
1618 // declaration aren't considered entities that can be separately instantiated
1619 // from the rest of the entity they are declared inside of.
1620 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1623 }
1624
1625 return Enum;
1626}
1627
1629 EnumDecl *Enum, EnumDecl *Pattern) {
1630 Enum->startDefinition();
1631
1632 // Update the location to refer to the definition.
1633 Enum->setLocation(Pattern->getLocation());
1634
1635 SmallVector<Decl*, 4> Enumerators;
1636
1637 EnumConstantDecl *LastEnumConst = nullptr;
1638 for (auto *EC : Pattern->enumerators()) {
1639 // The specified value for the enumerator.
1640 ExprResult Value((Expr *)nullptr);
1641 if (Expr *UninstValue = EC->getInitExpr()) {
1642 // The enumerator's value expression is a constant expression.
1645
1646 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1647 }
1648
1649 // Drop the initial value and continue.
1650 bool isInvalid = false;
1651 if (Value.isInvalid()) {
1652 Value = nullptr;
1653 isInvalid = true;
1654 }
1655
1656 EnumConstantDecl *EnumConst
1657 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1658 EC->getLocation(), EC->getIdentifier(),
1659 Value.get());
1660
1661 if (isInvalid) {
1662 if (EnumConst)
1663 EnumConst->setInvalidDecl();
1664 Enum->setInvalidDecl();
1665 }
1666
1667 if (EnumConst) {
1668 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1669
1670 EnumConst->setAccess(Enum->getAccess());
1671 Enum->addDecl(EnumConst);
1672 Enumerators.push_back(EnumConst);
1673 LastEnumConst = EnumConst;
1674
1675 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1676 !Enum->isScoped()) {
1677 // If the enumeration is within a function or method, record the enum
1678 // constant as a local.
1679 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1680 }
1681 }
1682 }
1683
1684 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1685 Enumerators, nullptr, ParsedAttributesView());
1686}
1687
1688Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1689 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1690}
1691
1692Decl *
1693TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1694 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1695}
1696
1697Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1698 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1699
1700 // Create a local instantiation scope for this class template, which
1701 // will contain the instantiations of the template parameters.
1703 TemplateParameterList *TempParams = D->getTemplateParameters();
1704 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1705 if (!InstParams)
1706 return nullptr;
1707
1708 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1709
1710 // Instantiate the qualifier. We have to do this first in case
1711 // we're a friend declaration, because if we are then we need to put
1712 // the new declaration in the appropriate context.
1713 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1714 if (QualifierLoc) {
1715 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1716 TemplateArgs);
1717 if (!QualifierLoc)
1718 return nullptr;
1719 }
1720
1721 CXXRecordDecl *PrevDecl = nullptr;
1722 ClassTemplateDecl *PrevClassTemplate = nullptr;
1723
1724 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1726 if (!Found.empty()) {
1727 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1728 if (PrevClassTemplate)
1729 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1730 }
1731 }
1732
1733 // If this isn't a friend, then it's a member template, in which
1734 // case we just want to build the instantiation in the
1735 // specialization. If it is a friend, we want to build it in
1736 // the appropriate context.
1737 DeclContext *DC = Owner;
1738 if (isFriend) {
1739 if (QualifierLoc) {
1740 CXXScopeSpec SS;
1741 SS.Adopt(QualifierLoc);
1742 DC = SemaRef.computeDeclContext(SS);
1743 if (!DC) return nullptr;
1744 } else {
1745 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1746 Pattern->getDeclContext(),
1747 TemplateArgs);
1748 }
1749
1750 // Look for a previous declaration of the template in the owning
1751 // context.
1752 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1755 SemaRef.LookupQualifiedName(R, DC);
1756
1757 if (R.isSingleResult()) {
1758 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1759 if (PrevClassTemplate)
1760 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1761 }
1762
1763 if (!PrevClassTemplate && QualifierLoc) {
1764 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1765 << llvm::to_underlying(D->getTemplatedDecl()->getTagKind())
1766 << Pattern->getDeclName() << DC << QualifierLoc.getSourceRange();
1767 return nullptr;
1768 }
1769 }
1770
1772 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1773 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1774 /*DelayTypeCreation=*/true);
1775 if (QualifierLoc)
1776 RecordInst->setQualifierInfo(QualifierLoc);
1777
1778 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1779 StartingScope);
1780
1781 ClassTemplateDecl *Inst
1783 D->getIdentifier(), InstParams, RecordInst);
1784 RecordInst->setDescribedClassTemplate(Inst);
1785
1786 if (isFriend) {
1787 assert(!Owner->isDependentContext());
1788 Inst->setLexicalDeclContext(Owner);
1789 RecordInst->setLexicalDeclContext(Owner);
1790 Inst->setObjectOfFriendDecl();
1791
1792 if (PrevClassTemplate) {
1793 Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
1794 RecordInst->setTypeForDecl(
1795 PrevClassTemplate->getTemplatedDecl()->getTypeForDecl());
1796 const ClassTemplateDecl *MostRecentPrevCT =
1797 PrevClassTemplate->getMostRecentDecl();
1798 TemplateParameterList *PrevParams =
1799 MostRecentPrevCT->getTemplateParameters();
1800
1801 // Make sure the parameter lists match.
1802 if (!SemaRef.TemplateParameterListsAreEqual(
1803 RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
1804 PrevParams, true, Sema::TPL_TemplateMatch))
1805 return nullptr;
1806
1807 // Do some additional validation, then merge default arguments
1808 // from the existing declarations.
1809 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1811 return nullptr;
1812
1813 Inst->setAccess(PrevClassTemplate->getAccess());
1814 } else {
1815 Inst->setAccess(D->getAccess());
1816 }
1817
1818 Inst->setObjectOfFriendDecl();
1819 // TODO: do we want to track the instantiation progeny of this
1820 // friend target decl?
1821 } else {
1822 Inst->setAccess(D->getAccess());
1823 if (!PrevClassTemplate)
1825 }
1826
1827 Inst->setPreviousDecl(PrevClassTemplate);
1828
1829 // Trigger creation of the type for the instantiation.
1831 RecordInst, Inst->getInjectedClassNameSpecialization());
1832
1833 // Finish handling of friends.
1834 if (isFriend) {
1835 DC->makeDeclVisibleInContext(Inst);
1836 return Inst;
1837 }
1838
1839 if (D->isOutOfLine()) {
1842 }
1843
1844 Owner->addDecl(Inst);
1845
1846 if (!PrevClassTemplate) {
1847 // Queue up any out-of-line partial specializations of this member
1848 // class template; the client will force their instantiation once
1849 // the enclosing class has been instantiated.
1851 D->getPartialSpecializations(PartialSpecs);
1852 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1853 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1854 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1855 }
1856
1857 return Inst;
1858}
1859
1860Decl *
1861TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1863 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1864
1865 // Lookup the already-instantiated declaration in the instantiation
1866 // of the class template and return that.
1868 = Owner->lookup(ClassTemplate->getDeclName());
1869 if (Found.empty())
1870 return nullptr;
1871
1872 ClassTemplateDecl *InstClassTemplate
1873 = dyn_cast<ClassTemplateDecl>(Found.front());
1874 if (!InstClassTemplate)
1875 return nullptr;
1876
1878 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1879 return Result;
1880
1881 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1882}
1883
1884Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1885 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1886 "Only static data member templates are allowed.");
1887
1888 // Create a local instantiation scope for this variable template, which
1889 // will contain the instantiations of the template parameters.
1891 TemplateParameterList *TempParams = D->getTemplateParameters();
1892 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1893 if (!InstParams)
1894 return nullptr;
1895
1896 VarDecl *Pattern = D->getTemplatedDecl();
1897 VarTemplateDecl *PrevVarTemplate = nullptr;
1898
1899 if (getPreviousDeclForInstantiation(Pattern)) {
1901 if (!Found.empty())
1902 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1903 }
1904
1905 VarDecl *VarInst =
1906 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1907 /*InstantiatingVarTemplate=*/true));
1908 if (!VarInst) return nullptr;
1909
1910 DeclContext *DC = Owner;
1911
1913 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1914 VarInst);
1915 VarInst->setDescribedVarTemplate(Inst);
1916 Inst->setPreviousDecl(PrevVarTemplate);
1917
1918 Inst->setAccess(D->getAccess());
1919 if (!PrevVarTemplate)
1921
1922 if (D->isOutOfLine()) {
1925 }
1926
1927 Owner->addDecl(Inst);
1928
1929 if (!PrevVarTemplate) {
1930 // Queue up any out-of-line partial specializations of this member
1931 // variable template; the client will force their instantiation once
1932 // the enclosing class has been instantiated.
1934 D->getPartialSpecializations(PartialSpecs);
1935 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1936 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1937 OutOfLineVarPartialSpecs.push_back(
1938 std::make_pair(Inst, PartialSpecs[I]));
1939 }
1940
1941 return Inst;
1942}
1943
1944Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1946 assert(D->isStaticDataMember() &&
1947 "Only static data member templates are allowed.");
1948
1949 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1950
1951 // Lookup the already-instantiated declaration and return that.
1952 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1953 assert(!Found.empty() && "Instantiation found nothing?");
1954
1955 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1956 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1957
1959 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1960 return Result;
1961
1962 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1963}
1964
1965Decl *
1966TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1967 // Create a local instantiation scope for this function template, which
1968 // will contain the instantiations of the template parameters and then get
1969 // merged with the local instantiation scope for the function template
1970 // itself.
1973
1974 TemplateParameterList *TempParams = D->getTemplateParameters();
1975 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1976 if (!InstParams)
1977 return nullptr;
1978
1979 FunctionDecl *Instantiated = nullptr;
1980 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1981 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1982 InstParams));
1983 else
1984 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1985 D->getTemplatedDecl(),
1986 InstParams));
1987
1988 if (!Instantiated)
1989 return nullptr;
1990
1991 // Link the instantiated function template declaration to the function
1992 // template from which it was instantiated.
1993 FunctionTemplateDecl *InstTemplate
1994 = Instantiated->getDescribedFunctionTemplate();
1995 InstTemplate->setAccess(D->getAccess());
1996 assert(InstTemplate &&
1997 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1998
1999 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
2000
2001 // Link the instantiation back to the pattern *unless* this is a
2002 // non-definition friend declaration.
2003 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
2004 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
2005 InstTemplate->setInstantiatedFromMemberTemplate(D);
2006
2007 // Make declarations visible in the appropriate context.
2008 if (!isFriend) {
2009 Owner->addDecl(InstTemplate);
2010 } else if (InstTemplate->getDeclContext()->isRecord() &&
2012 SemaRef.CheckFriendAccess(InstTemplate);
2013 }
2014
2015 return InstTemplate;
2016}
2017
2018Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
2019 CXXRecordDecl *PrevDecl = nullptr;
2020 if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2021 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
2022 PatternPrev,
2023 TemplateArgs);
2024 if (!Prev) return nullptr;
2025 PrevDecl = cast<CXXRecordDecl>(Prev);
2026 }
2027
2028 CXXRecordDecl *Record = nullptr;
2029 bool IsInjectedClassName = D->isInjectedClassName();
2030 if (D->isLambda())
2032 SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
2033 D->getLambdaDependencyKind(), D->isGenericLambda(),
2034 D->getLambdaCaptureDefault());
2035 else
2036 Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
2037 D->getBeginLoc(), D->getLocation(),
2038 D->getIdentifier(), PrevDecl,
2039 /*DelayTypeCreation=*/IsInjectedClassName);
2040 // Link the type of the injected-class-name to that of the outer class.
2041 if (IsInjectedClassName)
2042 (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
2043
2044 // Substitute the nested name specifier, if any.
2045 if (SubstQualifier(D, Record))
2046 return nullptr;
2047
2048 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
2049 StartingScope);
2050
2051 Record->setImplicit(D->isImplicit());
2052 // FIXME: Check against AS_none is an ugly hack to work around the issue that
2053 // the tag decls introduced by friend class declarations don't have an access
2054 // specifier. Remove once this area of the code gets sorted out.
2055 if (D->getAccess() != AS_none)
2056 Record->setAccess(D->getAccess());
2057 if (!IsInjectedClassName)
2058 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2059
2060 // If the original function was part of a friend declaration,
2061 // inherit its namespace state.
2062 if (D->getFriendObjectKind())
2063 Record->setObjectOfFriendDecl();
2064
2065 // Make sure that anonymous structs and unions are recorded.
2066 if (D->isAnonymousStructOrUnion())
2067 Record->setAnonymousStructOrUnion(true);
2068
2069 if (D->isLocalClass())
2071
2072 // Forward the mangling number from the template to the instantiated decl.
2074 SemaRef.Context.getManglingNumber(D));
2075
2076 // See if the old tag was defined along with a declarator.
2077 // If it did, mark the new tag as being associated with that declarator.
2080
2081 // See if the old tag was defined along with a typedef.
2082 // If it did, mark the new tag as being associated with that typedef.
2085
2086 Owner->addDecl(Record);
2087
2088 // DR1484 clarifies that the members of a local class are instantiated as part
2089 // of the instantiation of their enclosing entity.
2090 if (D->isCompleteDefinition() && D->isLocalClass()) {
2091 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
2092
2093 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
2095 /*Complain=*/true);
2096
2097 // For nested local classes, we will instantiate the members when we
2098 // reach the end of the outermost (non-nested) local class.
2099 if (!D->isCXXClassMember())
2100 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
2102
2103 // This class may have local implicit instantiations that need to be
2104 // performed within this scope.
2105 LocalInstantiations.perform();
2106 }
2107
2109
2110 if (IsInjectedClassName)
2111 assert(Record->isInjectedClassName() && "Broken injected-class-name");
2112
2113 return Record;
2114}
2115
2116/// Adjust the given function type for an instantiation of the
2117/// given declaration, to cope with modifications to the function's type that
2118/// aren't reflected in the type-source information.
2119///
2120/// \param D The declaration we're instantiating.
2121/// \param TInfo The already-instantiated type.
2123 FunctionDecl *D,
2124 TypeSourceInfo *TInfo) {
2125 const FunctionProtoType *OrigFunc
2126 = D->getType()->castAs<FunctionProtoType>();
2127 const FunctionProtoType *NewFunc
2128 = TInfo->getType()->castAs<FunctionProtoType>();
2129 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2130 return TInfo->getType();
2131
2132 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2133 NewEPI.ExtInfo = OrigFunc->getExtInfo();
2134 return Context.getFunctionType(NewFunc->getReturnType(),
2135 NewFunc->getParamTypes(), NewEPI);
2136}
2137
2138/// Normal class members are of more specific types and therefore
2139/// don't make it here. This function serves three purposes:
2140/// 1) instantiating function templates
2141/// 2) substituting friend and local function declarations
2142/// 3) substituting deduction guide declarations for nested class templates
2144 FunctionDecl *D, TemplateParameterList *TemplateParams,
2145 RewriteKind FunctionRewriteKind) {
2146 // Check whether there is already a function template specialization for
2147 // this declaration.
2148 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2149 bool isFriend;
2150 if (FunctionTemplate)
2151 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2152 else
2153 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2154
2155 // Friend function defined withing class template may stop being function
2156 // definition during AST merges from different modules, in this case decl
2157 // with function body should be used for instantiation.
2158 if (isFriend) {
2159 const FunctionDecl *Defn = nullptr;
2160 if (D->hasBody(Defn)) {
2161 D = const_cast<FunctionDecl *>(Defn);
2162 FunctionTemplate = Defn->getDescribedFunctionTemplate();
2163 }
2164 }
2165
2166 if (FunctionTemplate && !TemplateParams) {
2167 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2168
2169 void *InsertPos = nullptr;
2170 FunctionDecl *SpecFunc
2171 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2172
2173 // If we already have a function template specialization, return it.
2174 if (SpecFunc)
2175 return SpecFunc;
2176 }
2177
2178 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2179 Owner->isFunctionOrMethod() ||
2180 !(isa<Decl>(Owner) &&
2181 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2182 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2183
2184 ExplicitSpecifier InstantiatedExplicitSpecifier;
2185 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2186 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2187 TemplateArgs, DGuide->getExplicitSpecifier());
2188 if (InstantiatedExplicitSpecifier.isInvalid())
2189 return nullptr;
2190 }
2191
2193 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2194 if (!TInfo)
2195 return nullptr;
2197
2198 if (TemplateParams && TemplateParams->size()) {
2199 auto *LastParam =
2200 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2201 if (LastParam && LastParam->isImplicit() &&
2202 LastParam->hasTypeConstraint()) {
2203 // In abbreviated templates, the type-constraints of invented template
2204 // type parameters are instantiated with the function type, invalidating
2205 // the TemplateParameterList which relied on the template type parameter
2206 // not having a type constraint. Recreate the TemplateParameterList with
2207 // the updated parameter list.
2208 TemplateParams = TemplateParameterList::Create(
2209 SemaRef.Context, TemplateParams->getTemplateLoc(),
2210 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2211 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2212 }
2213 }
2214
2215 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2216 if (QualifierLoc) {
2217 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2218 TemplateArgs);
2219 if (!QualifierLoc)
2220 return nullptr;
2221 }
2222
2223 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2224
2225 // If we're instantiating a local function declaration, put the result
2226 // in the enclosing namespace; otherwise we need to find the instantiated
2227 // context.
2228 DeclContext *DC;
2229 if (D->isLocalExternDecl()) {
2230 DC = Owner;
2232 } else if (isFriend && QualifierLoc) {
2233 CXXScopeSpec SS;
2234 SS.Adopt(QualifierLoc);
2235 DC = SemaRef.computeDeclContext(SS);
2236 if (!DC) return nullptr;
2237 } else {
2239 TemplateArgs);
2240 }
2241
2242 DeclarationNameInfo NameInfo
2243 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2244
2245 if (FunctionRewriteKind != RewriteKind::None)
2246 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2247
2249 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2251 SemaRef.Context, DC, D->getInnerLocStart(),
2252 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2253 D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
2254 DGuide->getDeductionCandidateKind(), TrailingRequiresClause);
2255 Function->setAccess(D->getAccess());
2256 } else {
2258 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2259 D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(),
2260 D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(),
2261 TrailingRequiresClause);
2262 Function->setFriendConstraintRefersToEnclosingTemplate(
2263 D->FriendConstraintRefersToEnclosingTemplate());
2264 Function->setRangeEnd(D->getSourceRange().getEnd());
2265 }
2266
2267 if (D->isInlined())
2268 Function->setImplicitlyInline();
2269
2270 if (QualifierLoc)
2271 Function->setQualifierInfo(QualifierLoc);
2272
2273 if (D->isLocalExternDecl())
2274 Function->setLocalExternDecl();
2275
2276 DeclContext *LexicalDC = Owner;
2277 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2278 assert(D->getDeclContext()->isFileContext());
2279 LexicalDC = D->getDeclContext();
2280 }
2281 else if (D->isLocalExternDecl()) {
2282 LexicalDC = SemaRef.CurContext;
2283 }
2284
2285 Function->setLexicalDeclContext(LexicalDC);
2286
2287 // Attach the parameters
2288 for (unsigned P = 0; P < Params.size(); ++P)
2289 if (Params[P])
2290 Params[P]->setOwningFunction(Function);
2291 Function->setParams(Params);
2292
2293 if (TrailingRequiresClause)
2294 Function->setTrailingRequiresClause(TrailingRequiresClause);
2295
2296 if (TemplateParams) {
2297 // Our resulting instantiation is actually a function template, since we
2298 // are substituting only the outer template parameters. For example, given
2299 //
2300 // template<typename T>
2301 // struct X {
2302 // template<typename U> friend void f(T, U);
2303 // };
2304 //
2305 // X<int> x;
2306 //
2307 // We are instantiating the friend function template "f" within X<int>,
2308 // which means substituting int for T, but leaving "f" as a friend function
2309 // template.
2310 // Build the function template itself.
2311 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2312 Function->getLocation(),
2313 Function->getDeclName(),
2314 TemplateParams, Function);
2315 Function->setDescribedFunctionTemplate(FunctionTemplate);
2316
2317 FunctionTemplate->setLexicalDeclContext(LexicalDC);
2318
2319 if (isFriend && D->isThisDeclarationADefinition()) {
2320 FunctionTemplate->setInstantiatedFromMemberTemplate(
2321 D->getDescribedFunctionTemplate());
2322 }
2323 } else if (FunctionTemplate &&
2324 SemaRef.CodeSynthesisContexts.back().Kind !=
2326 // Record this function template specialization.
2327 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2328 Function->setFunctionTemplateSpecialization(FunctionTemplate,
2330 Innermost),
2331 /*InsertPos=*/nullptr);
2332 } else if (FunctionRewriteKind == RewriteKind::None) {
2333 if (isFriend && D->isThisDeclarationADefinition()) {
2334 // Do not connect the friend to the template unless it's actually a
2335 // definition. We don't want non-template functions to be marked as being
2336 // template instantiations.
2337 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2338 } else if (!isFriend) {
2339 // If this is not a function template, and this is not a friend (that is,
2340 // this is a locally declared function), save the instantiation
2341 // relationship for the purposes of constraint instantiation.
2342 Function->setInstantiatedFromDecl(D);
2343 }
2344 }
2345
2346 if (isFriend) {
2347 Function->setObjectOfFriendDecl();
2348 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2349 FT->setObjectOfFriendDecl();
2350 }
2351
2353 Function->setInvalidDecl();
2354
2355 bool IsExplicitSpecialization = false;
2356
2358 SemaRef, Function->getDeclName(), SourceLocation(),
2361 D->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
2362 : SemaRef.forRedeclarationInCurContext());
2363
2365 D->getDependentSpecializationInfo()) {
2366 assert(isFriend && "dependent specialization info on "
2367 "non-member non-friend function?");
2368
2369 // Instantiate the explicit template arguments.
2370 TemplateArgumentListInfo ExplicitArgs;
2371 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2372 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2373 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2374 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2375 ExplicitArgs))
2376 return nullptr;
2377 }
2378
2379 // Map the candidates for the primary template to their instantiations.
2380 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2381 if (NamedDecl *ND =
2382 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2383 Previous.addDecl(ND);
2384 else
2385 return nullptr;
2386 }
2387
2389 Function,
2390 DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2391 Previous))
2392 Function->setInvalidDecl();
2393
2394 IsExplicitSpecialization = true;
2395 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2396 D->getTemplateSpecializationArgsAsWritten()) {
2397 // The name of this function was written as a template-id.
2398 SemaRef.LookupQualifiedName(Previous, DC);
2399
2400 // Instantiate the explicit template arguments.
2401 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2402 ArgsWritten->getRAngleLoc());
2403 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2404 ExplicitArgs))
2405 return nullptr;
2406
2408 &ExplicitArgs,
2409 Previous))
2410 Function->setInvalidDecl();
2411
2412 IsExplicitSpecialization = true;
2413 } else if (TemplateParams || !FunctionTemplate) {
2414 // Look only into the namespace where the friend would be declared to
2415 // find a previous declaration. This is the innermost enclosing namespace,
2416 // as described in ActOnFriendFunctionDecl.
2418
2419 // In C++, the previous declaration we find might be a tag type
2420 // (class or enum). In this case, the new declaration will hide the
2421 // tag type. Note that this does not apply if we're declaring a
2422 // typedef (C++ [dcl.typedef]p4).
2423 if (Previous.isSingleTagDecl())
2424 Previous.clear();
2425
2426 // Filter out previous declarations that don't match the scope. The only
2427 // effect this has is to remove declarations found in inline namespaces
2428 // for friend declarations with unqualified names.
2429 if (isFriend && !QualifierLoc) {
2430 SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2431 /*ConsiderLinkage=*/ true,
2432 QualifierLoc.hasQualifier());
2433 }
2434 }
2435
2436 // Per [temp.inst], default arguments in function declarations at local scope
2437 // are instantiated along with the enclosing declaration. For example:
2438 //
2439 // template<typename T>
2440 // void ft() {
2441 // void f(int = []{ return T::value; }());
2442 // }
2443 // template void ft<int>(); // error: type 'int' cannot be used prior
2444 // to '::' because it has no members
2445 //
2446 // The error is issued during instantiation of ft<int>() because substitution
2447 // into the default argument fails; the default argument is instantiated even
2448 // though it is never used.
2449 if (Function->isLocalExternDecl()) {
2450 for (ParmVarDecl *PVD : Function->parameters()) {
2451 if (!PVD->hasDefaultArg())
2452 continue;
2453 if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2454 // If substitution fails, the default argument is set to a
2455 // RecoveryExpr that wraps the uninstantiated default argument so
2456 // that downstream diagnostics are omitted.
2457 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
2458 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2459 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2460 { UninstExpr }, UninstExpr->getType());
2461 if (ErrorResult.isUsable())
2462 PVD->setDefaultArg(ErrorResult.get());
2463 }
2464 }
2465 }
2466
2467 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2468 IsExplicitSpecialization,
2469 Function->isThisDeclarationADefinition());
2470
2471 // Check the template parameter list against the previous declaration. The
2472 // goal here is to pick up default arguments added since the friend was
2473 // declared; we know the template parameter lists match, since otherwise
2474 // we would not have picked this template as the previous declaration.
2475 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2477 TemplateParams,
2478 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2479 Function->isThisDeclarationADefinition()
2482 }
2483
2484 // If we're introducing a friend definition after the first use, trigger
2485 // instantiation.
2486 // FIXME: If this is a friend function template definition, we should check
2487 // to see if any specializations have been used.
2488 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2489 if (MemberSpecializationInfo *MSInfo =
2490 Function->getMemberSpecializationInfo()) {
2491 if (MSInfo->getPointOfInstantiation().isInvalid()) {
2492 SourceLocation Loc = D->getLocation(); // FIXME
2493 MSInfo->setPointOfInstantiation(Loc);
2494 SemaRef.PendingLocalImplicitInstantiations.push_back(
2495 std::make_pair(Function, Loc));
2496 }
2497 }
2498 }
2499
2500 if (D->isExplicitlyDefaulted()) {
2502 return nullptr;
2503 }
2504 if (D->isDeleted())
2505 SemaRef.SetDeclDeleted(Function, D->getLocation(), D->getDeletedMessage());
2506
2507 NamedDecl *PrincipalDecl =
2508 (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2509
2510 // If this declaration lives in a different context from its lexical context,
2511 // add it to the corresponding lookup table.
2512 if (isFriend ||
2513 (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2514 DC->makeDeclVisibleInContext(PrincipalDecl);
2515
2516 if (Function->isOverloadedOperator() && !DC->isRecord() &&
2518 PrincipalDecl->setNonMemberOperator();
2519
2520 return Function;
2521}
2522
2524 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2525 RewriteKind FunctionRewriteKind) {
2526 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2527 if (FunctionTemplate && !TemplateParams) {
2528 // We are creating a function template specialization from a function
2529 // template. Check whether there is already a function template
2530 // specialization for this particular set of template arguments.
2531 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2532
2533 void *InsertPos = nullptr;
2534 FunctionDecl *SpecFunc
2535 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2536
2537 // If we already have a function template specialization, return it.
2538 if (SpecFunc)
2539 return SpecFunc;
2540 }
2541
2542 bool isFriend;
2543 if (FunctionTemplate)
2544 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2545 else
2546 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2547
2548 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2549 !(isa<Decl>(Owner) &&
2550 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2551 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2552
2554 SemaRef, const_cast<CXXMethodDecl *>(D), TemplateArgs, Scope);
2555
2556 // Instantiate enclosing template arguments for friends.
2558 unsigned NumTempParamLists = 0;
2559 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2560 TempParamLists.resize(NumTempParamLists);
2561 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2562 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2563 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2564 if (!InstParams)
2565 return nullptr;
2566 TempParamLists[I] = InstParams;
2567 }
2568 }
2569
2570 auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(D);
2571 // deduction guides need this
2572 const bool CouldInstantiate =
2573 InstantiatedExplicitSpecifier.getExpr() == nullptr ||
2574 !InstantiatedExplicitSpecifier.getExpr()->isValueDependent();
2575
2576 // Delay the instantiation of the explicit-specifier until after the
2577 // constraints are checked during template argument deduction.
2578 if (CouldInstantiate ||
2579 SemaRef.CodeSynthesisContexts.back().Kind !=
2581 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2582 TemplateArgs, InstantiatedExplicitSpecifier);
2583
2584 if (InstantiatedExplicitSpecifier.isInvalid())
2585 return nullptr;
2586 } else {
2587 InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved);
2588 }
2589
2590 // Implicit destructors/constructors created for local classes in
2591 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2592 // Unfortunately there isn't enough context in those functions to
2593 // conditionally populate the TSI without breaking non-template related use
2594 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2595 // a proper transformation.
2596 if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
2597 !D->getTypeSourceInfo() &&
2598 isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2599 TypeSourceInfo *TSI =
2600 SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
2601 D->setTypeSourceInfo(TSI);
2602 }
2603
2605 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2606 if (!TInfo)
2607 return nullptr;
2609
2610 if (TemplateParams && TemplateParams->size()) {
2611 auto *LastParam =
2612 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2613 if (LastParam && LastParam->isImplicit() &&
2614 LastParam->hasTypeConstraint()) {
2615 // In abbreviated templates, the type-constraints of invented template
2616 // type parameters are instantiated with the function type, invalidating
2617 // the TemplateParameterList which relied on the template type parameter
2618 // not having a type constraint. Recreate the TemplateParameterList with
2619 // the updated parameter list.
2620 TemplateParams = TemplateParameterList::Create(
2621 SemaRef.Context, TemplateParams->getTemplateLoc(),
2622 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2623 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2624 }
2625 }
2626
2627 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2628 if (QualifierLoc) {
2629 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2630 TemplateArgs);
2631 if (!QualifierLoc)
2632 return nullptr;
2633 }
2634
2635 DeclContext *DC = Owner;
2636 if (isFriend) {
2637 if (QualifierLoc) {
2638 CXXScopeSpec SS;
2639 SS.Adopt(QualifierLoc);
2640 DC = SemaRef.computeDeclContext(SS);
2641
2642 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2643 return nullptr;
2644 } else {
2645 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2646 D->getDeclContext(),
2647 TemplateArgs);
2648 }
2649 if (!DC) return nullptr;
2650 }
2651
2652 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2653 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2654
2655 DeclarationNameInfo NameInfo
2656 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2657
2658 if (FunctionRewriteKind != RewriteKind::None)
2659 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2660
2661 // Build the instantiated method declaration.
2662 CXXMethodDecl *Method = nullptr;
2663
2664 SourceLocation StartLoc = D->getInnerLocStart();
2665 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2667 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2668 InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2669 Constructor->isInlineSpecified(), false,
2670 Constructor->getConstexprKind(), InheritedConstructor(),
2671 TrailingRequiresClause);
2672 Method->setRangeEnd(Constructor->getEndLoc());
2673 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2675 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2676 Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2677 Destructor->getConstexprKind(), TrailingRequiresClause);
2678 Method->setIneligibleOrNotSelected(true);
2679 Method->setRangeEnd(Destructor->getEndLoc());
2681 SemaRef.Context.getCanonicalType(
2682 SemaRef.Context.getTypeDeclType(Record))));
2683 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2685 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2686 Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2687 InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2688 Conversion->getEndLoc(), TrailingRequiresClause);
2689 } else {
2690 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2691 Method = CXXMethodDecl::Create(
2692 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2693 D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(),
2694 D->getEndLoc(), TrailingRequiresClause);
2695 }
2696
2697 if (D->isInlined())
2698 Method->setImplicitlyInline();
2699
2700 if (QualifierLoc)
2701 Method->setQualifierInfo(QualifierLoc);
2702
2703 if (TemplateParams) {
2704 // Our resulting instantiation is actually a function template, since we
2705 // are substituting only the outer template parameters. For example, given
2706 //
2707 // template<typename T>
2708 // struct X {
2709 // template<typename U> void f(T, U);
2710 // };
2711 //
2712 // X<int> x;
2713 //
2714 // We are instantiating the member template "f" within X<int>, which means
2715 // substituting int for T, but leaving "f" as a member function template.
2716 // Build the function template itself.
2717 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2718 Method->getLocation(),
2719 Method->getDeclName(),
2720 TemplateParams, Method);
2721 if (isFriend) {
2722 FunctionTemplate->setLexicalDeclContext(Owner);
2723 FunctionTemplate->setObjectOfFriendDecl();
2724 } else if (D->isOutOfLine())
2725 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2726 Method->setDescribedFunctionTemplate(FunctionTemplate);
2727 } else if (FunctionTemplate) {
2728 // Record this function template specialization.
2729 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2730 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2732 Innermost),
2733 /*InsertPos=*/nullptr);
2734 } else if (!isFriend && FunctionRewriteKind == RewriteKind::None) {
2735 // Record that this is an instantiation of a member function.
2737 }
2738
2739 // If we are instantiating a member function defined
2740 // out-of-line, the instantiation will have the same lexical
2741 // context (which will be a namespace scope) as the template.
2742 if (isFriend) {
2743 if (NumTempParamLists)
2745 SemaRef.Context,
2746 llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
2747
2748 Method->setLexicalDeclContext(Owner);
2749 Method->setObjectOfFriendDecl();
2750 } else if (D->isOutOfLine())
2752
2753 // Attach the parameters
2754 for (unsigned P = 0; P < Params.size(); ++P)
2755 Params[P]->setOwningFunction(Method);
2756 Method->setParams(Params);
2757
2758 if (InitMethodInstantiation(Method, D))
2759 Method->setInvalidDecl();
2760
2762 RedeclarationKind::ForExternalRedeclaration);
2763
2764 bool IsExplicitSpecialization = false;
2765
2766 // If the name of this function was written as a template-id, instantiate
2767 // the explicit template arguments.
2769 D->getDependentSpecializationInfo()) {
2770 // Instantiate the explicit template arguments.
2771 TemplateArgumentListInfo ExplicitArgs;
2772 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2773 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2774 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2775 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2776 ExplicitArgs))
2777 return nullptr;
2778 }
2779
2780 // Map the candidates for the primary template to their instantiations.
2781 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2782 if (NamedDecl *ND =
2783 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2784 Previous.addDecl(ND);
2785 else
2786 return nullptr;
2787 }
2788
2790 Method, DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2791 Previous))
2792 Method->setInvalidDecl();
2793
2794 IsExplicitSpecialization = true;
2795 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2796 D->getTemplateSpecializationArgsAsWritten()) {
2797 SemaRef.LookupQualifiedName(Previous, DC);
2798
2799 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2800 ArgsWritten->getRAngleLoc());
2801
2802 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2803 ExplicitArgs))
2804 return nullptr;
2805
2806 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2807 &ExplicitArgs,
2808 Previous))
2809 Method->setInvalidDecl();
2810
2811 IsExplicitSpecialization = true;
2812 } else if (!FunctionTemplate || TemplateParams || isFriend) {
2814
2815 // In C++, the previous declaration we find might be a tag type
2816 // (class or enum). In this case, the new declaration will hide the
2817 // tag type. Note that this does not apply if we're declaring a
2818 // typedef (C++ [dcl.typedef]p4).
2819 if (Previous.isSingleTagDecl())
2820 Previous.clear();
2821 }
2822
2823 // Per [temp.inst], default arguments in member functions of local classes
2824 // are instantiated along with the member function declaration. For example:
2825 //
2826 // template<typename T>
2827 // void ft() {
2828 // struct lc {
2829 // int operator()(int p = []{ return T::value; }());
2830 // };
2831 // }
2832 // template void ft<int>(); // error: type 'int' cannot be used prior
2833 // to '::'because it has no members
2834 //
2835 // The error is issued during instantiation of ft<int>()::lc::operator()
2836 // because substitution into the default argument fails; the default argument
2837 // is instantiated even though it is never used.
2839 for (unsigned P = 0; P < Params.size(); ++P) {
2840 if (!Params[P]->hasDefaultArg())
2841 continue;
2842 if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
2843 // If substitution fails, the default argument is set to a
2844 // RecoveryExpr that wraps the uninstantiated default argument so
2845 // that downstream diagnostics are omitted.
2846 Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
2847 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2848 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2849 { UninstExpr }, UninstExpr->getType());
2850 if (ErrorResult.isUsable())
2851 Params[P]->setDefaultArg(ErrorResult.get());
2852 }
2853 }
2854 }
2855
2856 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2857 IsExplicitSpecialization,
2859
2860 if (D->isPureVirtual())
2861 SemaRef.CheckPureMethod(Method, SourceRange());
2862
2863 // Propagate access. For a non-friend declaration, the access is
2864 // whatever we're propagating from. For a friend, it should be the
2865 // previous declaration we just found.
2866 if (isFriend && Method->getPreviousDecl())
2867 Method->setAccess(Method->getPreviousDecl()->getAccess());
2868 else
2869 Method->setAccess(D->getAccess());
2870 if (FunctionTemplate)
2871 FunctionTemplate->setAccess(Method->getAccess());
2872
2873 SemaRef.CheckOverrideControl(Method);
2874
2875 // If a function is defined as defaulted or deleted, mark it as such now.
2876 if (D->isExplicitlyDefaulted()) {
2877 if (SubstDefaultedFunction(Method, D))
2878 return nullptr;
2879 }
2880 if (D->isDeletedAsWritten())
2881 SemaRef.SetDeclDeleted(Method, Method->getLocation(),
2882 D->getDeletedMessage());
2883
2884 // If this is an explicit specialization, mark the implicitly-instantiated
2885 // template specialization as being an explicit specialization too.
2886 // FIXME: Is this necessary?
2887 if (IsExplicitSpecialization && !isFriend)
2888 SemaRef.CompleteMemberSpecialization(Method, Previous);
2889
2890 // If the method is a special member function, we need to mark it as
2891 // ineligible so that Owner->addDecl() won't mark the class as non trivial.
2892 // At the end of the class instantiation, we calculate eligibility again and
2893 // then we adjust trivility if needed.
2894 // We need this check to happen only after the method parameters are set,
2895 // because being e.g. a copy constructor depends on the instantiated
2896 // arguments.
2897 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
2898 if (Constructor->isDefaultConstructor() ||
2899 Constructor->isCopyOrMoveConstructor())
2900 Method->setIneligibleOrNotSelected(true);
2901 } else if (Method->isCopyAssignmentOperator() ||
2902 Method->isMoveAssignmentOperator()) {
2903 Method->setIneligibleOrNotSelected(true);
2904 }
2905
2906 // If there's a function template, let our caller handle it.
2907 if (FunctionTemplate) {
2908 // do nothing
2909
2910 // Don't hide a (potentially) valid declaration with an invalid one.
2911 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2912 // do nothing
2913
2914 // Otherwise, check access to friends and make them visible.
2915 } else if (isFriend) {
2916 // We only need to re-check access for methods which we didn't
2917 // manage to match during parsing.
2918 if (!D->getPreviousDecl())
2919 SemaRef.CheckFriendAccess(Method);
2920
2921 Record->makeDeclVisibleInContext(Method);
2922
2923 // Otherwise, add the declaration. We don't need to do this for
2924 // class-scope specializations because we'll have matched them with
2925 // the appropriate template.
2926 } else {
2927 Owner->addDecl(Method);
2928 }
2929
2930 // PR17480: Honor the used attribute to instantiate member function
2931 // definitions
2932 if (Method->hasAttr<UsedAttr>()) {
2933 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2935 if (const MemberSpecializationInfo *MSInfo =
2936 A->getMemberSpecializationInfo())
2937 Loc = MSInfo->getPointOfInstantiation();
2938 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2939 Loc = Spec->getPointOfInstantiation();
2940 SemaRef.MarkFunctionReferenced(Loc, Method);
2941 }
2942 }
2943
2944 return Method;
2945}
2946
2947Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2948 return VisitCXXMethodDecl(D);
2949}
2950
2951Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2952 return VisitCXXMethodDecl(D);
2953}
2954
2955Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2956 return VisitCXXMethodDecl(D);
2957}
2958
2959Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2960 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
2961 std::nullopt,
2962 /*ExpectParameterPack=*/false);
2963}
2964
2965Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2967 assert(D->getTypeForDecl()->isTemplateTypeParmType());
2968
2969 std::optional<unsigned> NumExpanded;
2970
2971 if (const TypeConstraint *TC = D->getTypeConstraint()) {
2972 if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2973 assert(TC->getTemplateArgsAsWritten() &&
2974 "type parameter can only be an expansion when explicit arguments "
2975 "are specified");
2976 // The template type parameter pack's type is a pack expansion of types.
2977 // Determine whether we need to expand this parameter pack into separate
2978 // types.
2980 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2981 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2982
2983 // Determine whether the set of unexpanded parameter packs can and should
2984 // be expanded.
2985 bool Expand = true;
2986 bool RetainExpansion = false;
2988 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2989 ->getEllipsisLoc(),
2990 SourceRange(TC->getConceptNameLoc(),
2991 TC->hasExplicitTemplateArgs() ?
2992 TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2993 TC->getConceptNameInfo().getEndLoc()),
2994 Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2995 return nullptr;
2996 }
2997 }
2998
3000 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
3001 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
3002 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
3003 D->hasTypeConstraint(), NumExpanded);
3004
3005 Inst->setAccess(AS_public);
3006 Inst->setImplicit(D->isImplicit());
3007 if (auto *TC = D->getTypeConstraint()) {
3008 if (!D->isImplicit()) {
3009 // Invented template parameter type constraints will be instantiated
3010 // with the corresponding auto-typed parameter as it might reference
3011 // other parameters.
3012 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
3013 EvaluateConstraints))
3014 return nullptr;
3015 }
3016 }
3017 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3018 TemplateArgumentLoc Output;
3019 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3020 Output))
3021 Inst->setDefaultArgument(SemaRef.getASTContext(), Output);
3022 }
3023
3024 // Introduce this template parameter's instantiation into the instantiation
3025 // scope.
3027
3028 return Inst;
3029}
3030
3031Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
3033 // Substitute into the type of the non-type template parameter.
3034 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
3035 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
3036 SmallVector<QualType, 4> ExpandedParameterPackTypes;
3037 bool IsExpandedParameterPack = false;
3038 TypeSourceInfo *DI;
3039 QualType T;
3040 bool Invalid = false;
3041
3042 if (D->isExpandedParameterPack()) {
3043 // The non-type template parameter pack is an already-expanded pack
3044 // expansion of types. Substitute into each of the expanded types.
3045 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
3046 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
3047 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
3048 TypeSourceInfo *NewDI =
3049 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
3050 D->getLocation(), D->getDeclName());
3051 if (!NewDI)
3052 return nullptr;
3053
3054 QualType NewT =
3056 if (NewT.isNull())
3057 return nullptr;
3058
3059 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3060 ExpandedParameterPackTypes.push_back(NewT);
3061 }
3062
3063 IsExpandedParameterPack = true;
3064 DI = D->getTypeSourceInfo();
3065 T = DI->getType();
3066 } else if (D->isPackExpansion()) {
3067 // The non-type template parameter pack's type is a pack expansion of types.
3068 // Determine whether we need to expand this parameter pack into separate
3069 // types.
3071 TypeLoc Pattern = Expansion.getPatternLoc();
3073 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
3074
3075 // Determine whether the set of unexpanded parameter packs can and should
3076 // be expanded.
3077 bool Expand = true;
3078 bool RetainExpansion = false;
3079 std::optional<unsigned> OrigNumExpansions =
3080 Expansion.getTypePtr()->getNumExpansions();
3081 std::optional<unsigned> NumExpansions = OrigNumExpansions;
3082 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
3083 Pattern.getSourceRange(),
3084 Unexpanded,
3085 TemplateArgs,
3086 Expand, RetainExpansion,
3087 NumExpansions))
3088 return nullptr;
3089
3090 if (Expand) {
3091 for (unsigned I = 0; I != *NumExpansions; ++I) {
3092 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3093 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
3094 D->getLocation(),
3095 D->getDeclName());
3096 if (!NewDI)
3097 return nullptr;
3098
3099 QualType NewT =
3101 if (NewT.isNull())
3102 return nullptr;
3103
3104 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3105 ExpandedParameterPackTypes.push_back(NewT);
3106 }
3107
3108 // Note that we have an expanded parameter pack. The "type" of this
3109 // expanded parameter pack is the original expansion type, but callers
3110 // will end up using the expanded parameter pack types for type-checking.
3111 IsExpandedParameterPack = true;
3112 DI = D->getTypeSourceInfo();
3113 T = DI->getType();
3114 } else {
3115 // We cannot fully expand the pack expansion now, so substitute into the
3116 // pattern and create a new pack expansion type.
3117 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3118 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
3119 D->getLocation(),
3120 D->getDeclName());
3121 if (!NewPattern)
3122 return nullptr;
3123
3124 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
3125 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
3126 NumExpansions);
3127 if (!DI)
3128 return nullptr;
3129
3130 T = DI->getType();
3131 }
3132 } else {
3133 // Simple case: substitution into a parameter that is not a parameter pack.
3134 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3135 D->getLocation(), D->getDeclName());
3136 if (!DI)
3137 return nullptr;
3138
3139 // Check that this type is acceptable for a non-type template parameter.
3141 if (T.isNull()) {
3142 T = SemaRef.Context.IntTy;
3143 Invalid = true;
3144 }
3145 }
3146
3148 if (IsExpandedParameterPack)
3150 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3151 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3152 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
3153 ExpandedParameterPackTypesAsWritten);
3154 else
3156 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3157 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3158 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
3159
3160 if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
3161 if (AutoLoc.isConstrained()) {
3162 SourceLocation EllipsisLoc;
3163 if (IsExpandedParameterPack)
3164 EllipsisLoc =
3165 DI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
3166 else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
3167 D->getPlaceholderTypeConstraint()))
3168 EllipsisLoc = Constraint->getEllipsisLoc();
3169 // Note: We attach the uninstantiated constriant here, so that it can be
3170 // instantiated relative to the top level, like all our other
3171 // constraints.
3172 if (SemaRef.AttachTypeConstraint(AutoLoc, /*NewConstrainedParm=*/Param,
3173 /*OrigConstrainedParm=*/D, EllipsisLoc))
3174 Invalid = true;
3175 }
3176
3177 Param->setAccess(AS_public);
3178 Param->setImplicit(D->isImplicit());
3179 if (Invalid)
3180 Param->setInvalidDecl();
3181
3182 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3183 EnterExpressionEvaluationContext ConstantEvaluated(
3186 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3187 Result))
3188 Param->setDefaultArgument(SemaRef.Context, Result);
3189 }
3190
3191 // Introduce this template parameter's instantiation into the instantiation
3192 // scope.
3194 return Param;
3195}
3196
3198 Sema &S,
3199 TemplateParameterList *Params,
3201 for (const auto &P : *Params) {
3202 if (P->isTemplateParameterPack())
3203 continue;
3204 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3205 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3206 Unexpanded);
3207 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3208 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3209 Unexpanded);
3210 }
3211}
3212
3213Decl *
3214TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3216 // Instantiate the template parameter list of the template template parameter.
3217 TemplateParameterList *TempParams = D->getTemplateParameters();
3218 TemplateParameterList *InstParams;
3220
3221 bool IsExpandedParameterPack = false;
3222
3223 if (D->isExpandedParameterPack()) {
3224 // The template template parameter pack is an already-expanded pack
3225 // expansion of template parameters. Substitute into each of the expanded
3226 // parameters.
3227 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3228 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3229 I != N; ++I) {
3231 TemplateParameterList *Expansion =
3232 SubstTemplateParams(D->getExpansionTemplateParameters(I));
3233 if (!Expansion)
3234 return nullptr;
3235 ExpandedParams.push_back(Expansion);
3236 }
3237
3238 IsExpandedParameterPack = true;
3239 InstParams = TempParams;
3240 } else if (D->isPackExpansion()) {
3241 // The template template parameter pack expands to a pack of template
3242 // template parameters. Determine whether we need to expand this parameter
3243 // pack into separate parameters.
3245 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
3246 Unexpanded);
3247
3248 // Determine whether the set of unexpanded parameter packs can and should
3249 // be expanded.
3250 bool Expand = true;
3251 bool RetainExpansion = false;
3252 std::optional<unsigned> NumExpansions;
3254 TempParams->getSourceRange(),
3255 Unexpanded,
3256 TemplateArgs,
3257 Expand, RetainExpansion,
3258 NumExpansions))
3259 return nullptr;
3260
3261 if (Expand) {
3262 for (unsigned I = 0; I != *NumExpansions; ++I) {
3263 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3265 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3266 if (!Expansion)
3267 return nullptr;
3268 ExpandedParams.push_back(Expansion);
3269 }
3270
3271 // Note that we have an expanded parameter pack. The "type" of this
3272 // expanded parameter pack is the original expansion type, but callers
3273 // will end up using the expanded parameter pack types for type-checking.
3274 IsExpandedParameterPack = true;
3275 InstParams = TempParams;
3276 } else {
3277 // We cannot fully expand the pack expansion now, so just substitute
3278 // into the pattern.
3279 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3280
3282 InstParams = SubstTemplateParams(TempParams);
3283 if (!InstParams)
3284 return nullptr;
3285 }
3286 } else {
3287 // Perform the actual substitution of template parameters within a new,
3288 // local instantiation scope.
3290 InstParams = SubstTemplateParams(TempParams);
3291 if (!InstParams)
3292 return nullptr;
3293 }
3294
3295 // Build the template template parameter.
3297 if (IsExpandedParameterPack)
3299 SemaRef.Context, Owner, D->getLocation(),
3300 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3301 D->getPosition(), D->getIdentifier(), D->wasDeclaredWithTypename(),
3302 InstParams, ExpandedParams);
3303 else
3305 SemaRef.Context, Owner, D->getLocation(),
3306 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3307 D->getPosition(), D->isParameterPack(), D->getIdentifier(),
3308 D->wasDeclaredWithTypename(), InstParams);
3309 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3310 NestedNameSpecifierLoc QualifierLoc =
3311 D->getDefaultArgument().getTemplateQualifierLoc();
3312 QualifierLoc =
3313 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3314 TemplateName TName = SemaRef.SubstTemplateName(
3315 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3316 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3317 if (!TName.isNull())
3318 Param->setDefaultArgument(
3319 SemaRef.Context,
3321 D->getDefaultArgument().getTemplateQualifierLoc(),
3322 D->getDefaultArgument().getTemplateNameLoc()));
3323 }
3324 Param->setAccess(AS_public);
3325 Param->setImplicit(D->isImplicit());
3326
3327 // Introduce this template parameter's instantiation into the instantiation
3328 // scope.
3330
3331 return Param;
3332}
3333
3334Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3335 // Using directives are never dependent (and never contain any types or
3336 // expressions), so they require no explicit instantiation work.
3337
3338 UsingDirectiveDecl *Inst
3339 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3340 D->getNamespaceKeyLocation(),
3341 D->getQualifierLoc(),
3342 D->getIdentLocation(),
3343 D->getNominatedNamespace(),
3344 D->getCommonAncestor());
3345
3346 // Add the using directive to its declaration context
3347 // only if this is not a function or method.
3348 if (!Owner->isFunctionOrMethod())
3349 Owner->addDecl(Inst);
3350
3351 return Inst;
3352}
3353
3355 BaseUsingDecl *Inst,
3356 LookupResult *Lookup) {
3357
3358 bool isFunctionScope = Owner->isFunctionOrMethod();
3359
3360 for (auto *Shadow : D->shadows()) {
3361 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3362 // reconstruct it in the case where it matters. Hm, can we extract it from
3363 // the DeclSpec when parsing and save it in the UsingDecl itself?
3364 NamedDecl *OldTarget = Shadow->getTargetDecl();
3365 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3366 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3367 OldTarget = BaseShadow;
3368
3369 NamedDecl *InstTarget = nullptr;
3370 if (auto *EmptyD =
3371 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3373 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3374 } else {
3375 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3376 Shadow->getLocation(), OldTarget, TemplateArgs));
3377 }
3378 if (!InstTarget)
3379 return nullptr;
3380
3381 UsingShadowDecl *PrevDecl = nullptr;
3382 if (Lookup &&
3383 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3384 continue;
3385
3386 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3387 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3388 Shadow->getLocation(), OldPrev, TemplateArgs));
3389
3390 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3391 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3392 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3393
3394 if (isFunctionScope)
3395 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3396 }
3397
3398 return Inst;
3399}
3400
3401Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3402
3403 // The nested name specifier may be dependent, for example
3404 // template <typename T> struct t {
3405 // struct s1 { T f1(); };
3406 // struct s2 : s1 { using s1::f1; };
3407 // };
3408 // template struct t<int>;
3409 // Here, in using s1::f1, s1 refers to t<T>::s1;
3410 // we need to substitute for t<int>::s1.
3411 NestedNameSpecifierLoc QualifierLoc
3412 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3413 TemplateArgs);
3414 if (!QualifierLoc)
3415 return nullptr;
3416
3417 // For an inheriting constructor declaration, the name of the using
3418 // declaration is the name of a constructor in this class, not in the
3419 // base class.
3420 DeclarationNameInfo NameInfo = D->getNameInfo();
3422 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3424 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3425
3426 // We only need to do redeclaration lookups if we're in a class scope (in
3427 // fact, it's not really even possible in non-class scopes).
3428 bool CheckRedeclaration = Owner->isRecord();
3429 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3430 RedeclarationKind::ForVisibleRedeclaration);
3431
3432 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3433 D->getUsingLoc(),
3434 QualifierLoc,
3435 NameInfo,
3436 D->hasTypename());
3437
3438 CXXScopeSpec SS;
3439 SS.Adopt(QualifierLoc);
3440 if (CheckRedeclaration) {
3441 Prev.setHideTags(false);
3442 SemaRef.LookupQualifiedName(Prev, Owner);
3443
3444 // Check for invalid redeclarations.
3445 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3446 D->hasTypename(), SS,
3447 D->getLocation(), Prev))
3448 NewUD->setInvalidDecl();
3449 }
3450
3451 if (!NewUD->isInvalidDecl() &&
3452 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3453 NameInfo, D->getLocation(), nullptr, D))
3454 NewUD->setInvalidDecl();
3455
3456 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3457 NewUD->setAccess(D->getAccess());
3458 Owner->addDecl(NewUD);
3459
3460 // Don't process the shadow decls for an invalid decl.
3461 if (NewUD->isInvalidDecl())
3462 return NewUD;
3463
3464 // If the using scope was dependent, or we had dependent bases, we need to
3465 // recheck the inheritance
3468
3469 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3470}
3471
3472Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3473 // Cannot be a dependent type, but still could be an instantiation
3474 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3475 D->getLocation(), D->getEnumDecl(), TemplateArgs));
3476
3477 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3478 return nullptr;
3479
3480 TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3481 D->getLocation(), D->getDeclName());
3482
3483 if (!TSI)
3484 return nullptr;
3485
3486 UsingEnumDecl *NewUD =
3487 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3488 D->getEnumLoc(), D->getLocation(), TSI);
3489
3491 NewUD->setAccess(D->getAccess());
3492 Owner->addDecl(NewUD);
3493
3494 // Don't process the shadow decls for an invalid decl.
3495 if (NewUD->isInvalidDecl())
3496 return NewUD;
3497
3498 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3499 // cannot be dependent, and will therefore have been checked during template
3500 // definition.
3501
3502 return VisitBaseUsingDecls(D, NewUD, nullptr);
3503}
3504
3505Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3506 // Ignore these; we handle them in bulk when processing the UsingDecl.
3507 return nullptr;
3508}
3509
3510Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3512 // Ignore these; we handle them in bulk when processing the UsingDecl.
3513 return nullptr;
3514}
3515
3516template <typename T>
3517Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3518 T *D, bool InstantiatingPackElement) {
3519 // If this is a pack expansion, expand it now.
3520 if (D->isPackExpansion() && !InstantiatingPackElement) {
3522 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3523 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3524
3525 // Determine whether the set of unexpanded parameter packs can and should
3526 // be expanded.
3527 bool Expand = true;
3528 bool RetainExpansion = false;
3529 std::optional<unsigned> NumExpansions;
3531 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3532 Expand, RetainExpansion, NumExpansions))
3533 return nullptr;
3534
3535 // This declaration cannot appear within a function template signature,
3536 // so we can't have a partial argument list for a parameter pack.
3537 assert(!RetainExpansion &&
3538 "should never need to retain an expansion for UsingPackDecl");
3539
3540 if (!Expand) {
3541 // We cannot fully expand the pack expansion now, so substitute into the
3542 // pattern and create a new pack expansion.
3543 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3544 return instantiateUnresolvedUsingDecl(D, true);
3545 }
3546
3547 // Within a function, we don't have any normal way to check for conflicts
3548 // between shadow declarations from different using declarations in the
3549 // same pack expansion, but this is always ill-formed because all expansions
3550 // must produce (conflicting) enumerators.
3551 //
3552 // Sadly we can't just reject this in the template definition because it
3553 // could be valid if the pack is empty or has exactly one expansion.
3554 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3555 SemaRef.Diag(D->getEllipsisLoc(),
3556 diag::err_using_decl_redeclaration_expansion);
3557 return nullptr;
3558 }
3559
3560 // Instantiate the slices of this pack and build a UsingPackDecl.
3561 SmallVector<NamedDecl*, 8> Expansions;
3562 for (unsigned I = 0; I != *NumExpansions; ++I) {
3563 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3564 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3565 if (!Slice)
3566 return nullptr;
3567 // Note that we can still get unresolved using declarations here, if we
3568 // had arguments for all packs but the pattern also contained other
3569 // template arguments (this only happens during partial substitution, eg
3570 // into the body of a generic lambda in a function template).
3571 Expansions.push_back(cast<NamedDecl>(Slice));
3572 }
3573
3574 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3577 return NewD;
3578 }
3579
3580 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3581 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3582
3583 NestedNameSpecifierLoc QualifierLoc
3584 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3585 TemplateArgs);
3586 if (!QualifierLoc)
3587 return nullptr;
3588
3589 CXXScopeSpec SS;
3590 SS.Adopt(QualifierLoc);
3591
3592 DeclarationNameInfo NameInfo
3593 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3594
3595 // Produce a pack expansion only if we're not instantiating a particular
3596 // slice of a pack expansion.
3597 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3598 SemaRef.ArgumentPackSubstitutionIndex != -1;
3599 SourceLocation EllipsisLoc =
3600 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3601
3602 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3603 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3604 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3605 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3607 /*IsInstantiation*/ true, IsUsingIfExists);
3608 if (UD) {
3609 SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3611 }
3612
3613 return UD;
3614}
3615
3616Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3618 return instantiateUnresolvedUsingDecl(D);
3619}
3620
3621Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3623 return instantiateUnresolvedUsingDecl(D);
3624}
3625
3626Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3628 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3629}
3630
3631Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3632 SmallVector<NamedDecl*, 8> Expansions;
3633 for (auto *UD : D->expansions()) {
3634 if (NamedDecl *NewUD =
3635 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3636 Expansions.push_back(NewUD);
3637 else
3638 return nullptr;
3639 }
3640
3641 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3644 return NewD;
3645}
3646
3647Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3650 for (auto *I : D->varlist()) {
3651 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3652 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3653 Vars.push_back(Var);
3654 }
3655
3657 SemaRef.OpenMP().CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3658
3659 TD->setAccess(AS_public);
3660 Owner->addDecl(TD);
3661
3662 return TD;
3663}
3664
3665Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3667 for (auto *I : D->varlist()) {
3668 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3669 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3670 Vars.push_back(Var);
3671 }
3673 // Copy map clauses from the original mapper.
3674 for (OMPClause *C : D->clauselists()) {
3675 OMPClause *IC = nullptr;
3676 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3677 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3678 if (!NewE.isUsable())
3679 continue;
3680 IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause(
3681 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3682 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
3683 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3684 if (!NewE.isUsable())
3685 continue;
3686 IC = SemaRef.OpenMP().ActOnOpenMPAlignClause(
3687 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3688 // If align clause value ends up being invalid, this can end up null.
3689 if (!IC)
3690 continue;
3691 }
3692 Clauses.push_back(IC);
3693 }
3694
3696 D->getLocation(), Vars, Clauses, Owner);
3697 if (Res.get().isNull())
3698 return nullptr;
3699 return Res.get().getSingleDecl();
3700}
3701
3702Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3703 llvm_unreachable(
3704 "Requires directive cannot be instantiated within a dependent context");
3705}
3706
3707Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3709 // Instantiate type and check if it is allowed.
3710 const bool RequiresInstantiation =
3711 D->getType()->isDependentType() ||
3712 D->getType()->isInstantiationDependentType() ||
3713 D->getType()->containsUnexpandedParameterPack();
3714 QualType SubstReductionType;
3715 if (RequiresInstantiation) {
3716 SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType(
3717 D->getLocation(),
3719 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3720 } else {
3721 SubstReductionType = D->getType();
3722 }
3723 if (SubstReductionType.isNull())
3724 return nullptr;
3725 Expr *Combiner = D->getCombiner();
3726 Expr *Init = D->getInitializer();
3727 bool IsCorrect = true;
3728 // Create instantiated copy.
3729 std::pair<QualType, SourceLocation> ReductionTypes[] = {
3730 std::make_pair(SubstReductionType, D->getLocation())};
3731 auto *PrevDeclInScope = D->getPrevDeclInScope();
3732 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3733 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3734 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
3735 PrevDeclInScope)));
3736 }
3738 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3739 PrevDeclInScope);
3740 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3742 Expr *SubstCombiner = nullptr;
3743 Expr *SubstInitializer = nullptr;
3744 // Combiners instantiation sequence.
3745 if (Combiner) {
3747 /*S=*/nullptr, NewDRD);
3749 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3750 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3752 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3753 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3754 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3755 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3756 ThisContext);
3757 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3759 SubstCombiner);
3760 }
3761 // Initializers instantiation sequence.
3762 if (Init) {
3763 VarDecl *OmpPrivParm =
3765 /*S=*/nullptr, NewDRD);
3767 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3768 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3770 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3771 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3772 if (D->getInitializerKind() == OMPDeclareReductionInitKind::Call) {
3773 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3774 } else {
3775 auto *OldPrivParm =
3776 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3777 IsCorrect = IsCorrect && OldPrivParm->hasInit();
3778 if (IsCorrect)
3779 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3780 TemplateArgs);
3781 }
3783 NewDRD, SubstInitializer, OmpPrivParm);
3784 }
3785 IsCorrect = IsCorrect && SubstCombiner &&
3786 (!Init ||
3787 (D->getInitializerKind() == OMPDeclareReductionInitKind::Call &&
3788 SubstInitializer) ||
3789 (D->getInitializerKind() != OMPDeclareReductionInitKind::Call &&
3790 !SubstInitializer));
3791
3793 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3794
3795 return NewDRD;
3796}
3797
3798Decl *
3799TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3800 // Instantiate type and check if it is allowed.
3801 const bool RequiresInstantiation =
3802 D->getType()->isDependentType() ||
3803 D->getType()->isInstantiationDependentType() ||
3804 D->getType()->containsUnexpandedParameterPack();
3805 QualType SubstMapperTy;
3806 DeclarationName VN = D->getVarName();
3807 if (RequiresInstantiation) {
3808 SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType(
3809 D->getLocation(),
3810 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3811 D->getLocation(), VN)));
3812 } else {
3813 SubstMapperTy = D->getType();
3814 }
3815 if (SubstMapperTy.isNull())
3816 return nullptr;
3817 // Create an instantiated copy of mapper.
3818 auto *PrevDeclInScope = D->getPrevDeclInScope();
3819 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3820 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3821 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
3822 PrevDeclInScope)));
3823 }
3824 bool IsCorrect = true;
3826 // Instantiate the mapper variable.
3827 DeclarationNameInfo DirName;
3828 SemaRef.OpenMP().StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3829 /*S=*/nullptr,
3830 (*D->clauselist_begin())->getBeginLoc());
3831 ExprResult MapperVarRef =
3833 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3835 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3836 cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3837 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3838 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3839 ThisContext);
3840 // Instantiate map clauses.
3841 for (OMPClause *C : D->clauselists()) {
3842 auto *OldC = cast<OMPMapClause>(C);
3843 SmallVector<Expr *, 4> NewVars;
3844 for (Expr *OE : OldC->varlist()) {
3845 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3846 if (!NE) {
3847 IsCorrect = false;
3848 break;
3849 }
3850 NewVars.push_back(NE);
3851 }
3852 if (!IsCorrect)
3853 break;
3854 NestedNameSpecifierLoc NewQualifierLoc =
3855 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3856 TemplateArgs);
3857 CXXScopeSpec SS;
3858 SS.Adopt(NewQualifierLoc);
3859 DeclarationNameInfo NewNameInfo =
3860 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3861 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3862 OldC->getEndLoc());
3863 OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause(
3864 OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
3865 OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
3866 OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
3867 NewVars, Locs);
3868 Clauses.push_back(NewC);
3869 }
3870 SemaRef.OpenMP().EndOpenMPDSABlock(nullptr);
3871 if (!IsCorrect)
3872 return nullptr;
3874 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3875 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3876 Decl *NewDMD = DG.get().getSingleDecl();
3878 return NewDMD;
3879}
3880
3881Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3882 OMPCapturedExprDecl * /*D*/) {
3883 llvm_unreachable("Should not be met in templates");
3884}
3885
3887 return VisitFunctionDecl(D, nullptr);
3888}
3889
3890Decl *
3891TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3892 Decl *Inst = VisitFunctionDecl(D, nullptr);
3893 if (Inst && !D->getDescribedFunctionTemplate())
3894 Owner->addDecl(Inst);
3895 return Inst;
3896}
3897
3899 return VisitCXXMethodDecl(D, nullptr);
3900}
3901
3902Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3903 llvm_unreachable("There are only CXXRecordDecls in C++");
3904}
3905
3906Decl *
3907TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3909 // As a MS extension, we permit class-scope explicit specialization
3910 // of member class templates.
3911 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3912 assert(ClassTemplate->getDeclContext()->isRecord() &&
3913 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3914 "can only instantiate an explicit specialization "
3915 "for a member class template");
3916
3917 // Lookup the already-instantiated declaration in the instantiation
3918 // of the class template.
3919 ClassTemplateDecl *InstClassTemplate =
3920 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3921 D->getLocation(), ClassTemplate, TemplateArgs));
3922 if (!InstClassTemplate)
3923 return nullptr;
3924
3925 // Substitute into the template arguments of the class template explicit
3926 // specialization.
3927 TemplateArgumentListInfo InstTemplateArgs;
3928 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3929 D->getTemplateArgsAsWritten()) {
3930 InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3931 InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3932
3933 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3934 TemplateArgs, InstTemplateArgs))
3935 return nullptr;
3936 }
3937
3938 // Check that the template argument list is well-formed for this
3939 // class template.
3940 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3941 if (SemaRef.CheckTemplateArgumentList(
3942 InstClassTemplate, D->getLocation(), InstTemplateArgs,
3943 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
3944 /*UpdateArgsWithConversions=*/true))
3945 return nullptr;
3946
3947 // Figure out where to insert this class template explicit specialization
3948 // in the member template's set of class template explicit specializations.
3949 void *InsertPos = nullptr;
3951 InstClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3952
3953 // Check whether we've already seen a conflicting instantiation of this
3954 // declaration (for instance, if there was a prior implicit instantiation).
3955 bool Ignored;
3956 if (PrevDecl &&
3958 D->getSpecializationKind(),
3959 PrevDecl,
3960 PrevDecl->getSpecializationKind(),
3961 PrevDecl->getPointOfInstantiation(),
3962 Ignored))
3963 return nullptr;
3964
3965 // If PrevDecl was a definition and D is also a definition, diagnose.
3966 // This happens in cases like:
3967 //
3968 // template<typename T, typename U>
3969 // struct Outer {
3970 // template<typename X> struct Inner;
3971 // template<> struct Inner<T> {};
3972 // template<> struct Inner<U> {};
3973 // };
3974 //
3975 // Outer<int, int> outer; // error: the explicit specializations of Inner
3976 // // have the same signature.
3977 if (PrevDecl && PrevDecl->getDefinition() &&
3978 D->isThisDeclarationADefinition()) {
3979 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3980 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3981 diag::note_previous_definition);
3982 return nullptr;
3983 }
3984
3985 // Create the class template partial specialization declaration.
3988 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3989 D->getLocation(), InstClassTemplate, CanonicalConverted, PrevDecl);
3990 InstD->setTemplateArgsAsWritten(InstTemplateArgs);
3991
3992 // Add this partial specialization to the set of class template partial
3993 // specializations.
3994 if (!PrevDecl)
3995 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3996
3997 // Substitute the nested name specifier, if any.
3998 if (SubstQualifier(D, InstD))
3999 return nullptr;
4000
4001 InstD->setAccess(D->getAccess());
4003 InstD->setSpecializationKind(D->getSpecializationKind());
4004 InstD->setExternKeywordLoc(D->getExternKeywordLoc());
4005 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
4006
4007 Owner->addDecl(InstD);
4008
4009 // Instantiate the members of the class-scope explicit specialization eagerly.
4010 // We don't have support for lazy instantiation of an explicit specialization
4011 // yet, and MSVC eagerly instantiates in this case.
4012 // FIXME: This is wrong in standard C++.
4013 if (D->isThisDeclarationADefinition() &&
4014 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
4016 /*Complain=*/true))
4017 return nullptr;
4018
4019 return InstD;
4020}
4021
4024
4025 TemplateArgumentListInfo VarTemplateArgsInfo;
4026 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
4027 assert(VarTemplate &&
4028 "A template specialization without specialized template?");
4029
4030 VarTemplateDecl *InstVarTemplate =
4031 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
4032 D->getLocation(), VarTemplate, TemplateArgs));
4033 if (!InstVarTemplate)
4034 return nullptr;
4035
4036 // Substitute the current template arguments.
4037 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4038 D->getTemplateArgsAsWritten()) {
4039 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4040 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4041
4042 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4043 TemplateArgs, VarTemplateArgsInfo))
4044 return nullptr;
4045 }
4046
4047 // Check that the template argument list is well-formed for this template.
4048 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4049 if (SemaRef.CheckTemplateArgumentList(
4050 InstVarTemplate, D->getLocation(), VarTemplateArgsInfo,
4051 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
4052 /*UpdateArgsWithConversions=*/true))
4053 return nullptr;
4054
4055 // Check whether we've already seen a declaration of this specialization.
4056 void *InsertPos = nullptr;
4058 InstVarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4059
4060 // Check whether we've already seen a conflicting instantiation of this
4061 // declaration (for instance, if there was a prior implicit instantiation).
4062 bool Ignored;
4063 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
4064 D->getLocation(), D->getSpecializationKind(), PrevDecl,
4065 PrevDecl->getSpecializationKind(),
4066 PrevDecl->getPointOfInstantiation(), Ignored))
4067 return nullptr;
4068
4070 InstVarTemplate, D, VarTemplateArgsInfo, CanonicalConverted, PrevDecl);
4071}
4072
4074 VarTemplateDecl *VarTemplate, VarDecl *D,
4075 const TemplateArgumentListInfo &TemplateArgsInfo,
4078
4079 // Do substitution on the type of the declaration
4080 TypeSourceInfo *DI =
4081 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
4082 D->getTypeSpecStartLoc(), D->getDeclName());
4083 if (!DI)
4084 return nullptr;
4085
4086 if (DI->getType()->isFunctionType()) {
4087 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
4088 << D->isStaticDataMember() << DI->getType();
4089 return nullptr;
4090 }
4091
4092 // Build the instantiated declaration
4094 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
4095 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
4096 Var->setTemplateArgsAsWritten(TemplateArgsInfo);
4097 if (!PrevDecl) {
4098 void *InsertPos = nullptr;
4099 VarTemplate->findSpecialization(Converted, InsertPos);
4100 VarTemplate->AddSpecialization(Var, InsertPos);
4101 }
4102
4103 if (SemaRef.getLangOpts().OpenCL)
4104 SemaRef.deduceOpenCLAddressSpace(Var);
4105
4106 // Substitute the nested name specifier, if any.
4107 if (SubstQualifier(D, Var))
4108 return nullptr;
4109
4110 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
4111 StartingScope, false, PrevDecl);
4112
4113 return Var;
4114}
4115
4116Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
4117 llvm_unreachable("@defs is not supported in Objective-C++");
4118}
4119
4120Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
4121 // FIXME: We need to be able to instantiate FriendTemplateDecls.
4122 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
4124 "cannot instantiate %0 yet");
4125 SemaRef.Diag(D->getLocation(), DiagID)
4126 << D->getDeclKindName();
4127
4128 return nullptr;
4129}
4130
4131Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
4132 llvm_unreachable("Concept definitions cannot reside inside a template");
4133}
4134
4135Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4137 llvm_unreachable("Concept specializations cannot reside inside a template");
4138}
4139
4140Decl *
4141TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4143 D->getBeginLoc());
4144}
4145
4147 llvm_unreachable("Unexpected decl");
4148}
4149
4151 const MultiLevelTemplateArgumentList &TemplateArgs) {
4152 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4153 if (D->isInvalidDecl())
4154 return nullptr;
4155
4156 Decl *SubstD;
4158 SubstD = Instantiator.Visit(D);
4159 });
4160 return SubstD;
4161}
4162
4164 FunctionDecl *Orig, QualType &T,
4165 TypeSourceInfo *&TInfo,
4166 DeclarationNameInfo &NameInfo) {
4168
4169 // C++2a [class.compare.default]p3:
4170 // the return type is replaced with bool
4171 auto *FPT = T->castAs<FunctionProtoType>();
4172 T = SemaRef.Context.getFunctionType(
4173 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4174
4175 // Update the return type in the source info too. The most straightforward
4176 // way is to create new TypeSourceInfo for the new type. Use the location of
4177 // the '= default' as the location of the new type.
4178 //
4179 // FIXME: Set the correct return type when we initially transform the type,
4180 // rather than delaying it to now.
4181 TypeSourceInfo *NewTInfo =
4182 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4183 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4184 assert(OldLoc && "type of function is not a function type?");
4185 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4186 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4187 NewLoc.setParam(I, OldLoc.getParam(I));
4188 TInfo = NewTInfo;
4189
4190 // and the declarator-id is replaced with operator==
4191 NameInfo.setName(
4192 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4193}
4194
4196 FunctionDecl *Spaceship) {
4197 if (Spaceship->isInvalidDecl())
4198 return nullptr;
4199
4200 // C++2a [class.compare.default]p3:
4201 // an == operator function is declared implicitly [...] with the same
4202 // access and function-definition and in the same class scope as the
4203 // three-way comparison operator function
4204 MultiLevelTemplateArgumentList NoTemplateArgs;
4206 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4207 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4208 Decl *R;
4209 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4210 R = Instantiator.VisitCXXMethodDecl(
4211 MD, /*TemplateParams=*/nullptr,
4213 } else {
4214 assert(Spaceship->getFriendObjectKind() &&
4215 "defaulted spaceship is neither a member nor a friend");
4216
4217 R = Instantiator.VisitFunctionDecl(
4218 Spaceship, /*TemplateParams=*/nullptr,
4220 if (!R)
4221 return nullptr;
4222
4223 FriendDecl *FD =
4224 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4225 cast<NamedDecl>(R), Spaceship->getBeginLoc());
4226 FD->setAccess(AS_public);
4227 RD->addDecl(FD);
4228 }
4229 return cast_or_null<FunctionDecl>(R);
4230}
4231
4232/// Instantiates a nested template parameter list in the current
4233/// instantiation context.
4234///
4235/// \param L The parameter list to instantiate
4236///
4237/// \returns NULL if there was an error
4240 // Get errors for all the parameters before bailing out.
4241 bool Invalid = false;
4242
4243 unsigned N = L->size();
4244 typedef SmallVector<NamedDecl *, 8> ParamVector;
4245 ParamVector Params;
4246 Params.reserve(N);
4247 for (auto &P : *L) {
4248 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4249 Params.push_back(D);
4250 Invalid = Invalid || !D || D->isInvalidDecl();
4251 }
4252
4253 // Clean up if we had an error.
4254 if (Invalid)
4255 return nullptr;
4256
4257 Expr *InstRequiresClause = L->getRequiresClause();
4258
4261 L->getLAngleLoc(), Params,
4262 L->getRAngleLoc(), InstRequiresClause);
4263 return InstL;
4264}
4265
4268 const MultiLevelTemplateArgumentList &TemplateArgs,
4269 bool EvaluateConstraints) {
4270 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4271 Instantiator.setEvaluateConstraints(EvaluateConstraints);
4272 return Instantiator.SubstTemplateParams(Params);
4273}
4274
4275/// Instantiate the declaration of a class template partial
4276/// specialization.
4277///
4278/// \param ClassTemplate the (instantiated) class template that is partially
4279// specialized by the instantiation of \p PartialSpec.
4280///
4281/// \param PartialSpec the (uninstantiated) class template partial
4282/// specialization that we are instantiating.
4283///
4284/// \returns The instantiated partial specialization, if successful; otherwise,
4285/// NULL to indicate an error.
4288 ClassTemplateDecl *ClassTemplate,
4290 // Create a local instantiation scope for this class template partial
4291 // specialization, which will contain the instantiations of the template
4292 // parameters.
4294
4295 // Substitute into the template parameters of the class template partial
4296 // specialization.
4297 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4298 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4299 if (!InstParams)
4300 return nullptr;
4301
4302 // Substitute into the template arguments of the class template partial
4303 // specialization.
4304 const ASTTemplateArgumentListInfo *TemplArgInfo
4305 = PartialSpec->getTemplateArgsAsWritten();
4306 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4307 TemplArgInfo->RAngleLoc);
4308 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4309 InstTemplateArgs))
4310 return nullptr;
4311
4312 // Check that the template argument list is well-formed for this
4313 // class template.
4314 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4315 if (SemaRef.CheckTemplateArgumentList(
4316 ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4317 /*DefaultArgs=*/{},
4318 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4319 return nullptr;
4320
4321 // Check these arguments are valid for a template partial specialization.
4323 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4324 CanonicalConverted))
4325 return nullptr;
4326
4327 // Figure out where to insert this class template partial specialization
4328 // in the member template's set of class template partial specializations.
4329 void *InsertPos = nullptr;
4331 ClassTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4332 InsertPos);
4333
4334 // Build the canonical type that describes the converted template
4335 // arguments of the class template partial specialization.
4337 TemplateName(ClassTemplate), CanonicalConverted);
4338
4339 // Create the class template partial specialization declaration.
4342 SemaRef.Context, PartialSpec->getTagKind(), Owner,
4343 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4344 ClassTemplate, CanonicalConverted, CanonType,
4345 /*PrevDecl=*/nullptr);
4346
4347 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4348
4349 // Substitute the nested name specifier, if any.
4350 if (SubstQualifier(PartialSpec, InstPartialSpec))
4351 return nullptr;
4352
4353 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4354
4355 if (PrevDecl) {
4356 // We've already seen a partial specialization with the same template
4357 // parameters and template arguments. This can happen, for example, when
4358 // substituting the outer template arguments ends up causing two
4359 // class template partial specializations of a member class template
4360 // to have identical forms, e.g.,
4361 //
4362 // template<typename T, typename U>
4363 // struct Outer {
4364 // template<typename X, typename Y> struct Inner;
4365 // template<typename Y> struct Inner<T, Y>;
4366 // template<typename Y> struct Inner<U, Y>;
4367 // };
4368 //
4369 // Outer<int, int> outer; // error: the partial specializations of Inner
4370 // // have the same signature.
4371 SemaRef.Diag(InstPartialSpec->getLocation(),
4372 diag::err_partial_spec_redeclared)
4373 << InstPartialSpec;
4374 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4375 << SemaRef.Context.getTypeDeclType(PrevDecl);
4376 return nullptr;
4377 }
4378
4379 // Check the completed partial specialization.
4380 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4381
4382 // Add this partial specialization to the set of class template partial
4383 // specializations.
4384 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4385 /*InsertPos=*/nullptr);
4386 return InstPartialSpec;
4387}
4388
4389/// Instantiate the declaration of a variable template partial
4390/// specialization.
4391///
4392/// \param VarTemplate the (instantiated) variable template that is partially
4393/// specialized by the instantiation of \p PartialSpec.
4394///
4395/// \param PartialSpec the (uninstantiated) variable template partial
4396/// specialization that we are instantiating.
4397///
4398/// \returns The instantiated partial specialization, if successful; otherwise,
4399/// NULL to indicate an error.
4402 VarTemplateDecl *VarTemplate,
4404 // Create a local instantiation scope for this variable template partial
4405 // specialization, which will contain the instantiations of the template
4406 // parameters.
4408
4409 // Substitute into the template parameters of the variable template partial
4410 // specialization.
4411 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4412 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4413 if (!InstParams)
4414 return nullptr;
4415
4416 // Substitute into the template arguments of the variable template partial
4417 // specialization.
4418 const ASTTemplateArgumentListInfo *TemplArgInfo
4419 = PartialSpec->getTemplateArgsAsWritten();
4420 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4421 TemplArgInfo->RAngleLoc);
4422 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4423 InstTemplateArgs))
4424 return nullptr;
4425
4426 // Check that the template argument list is well-formed for this
4427 // class template.
4428 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4429 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
4430 InstTemplateArgs, /*DefaultArgs=*/{},
4431 /*PartialTemplateArgs=*/false,
4432 SugaredConverted, CanonicalConverted))
4433 return nullptr;
4434
4435 // Check these arguments are valid for a template partial specialization.
4437 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4438 CanonicalConverted))
4439 return nullptr;
4440
4441 // Figure out where to insert this variable template partial specialization
4442 // in the member template's set of variable template partial specializations.
4443 void *InsertPos = nullptr;
4445 VarTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4446 InsertPos);
4447
4448 // Do substitution on the type of the declaration
4449 TypeSourceInfo *DI = SemaRef.SubstType(
4450 PartialSpec->getTypeSourceInfo(), TemplateArgs,
4451 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4452 if (!DI)
4453 return nullptr;
4454
4455 if (DI->getType()->isFunctionType()) {
4456 SemaRef.Diag(PartialSpec->getLocation(),
4457 diag::err_variable_instantiates_to_function)
4458 << PartialSpec->isStaticDataMember() << DI->getType();
4459 return nullptr;
4460 }
4461
4462 // Create the variable template partial specialization declaration.
4463 VarTemplatePartialSpecializationDecl *InstPartialSpec =
4465 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4466 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4467 DI, PartialSpec->getStorageClass(), CanonicalConverted);
4468
4469 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4470
4471 // Substitute the nested name specifier, if any.
4472 if (SubstQualifier(PartialSpec, InstPartialSpec))
4473 return nullptr;
4474
4475 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4476
4477 if (PrevDecl) {
4478 // We've already seen a partial specialization with the same template
4479 // parameters and template arguments. This can happen, for example, when
4480 // substituting the outer template arguments ends up causing two
4481 // variable template partial specializations of a member variable template
4482 // to have identical forms, e.g.,
4483 //
4484 // template<typename T, typename U>
4485 // struct Outer {
4486 // template<typename X, typename Y> pair<X,Y> p;
4487 // template<typename Y> pair<T, Y> p;
4488 // template<typename Y> pair<U, Y> p;
4489 // };
4490 //
4491 // Outer<int, int> outer; // error: the partial specializations of Inner
4492 // // have the same signature.
4493 SemaRef.Diag(PartialSpec->getLocation(),
4494 diag::err_var_partial_spec_redeclared)
4495 << InstPartialSpec;
4496 SemaRef.Diag(PrevDecl->getLocation(),
4497 diag::note_var_prev_partial_spec_here);
4498 return nullptr;
4499 }
4500 // Check the completed partial specialization.
4501 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4502
4503 // Add this partial specialization to the set of variable template partial
4504 // specializations. The instantiation of the initializer is not necessary.
4505 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4506
4507 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4508 LateAttrs, Owner, StartingScope);
4509
4510 return InstPartialSpec;
4511}
4512
4516 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4517 assert(OldTInfo && "substituting function without type source info");
4518 assert(Params.empty() && "parameter vector is non-empty at start");
4519
4520 CXXRecordDecl *ThisContext = nullptr;
4521 Qualifiers ThisTypeQuals;
4522 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4523 ThisContext = cast<CXXRecordDecl>(Owner);
4524 ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
4525 }
4526
4527 TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
4528 OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
4529 ThisContext, ThisTypeQuals, EvaluateConstraints);
4530 if (!NewTInfo)
4531 return nullptr;
4532
4533 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4534 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4535 if (NewTInfo != OldTInfo) {
4536 // Get parameters from the new type info.
4537 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4538 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4539 unsigned NewIdx = 0;
4540 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4541 OldIdx != NumOldParams; ++OldIdx) {
4542 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4543 if (!OldParam)
4544 return nullptr;
4545
4547
4548 std::optional<unsigned> NumArgumentsInExpansion;
4549 if (OldParam->isParameterPack())
4550 NumArgumentsInExpansion =
4551 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4552 TemplateArgs);
4553 if (!NumArgumentsInExpansion) {
4554 // Simple case: normal parameter, or a parameter pack that's
4555 // instantiated to a (still-dependent) parameter pack.
4556 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4557 Params.push_back(NewParam);
4558 Scope->InstantiatedLocal(OldParam, NewParam);
4559 } else {
4560 // Parameter pack expansion: make the instantiation an argument pack.
4561 Scope->MakeInstantiatedLocalArgPack(OldParam);
4562 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4563 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4564 Params.push_back(NewParam);
4565 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4566 }
4567 }
4568 }
4569 } else {
4570 // The function type itself was not dependent and therefore no
4571 // substitution occurred. However, we still need to instantiate
4572 // the function parameters themselves.
4573 const FunctionProtoType *OldProto =
4574 cast<FunctionProtoType>(OldProtoLoc.getType());
4575 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4576 ++i) {
4577 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4578 if (!OldParam) {
4579 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4580 D, D->getLocation(), OldProto->getParamType(i)));
4581 continue;
4582 }
4583
4584 ParmVarDecl *Parm =
4585 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4586 if (!Parm)
4587 return nullptr;
4588 Params.push_back(Parm);
4589 }
4590 }
4591 } else {
4592 // If the type of this function, after ignoring parentheses, is not
4593 // *directly* a function type, then we're instantiating a function that
4594 // was declared via a typedef or with attributes, e.g.,
4595 //
4596 // typedef int functype(int, int);
4597 // functype func;
4598 // int __cdecl meth(int, int);
4599 //
4600 // In this case, we'll just go instantiate the ParmVarDecls that we
4601 // synthesized in the method declaration.
4602 SmallVector<QualType, 4> ParamTypes;
4603 Sema::ExtParameterInfoBuilder ExtParamInfos;
4604 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4605 TemplateArgs, ParamTypes, &Params,
4606 ExtParamInfos))
4607 return nullptr;
4608 }
4609
4610 return NewTInfo;
4611}
4612
4613void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
4614 const FunctionDecl *PatternDecl,
4616 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(getFunctionScopes().back());
4617
4618 for (auto *decl : PatternDecl->decls()) {
4619 if (!isa<VarDecl>(decl) || isa<ParmVarDecl>(decl))
4620 continue;
4621
4622 VarDecl *VD = cast<VarDecl>(decl);
4623 IdentifierInfo *II = VD->getIdentifier();
4624
4625 auto it = llvm::find_if(Function->decls(), [&](Decl *inst) {
4626 VarDecl *InstVD = dyn_cast<VarDecl>(inst);
4627 return InstVD && InstVD->isLocalVarDecl() &&
4628 InstVD->getIdentifier() == II;
4629 });
4630
4631 if (it == Function->decls().end())
4632 continue;
4633
4634 Scope.InstantiatedLocal(VD, *it);
4635 LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false,
4636 /*isNested=*/false, VD->getLocation(), SourceLocation(),
4637 VD->getType(), /*Invalid=*/false);
4638 }
4639}
4640
4641bool Sema::addInstantiatedParametersToScope(
4642 FunctionDecl *Function, const FunctionDecl *PatternDecl,
4644 const MultiLevelTemplateArgumentList &TemplateArgs) {
4645 unsigned FParamIdx = 0;
4646 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4647 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4648 if (!PatternParam->isParameterPack()) {
4649 // Simple case: not a parameter pack.
4650 assert(FParamIdx < Function->getNumParams());
4651 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4652 FunctionParam->setDeclName(PatternParam->getDeclName());
4653 // If the parameter's type is not dependent, update it to match the type
4654 // in the pattern. They can differ in top-level cv-qualifiers, and we want
4655 // the pattern's type here. If the type is dependent, they can't differ,
4656 // per core issue 1668. Substitute into the type from the pattern, in case
4657 // it's instantiation-dependent.
4658 // FIXME: Updating the type to work around this is at best fragile.
4659 if (!PatternDecl->getType()->isDependentType()) {
4660 QualType T = SubstType(PatternParam->getType(), TemplateArgs,
4661 FunctionParam->getLocation(),
4662 FunctionParam->getDeclName());
4663 if (T.isNull())
4664 return true;
4665 FunctionParam->setType(T);
4666 }
4667
4668 Scope.InstantiatedLocal(PatternParam, FunctionParam);
4669 ++FParamIdx;
4670 continue;
4671 }
4672
4673 // Expand the parameter pack.
4674 Scope.MakeInstantiatedLocalArgPack(PatternParam);
4675 std::optional<unsigned> NumArgumentsInExpansion =
4676 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4677 if (NumArgumentsInExpansion) {
4678 QualType PatternType =
4679 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4680 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4681 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4682 FunctionParam->setDeclName(PatternParam->getDeclName());
4683 if (!PatternDecl->getType()->isDependentType()) {
4684 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
4685 QualType T =
4686 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
4687 FunctionParam->getDeclName());
4688 if (T.isNull())
4689 return true;
4690 FunctionParam->setType(T);
4691 }
4692
4693 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4694 ++FParamIdx;
4695 }
4696 }
4697 }
4698
4699 return false;
4700}
4701
4703 ParmVarDecl *Param) {
4704 assert(Param->hasUninstantiatedDefaultArg());
4705
4706 // FIXME: We don't track member specialization info for non-defining
4707 // friend declarations, so we will not be able to later find the function
4708 // pattern. As a workaround, don't instantiate the default argument in this
4709 // case. This is correct per the standard and only an issue for recovery
4710 // purposes. [dcl.fct.default]p4:
4711 // if a friend declaration D specifies a default argument expression,
4712 // that declaration shall be a definition.
4713 if (FD->getFriendObjectKind() != Decl::FOK_None &&
4715 return true;
4716
4717 // Instantiate the expression.
4718 //
4719 // FIXME: Pass in a correct Pattern argument, otherwise
4720 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4721 //
4722 // template<typename T>
4723 // struct A {
4724 // static int FooImpl();
4725 //
4726 // template<typename Tp>
4727 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4728 // // template argument list [[T], [Tp]], should be [[Tp]].
4729 // friend A<Tp> Foo(int a);
4730 // };
4731 //
4732 // template<typename T>
4733 // A<T> Foo(int a = A<T>::FooImpl());
4735 FD, FD->getLexicalDeclContext(),
4736 /*Final=*/false, /*Innermost=*/std::nullopt,
4737 /*RelativeToPrimary=*/true, /*Pattern=*/nullptr,