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