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