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