clang 20.0.0git
SemaTemplateInstantiateDecl.cpp
Go to the documentation of this file.
1//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===/
7//
8// This file implements C++ template instantiation for declarations.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
21#include "clang/AST/TypeLoc.h"
26#include "clang/Sema/Lookup.h"
29#include "clang/Sema/SemaCUDA.h"
30#include "clang/Sema/SemaHLSL.h"
31#include "clang/Sema/SemaObjC.h"
34#include "clang/Sema/Template.h"
36#include "llvm/Support/TimeProfiler.h"
37#include <optional>
38
39using namespace clang;
40
41static bool isDeclWithinFunction(const Decl *D) {
42 const DeclContext *DC = D->getDeclContext();
43 if (DC->isFunctionOrMethod())
44 return true;
45
46 if (DC->isRecord())
47 return cast<CXXRecordDecl>(DC)->isLocalClass();
48
49 return false;
50}
51
52template<typename DeclT>
53static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
54 const MultiLevelTemplateArgumentList &TemplateArgs) {
55 if (!OldDecl->getQualifierLoc())
56 return false;
57
58 assert((NewDecl->getFriendObjectKind() ||
59 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
60 "non-friend with qualified name defined in dependent context");
61 Sema::ContextRAII SavedContext(
62 SemaRef,
63 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
64 ? NewDecl->getLexicalDeclContext()
65 : OldDecl->getLexicalDeclContext()));
66
67 NestedNameSpecifierLoc NewQualifierLoc
68 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
69 TemplateArgs);
70
71 if (!NewQualifierLoc)
72 return true;
73
74 NewDecl->setQualifierInfo(NewQualifierLoc);
75 return false;
76}
77
79 DeclaratorDecl *NewDecl) {
80 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
81}
82
84 TagDecl *NewDecl) {
85 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
86}
87
88// Include attribute instantiation code.
89#include "clang/Sema/AttrTemplateInstantiate.inc"
90
92 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
93 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
94 if (Aligned->isAlignmentExpr()) {
95 // The alignment expression is a constant expression.
98 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
99 if (!Result.isInvalid())
100 S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
101 } else {
103 S.SubstType(Aligned->getAlignmentType(), TemplateArgs,
104 Aligned->getLocation(), DeclarationName())) {
105 if (!S.CheckAlignasTypeArgument(Aligned->getSpelling(), Result,
106 Aligned->getLocation(),
107 Result->getTypeLoc().getSourceRange()))
108 S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
109 }
110 }
111}
112
114 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
115 const AlignedAttr *Aligned, Decl *New) {
116 if (!Aligned->isPackExpansion()) {
117 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
118 return;
119 }
120
122 if (Aligned->isAlignmentExpr())
123 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
124 Unexpanded);
125 else
126 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
127 Unexpanded);
128 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
129
130 // Determine whether we can expand this attribute pack yet.
131 bool Expand = true, RetainExpansion = false;
132 std::optional<unsigned> NumExpansions;
133 // FIXME: Use the actual location of the ellipsis.
134 SourceLocation EllipsisLoc = Aligned->getLocation();
135 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
136 Unexpanded, TemplateArgs, Expand,
137 RetainExpansion, NumExpansions))
138 return;
139
140 if (!Expand) {
142 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
143 } else {
144 for (unsigned I = 0; I != *NumExpansions; ++I) {
146 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
147 }
148 }
149}
150
152 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
153 const AssumeAlignedAttr *Aligned, Decl *New) {
154 // The alignment expression is a constant expression.
157
158 Expr *E, *OE = nullptr;
159 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
160 if (Result.isInvalid())
161 return;
162 E = Result.getAs<Expr>();
163
164 if (Aligned->getOffset()) {
165 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
166 if (Result.isInvalid())
167 return;
168 OE = Result.getAs<Expr>();
169 }
170
171 S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
172}
173
175 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
176 const AlignValueAttr *Aligned, Decl *New) {
177 // The alignment expression is a constant expression.
180 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
181 if (!Result.isInvalid())
182 S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
183}
184
186 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
187 const AllocAlignAttr *Align, Decl *New) {
189 S.getASTContext(),
190 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
191 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
192 S.AddAllocAlignAttr(New, *Align, Param);
193}
194
196 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
197 const AnnotateAttr *Attr, Decl *New) {
200
201 // If the attribute has delayed arguments it will have to instantiate those
202 // and handle them as new arguments for the attribute.
203 bool HasDelayedArgs = Attr->delayedArgs_size();
204
205 ArrayRef<Expr *> ArgsToInstantiate =
206 HasDelayedArgs
207 ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
208 : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
209
211 if (S.SubstExprs(ArgsToInstantiate,
212 /*IsCall=*/false, TemplateArgs, Args))
213 return;
214
215 StringRef Str = Attr->getAnnotation();
216 if (HasDelayedArgs) {
217 if (Args.size() < 1) {
218 S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
219 << Attr << 1;
220 return;
221 }
222
223 if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
224 return;
225
227 ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
228 std::swap(Args, ActualArgs);
229 }
230 auto *AA = S.CreateAnnotationAttr(*Attr, Str, Args);
231 if (AA) {
232 New->addAttr(AA);
233 }
234}
235
237 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
238 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
239 Expr *Cond = nullptr;
240 {
241 Sema::ContextRAII SwitchContext(S, New);
244 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
245 if (Result.isInvalid())
246 return nullptr;
247 Cond = Result.getAs<Expr>();
248 }
249 if (!Cond->isTypeDependent()) {
251 if (Converted.isInvalid())
252 return nullptr;
253 Cond = Converted.get();
254 }
255
257 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
258 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
259 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
260 for (const auto &P : Diags)
261 S.Diag(P.first, P.second);
262 return nullptr;
263 }
264 return Cond;
265}
266
268 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
269 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
271 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
272
273 if (Cond)
274 New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
275 Cond, EIA->getMessage()));
276}
277
279 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
280 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
282 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
283
284 if (Cond)
285 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
286 S.getASTContext(), *DIA, Cond, DIA->getMessage(),
287 DIA->getDiagnosticType(), DIA->getArgDependent(), New));
288}
289
290// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
291// template A as the base and arguments from TemplateArgs.
293 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
294 const CUDALaunchBoundsAttr &Attr, Decl *New) {
295 // The alignment expression is a constant expression.
298
299 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
300 if (Result.isInvalid())
301 return;
302 Expr *MaxThreads = Result.getAs<Expr>();
303
304 Expr *MinBlocks = nullptr;
305 if (Attr.getMinBlocks()) {
306 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
307 if (Result.isInvalid())
308 return;
309 MinBlocks = Result.getAs<Expr>();
310 }
311
312 Expr *MaxBlocks = nullptr;
313 if (Attr.getMaxBlocks()) {
314 Result = S.SubstExpr(Attr.getMaxBlocks(), TemplateArgs);
315 if (Result.isInvalid())
316 return;
317 MaxBlocks = Result.getAs<Expr>();
318 }
319
320 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks, MaxBlocks);
321}
322
323static void
325 const MultiLevelTemplateArgumentList &TemplateArgs,
326 const ModeAttr &Attr, Decl *New) {
327 S.AddModeAttr(New, Attr, Attr.getMode(),
328 /*InInstantiation=*/true);
329}
330
331/// Instantiation of 'declare simd' attribute and its arguments.
333 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
334 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
335 // Allow 'this' in clauses with varlist.
336 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
337 New = FTD->getTemplatedDecl();
338 auto *FD = cast<FunctionDecl>(New);
339 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
340 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
341 SmallVector<unsigned, 4> LinModifiers;
342
343 auto SubstExpr = [&](Expr *E) -> ExprResult {
344 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
345 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
346 Sema::ContextRAII SavedContext(S, FD);
348 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
349 Local.InstantiatedLocal(
350 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
351 return S.SubstExpr(E, TemplateArgs);
352 }
353 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
354 FD->isCXXInstanceMember());
355 return S.SubstExpr(E, TemplateArgs);
356 };
357
358 // Substitute a single OpenMP clause, which is a potentially-evaluated
359 // full-expression.
360 auto Subst = [&](Expr *E) -> ExprResult {
363 ExprResult Res = SubstExpr(E);
364 if (Res.isInvalid())
365 return Res;
366 return S.ActOnFinishFullExpr(Res.get(), false);
367 };
368
369 ExprResult Simdlen;
370 if (auto *E = Attr.getSimdlen())
371 Simdlen = Subst(E);
372
373 if (Attr.uniforms_size() > 0) {
374 for(auto *E : Attr.uniforms()) {
375 ExprResult Inst = Subst(E);
376 if (Inst.isInvalid())
377 continue;
378 Uniforms.push_back(Inst.get());
379 }
380 }
381
382 auto AI = Attr.alignments_begin();
383 for (auto *E : Attr.aligneds()) {
384 ExprResult Inst = Subst(E);
385 if (Inst.isInvalid())
386 continue;
387 Aligneds.push_back(Inst.get());
388 Inst = ExprEmpty();
389 if (*AI)
390 Inst = S.SubstExpr(*AI, TemplateArgs);
391 Alignments.push_back(Inst.get());
392 ++AI;
393 }
394
395 auto SI = Attr.steps_begin();
396 for (auto *E : Attr.linears()) {
397 ExprResult Inst = Subst(E);
398 if (Inst.isInvalid())
399 continue;
400 Linears.push_back(Inst.get());
401 Inst = ExprEmpty();
402 if (*SI)
403 Inst = S.SubstExpr(*SI, TemplateArgs);
404 Steps.push_back(Inst.get());
405 ++SI;
406 }
407 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
409 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
410 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
411 Attr.getRange());
412}
413
414/// Instantiation of 'declare variant' attribute and its arguments.
416 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
417 const OMPDeclareVariantAttr &Attr, Decl *New) {
418 // Allow 'this' in clauses with varlist.
419 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
420 New = FTD->getTemplatedDecl();
421 auto *FD = cast<FunctionDecl>(New);
422 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
423
424 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
425 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
426 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
427 Sema::ContextRAII SavedContext(S, FD);
429 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
430 Local.InstantiatedLocal(
431 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
432 return S.SubstExpr(E, TemplateArgs);
433 }
434 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
435 FD->isCXXInstanceMember());
436 return S.SubstExpr(E, TemplateArgs);
437 };
438
439 // Substitute a single OpenMP clause, which is a potentially-evaluated
440 // full-expression.
441 auto &&Subst = [&SubstExpr, &S](Expr *E) {
444 ExprResult Res = SubstExpr(E);
445 if (Res.isInvalid())
446 return Res;
447 return S.ActOnFinishFullExpr(Res.get(), false);
448 };
449
450 ExprResult VariantFuncRef;
451 if (Expr *E = Attr.getVariantFuncRef()) {
452 // Do not mark function as is used to prevent its emission if this is the
453 // only place where it is used.
456 VariantFuncRef = Subst(E);
457 }
458
459 // Copy the template version of the OMPTraitInfo and run substitute on all
460 // score and condition expressiosn.
462 TI = *Attr.getTraitInfos();
463
464 // Try to substitute template parameters in score and condition expressions.
465 auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
466 if (E) {
469 ExprResult ER = Subst(E);
470 if (ER.isUsable())
471 E = ER.get();
472 else
473 return true;
474 }
475 return false;
476 };
477 if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
478 return;
479
480 Expr *E = VariantFuncRef.get();
481
482 // Check function/variant ref for `omp declare variant` but not for `omp
483 // begin declare variant` (which use implicit attributes).
484 std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
486 S.ConvertDeclToDeclGroup(New), E, TI, Attr.appendArgs_size(),
487 Attr.getRange());
488
489 if (!DeclVarData)
490 return;
491
492 E = DeclVarData->second;
493 FD = DeclVarData->first;
494
495 if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
496 if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
497 if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
498 if (!VariantFTD->isThisDeclarationADefinition())
499 return;
502 S.Context, TemplateArgs.getInnermost());
503
504 auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
505 New->getLocation());
506 if (!SubstFD)
507 return;
509 SubstFD->getType(), FD->getType(),
510 /* OfBlockPointer */ false,
511 /* Unqualified */ false, /* AllowCXX */ true);
512 if (NewType.isNull())
513 return;
515 New->getLocation(), SubstFD, /* Recursive */ true,
516 /* DefinitionRequired */ false, /* AtEndOfTU */ false);
517 SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
519 SourceLocation(), SubstFD,
520 /* RefersToEnclosingVariableOrCapture */ false,
521 /* NameLoc */ SubstFD->getLocation(),
522 SubstFD->getType(), ExprValueKind::VK_PRValue);
523 }
524 }
525 }
526
527 SmallVector<Expr *, 8> NothingExprs;
528 SmallVector<Expr *, 8> NeedDevicePtrExprs;
530
531 for (Expr *E : Attr.adjustArgsNothing()) {
532 ExprResult ER = Subst(E);
533 if (ER.isInvalid())
534 continue;
535 NothingExprs.push_back(ER.get());
536 }
537 for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
538 ExprResult ER = Subst(E);
539 if (ER.isInvalid())
540 continue;
541 NeedDevicePtrExprs.push_back(ER.get());
542 }
543 for (OMPInteropInfo &II : Attr.appendArgs()) {
544 // When prefer_type is implemented for append_args handle them here too.
545 AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
546 }
547
549 FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
551}
552
554 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
555 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
556 // Both min and max expression are constant expressions.
559
560 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
561 if (Result.isInvalid())
562 return;
563 Expr *MinExpr = Result.getAs<Expr>();
564
565 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
566 if (Result.isInvalid())
567 return;
568 Expr *MaxExpr = Result.getAs<Expr>();
569
570 S.AMDGPU().addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
571}
572
574 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) {
575 if (!ES.getExpr())
576 return ES;
577 Expr *OldCond = ES.getExpr();
578 Expr *Cond = nullptr;
579 {
582 ExprResult SubstResult = SubstExpr(OldCond, TemplateArgs);
583 if (SubstResult.isInvalid()) {
585 }
586 Cond = SubstResult.get();
587 }
588 ExplicitSpecifier Result(Cond, ES.getKind());
589 if (!Cond->isTypeDependent())
591 return Result;
592}
593
595 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
596 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
597 // Both min and max expression are constant expressions.
600
601 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
602 if (Result.isInvalid())
603 return;
604 Expr *MinExpr = Result.getAs<Expr>();
605
606 Expr *MaxExpr = nullptr;
607 if (auto Max = Attr.getMax()) {
608 Result = S.SubstExpr(Max, TemplateArgs);
609 if (Result.isInvalid())
610 return;
611 MaxExpr = Result.getAs<Expr>();
612 }
613
614 S.AMDGPU().addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
615}
616
618 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
619 const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New) {
622
623 ExprResult ResultX = S.SubstExpr(Attr.getMaxNumWorkGroupsX(), TemplateArgs);
624 if (!ResultX.isUsable())
625 return;
626 ExprResult ResultY = S.SubstExpr(Attr.getMaxNumWorkGroupsY(), TemplateArgs);
627 if (!ResultY.isUsable())
628 return;
629 ExprResult ResultZ = S.SubstExpr(Attr.getMaxNumWorkGroupsZ(), TemplateArgs);
630 if (!ResultZ.isUsable())
631 return;
632
633 Expr *XExpr = ResultX.getAs<Expr>();
634 Expr *YExpr = ResultY.getAs<Expr>();
635 Expr *ZExpr = ResultZ.getAs<Expr>();
636
637 S.AMDGPU().addAMDGPUMaxNumWorkGroupsAttr(New, Attr, XExpr, YExpr, ZExpr);
638}
639
640// This doesn't take any template parameters, but we have a custom action that
641// needs to happen when the kernel itself is instantiated. We need to run the
642// ItaniumMangler to mark the names required to name this kernel.
644 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
645 const SYCLKernelAttr &Attr, Decl *New) {
646 New->addAttr(Attr.clone(S.getASTContext()));
647}
648
649/// Determine whether the attribute A might be relevant to the declaration D.
650/// If not, we can skip instantiating it. The attribute may or may not have
651/// been instantiated yet.
652static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
653 // 'preferred_name' is only relevant to the matching specialization of the
654 // template.
655 if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
656 QualType T = PNA->getTypedefType();
657 const auto *RD = cast<CXXRecordDecl>(D);
658 if (!T->isDependentType() && !RD->isDependentContext() &&
660 return false;
661 for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
662 if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
663 PNA->getTypedefType()))
664 return false;
665 return true;
666 }
667
668 if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
669 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
670 switch (BA->getID()) {
671 case Builtin::BIforward:
672 // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
673 // type and returns an lvalue reference type. The library implementation
674 // will produce an error in this case; don't get in its way.
675 if (FD && FD->getNumParams() >= 1 &&
678 return false;
679 }
680 [[fallthrough]];
681 case Builtin::BImove:
682 case Builtin::BImove_if_noexcept:
683 // HACK: Super-old versions of libc++ (3.1 and earlier) provide
684 // std::forward and std::move overloads that sometimes return by value
685 // instead of by reference when building in C++98 mode. Don't treat such
686 // cases as builtins.
687 if (FD && !FD->getReturnType()->isReferenceType())
688 return false;
689 break;
690 }
691 }
692
693 return true;
694}
695
697 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
698 const HLSLParamModifierAttr *Attr, Decl *New) {
699 ParmVarDecl *P = cast<ParmVarDecl>(New);
700 P->addAttr(Attr->clone(S.getASTContext()));
701 P->setType(S.HLSL().getInoutParameterType(P->getType()));
702}
703
705 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
706 Decl *New, LateInstantiatedAttrVec *LateAttrs,
707 LocalInstantiationScope *OuterMostScope) {
708 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
709 // FIXME: This function is called multiple times for the same template
710 // specialization. We should only instantiate attributes that were added
711 // since the previous instantiation.
712 for (const auto *TmplAttr : Tmpl->attrs()) {
713 if (!isRelevantAttr(*this, New, TmplAttr))
714 continue;
715
716 // FIXME: If any of the special case versions from InstantiateAttrs become
717 // applicable to template declaration, we'll need to add them here.
718 CXXThisScopeRAII ThisScope(
719 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
720 Qualifiers(), ND->isCXXInstanceMember());
721
723 TmplAttr, Context, *this, TemplateArgs);
724 if (NewAttr && isRelevantAttr(*this, New, NewAttr))
725 New->addAttr(NewAttr);
726 }
727 }
728}
729
732 switch (A->getKind()) {
733 case clang::attr::CFConsumed:
735 case clang::attr::OSConsumed:
737 case clang::attr::NSConsumed:
739 default:
740 llvm_unreachable("Wrong argument supplied");
741 }
742}
743
745 const Decl *Tmpl, Decl *New,
746 LateInstantiatedAttrVec *LateAttrs,
747 LocalInstantiationScope *OuterMostScope) {
748 for (const auto *TmplAttr : Tmpl->attrs()) {
749 if (!isRelevantAttr(*this, New, TmplAttr))
750 continue;
751
752 // FIXME: This should be generalized to more than just the AlignedAttr.
753 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
754 if (Aligned && Aligned->isAlignmentDependent()) {
755 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
756 continue;
757 }
758
759 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
760 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
761 continue;
762 }
763
764 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
765 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
766 continue;
767 }
768
769 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
770 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
771 continue;
772 }
773
774 if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
775 instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
776 continue;
777 }
778
779 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
780 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
781 cast<FunctionDecl>(New));
782 continue;
783 }
784
785 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
786 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
787 cast<FunctionDecl>(New));
788 continue;
789 }
790
791 if (const auto *CUDALaunchBounds =
792 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
794 *CUDALaunchBounds, New);
795 continue;
796 }
797
798 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
799 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
800 continue;
801 }
802
803 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
804 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
805 continue;
806 }
807
808 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
809 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
810 continue;
811 }
812
813 if (const auto *AMDGPUFlatWorkGroupSize =
814 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
816 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
817 }
818
819 if (const auto *AMDGPUFlatWorkGroupSize =
820 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
822 *AMDGPUFlatWorkGroupSize, New);
823 }
824
825 if (const auto *AMDGPUMaxNumWorkGroups =
826 dyn_cast<AMDGPUMaxNumWorkGroupsAttr>(TmplAttr)) {
828 *this, TemplateArgs, *AMDGPUMaxNumWorkGroups, New);
829 }
830
831 if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(TmplAttr)) {
832 instantiateDependentHLSLParamModifierAttr(*this, TemplateArgs, ParamAttr,
833 New);
834 continue;
835 }
836
837 // Existing DLL attribute on the instantiation takes precedence.
838 if (TmplAttr->getKind() == attr::DLLExport ||
839 TmplAttr->getKind() == attr::DLLImport) {
840 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
841 continue;
842 }
843 }
844
845 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
846 Swift().AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
847 continue;
848 }
849
850 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
851 isa<CFConsumedAttr>(TmplAttr)) {
852 ObjC().AddXConsumedAttr(New, *TmplAttr,
854 /*template instantiation=*/true);
855 continue;
856 }
857
858 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
859 if (!New->hasAttr<PointerAttr>())
860 New->addAttr(A->clone(Context));
861 continue;
862 }
863
864 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
865 if (!New->hasAttr<OwnerAttr>())
866 New->addAttr(A->clone(Context));
867 continue;
868 }
869
870 if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
871 instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
872 continue;
873 }
874
875 if (auto *A = dyn_cast<CUDAGridConstantAttr>(TmplAttr)) {
876 if (!New->hasAttr<CUDAGridConstantAttr>())
877 New->addAttr(A->clone(Context));
878 continue;
879 }
880
881 assert(!TmplAttr->isPackExpansion());
882 if (TmplAttr->isLateParsed() && LateAttrs) {
883 // Late parsed attributes must be instantiated and attached after the
884 // enclosing class has been instantiated. See Sema::InstantiateClass.
885 LocalInstantiationScope *Saved = nullptr;
887 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
888 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
889 } else {
890 // Allow 'this' within late-parsed attributes.
891 auto *ND = cast<NamedDecl>(New);
892 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
893 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
894 ND->isCXXInstanceMember());
895
897 *this, TemplateArgs);
898 if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
899 New->addAttr(NewAttr);
900 }
901 }
902}
903
905 for (const auto *Attr : Pattern->attrs()) {
906 if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
907 if (!Inst->hasAttr<StrictFPAttr>())
908 Inst->addAttr(A->clone(getASTContext()));
909 continue;
910 }
911 }
912}
913
916 Ctor->isDefaultConstructor());
917 unsigned NumParams = Ctor->getNumParams();
918 if (NumParams == 0)
919 return;
920 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
921 if (!Attr)
922 return;
923 for (unsigned I = 0; I != NumParams; ++I) {
925 Ctor->getParamDecl(I));
927 }
928}
929
930/// Get the previous declaration of a declaration for the purposes of template
931/// instantiation. If this finds a previous declaration, then the previous
932/// declaration of the instantiation of D should be an instantiation of the
933/// result of this function.
934template<typename DeclT>
935static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
936 DeclT *Result = D->getPreviousDecl();
937
938 // If the declaration is within a class, and the previous declaration was
939 // merged from a different definition of that class, then we don't have a
940 // previous declaration for the purpose of template instantiation.
941 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
942 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
943 return nullptr;
944
945 return Result;
946}
947
948Decl *
949TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
950 llvm_unreachable("Translation units cannot be instantiated");
951}
952
953Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
954 llvm_unreachable("HLSL buffer declarations cannot be instantiated");
955}
956
957Decl *
958TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
959 llvm_unreachable("pragma comment cannot be instantiated");
960}
961
962Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
964 llvm_unreachable("pragma comment cannot be instantiated");
965}
966
967Decl *
968TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
969 llvm_unreachable("extern \"C\" context cannot be instantiated");
970}
971
972Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
973 llvm_unreachable("GUID declaration cannot be instantiated");
974}
975
976Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
978 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
979}
980
981Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
983 llvm_unreachable("template parameter objects cannot be instantiated");
984}
985
986Decl *
987TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
988 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
989 D->getIdentifier());
990 SemaRef.InstantiateAttrs(TemplateArgs, D, Inst, LateAttrs, StartingScope);
991 Owner->addDecl(Inst);
992 return Inst;
993}
994
995Decl *
996TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
997 llvm_unreachable("Namespaces cannot be instantiated");
998}
999
1000Decl *
1001TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1002 NamespaceAliasDecl *Inst
1003 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
1004 D->getNamespaceLoc(),
1005 D->getAliasLoc(),
1006 D->getIdentifier(),
1007 D->getQualifierLoc(),
1008 D->getTargetNameLoc(),
1009 D->getNamespace());
1010 Owner->addDecl(Inst);
1011 return Inst;
1012}
1013
1015 bool IsTypeAlias) {
1016 bool Invalid = false;
1017 TypeSourceInfo *DI = D->getTypeSourceInfo();
1020 DI = SemaRef.SubstType(DI, TemplateArgs,
1021 D->getLocation(), D->getDeclName());
1022 if (!DI) {
1023 Invalid = true;
1024 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
1025 }
1026 } else {
1028 }
1029
1030 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
1031 // libstdc++ relies upon this bug in its implementation of common_type. If we
1032 // happen to be processing that implementation, fake up the g++ ?:
1033 // semantics. See LWG issue 2141 for more information on the bug. The bugs
1034 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
1035 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
1036 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1037 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
1038 DT->isReferenceType() &&
1039 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
1040 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
1041 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
1043 // Fold it to the (non-reference) type which g++ would have produced.
1044 DI = SemaRef.Context.getTrivialTypeSourceInfo(
1046
1047 // Create the new typedef
1048 TypedefNameDecl *Typedef;
1049 if (IsTypeAlias)
1050 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1051 D->getLocation(), D->getIdentifier(), DI);
1052 else
1053 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1054 D->getLocation(), D->getIdentifier(), DI);
1055 if (Invalid)
1056 Typedef->setInvalidDecl();
1057
1058 // If the old typedef was the name for linkage purposes of an anonymous
1059 // tag decl, re-establish that relationship for the new typedef.
1060 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1061 TagDecl *oldTag = oldTagType->getDecl();
1062 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1063 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
1064 assert(!newTag->hasNameForLinkage());
1065 newTag->setTypedefNameForAnonDecl(Typedef);
1066 }
1067 }
1068
1070 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1071 TemplateArgs);
1072 if (!InstPrev)
1073 return nullptr;
1074
1075 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1076
1077 // If the typedef types are not identical, reject them.
1078 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1079
1080 Typedef->setPreviousDecl(InstPrevTypedef);
1081 }
1082
1083 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1084
1085 if (D->getUnderlyingType()->getAs<DependentNameType>())
1086 SemaRef.inferGslPointerAttribute(Typedef);
1087
1088 Typedef->setAccess(D->getAccess());
1089 Typedef->setReferenced(D->isReferenced());
1090
1091 return Typedef;
1092}
1093
1094Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1095 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1096 if (Typedef)
1097 Owner->addDecl(Typedef);
1098 return Typedef;
1099}
1100
1101Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1102 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1103 if (Typedef)
1104 Owner->addDecl(Typedef);
1105 return Typedef;
1106}
1107
1110 // Create a local instantiation scope for this type alias template, which
1111 // will contain the instantiations of the template parameters.
1113
1114 TemplateParameterList *TempParams = D->getTemplateParameters();
1115 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1116 if (!InstParams)
1117 return nullptr;
1118
1119 TypeAliasDecl *Pattern = D->getTemplatedDecl();
1120 Sema::InstantiatingTemplate InstTemplate(
1121 SemaRef, D->getBeginLoc(), D,
1122 D->getTemplateDepth() >= TemplateArgs.getNumLevels()
1124 : (TemplateArgs.begin() + TemplateArgs.getNumLevels() - 1 -
1126 ->Args);
1127 if (InstTemplate.isInvalid())
1128 return nullptr;
1129
1130 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1131 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
1133 if (!Found.empty()) {
1134 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1135 }
1136 }
1137
1138 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1139 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1140 if (!AliasInst)
1141 return nullptr;
1142
1145 D->getDeclName(), InstParams, AliasInst);
1146 AliasInst->setDescribedAliasTemplate(Inst);
1147 if (PrevAliasTemplate)
1148 Inst->setPreviousDecl(PrevAliasTemplate);
1149
1150 Inst->setAccess(D->getAccess());
1151
1152 if (!PrevAliasTemplate)
1154
1155 return Inst;
1156}
1157
1158Decl *
1159TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1161 if (Inst)
1162 Owner->addDecl(Inst);
1163
1164 return Inst;
1165}
1166
1167Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1168 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1169 D->getIdentifier());
1170 NewBD->setReferenced(D->isReferenced());
1172 return NewBD;
1173}
1174
1175Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1176 // Transform the bindings first.
1178 for (auto *OldBD : D->bindings())
1179 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1180 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1181
1182 auto *NewDD = cast_or_null<DecompositionDecl>(
1183 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1184
1185 if (!NewDD || NewDD->isInvalidDecl())
1186 for (auto *NewBD : NewBindings)
1187 NewBD->setInvalidDecl();
1188
1189 return NewDD;
1190}
1191
1193 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1194}
1195
1197 bool InstantiatingVarTemplate,
1199
1200 // Do substitution on the type of the declaration
1201 TypeSourceInfo *DI = SemaRef.SubstType(
1202 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1203 D->getDeclName(), /*AllowDeducedTST*/true);
1204 if (!DI)
1205 return nullptr;
1206
1207 if (DI->getType()->isFunctionType()) {
1208 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1209 << D->isStaticDataMember() << DI->getType();
1210 return nullptr;
1211 }
1212
1213 DeclContext *DC = Owner;
1214 if (D->isLocalExternDecl())
1216
1217 // Build the instantiated declaration.
1218 VarDecl *Var;
1219 if (Bindings)
1220 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1221 D->getLocation(), DI->getType(), DI,
1222 D->getStorageClass(), *Bindings);
1223 else
1224 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1225 D->getLocation(), D->getIdentifier(), DI->getType(),
1226 DI, D->getStorageClass());
1227
1228 // In ARC, infer 'retaining' for variables of retainable type.
1229 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1230 SemaRef.ObjC().inferObjCARCLifetime(Var))
1231 Var->setInvalidDecl();
1232
1233 if (SemaRef.getLangOpts().OpenCL)
1234 SemaRef.deduceOpenCLAddressSpace(Var);
1235
1236 // Substitute the nested name specifier, if any.
1237 if (SubstQualifier(D, Var))
1238 return nullptr;
1239
1240 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1241 StartingScope, InstantiatingVarTemplate);
1242 if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1243 QualType RT;
1244 if (auto *F = dyn_cast<FunctionDecl>(DC))
1245 RT = F->getReturnType();
1246 else if (isa<BlockDecl>(DC))
1247 RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1248 ->getReturnType();
1249 else
1250 llvm_unreachable("Unknown context type");
1251
1252 // This is the last chance we have of checking copy elision eligibility
1253 // for functions in dependent contexts. The sema actions for building
1254 // the return statement during template instantiation will have no effect
1255 // regarding copy elision, since NRVO propagation runs on the scope exit
1256 // actions, and these are not run on instantiation.
1257 // This might run through some VarDecls which were returned from non-taken
1258 // 'if constexpr' branches, and these will end up being constructed on the
1259 // return slot even if they will never be returned, as a sort of accidental
1260 // 'optimization'. Notably, functions with 'auto' return types won't have it
1261 // deduced by this point. Coupled with the limitation described
1262 // previously, this makes it very hard to support copy elision for these.
1263 Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1264 bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1265 Var->setNRVOVariable(NRVO);
1266 }
1267
1268 Var->setImplicit(D->isImplicit());
1269
1270 if (Var->isStaticLocal())
1271 SemaRef.CheckStaticLocalForDllExport(Var);
1272
1273 if (Var->getTLSKind())
1275
1276 return Var;
1277}
1278
1279Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1280 AccessSpecDecl* AD
1281 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1282 D->getAccessSpecifierLoc(), D->getColonLoc());
1283 Owner->addHiddenDecl(AD);
1284 return AD;
1285}
1286
1287Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1288 bool Invalid = false;
1289 TypeSourceInfo *DI = D->getTypeSourceInfo();
1292 DI = SemaRef.SubstType(DI, TemplateArgs,
1293 D->getLocation(), D->getDeclName());
1294 if (!DI) {
1295 DI = D->getTypeSourceInfo();
1296 Invalid = true;
1297 } else if (DI->getType()->isFunctionType()) {
1298 // C++ [temp.arg.type]p3:
1299 // If a declaration acquires a function type through a type
1300 // dependent on a template-parameter and this causes a
1301 // declaration that does not use the syntactic form of a
1302 // function declarator to have function type, the program is
1303 // ill-formed.
1304 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1305 << DI->getType();
1306 Invalid = true;
1307 }
1308 } else {
1310 }
1311
1312 Expr *BitWidth = D->getBitWidth();
1313 if (Invalid)
1314 BitWidth = nullptr;
1315 else if (BitWidth) {
1316 // The bit-width expression is a constant expression.
1319
1320 ExprResult InstantiatedBitWidth
1321 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1322 if (InstantiatedBitWidth.isInvalid()) {
1323 Invalid = true;
1324 BitWidth = nullptr;
1325 } else
1326 BitWidth = InstantiatedBitWidth.getAs<Expr>();
1327 }
1328
1329 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1330 DI->getType(), DI,
1331 cast<RecordDecl>(Owner),
1332 D->getLocation(),
1333 D->isMutable(),
1334 BitWidth,
1335 D->getInClassInitStyle(),
1336 D->getInnerLocStart(),
1337 D->getAccess(),
1338 nullptr);
1339 if (!Field) {
1340 cast<Decl>(Owner)->setInvalidDecl();
1341 return nullptr;
1342 }
1343
1344 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1345
1346 if (Field->hasAttrs())
1347 SemaRef.CheckAlignasUnderalignment(Field);
1348
1349 if (Invalid)
1350 Field->setInvalidDecl();
1351
1352 if (!Field->getDeclName() || Field->isPlaceholderVar(SemaRef.getLangOpts())) {
1353 // Keep track of where this decl came from.
1355 }
1356 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1357 if (Parent->isAnonymousStructOrUnion() &&
1358 Parent->getRedeclContext()->isFunctionOrMethod())
1360 }
1361
1362 Field->setImplicit(D->isImplicit());
1363 Field->setAccess(D->getAccess());
1364 Owner->addDecl(Field);
1365
1366 return Field;
1367}
1368
1369Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1370 bool Invalid = false;
1371 TypeSourceInfo *DI = D->getTypeSourceInfo();
1372
1373 if (DI->getType()->isVariablyModifiedType()) {
1374 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1375 << D;
1376 Invalid = true;
1377 } else if (DI->getType()->isInstantiationDependentType()) {
1378 DI = SemaRef.SubstType(DI, TemplateArgs,
1379 D->getLocation(), D->getDeclName());
1380 if (!DI) {
1381 DI = D->getTypeSourceInfo();
1382 Invalid = true;
1383 } else if (DI->getType()->isFunctionType()) {
1384 // C++ [temp.arg.type]p3:
1385 // If a declaration acquires a function type through a type
1386 // dependent on a template-parameter and this causes a
1387 // declaration that does not use the syntactic form of a
1388 // function declarator to have function type, the program is
1389 // ill-formed.
1390 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1391 << DI->getType();
1392 Invalid = true;
1393 }
1394 } else {
1396 }
1397
1399 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1400 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1401
1402 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1403 StartingScope);
1404
1405 if (Invalid)
1406 Property->setInvalidDecl();
1407
1408 Property->setAccess(D->getAccess());
1409 Owner->addDecl(Property);
1410
1411 return Property;
1412}
1413
1414Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1415 NamedDecl **NamedChain =
1416 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1417
1418 int i = 0;
1419 for (auto *PI : D->chain()) {
1420 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1421 TemplateArgs);
1422 if (!Next)
1423 return nullptr;
1424
1425 NamedChain[i++] = Next;
1426 }
1427
1428 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1430 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1431 {NamedChain, D->getChainingSize()});
1432
1433 for (const auto *Attr : D->attrs())
1434 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1435
1436 IndirectField->setImplicit(D->isImplicit());
1437 IndirectField->setAccess(D->getAccess());
1438 Owner->addDecl(IndirectField);
1439 return IndirectField;
1440}
1441
1442Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1443 // Handle friend type expressions by simply substituting template
1444 // parameters into the pattern type and checking the result.
1445 if (TypeSourceInfo *Ty = D->getFriendType()) {
1446 TypeSourceInfo *InstTy;
1447 // If this is an unsupported friend, don't bother substituting template
1448 // arguments into it. The actual type referred to won't be used by any
1449 // parts of Clang, and may not be valid for instantiating. Just use the
1450 // same info for the instantiated friend.
1451 if (D->isUnsupportedFriend()) {
1452 InstTy = Ty;
1453 } else {
1454 if (D->isPackExpansion()) {
1456 SemaRef.collectUnexpandedParameterPacks(Ty->getTypeLoc(), Unexpanded);
1457 assert(!Unexpanded.empty() && "Pack expansion without packs");
1458
1459 bool ShouldExpand = true;
1460 bool RetainExpansion = false;
1461 std::optional<unsigned> NumExpansions;
1463 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded,
1464 TemplateArgs, ShouldExpand, RetainExpansion, NumExpansions))
1465 return nullptr;
1466
1467 assert(!RetainExpansion &&
1468 "should never retain an expansion for a variadic friend decl");
1469
1470 if (ShouldExpand) {
1472 for (unsigned I = 0; I != *NumExpansions; I++) {
1473 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1474 TypeSourceInfo *TSI = SemaRef.SubstType(
1475 Ty, TemplateArgs, D->getEllipsisLoc(), DeclarationName());
1476 if (!TSI)
1477 return nullptr;
1478
1479 auto FD =
1480 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1481 TSI, D->getFriendLoc());
1482
1483 FD->setAccess(AS_public);
1484 Owner->addDecl(FD);
1485 Decls.push_back(FD);
1486 }
1487
1488 // Just drop this node; we have no use for it anymore.
1489 return nullptr;
1490 }
1491 }
1492
1493 InstTy = SemaRef.SubstType(Ty, TemplateArgs, D->getLocation(),
1494 DeclarationName());
1495 }
1496 if (!InstTy)
1497 return nullptr;
1498
1500 SemaRef.Context, Owner, D->getLocation(), InstTy, D->getFriendLoc());
1501 FD->setAccess(AS_public);
1502 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1503 Owner->addDecl(FD);
1504 return FD;
1505 }
1506
1507 NamedDecl *ND = D->getFriendDecl();
1508 assert(ND && "friend decl must be a decl or a type!");
1509
1510 // All of the Visit implementations for the various potential friend
1511 // declarations have to be carefully written to work for friend
1512 // objects, with the most important detail being that the target
1513 // decl should almost certainly not be placed in Owner.
1514 Decl *NewND = Visit(ND);
1515 if (!NewND) return nullptr;
1516
1517 FriendDecl *FD =
1518 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1519 cast<NamedDecl>(NewND), D->getFriendLoc());
1520 FD->setAccess(AS_public);
1521 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1522 Owner->addDecl(FD);
1523 return FD;
1524}
1525
1526Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1527 Expr *AssertExpr = D->getAssertExpr();
1528
1529 // The expression in a static assertion is a constant expression.
1532
1533 ExprResult InstantiatedAssertExpr
1534 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1535 if (InstantiatedAssertExpr.isInvalid())
1536 return nullptr;
1537
1538 ExprResult InstantiatedMessageExpr =
1539 SemaRef.SubstExpr(D->getMessage(), TemplateArgs);
1540 if (InstantiatedMessageExpr.isInvalid())
1541 return nullptr;
1542
1543 return SemaRef.BuildStaticAssertDeclaration(
1544 D->getLocation(), InstantiatedAssertExpr.get(),
1545 InstantiatedMessageExpr.get(), D->getRParenLoc(), D->isFailed());
1546}
1547
1548Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1549 EnumDecl *PrevDecl = nullptr;
1550 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1551 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1552 PatternPrev,
1553 TemplateArgs);
1554 if (!Prev) return nullptr;
1555 PrevDecl = cast<EnumDecl>(Prev);
1556 }
1557
1558 EnumDecl *Enum =
1559 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1560 D->getLocation(), D->getIdentifier(), PrevDecl,
1561 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1562 if (D->isFixed()) {
1563 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1564 // If we have type source information for the underlying type, it means it
1565 // has been explicitly set by the user. Perform substitution on it before
1566 // moving on.
1567 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1568 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1569 DeclarationName());
1570 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1571 Enum->setIntegerType(SemaRef.Context.IntTy);
1572 else
1573 Enum->setIntegerTypeSourceInfo(NewTI);
1574
1575 // C++23 [conv.prom]p4
1576 // if integral promotion can be applied to its underlying type, a prvalue
1577 // of an unscoped enumeration type whose underlying type is fixed can also
1578 // be converted to a prvalue of the promoted underlying type.
1579 //
1580 // FIXME: that logic is already implemented in ActOnEnumBody, factor out
1581 // into (Re)BuildEnumBody.
1582 QualType UnderlyingType = Enum->getIntegerType();
1583 Enum->setPromotionType(
1584 SemaRef.Context.isPromotableIntegerType(UnderlyingType)
1585 ? SemaRef.Context.getPromotedIntegerType(UnderlyingType)
1586 : UnderlyingType);
1587 } else {
1588 assert(!D->getIntegerType()->isDependentType()
1589 && "Dependent type without type source info");
1590 Enum->setIntegerType(D->getIntegerType());
1591 }
1592 }
1593
1594 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1595
1596 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1597 Enum->setAccess(D->getAccess());
1598 // Forward the mangling number from the template to the instantiated decl.
1600 // See if the old tag was defined along with a declarator.
1601 // If it did, mark the new tag as being associated with that declarator.
1604 // See if the old tag was defined along with a typedef.
1605 // If it did, mark the new tag as being associated with that typedef.
1608 if (SubstQualifier(D, Enum)) return nullptr;
1609 Owner->addDecl(Enum);
1610
1611 EnumDecl *Def = D->getDefinition();
1612 if (Def && Def != D) {
1613 // If this is an out-of-line definition of an enum member template, check
1614 // that the underlying types match in the instantiation of both
1615 // declarations.
1616 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1617 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1618 QualType DefnUnderlying =
1619 SemaRef.SubstType(TI->getType(), TemplateArgs,
1620 UnderlyingLoc, DeclarationName());
1621 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1622 DefnUnderlying, /*IsFixed=*/true, Enum);
1623 }
1624 }
1625
1626 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1627 // specialization causes the implicit instantiation of the declarations, but
1628 // not the definitions of scoped member enumerations.
1629 //
1630 // DR1484 clarifies that enumeration definitions inside of a template
1631 // declaration aren't considered entities that can be separately instantiated
1632 // from the rest of the entity they are declared inside of.
1633 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1636 }
1637
1638 return Enum;
1639}
1640
1642 EnumDecl *Enum, EnumDecl *Pattern) {
1643 Enum->startDefinition();
1644
1645 // Update the location to refer to the definition.
1646 Enum->setLocation(Pattern->getLocation());
1647
1648 SmallVector<Decl*, 4> Enumerators;
1649
1650 EnumConstantDecl *LastEnumConst = nullptr;
1651 for (auto *EC : Pattern->enumerators()) {
1652 // The specified value for the enumerator.
1653 ExprResult Value((Expr *)nullptr);
1654 if (Expr *UninstValue = EC->getInitExpr()) {
1655 // The enumerator's value expression is a constant expression.
1658
1659 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1660 }
1661
1662 // Drop the initial value and continue.
1663 bool isInvalid = false;
1664 if (Value.isInvalid()) {
1665 Value = nullptr;
1666 isInvalid = true;
1667 }
1668
1669 EnumConstantDecl *EnumConst
1670 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1671 EC->getLocation(), EC->getIdentifier(),
1672 Value.get());
1673
1674 if (isInvalid) {
1675 if (EnumConst)
1676 EnumConst->setInvalidDecl();
1677 Enum->setInvalidDecl();
1678 }
1679
1680 if (EnumConst) {
1681 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1682
1683 EnumConst->setAccess(Enum->getAccess());
1684 Enum->addDecl(EnumConst);
1685 Enumerators.push_back(EnumConst);
1686 LastEnumConst = EnumConst;
1687
1688 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1689 !Enum->isScoped()) {
1690 // If the enumeration is within a function or method, record the enum
1691 // constant as a local.
1692 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1693 }
1694 }
1695 }
1696
1697 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1698 Enumerators, nullptr, ParsedAttributesView());
1699}
1700
1701Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1702 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1703}
1704
1705Decl *
1706TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1707 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1708}
1709
1710Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1711 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1712
1713 // Create a local instantiation scope for this class template, which
1714 // will contain the instantiations of the template parameters.
1716 TemplateParameterList *TempParams = D->getTemplateParameters();
1717 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1718 if (!InstParams)
1719 return nullptr;
1720
1721 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1722
1723 // Instantiate the qualifier. We have to do this first in case
1724 // we're a friend declaration, because if we are then we need to put
1725 // the new declaration in the appropriate context.
1726 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1727 if (QualifierLoc) {
1728 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1729 TemplateArgs);
1730 if (!QualifierLoc)
1731 return nullptr;
1732 }
1733
1734 CXXRecordDecl *PrevDecl = nullptr;
1735 ClassTemplateDecl *PrevClassTemplate = nullptr;
1736
1737 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1739 if (!Found.empty()) {
1740 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1741 if (PrevClassTemplate)
1742 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1743 }
1744 }
1745
1746 // If this isn't a friend, then it's a member template, in which
1747 // case we just want to build the instantiation in the
1748 // specialization. If it is a friend, we want to build it in
1749 // the appropriate context.
1750 DeclContext *DC = Owner;
1751 if (isFriend) {
1752 if (QualifierLoc) {
1753 CXXScopeSpec SS;
1754 SS.Adopt(QualifierLoc);
1755 DC = SemaRef.computeDeclContext(SS);
1756 if (!DC) return nullptr;
1757 } else {
1758 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1759 Pattern->getDeclContext(),
1760 TemplateArgs);
1761 }
1762
1763 // Look for a previous declaration of the template in the owning
1764 // context.
1765 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1768 SemaRef.LookupQualifiedName(R, DC);
1769
1770 if (R.isSingleResult()) {
1771 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1772 if (PrevClassTemplate)
1773 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1774 }
1775
1776 if (!PrevClassTemplate && QualifierLoc) {
1777 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1778 << llvm::to_underlying(D->getTemplatedDecl()->getTagKind())
1779 << Pattern->getDeclName() << DC << QualifierLoc.getSourceRange();
1780 return nullptr;
1781 }
1782 }
1783
1785 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1786 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1787 /*DelayTypeCreation=*/true);
1788 if (QualifierLoc)
1789 RecordInst->setQualifierInfo(QualifierLoc);
1790
1791 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1792 StartingScope);
1793
1794 ClassTemplateDecl *Inst
1796 D->getIdentifier(), InstParams, RecordInst);
1797 RecordInst->setDescribedClassTemplate(Inst);
1798
1799 if (isFriend) {
1800 assert(!Owner->isDependentContext());
1801 Inst->setLexicalDeclContext(Owner);
1802 RecordInst->setLexicalDeclContext(Owner);
1803 Inst->setObjectOfFriendDecl();
1804
1805 if (PrevClassTemplate) {
1806 Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
1807 RecordInst->setTypeForDecl(
1808 PrevClassTemplate->getTemplatedDecl()->getTypeForDecl());
1809 const ClassTemplateDecl *MostRecentPrevCT =
1810 PrevClassTemplate->getMostRecentDecl();
1811 TemplateParameterList *PrevParams =
1812 MostRecentPrevCT->getTemplateParameters();
1813
1814 // Make sure the parameter lists match.
1815 if (!SemaRef.TemplateParameterListsAreEqual(
1816 RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
1817 PrevParams, true, Sema::TPL_TemplateMatch))
1818 return nullptr;
1819
1820 // Do some additional validation, then merge default arguments
1821 // from the existing declarations.
1822 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1824 return nullptr;
1825
1826 Inst->setAccess(PrevClassTemplate->getAccess());
1827 } else {
1828 Inst->setAccess(D->getAccess());
1829 }
1830
1831 Inst->setObjectOfFriendDecl();
1832 // TODO: do we want to track the instantiation progeny of this
1833 // friend target decl?
1834 } else {
1835 Inst->setAccess(D->getAccess());
1836 if (!PrevClassTemplate)
1838 }
1839
1840 Inst->setPreviousDecl(PrevClassTemplate);
1841
1842 // Trigger creation of the type for the instantiation.
1844 RecordInst, Inst->getInjectedClassNameSpecialization());
1845
1846 // Finish handling of friends.
1847 if (isFriend) {
1848 DC->makeDeclVisibleInContext(Inst);
1849 return Inst;
1850 }
1851
1852 if (D->isOutOfLine()) {
1855 }
1856
1857 Owner->addDecl(Inst);
1858
1859 if (!PrevClassTemplate) {
1860 // Queue up any out-of-line partial specializations of this member
1861 // class template; the client will force their instantiation once
1862 // the enclosing class has been instantiated.
1864 D->getPartialSpecializations(PartialSpecs);
1865 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1866 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1867 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1868 }
1869
1870 return Inst;
1871}
1872
1873Decl *
1874TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1876 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1877
1878 // Lookup the already-instantiated declaration in the instantiation
1879 // of the class template and return that.
1881 = Owner->lookup(ClassTemplate->getDeclName());
1882 if (Found.empty())
1883 return nullptr;
1884
1885 ClassTemplateDecl *InstClassTemplate
1886 = dyn_cast<ClassTemplateDecl>(Found.front());
1887 if (!InstClassTemplate)
1888 return nullptr;
1889
1891 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1892 return Result;
1893
1894 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1895}
1896
1897Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1898 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1899 "Only static data member templates are allowed.");
1900
1901 // Create a local instantiation scope for this variable template, which
1902 // will contain the instantiations of the template parameters.
1904 TemplateParameterList *TempParams = D->getTemplateParameters();
1905 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1906 if (!InstParams)
1907 return nullptr;
1908
1909 VarDecl *Pattern = D->getTemplatedDecl();
1910 VarTemplateDecl *PrevVarTemplate = nullptr;
1911
1912 if (getPreviousDeclForInstantiation(Pattern)) {
1914 if (!Found.empty())
1915 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1916 }
1917
1918 VarDecl *VarInst =
1919 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1920 /*InstantiatingVarTemplate=*/true));
1921 if (!VarInst) return nullptr;
1922
1923 DeclContext *DC = Owner;
1924
1926 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1927 VarInst);
1928 VarInst->setDescribedVarTemplate(Inst);
1929 Inst->setPreviousDecl(PrevVarTemplate);
1930
1931 Inst->setAccess(D->getAccess());
1932 if (!PrevVarTemplate)
1934
1935 if (D->isOutOfLine()) {
1938 }
1939
1940 Owner->addDecl(Inst);
1941
1942 if (!PrevVarTemplate) {
1943 // Queue up any out-of-line partial specializations of this member
1944 // variable template; the client will force their instantiation once
1945 // the enclosing class has been instantiated.
1947 D->getPartialSpecializations(PartialSpecs);
1948 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1949 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1950 OutOfLineVarPartialSpecs.push_back(
1951 std::make_pair(Inst, PartialSpecs[I]));
1952 }
1953
1954 return Inst;
1955}
1956
1957Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1959 assert(D->isStaticDataMember() &&
1960 "Only static data member templates are allowed.");
1961
1962 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1963
1964 // Lookup the already-instantiated declaration and return that.
1965 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1966 assert(!Found.empty() && "Instantiation found nothing?");
1967
1968 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1969 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1970
1972 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1973 return Result;
1974
1975 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1976}
1977
1978Decl *
1979TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1980 // Create a local instantiation scope for this function template, which
1981 // will contain the instantiations of the template parameters and then get
1982 // merged with the local instantiation scope for the function template
1983 // itself.
1986
1987 TemplateParameterList *TempParams = D->getTemplateParameters();
1988 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1989 if (!InstParams)
1990 return nullptr;
1991
1992 FunctionDecl *Instantiated = nullptr;
1993 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1994 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1995 InstParams));
1996 else
1997 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1998 D->getTemplatedDecl(),
1999 InstParams));
2000
2001 if (!Instantiated)
2002 return nullptr;
2003
2004 // Link the instantiated function template declaration to the function
2005 // template from which it was instantiated.
2006 FunctionTemplateDecl *InstTemplate
2007 = Instantiated->getDescribedFunctionTemplate();
2008 InstTemplate->setAccess(D->getAccess());
2009 assert(InstTemplate &&
2010 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
2011
2012 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
2013
2014 // Link the instantiation back to the pattern *unless* this is a
2015 // non-definition friend declaration.
2016 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
2017 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
2018 InstTemplate->setInstantiatedFromMemberTemplate(D);
2019
2020 // Make declarations visible in the appropriate context.
2021 if (!isFriend) {
2022 Owner->addDecl(InstTemplate);
2023 } else if (InstTemplate->getDeclContext()->isRecord() &&
2025 SemaRef.CheckFriendAccess(InstTemplate);
2026 }
2027
2028 return InstTemplate;
2029}
2030
2031Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
2032 CXXRecordDecl *PrevDecl = nullptr;
2033 if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2034 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
2035 PatternPrev,
2036 TemplateArgs);
2037 if (!Prev) return nullptr;
2038 PrevDecl = cast<CXXRecordDecl>(Prev);
2039 }
2040
2041 CXXRecordDecl *Record = nullptr;
2042 bool IsInjectedClassName = D->isInjectedClassName();
2043 if (D->isLambda())
2045 SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
2046 D->getLambdaDependencyKind(), D->isGenericLambda(),
2047 D->getLambdaCaptureDefault());
2048 else
2049 Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
2050 D->getBeginLoc(), D->getLocation(),
2051 D->getIdentifier(), PrevDecl,
2052 /*DelayTypeCreation=*/IsInjectedClassName);
2053 // Link the type of the injected-class-name to that of the outer class.
2054 if (IsInjectedClassName)
2055 (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
2056
2057 // Substitute the nested name specifier, if any.
2058 if (SubstQualifier(D, Record))
2059 return nullptr;
2060
2061 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
2062 StartingScope);
2063
2064 Record->setImplicit(D->isImplicit());
2065 // FIXME: Check against AS_none is an ugly hack to work around the issue that
2066 // the tag decls introduced by friend class declarations don't have an access
2067 // specifier. Remove once this area of the code gets sorted out.
2068 if (D->getAccess() != AS_none)
2069 Record->setAccess(D->getAccess());
2070 if (!IsInjectedClassName)
2071 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2072
2073 // If the original function was part of a friend declaration,
2074 // inherit its namespace state.
2075 if (D->getFriendObjectKind())
2076 Record->setObjectOfFriendDecl();
2077
2078 // Make sure that anonymous structs and unions are recorded.
2079 if (D->isAnonymousStructOrUnion())
2080 Record->setAnonymousStructOrUnion(true);
2081
2082 if (D->isLocalClass())
2084
2085 // Forward the mangling number from the template to the instantiated decl.
2087 SemaRef.Context.getManglingNumber(D));
2088
2089 // See if the old tag was defined along with a declarator.
2090 // If it did, mark the new tag as being associated with that declarator.
2093
2094 // See if the old tag was defined along with a typedef.
2095 // If it did, mark the new tag as being associated with that typedef.
2098
2099 Owner->addDecl(Record);
2100
2101 // DR1484 clarifies that the members of a local class are instantiated as part
2102 // of the instantiation of their enclosing entity.
2103 if (D->isCompleteDefinition() && D->isLocalClass()) {
2104 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
2105
2106 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
2108 /*Complain=*/true);
2109
2110 // For nested local classes, we will instantiate the members when we
2111 // reach the end of the outermost (non-nested) local class.
2112 if (!D->isCXXClassMember())
2113 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
2115
2116 // This class may have local implicit instantiations that need to be
2117 // performed within this scope.
2118 LocalInstantiations.perform();
2119 }
2120
2122
2123 if (IsInjectedClassName)
2124 assert(Record->isInjectedClassName() && "Broken injected-class-name");
2125
2126 return Record;
2127}
2128
2129/// Adjust the given function type for an instantiation of the
2130/// given declaration, to cope with modifications to the function's type that
2131/// aren't reflected in the type-source information.
2132///
2133/// \param D The declaration we're instantiating.
2134/// \param TInfo The already-instantiated type.
2136 FunctionDecl *D,
2137 TypeSourceInfo *TInfo) {
2138 const FunctionProtoType *OrigFunc
2139 = D->getType()->castAs<FunctionProtoType>();
2140 const FunctionProtoType *NewFunc
2141 = TInfo->getType()->castAs<FunctionProtoType>();
2142 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2143 return TInfo->getType();
2144
2145 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2146 NewEPI.ExtInfo = OrigFunc->getExtInfo();
2147 return Context.getFunctionType(NewFunc->getReturnType(),
2148 NewFunc->getParamTypes(), NewEPI);
2149}
2150
2151/// Normal class members are of more specific types and therefore
2152/// don't make it here. This function serves three purposes:
2153/// 1) instantiating function templates
2154/// 2) substituting friend and local function declarations
2155/// 3) substituting deduction guide declarations for nested class templates
2157 FunctionDecl *D, TemplateParameterList *TemplateParams,
2158 RewriteKind FunctionRewriteKind) {
2159 // Check whether there is already a function template specialization for
2160 // this declaration.
2161 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2162 bool isFriend;
2163 if (FunctionTemplate)
2164 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2165 else
2166 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2167
2168 // Friend function defined withing class template may stop being function
2169 // definition during AST merges from different modules, in this case decl
2170 // with function body should be used for instantiation.
2171 if (isFriend) {
2172 const FunctionDecl *Defn = nullptr;
2173 if (D->hasBody(Defn)) {
2174 D = const_cast<FunctionDecl *>(Defn);
2175 FunctionTemplate = Defn->getDescribedFunctionTemplate();
2176 }
2177 }
2178
2179 if (FunctionTemplate && !TemplateParams) {
2180 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2181
2182 void *InsertPos = nullptr;
2183 FunctionDecl *SpecFunc
2184 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2185
2186 // If we already have a function template specialization, return it.
2187 if (SpecFunc)
2188 return SpecFunc;
2189 }
2190
2191 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2192 Owner->isFunctionOrMethod() ||
2193 !(isa<Decl>(Owner) &&
2194 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2195 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2196
2197 ExplicitSpecifier InstantiatedExplicitSpecifier;
2198 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2199 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2200 TemplateArgs, DGuide->getExplicitSpecifier());
2201 if (InstantiatedExplicitSpecifier.isInvalid())
2202 return nullptr;
2203 }
2204
2206 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2207 if (!TInfo)
2208 return nullptr;
2210
2211 if (TemplateParams && TemplateParams->size()) {
2212 auto *LastParam =
2213 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2214 if (LastParam && LastParam->isImplicit() &&
2215 LastParam->hasTypeConstraint()) {
2216 // In abbreviated templates, the type-constraints of invented template
2217 // type parameters are instantiated with the function type, invalidating
2218 // the TemplateParameterList which relied on the template type parameter
2219 // not having a type constraint. Recreate the TemplateParameterList with
2220 // the updated parameter list.
2221 TemplateParams = TemplateParameterList::Create(
2222 SemaRef.Context, TemplateParams->getTemplateLoc(),
2223 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2224 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2225 }
2226 }
2227
2228 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2229 if (QualifierLoc) {
2230 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2231 TemplateArgs);
2232 if (!QualifierLoc)
2233 return nullptr;
2234 }
2235
2236 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2237
2238 // If we're instantiating a local function declaration, put the result
2239 // in the enclosing namespace; otherwise we need to find the instantiated
2240 // context.
2241 DeclContext *DC;
2242 if (D->isLocalExternDecl()) {
2243 DC = Owner;
2245 } else if (isFriend && QualifierLoc) {
2246 CXXScopeSpec SS;
2247 SS.Adopt(QualifierLoc);
2248 DC = SemaRef.computeDeclContext(SS);
2249 if (!DC) return nullptr;
2250 } else {
2252 TemplateArgs);
2253 }
2254
2255 DeclarationNameInfo NameInfo
2256 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2257
2258 if (FunctionRewriteKind != RewriteKind::None)
2259 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2260
2262 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2264 SemaRef.Context, DC, D->getInnerLocStart(),
2265 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2266 D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
2267 DGuide->getDeductionCandidateKind(), TrailingRequiresClause);
2268 Function->setAccess(D->getAccess());
2269 } else {
2271 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2272 D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(),
2273 D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(),
2274 TrailingRequiresClause);
2275 Function->setFriendConstraintRefersToEnclosingTemplate(
2276 D->FriendConstraintRefersToEnclosingTemplate());
2277 Function->setRangeEnd(D->getSourceRange().getEnd());
2278 }
2279
2280 if (D->isInlined())
2281 Function->setImplicitlyInline();
2282
2283 if (QualifierLoc)
2284 Function->setQualifierInfo(QualifierLoc);
2285
2286 if (D->isLocalExternDecl())
2287 Function->setLocalExternDecl();
2288
2289 DeclContext *LexicalDC = Owner;
2290 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2291 assert(D->getDeclContext()->isFileContext());
2292 LexicalDC = D->getDeclContext();
2293 }
2294 else if (D->isLocalExternDecl()) {
2295 LexicalDC = SemaRef.CurContext;
2296 }
2297
2298 Function->setLexicalDeclContext(LexicalDC);
2299
2300 // Attach the parameters
2301 for (unsigned P = 0; P < Params.size(); ++P)
2302 if (Params[P])
2303 Params[P]->setOwningFunction(Function);
2304 Function->setParams(Params);
2305
2306 if (TrailingRequiresClause)
2307 Function->setTrailingRequiresClause(TrailingRequiresClause);
2308
2309 if (TemplateParams) {
2310 // Our resulting instantiation is actually a function template, since we
2311 // are substituting only the outer template parameters. For example, given
2312 //
2313 // template<typename T>
2314 // struct X {
2315 // template<typename U> friend void f(T, U);
2316 // };
2317 //
2318 // X<int> x;
2319 //
2320 // We are instantiating the friend function template "f" within X<int>,
2321 // which means substituting int for T, but leaving "f" as a friend function
2322 // template.
2323 // Build the function template itself.
2324 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2325 Function->getLocation(),
2326 Function->getDeclName(),
2327 TemplateParams, Function);
2328 Function->setDescribedFunctionTemplate(FunctionTemplate);
2329
2330 FunctionTemplate->setLexicalDeclContext(LexicalDC);
2331
2332 if (isFriend && D->isThisDeclarationADefinition()) {
2333 FunctionTemplate->setInstantiatedFromMemberTemplate(
2334 D->getDescribedFunctionTemplate());
2335 }
2336 } else if (FunctionTemplate &&
2337 SemaRef.CodeSynthesisContexts.back().Kind !=
2339 // Record this function template specialization.
2340 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2341 Function->setFunctionTemplateSpecialization(FunctionTemplate,
2343 Innermost),
2344 /*InsertPos=*/nullptr);
2345 } else if (FunctionRewriteKind == RewriteKind::None) {
2346 if (isFriend && D->isThisDeclarationADefinition()) {
2347 // Do not connect the friend to the template unless it's actually a
2348 // definition. We don't want non-template functions to be marked as being
2349 // template instantiations.
2350 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2351 } else if (!isFriend) {
2352 // If this is not a function template, and this is not a friend (that is,
2353 // this is a locally declared function), save the instantiation
2354 // relationship for the purposes of constraint instantiation.
2355 Function->setInstantiatedFromDecl(D);
2356 }
2357 }
2358
2359 if (isFriend) {
2360 Function->setObjectOfFriendDecl();
2361 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2362 FT->setObjectOfFriendDecl();
2363 }
2364
2366 Function->setInvalidDecl();
2367
2368 bool IsExplicitSpecialization = false;
2369
2371 SemaRef, Function->getDeclName(), SourceLocation(),
2374 D->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
2375 : SemaRef.forRedeclarationInCurContext());
2376
2378 D->getDependentSpecializationInfo()) {
2379 assert(isFriend && "dependent specialization info on "
2380 "non-member non-friend function?");
2381
2382 // Instantiate the explicit template arguments.
2383 TemplateArgumentListInfo ExplicitArgs;
2384 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2385 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2386 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2387 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2388 ExplicitArgs))
2389 return nullptr;
2390 }
2391
2392 // Map the candidates for the primary template to their instantiations.
2393 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2394 if (NamedDecl *ND =
2395 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2396 Previous.addDecl(ND);
2397 else
2398 return nullptr;
2399 }
2400
2402 Function,
2403 DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2404 Previous))
2405 Function->setInvalidDecl();
2406
2407 IsExplicitSpecialization = true;
2408 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2409 D->getTemplateSpecializationArgsAsWritten()) {
2410 // The name of this function was written as a template-id.
2411 SemaRef.LookupQualifiedName(Previous, DC);
2412
2413 // Instantiate the explicit template arguments.
2414 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2415 ArgsWritten->getRAngleLoc());
2416 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2417 ExplicitArgs))
2418 return nullptr;
2419
2421 &ExplicitArgs,
2422 Previous))
2423 Function->setInvalidDecl();
2424
2425 IsExplicitSpecialization = true;
2426 } else if (TemplateParams || !FunctionTemplate) {
2427 // Look only into the namespace where the friend would be declared to
2428 // find a previous declaration. This is the innermost enclosing namespace,
2429 // as described in ActOnFriendFunctionDecl.
2431
2432 // In C++, the previous declaration we find might be a tag type
2433 // (class or enum). In this case, the new declaration will hide the
2434 // tag type. Note that this does not apply if we're declaring a
2435 // typedef (C++ [dcl.typedef]p4).
2436 if (Previous.isSingleTagDecl())
2437 Previous.clear();
2438
2439 // Filter out previous declarations that don't match the scope. The only
2440 // effect this has is to remove declarations found in inline namespaces
2441 // for friend declarations with unqualified names.
2442 if (isFriend && !QualifierLoc) {
2443 SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2444 /*ConsiderLinkage=*/ true,
2445 QualifierLoc.hasQualifier());
2446 }
2447 }
2448
2449 // Per [temp.inst], default arguments in function declarations at local scope
2450 // are instantiated along with the enclosing declaration. For example:
2451 //
2452 // template<typename T>
2453 // void ft() {
2454 // void f(int = []{ return T::value; }());
2455 // }
2456 // template void ft<int>(); // error: type 'int' cannot be used prior
2457 // to '::' because it has no members
2458 //
2459 // The error is issued during instantiation of ft<int>() because substitution
2460 // into the default argument fails; the default argument is instantiated even
2461 // though it is never used.
2462 if (Function->isLocalExternDecl()) {
2463 for (ParmVarDecl *PVD : Function->parameters()) {
2464 if (!PVD->hasDefaultArg())
2465 continue;
2466 if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2467 // If substitution fails, the default argument is set to a
2468 // RecoveryExpr that wraps the uninstantiated default argument so
2469 // that downstream diagnostics are omitted.
2470 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
2471 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2472 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2473 { UninstExpr }, UninstExpr->getType());
2474 if (ErrorResult.isUsable())
2475 PVD->setDefaultArg(ErrorResult.get());
2476 }
2477 }
2478 }
2479
2480 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2481 IsExplicitSpecialization,
2482 Function->isThisDeclarationADefinition());
2483
2484 // Check the template parameter list against the previous declaration. The
2485 // goal here is to pick up default arguments added since the friend was
2486 // declared; we know the template parameter lists match, since otherwise
2487 // we would not have picked this template as the previous declaration.
2488 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2490 TemplateParams,
2491 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2492 Function->isThisDeclarationADefinition()
2495 }
2496
2497 // If we're introducing a friend definition after the first use, trigger
2498 // instantiation.
2499 // FIXME: If this is a friend function template definition, we should check
2500 // to see if any specializations have been used.
2501 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2502 if (MemberSpecializationInfo *MSInfo =
2503 Function->getMemberSpecializationInfo()) {
2504 if (MSInfo->getPointOfInstantiation().isInvalid()) {
2505 SourceLocation Loc = D->getLocation(); // FIXME
2506 MSInfo->setPointOfInstantiation(Loc);
2507 SemaRef.PendingLocalImplicitInstantiations.push_back(
2508 std::make_pair(Function, Loc));
2509 }
2510 }
2511 }
2512
2513 if (D->isExplicitlyDefaulted()) {
2515 return nullptr;
2516 }
2517 if (D->isDeleted())
2518 SemaRef.SetDeclDeleted(Function, D->getLocation(), D->getDeletedMessage());
2519
2520 NamedDecl *PrincipalDecl =
2521 (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2522
2523 // If this declaration lives in a different context from its lexical context,
2524 // add it to the corresponding lookup table.
2525 if (isFriend ||
2526 (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2527 DC->makeDeclVisibleInContext(PrincipalDecl);
2528
2529 if (Function->isOverloadedOperator() && !DC->isRecord() &&
2531 PrincipalDecl->setNonMemberOperator();
2532
2533 return Function;
2534}
2535
2537 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2538 RewriteKind FunctionRewriteKind) {
2539 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2540 if (FunctionTemplate && !TemplateParams) {
2541 // We are creating a function template specialization from a function
2542 // template. Check whether there is already a function template
2543 // specialization for this particular set of template arguments.
2544 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2545
2546 void *InsertPos = nullptr;
2547 FunctionDecl *SpecFunc
2548 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2549
2550 // If we already have a function template specialization, return it.
2551 if (SpecFunc)
2552 return SpecFunc;
2553 }
2554
2555 bool isFriend;
2556 if (FunctionTemplate)
2557 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2558 else
2559 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2560
2561 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2562 !(isa<Decl>(Owner) &&
2563 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2564 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2565
2567 SemaRef, const_cast<CXXMethodDecl *>(D), TemplateArgs, Scope);
2568
2569 // Instantiate enclosing template arguments for friends.
2571 unsigned NumTempParamLists = 0;
2572 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2573 TempParamLists.resize(NumTempParamLists);
2574 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2575 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2576 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2577 if (!InstParams)
2578 return nullptr;
2579 TempParamLists[I] = InstParams;
2580 }
2581 }
2582
2583 auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(D);
2584 // deduction guides need this
2585 const bool CouldInstantiate =
2586 InstantiatedExplicitSpecifier.getExpr() == nullptr ||
2587 !InstantiatedExplicitSpecifier.getExpr()->isValueDependent();
2588
2589 // Delay the instantiation of the explicit-specifier until after the
2590 // constraints are checked during template argument deduction.
2591 if (CouldInstantiate ||
2592 SemaRef.CodeSynthesisContexts.back().Kind !=
2594 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2595 TemplateArgs, InstantiatedExplicitSpecifier);
2596
2597 if (InstantiatedExplicitSpecifier.isInvalid())
2598 return nullptr;
2599 } else {
2600 InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved);
2601 }
2602
2603 // Implicit destructors/constructors created for local classes in
2604 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2605 // Unfortunately there isn't enough context in those functions to
2606 // conditionally populate the TSI without breaking non-template related use
2607 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2608 // a proper transformation.
2609 if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
2610 !D->getTypeSourceInfo() &&
2611 isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2612 TypeSourceInfo *TSI =
2613 SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
2614 D->setTypeSourceInfo(TSI);
2615 }
2616
2618 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2619 if (!TInfo)
2620 return nullptr;
2622
2623 if (TemplateParams && TemplateParams->size()) {
2624 auto *LastParam =
2625 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2626 if (LastParam && LastParam->isImplicit() &&
2627 LastParam->hasTypeConstraint()) {
2628 // In abbreviated templates, the type-constraints of invented template
2629 // type parameters are instantiated with the function type, invalidating
2630 // the TemplateParameterList which relied on the template type parameter
2631 // not having a type constraint. Recreate the TemplateParameterList with
2632 // the updated parameter list.
2633 TemplateParams = TemplateParameterList::Create(
2634 SemaRef.Context, TemplateParams->getTemplateLoc(),
2635 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2636 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2637 }
2638 }
2639
2640 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2641 if (QualifierLoc) {
2642 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2643 TemplateArgs);
2644 if (!QualifierLoc)
2645 return nullptr;
2646 }
2647
2648 DeclContext *DC = Owner;
2649 if (isFriend) {
2650 if (QualifierLoc) {
2651 CXXScopeSpec SS;
2652 SS.Adopt(QualifierLoc);
2653 DC = SemaRef.computeDeclContext(SS);
2654
2655 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2656 return nullptr;
2657 } else {
2658 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2659 D->getDeclContext(),
2660 TemplateArgs);
2661 }
2662 if (!DC) return nullptr;
2663 }
2664
2665 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2666 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2667
2668 DeclarationNameInfo NameInfo
2669 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2670
2671 if (FunctionRewriteKind != RewriteKind::None)
2672 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2673
2674 // Build the instantiated method declaration.
2675 CXXMethodDecl *Method = nullptr;
2676
2677 SourceLocation StartLoc = D->getInnerLocStart();
2678 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2680 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2681 InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2682 Constructor->isInlineSpecified(), false,
2683 Constructor->getConstexprKind(), InheritedConstructor(),
2684 TrailingRequiresClause);
2685 Method->setRangeEnd(Constructor->getEndLoc());
2686 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2688 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2689 Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2690 Destructor->getConstexprKind(), TrailingRequiresClause);
2691 Method->setIneligibleOrNotSelected(true);
2692 Method->setRangeEnd(Destructor->getEndLoc());
2694 SemaRef.Context.getCanonicalType(
2695 SemaRef.Context.getTypeDeclType(Record))));
2696 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2698 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2699 Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2700 InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2701 Conversion->getEndLoc(), TrailingRequiresClause);
2702 } else {
2703 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2704 Method = CXXMethodDecl::Create(
2705 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2706 D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(),
2707 D->getEndLoc(), TrailingRequiresClause);
2708 }
2709
2710 if (D->isInlined())
2711 Method->setImplicitlyInline();
2712
2713 if (QualifierLoc)
2714 Method->setQualifierInfo(QualifierLoc);
2715
2716 if (TemplateParams) {
2717 // Our resulting instantiation is actually a function template, since we
2718 // are substituting only the outer template parameters. For example, given
2719 //
2720 // template<typename T>
2721 // struct X {
2722 // template<typename U> void f(T, U);
2723 // };
2724 //
2725 // X<int> x;
2726 //
2727 // We are instantiating the member template "f" within X<int>, which means
2728 // substituting int for T, but leaving "f" as a member function template.
2729 // Build the function template itself.
2730 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2731 Method->getLocation(),
2732 Method->getDeclName(),
2733 TemplateParams, Method);
2734 if (isFriend) {
2735 FunctionTemplate->setLexicalDeclContext(Owner);
2736 FunctionTemplate->setObjectOfFriendDecl();
2737 } else if (D->isOutOfLine())
2738 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2739 Method->setDescribedFunctionTemplate(FunctionTemplate);
2740 } else if (FunctionTemplate) {
2741 // Record this function template specialization.
2742 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2743 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2745 Innermost),
2746 /*InsertPos=*/nullptr);
2747 } else if (!isFriend && FunctionRewriteKind == RewriteKind::None) {
2748 // Record that this is an instantiation of a member function.
2750 }
2751
2752 // If we are instantiating a member function defined
2753 // out-of-line, the instantiation will have the same lexical
2754 // context (which will be a namespace scope) as the template.
2755 if (isFriend) {
2756 if (NumTempParamLists)
2758 SemaRef.Context,
2759 llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
2760
2761 Method->setLexicalDeclContext(Owner);
2762 Method->setObjectOfFriendDecl();
2763 } else if (D->isOutOfLine())
2765
2766 // Attach the parameters
2767 for (unsigned P = 0; P < Params.size(); ++P)
2768 Params[P]->setOwningFunction(Method);
2769 Method->setParams(Params);
2770
2771 if (InitMethodInstantiation(Method, D))
2772 Method->setInvalidDecl();
2773
2775 RedeclarationKind::ForExternalRedeclaration);
2776
2777 bool IsExplicitSpecialization = false;
2778
2779 // If the name of this function was written as a template-id, instantiate
2780 // the explicit template arguments.
2782 D->getDependentSpecializationInfo()) {
2783 // Instantiate the explicit template arguments.
2784 TemplateArgumentListInfo ExplicitArgs;
2785 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2786 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2787 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2788 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2789 ExplicitArgs))
2790 return nullptr;
2791 }
2792
2793 // Map the candidates for the primary template to their instantiations.
2794 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2795 if (NamedDecl *ND =
2796 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2797 Previous.addDecl(ND);
2798 else
2799 return nullptr;
2800 }
2801
2803 Method, DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2804 Previous))
2805 Method->setInvalidDecl();
2806
2807 IsExplicitSpecialization = true;
2808 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2809 D->getTemplateSpecializationArgsAsWritten()) {
2810 SemaRef.LookupQualifiedName(Previous, DC);
2811
2812 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2813 ArgsWritten->getRAngleLoc());
2814
2815 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2816 ExplicitArgs))
2817 return nullptr;
2818
2819 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2820 &ExplicitArgs,
2821 Previous))
2822 Method->setInvalidDecl();
2823
2824 IsExplicitSpecialization = true;
2825 } else if (!FunctionTemplate || TemplateParams || isFriend) {
2827
2828 // In C++, the previous declaration we find might be a tag type
2829 // (class or enum). In this case, the new declaration will hide the
2830 // tag type. Note that this does not apply if we're declaring a
2831 // typedef (C++ [dcl.typedef]p4).
2832 if (Previous.isSingleTagDecl())
2833 Previous.clear();
2834 }
2835
2836 // Per [temp.inst], default arguments in member functions of local classes
2837 // are instantiated along with the member function declaration. For example:
2838 //
2839 // template<typename T>
2840 // void ft() {
2841 // struct lc {
2842 // int operator()(int p = []{ return T::value; }());
2843 // };
2844 // }
2845 // template void ft<int>(); // error: type 'int' cannot be used prior
2846 // to '::'because it has no members
2847 //
2848 // The error is issued during instantiation of ft<int>()::lc::operator()
2849 // because substitution into the default argument fails; the default argument
2850 // is instantiated even though it is never used.
2852 for (unsigned P = 0; P < Params.size(); ++P) {
2853 if (!Params[P]->hasDefaultArg())
2854 continue;
2855 if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
2856 // If substitution fails, the default argument is set to a
2857 // RecoveryExpr that wraps the uninstantiated default argument so
2858 // that downstream diagnostics are omitted.
2859 Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
2860 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2861 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2862 { UninstExpr }, UninstExpr->getType());
2863 if (ErrorResult.isUsable())
2864 Params[P]->setDefaultArg(ErrorResult.get());
2865 }
2866 }
2867 }
2868
2869 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2870 IsExplicitSpecialization,
2872
2873 if (D->isPureVirtual())
2874 SemaRef.CheckPureMethod(Method, SourceRange());
2875
2876 // Propagate access. For a non-friend declaration, the access is
2877 // whatever we're propagating from. For a friend, it should be the
2878 // previous declaration we just found.
2879 if (isFriend && Method->getPreviousDecl())
2880 Method->setAccess(Method->getPreviousDecl()->getAccess());
2881 else
2882 Method->setAccess(D->getAccess());
2883 if (FunctionTemplate)
2884 FunctionTemplate->setAccess(Method->getAccess());
2885
2886 SemaRef.CheckOverrideControl(Method);
2887
2888 // If a function is defined as defaulted or deleted, mark it as such now.
2889 if (D->isExplicitlyDefaulted()) {
2890 if (SubstDefaultedFunction(Method, D))
2891 return nullptr;
2892 }
2893 if (D->isDeletedAsWritten())
2894 SemaRef.SetDeclDeleted(Method, Method->getLocation(),
2895 D->getDeletedMessage());
2896
2897 // If this is an explicit specialization, mark the implicitly-instantiated
2898 // template specialization as being an explicit specialization too.
2899 // FIXME: Is this necessary?
2900 if (IsExplicitSpecialization && !isFriend)
2901 SemaRef.CompleteMemberSpecialization(Method, Previous);
2902
2903 // If the method is a special member function, we need to mark it as
2904 // ineligible so that Owner->addDecl() won't mark the class as non trivial.
2905 // At the end of the class instantiation, we calculate eligibility again and
2906 // then we adjust trivility if needed.
2907 // We need this check to happen only after the method parameters are set,
2908 // because being e.g. a copy constructor depends on the instantiated
2909 // arguments.
2910 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
2911 if (Constructor->isDefaultConstructor() ||
2912 Constructor->isCopyOrMoveConstructor())
2913 Method->setIneligibleOrNotSelected(true);
2914 } else if (Method->isCopyAssignmentOperator() ||
2915 Method->isMoveAssignmentOperator()) {
2916 Method->setIneligibleOrNotSelected(true);
2917 }
2918
2919 // If there's a function template, let our caller handle it.
2920 if (FunctionTemplate) {
2921 // do nothing
2922
2923 // Don't hide a (potentially) valid declaration with an invalid one.
2924 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2925 // do nothing
2926
2927 // Otherwise, check access to friends and make them visible.
2928 } else if (isFriend) {
2929 // We only need to re-check access for methods which we didn't
2930 // manage to match during parsing.
2931 if (!D->getPreviousDecl())
2932 SemaRef.CheckFriendAccess(Method);
2933
2934 Record->makeDeclVisibleInContext(Method);
2935
2936 // Otherwise, add the declaration. We don't need to do this for
2937 // class-scope specializations because we'll have matched them with
2938 // the appropriate template.
2939 } else {
2940 Owner->addDecl(Method);
2941 }
2942
2943 // PR17480: Honor the used attribute to instantiate member function
2944 // definitions
2945 if (Method->hasAttr<UsedAttr>()) {
2946 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2948 if (const MemberSpecializationInfo *MSInfo =
2949 A->getMemberSpecializationInfo())
2950 Loc = MSInfo->getPointOfInstantiation();
2951 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2952 Loc = Spec->getPointOfInstantiation();
2953 SemaRef.MarkFunctionReferenced(Loc, Method);
2954 }
2955 }
2956
2957 return Method;
2958}
2959
2960Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2961 return VisitCXXMethodDecl(D);
2962}
2963
2964Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2965 return VisitCXXMethodDecl(D);
2966}
2967
2968Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2969 return VisitCXXMethodDecl(D);
2970}
2971
2972Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2973 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
2974 std::nullopt,
2975 /*ExpectParameterPack=*/false);
2976}
2977
2978Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2980 assert(D->getTypeForDecl()->isTemplateTypeParmType());
2981
2982 std::optional<unsigned> NumExpanded;
2983
2984 if (const TypeConstraint *TC = D->getTypeConstraint()) {
2985 if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2986 assert(TC->getTemplateArgsAsWritten() &&
2987 "type parameter can only be an expansion when explicit arguments "
2988 "are specified");
2989 // The template type parameter pack's type is a pack expansion of types.
2990 // Determine whether we need to expand this parameter pack into separate
2991 // types.
2993 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2994 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2995
2996 // Determine whether the set of unexpanded parameter packs can and should
2997 // be expanded.
2998 bool Expand = true;
2999 bool RetainExpansion = false;
3001 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3002 ->getEllipsisLoc(),
3003 SourceRange(TC->getConceptNameLoc(),
3004 TC->hasExplicitTemplateArgs() ?
3005 TC->getTemplateArgsAsWritten()->getRAngleLoc() :
3006 TC->getConceptNameInfo().getEndLoc()),
3007 Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
3008 return nullptr;
3009 }
3010 }
3011
3013 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
3014 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
3015 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
3016 D->hasTypeConstraint(), NumExpanded);
3017
3018 Inst->setAccess(AS_public);
3019 Inst->setImplicit(D->isImplicit());
3020 if (auto *TC = D->getTypeConstraint()) {
3021 if (!D->isImplicit()) {
3022 // Invented template parameter type constraints will be instantiated
3023 // with the corresponding auto-typed parameter as it might reference
3024 // other parameters.
3025 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
3026 EvaluateConstraints))
3027 return nullptr;
3028 }
3029 }
3030 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3031 TemplateArgumentLoc Output;
3032 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3033 Output))
3034 Inst->setDefaultArgument(SemaRef.getASTContext(), Output);
3035 }
3036
3037 // Introduce this template parameter's instantiation into the instantiation
3038 // scope.
3040
3041 return Inst;
3042}
3043
3044Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
3046 // Substitute into the type of the non-type template parameter.
3047 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
3048 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
3049 SmallVector<QualType, 4> ExpandedParameterPackTypes;
3050 bool IsExpandedParameterPack = false;
3051 TypeSourceInfo *DI;
3052 QualType T;
3053 bool Invalid = false;
3054
3055 if (D->isExpandedParameterPack()) {
3056 // The non-type template parameter pack is an already-expanded pack
3057 // expansion of types. Substitute into each of the expanded types.
3058 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
3059 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
3060 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
3061 TypeSourceInfo *NewDI =
3062 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
3063 D->getLocation(), D->getDeclName());
3064 if (!NewDI)
3065 return nullptr;
3066
3067 QualType NewT =
3069 if (NewT.isNull())
3070 return nullptr;
3071
3072 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3073 ExpandedParameterPackTypes.push_back(NewT);
3074 }
3075
3076 IsExpandedParameterPack = true;
3077 DI = D->getTypeSourceInfo();
3078 T = DI->getType();
3079 } else if (D->isPackExpansion()) {
3080 // The non-type template parameter pack's type is a pack expansion of types.
3081 // Determine whether we need to expand this parameter pack into separate
3082 // types.
3084 TypeLoc Pattern = Expansion.getPatternLoc();
3086 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
3087
3088 // Determine whether the set of unexpanded parameter packs can and should
3089 // be expanded.
3090 bool Expand = true;
3091 bool RetainExpansion = false;
3092 std::optional<unsigned> OrigNumExpansions =
3093 Expansion.getTypePtr()->getNumExpansions();
3094 std::optional<unsigned> NumExpansions = OrigNumExpansions;
3095 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
3096 Pattern.getSourceRange(),
3097 Unexpanded,
3098 TemplateArgs,
3099 Expand, RetainExpansion,
3100 NumExpansions))
3101 return nullptr;
3102
3103 if (Expand) {
3104 for (unsigned I = 0; I != *NumExpansions; ++I) {
3105 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3106 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
3107 D->getLocation(),
3108 D->getDeclName());
3109 if (!NewDI)
3110 return nullptr;
3111
3112 QualType NewT =
3114 if (NewT.isNull())
3115 return nullptr;
3116
3117 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3118 ExpandedParameterPackTypes.push_back(NewT);
3119 }
3120
3121 // Note that we have an expanded parameter pack. The "type" of this
3122 // expanded parameter pack is the original expansion type, but callers
3123 // will end up using the expanded parameter pack types for type-checking.
3124 IsExpandedParameterPack = true;
3125 DI = D->getTypeSourceInfo();
3126 T = DI->getType();
3127 } else {
3128 // We cannot fully expand the pack expansion now, so substitute into the
3129 // pattern and create a new pack expansion type.
3130 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3131 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
3132 D->getLocation(),
3133 D->getDeclName());
3134 if (!NewPattern)
3135 return nullptr;
3136
3137 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
3138 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
3139 NumExpansions);
3140 if (!DI)
3141 return nullptr;
3142
3143 T = DI->getType();
3144 }
3145 } else {
3146 // Simple case: substitution into a parameter that is not a parameter pack.
3147 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3148 D->getLocation(), D->getDeclName());
3149 if (!DI)
3150 return nullptr;
3151
3152 // Check that this type is acceptable for a non-type template parameter.
3154 if (T.isNull()) {
3155 T = SemaRef.Context.IntTy;
3156 Invalid = true;
3157 }
3158 }
3159
3161 if (IsExpandedParameterPack)
3163 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3164 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3165 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
3166 ExpandedParameterPackTypesAsWritten);
3167 else
3169 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3170 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3171 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
3172
3173 if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
3174 if (AutoLoc.isConstrained()) {
3175 SourceLocation EllipsisLoc;
3176 if (IsExpandedParameterPack)
3177 EllipsisLoc =
3178 DI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
3179 else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
3180 D->getPlaceholderTypeConstraint()))
3181 EllipsisLoc = Constraint->getEllipsisLoc();
3182 // Note: We attach the uninstantiated constriant here, so that it can be
3183 // instantiated relative to the top level, like all our other
3184 // constraints.
3185 if (SemaRef.AttachTypeConstraint(AutoLoc, /*NewConstrainedParm=*/Param,
3186 /*OrigConstrainedParm=*/D, EllipsisLoc))
3187 Invalid = true;
3188 }
3189
3190 Param->setAccess(AS_public);
3191 Param->setImplicit(D->isImplicit());
3192 if (Invalid)
3193 Param->setInvalidDecl();
3194
3195 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3196 EnterExpressionEvaluationContext ConstantEvaluated(
3199 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3200 Result))
3201 Param->setDefaultArgument(SemaRef.Context, Result);
3202 }
3203
3204 // Introduce this template parameter's instantiation into the instantiation
3205 // scope.
3207 return Param;
3208}
3209
3211 Sema &S,
3212 TemplateParameterList *Params,
3214 for (const auto &P : *Params) {
3215 if (P->isTemplateParameterPack())
3216 continue;
3217 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3218 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3219 Unexpanded);
3220 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3221 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3222 Unexpanded);
3223 }
3224}
3225
3226Decl *
3227TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3229 // Instantiate the template parameter list of the template template parameter.
3230 TemplateParameterList *TempParams = D->getTemplateParameters();
3231 TemplateParameterList *InstParams;
3233
3234 bool IsExpandedParameterPack = false;
3235
3236 if (D->isExpandedParameterPack()) {
3237 // The template template parameter pack is an already-expanded pack
3238 // expansion of template parameters. Substitute into each of the expanded
3239 // parameters.
3240 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3241 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3242 I != N; ++I) {
3244 TemplateParameterList *Expansion =
3245 SubstTemplateParams(D->getExpansionTemplateParameters(I));
3246 if (!Expansion)
3247 return nullptr;
3248 ExpandedParams.push_back(Expansion);
3249 }
3250
3251 IsExpandedParameterPack = true;
3252 InstParams = TempParams;
3253 } else if (D->isPackExpansion()) {
3254 // The template template parameter pack expands to a pack of template
3255 // template parameters. Determine whether we need to expand this parameter
3256 // pack into separate parameters.
3258 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
3259 Unexpanded);
3260
3261 // Determine whether the set of unexpanded parameter packs can and should
3262 // be expanded.
3263 bool Expand = true;
3264 bool RetainExpansion = false;
3265 std::optional<unsigned> NumExpansions;
3267 TempParams->getSourceRange(),
3268 Unexpanded,
3269 TemplateArgs,
3270 Expand, RetainExpansion,
3271 NumExpansions))
3272 return nullptr;
3273
3274 if (Expand) {
3275 for (unsigned I = 0; I != *NumExpansions; ++I) {
3276 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3278 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3279 if (!Expansion)
3280 return nullptr;
3281 ExpandedParams.push_back(Expansion);
3282 }
3283
3284 // Note that we have an expanded parameter pack. The "type" of this
3285 // expanded parameter pack is the original expansion type, but callers
3286 // will end up using the expanded parameter pack types for type-checking.
3287 IsExpandedParameterPack = true;
3288 InstParams = TempParams;
3289 } else {
3290 // We cannot fully expand the pack expansion now, so just substitute
3291 // into the pattern.
3292 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3293
3295 InstParams = SubstTemplateParams(TempParams);
3296 if (!InstParams)
3297 return nullptr;
3298 }
3299 } else {
3300 // Perform the actual substitution of template parameters within a new,
3301 // local instantiation scope.
3303 InstParams = SubstTemplateParams(TempParams);
3304 if (!InstParams)
3305 return nullptr;
3306 }
3307
3308 // Build the template template parameter.
3310 if (IsExpandedParameterPack)
3312 SemaRef.Context, Owner, D->getLocation(),
3313 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3314 D->getPosition(), D->getIdentifier(), D->wasDeclaredWithTypename(),
3315 InstParams, ExpandedParams);
3316 else
3318 SemaRef.Context, Owner, D->getLocation(),
3319 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3320 D->getPosition(), D->isParameterPack(), D->getIdentifier(),
3321 D->wasDeclaredWithTypename(), InstParams);
3322 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3323 NestedNameSpecifierLoc QualifierLoc =
3324 D->getDefaultArgument().getTemplateQualifierLoc();
3325 QualifierLoc =
3326 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3327 TemplateName TName = SemaRef.SubstTemplateName(
3328 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3329 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3330 if (!TName.isNull())
3331 Param->setDefaultArgument(
3332 SemaRef.Context,
3334 D->getDefaultArgument().getTemplateQualifierLoc(),
3335 D->getDefaultArgument().getTemplateNameLoc()));
3336 }
3337 Param->setAccess(AS_public);
3338 Param->setImplicit(D->isImplicit());
3339
3340 // Introduce this template parameter's instantiation into the instantiation
3341 // scope.
3343
3344 return Param;
3345}
3346
3347Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3348 // Using directives are never dependent (and never contain any types or
3349 // expressions), so they require no explicit instantiation work.
3350
3351 UsingDirectiveDecl *Inst
3352 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3353 D->getNamespaceKeyLocation(),
3354 D->getQualifierLoc(),
3355 D->getIdentLocation(),
3356 D->getNominatedNamespace(),
3357 D->getCommonAncestor());
3358
3359 // Add the using directive to its declaration context
3360 // only if this is not a function or method.
3361 if (!Owner->isFunctionOrMethod())
3362 Owner->addDecl(Inst);
3363
3364 return Inst;
3365}
3366
3368 BaseUsingDecl *Inst,
3369 LookupResult *Lookup) {
3370
3371 bool isFunctionScope = Owner->isFunctionOrMethod();
3372
3373 for (auto *Shadow : D->shadows()) {
3374 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3375 // reconstruct it in the case where it matters. Hm, can we extract it from
3376 // the DeclSpec when parsing and save it in the UsingDecl itself?
3377 NamedDecl *OldTarget = Shadow->getTargetDecl();
3378 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3379 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3380 OldTarget = BaseShadow;
3381
3382 NamedDecl *InstTarget = nullptr;
3383 if (auto *EmptyD =
3384 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3386 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3387 } else {
3388 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3389 Shadow->getLocation(), OldTarget, TemplateArgs));
3390 }
3391 if (!InstTarget)
3392 return nullptr;
3393
3394 UsingShadowDecl *PrevDecl = nullptr;
3395 if (Lookup &&
3396 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3397 continue;
3398
3399 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3400 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3401 Shadow->getLocation(), OldPrev, TemplateArgs));
3402
3403 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3404 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3405 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3406
3407 if (isFunctionScope)
3408 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3409 }
3410
3411 return Inst;
3412}
3413
3414Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3415
3416 // The nested name specifier may be dependent, for example
3417 // template <typename T> struct t {
3418 // struct s1 { T f1(); };
3419 // struct s2 : s1 { using s1::f1; };
3420 // };
3421 // template struct t<int>;
3422 // Here, in using s1::f1, s1 refers to t<T>::s1;
3423 // we need to substitute for t<int>::s1.
3424 NestedNameSpecifierLoc QualifierLoc
3425 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3426 TemplateArgs);
3427 if (!QualifierLoc)
3428 return nullptr;
3429
3430 // For an inheriting constructor declaration, the name of the using
3431 // declaration is the name of a constructor in this class, not in the
3432 // base class.
3433 DeclarationNameInfo NameInfo = D->getNameInfo();
3435 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3437 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3438
3439 // We only need to do redeclaration lookups if we're in a class scope (in
3440 // fact, it's not really even possible in non-class scopes).
3441 bool CheckRedeclaration = Owner->isRecord();
3442 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3443 RedeclarationKind::ForVisibleRedeclaration);
3444
3445 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3446 D->getUsingLoc(),
3447 QualifierLoc,
3448 NameInfo,
3449 D->hasTypename());
3450
3451 CXXScopeSpec SS;
3452 SS.Adopt(QualifierLoc);
3453 if (CheckRedeclaration) {
3454 Prev.setHideTags(false);
3455 SemaRef.LookupQualifiedName(Prev, Owner);
3456
3457 // Check for invalid redeclarations.
3458 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3459 D->hasTypename(), SS,
3460 D->getLocation(), Prev))
3461 NewUD->setInvalidDecl();
3462 }
3463
3464 if (!NewUD->isInvalidDecl() &&
3465 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3466 NameInfo, D->getLocation(), nullptr, D))
3467 NewUD->setInvalidDecl();
3468
3469 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3470 NewUD->setAccess(D->getAccess());
3471 Owner->addDecl(NewUD);
3472
3473 // Don't process the shadow decls for an invalid decl.
3474 if (NewUD->isInvalidDecl())
3475 return NewUD;
3476
3477 // If the using scope was dependent, or we had dependent bases, we need to
3478 // recheck the inheritance
3481
3482 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3483}
3484
3485Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3486 // Cannot be a dependent type, but still could be an instantiation
3487 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3488 D->getLocation(), D->getEnumDecl(), TemplateArgs));
3489
3490 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3491 return nullptr;
3492
3493 TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3494 D->getLocation(), D->getDeclName());
3495
3496 if (!TSI)
3497 return nullptr;
3498
3499 UsingEnumDecl *NewUD =
3500 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3501 D->getEnumLoc(), D->getLocation(), TSI);
3502
3504 NewUD->setAccess(D->getAccess());
3505 Owner->addDecl(NewUD);
3506
3507 // Don't process the shadow decls for an invalid decl.
3508 if (NewUD->isInvalidDecl())
3509 return NewUD;
3510
3511 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3512 // cannot be dependent, and will therefore have been checked during template
3513 // definition.
3514
3515 return VisitBaseUsingDecls(D, NewUD, nullptr);
3516}
3517
3518Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3519 // Ignore these; we handle them in bulk when processing the UsingDecl.
3520 return nullptr;
3521}
3522
3523Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3525 // Ignore these; we handle them in bulk when processing the UsingDecl.
3526 return nullptr;
3527}
3528
3529template <typename T>
3530Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3531 T *D, bool InstantiatingPackElement) {
3532 // If this is a pack expansion, expand it now.
3533 if (D->isPackExpansion() && !InstantiatingPackElement) {
3535 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3536 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3537
3538 // Determine whether the set of unexpanded parameter packs can and should
3539 // be expanded.
3540 bool Expand = true;
3541 bool RetainExpansion = false;
3542 std::optional<unsigned> NumExpansions;
3544 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3545 Expand, RetainExpansion, NumExpansions))
3546 return nullptr;
3547
3548 // This declaration cannot appear within a function template signature,
3549 // so we can't have a partial argument list for a parameter pack.
3550 assert(!RetainExpansion &&
3551 "should never need to retain an expansion for UsingPackDecl");
3552
3553 if (!Expand) {
3554 // We cannot fully expand the pack expansion now, so substitute into the
3555 // pattern and create a new pack expansion.
3556 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3557 return instantiateUnresolvedUsingDecl(D, true);
3558 }
3559
3560 // Within a function, we don't have any normal way to check for conflicts
3561 // between shadow declarations from different using declarations in the
3562 // same pack expansion, but this is always ill-formed because all expansions
3563 // must produce (conflicting) enumerators.
3564 //
3565 // Sadly we can't just reject this in the template definition because it
3566 // could be valid if the pack is empty or has exactly one expansion.
3567 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3568 SemaRef.Diag(D->getEllipsisLoc(),
3569 diag::err_using_decl_redeclaration_expansion);
3570 return nullptr;
3571 }
3572
3573 // Instantiate the slices of this pack and build a UsingPackDecl.
3574 SmallVector<NamedDecl*, 8> Expansions;
3575 for (unsigned I = 0; I != *NumExpansions; ++I) {
3576 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3577 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3578 if (!Slice)
3579 return nullptr;
3580 // Note that we can still get unresolved using declarations here, if we
3581 // had arguments for all packs but the pattern also contained other
3582 // template arguments (this only happens during partial substitution, eg
3583 // into the body of a generic lambda in a function template).
3584 Expansions.push_back(cast<NamedDecl>(Slice));
3585 }
3586
3587 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3590 return NewD;
3591 }
3592
3593 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3594 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3595
3596 NestedNameSpecifierLoc QualifierLoc
3597 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3598 TemplateArgs);
3599 if (!QualifierLoc)
3600 return nullptr;
3601
3602 CXXScopeSpec SS;
3603 SS.Adopt(QualifierLoc);
3604
3605 DeclarationNameInfo NameInfo
3606 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3607
3608 // Produce a pack expansion only if we're not instantiating a particular
3609 // slice of a pack expansion.
3610 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3611 SemaRef.ArgumentPackSubstitutionIndex != -1;
3612 SourceLocation EllipsisLoc =
3613 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3614
3615 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3616 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3617 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3618 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3620 /*IsInstantiation*/ true, IsUsingIfExists);
3621 if (UD) {
3622 SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3624 }
3625
3626 return UD;
3627}
3628
3629Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3631 return instantiateUnresolvedUsingDecl(D);
3632}
3633
3634Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3636 return instantiateUnresolvedUsingDecl(D);
3637}
3638
3639Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3641 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3642}
3643
3644Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3645 SmallVector<NamedDecl*, 8> Expansions;
3646 for (auto *UD : D->expansions()) {
3647 if (NamedDecl *NewUD =
3648 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3649 Expansions.push_back(NewUD);
3650 else
3651 return nullptr;
3652 }
3653
3654 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3657 return NewD;
3658}
3659
3660Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3663 for (auto *I : D->varlist()) {
3664 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3665 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3666 Vars.push_back(Var);
3667 }
3668
3670 SemaRef.OpenMP().CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3671
3672 TD->setAccess(AS_public);
3673 Owner->addDecl(TD);
3674
3675 return TD;
3676}
3677
3678Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3680 for (auto *I : D->varlist()) {
3681 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3682 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3683 Vars.push_back(Var);
3684 }
3686 // Copy map clauses from the original mapper.
3687 for (OMPClause *C : D->clauselists()) {
3688 OMPClause *IC = nullptr;
3689 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3690 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3691 if (!NewE.isUsable())
3692 continue;
3693 IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause(
3694 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3695 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
3696 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3697 if (!NewE.isUsable())
3698 continue;
3699 IC = SemaRef.OpenMP().ActOnOpenMPAlignClause(
3700 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3701 // If align clause value ends up being invalid, this can end up null.
3702 if (!IC)
3703 continue;
3704 }
3705 Clauses.push_back(IC);
3706 }
3707
3709 D->getLocation(), Vars, Clauses, Owner);
3710 if (Res.get().isNull())
3711 return nullptr;
3712 return Res.get().getSingleDecl();
3713}
3714
3715Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3716 llvm_unreachable(
3717 "Requires directive cannot be instantiated within a dependent context");
3718}
3719
3720Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3722 // Instantiate type and check if it is allowed.
3723 const bool RequiresInstantiation =
3724 D->getType()->isDependentType() ||
3725 D->getType()->isInstantiationDependentType() ||
3726 D->getType()->containsUnexpandedParameterPack();
3727 QualType SubstReductionType;
3728 if (RequiresInstantiation) {
3729 SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType(
3730 D->getLocation(),
3732 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3733 } else {
3734 SubstReductionType = D->getType();
3735 }
3736 if (SubstReductionType.isNull())
3737 return nullptr;
3738 Expr *Combiner = D->getCombiner();
3739 Expr *Init = D->getInitializer();
3740 bool IsCorrect = true;
3741 // Create instantiated copy.
3742 std::pair<QualType, SourceLocation> ReductionTypes[] = {
3743 std::make_pair(SubstReductionType, D->getLocation())};
3744 auto *PrevDeclInScope = D->getPrevDeclInScope();
3745 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3746 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3747 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
3748 PrevDeclInScope)));
3749 }
3751 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3752 PrevDeclInScope);
3753 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3755 Expr *SubstCombiner = nullptr;
3756 Expr *SubstInitializer = nullptr;
3757 // Combiners instantiation sequence.
3758 if (Combiner) {
3760 /*S=*/nullptr, NewDRD);
3762 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3763 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3765 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3766 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3767 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3768 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3769 ThisContext);
3770 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3772 SubstCombiner);
3773 }
3774 // Initializers instantiation sequence.
3775 if (Init) {
3776 VarDecl *OmpPrivParm =
3778 /*S=*/nullptr, NewDRD);
3780 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3781 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3783 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3784 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3785 if (D->getInitializerKind() == OMPDeclareReductionInitKind::Call) {
3786 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3787 } else {
3788 auto *OldPrivParm =
3789 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3790 IsCorrect = IsCorrect && OldPrivParm->hasInit();
3791 if (IsCorrect)
3792 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3793 TemplateArgs);
3794 }
3796 NewDRD, SubstInitializer, OmpPrivParm);
3797 }
3798 IsCorrect = IsCorrect && SubstCombiner &&
3799 (!Init ||
3800 (D->getInitializerKind() == OMPDeclareReductionInitKind::Call &&
3801 SubstInitializer) ||
3802 (D->getInitializerKind() != OMPDeclareReductionInitKind::Call &&
3803 !SubstInitializer));
3804
3806 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3807
3808 return NewDRD;
3809}
3810
3811Decl *
3812TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3813 // Instantiate type and check if it is allowed.
3814 const bool RequiresInstantiation =
3815 D->getType()->isDependentType() ||
3816 D->getType()->isInstantiationDependentType() ||
3817 D->getType()->containsUnexpandedParameterPack();
3818 QualType SubstMapperTy;
3819 DeclarationName VN = D->getVarName();
3820 if (RequiresInstantiation) {
3821 SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType(
3822 D->getLocation(),
3823 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3824 D->getLocation(), VN)));
3825 } else {
3826 SubstMapperTy = D->getType();
3827 }
3828 if (SubstMapperTy.isNull())
3829 return nullptr;
3830 // Create an instantiated copy of mapper.
3831 auto *PrevDeclInScope = D->getPrevDeclInScope();
3832 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3833 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3834 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
3835 PrevDeclInScope)));
3836 }
3837 bool IsCorrect = true;
3839 // Instantiate the mapper variable.
3840 DeclarationNameInfo DirName;
3841 SemaRef.OpenMP().StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3842 /*S=*/nullptr,
3843 (*D->clauselist_begin())->getBeginLoc());
3844 ExprResult MapperVarRef =
3846 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3848 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3849 cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3850 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3851 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3852 ThisContext);
3853 // Instantiate map clauses.
3854 for (OMPClause *C : D->clauselists()) {
3855 auto *OldC = cast<OMPMapClause>(C);
3856 SmallVector<Expr *, 4> NewVars;
3857 for (Expr *OE : OldC->varlist()) {
3858 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3859 if (!NE) {
3860 IsCorrect = false;
3861 break;
3862 }
3863 NewVars.push_back(NE);
3864 }
3865 if (!IsCorrect)
3866 break;
3867 NestedNameSpecifierLoc NewQualifierLoc =
3868 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3869 TemplateArgs);
3870 CXXScopeSpec SS;
3871 SS.Adopt(NewQualifierLoc);
3872 DeclarationNameInfo NewNameInfo =
3873 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3874 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3875 OldC->getEndLoc());
3876 OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause(
3877 OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
3878 OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
3879 OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
3880 NewVars, Locs);
3881 Clauses.push_back(NewC);
3882 }
3883 SemaRef.OpenMP().EndOpenMPDSABlock(nullptr);
3884 if (!IsCorrect)
3885 return nullptr;
3887 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3888 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3889 Decl *NewDMD = DG.get().getSingleDecl();
3891 return NewDMD;
3892}
3893
3894Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3895 OMPCapturedExprDecl * /*D*/) {
3896 llvm_unreachable("Should not be met in templates");
3897}
3898
3900 return VisitFunctionDecl(D, nullptr);
3901}
3902
3903Decl *
3904TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3905 Decl *Inst = VisitFunctionDecl(D, nullptr);
3906 if (Inst && !D->getDescribedFunctionTemplate())
3907 Owner->addDecl(Inst);
3908 return Inst;
3909}
3910
3912 return VisitCXXMethodDecl(D, nullptr);
3913}
3914
3915Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3916 llvm_unreachable("There are only CXXRecordDecls in C++");
3917}
3918
3919Decl *
3920TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3922 // As a MS extension, we permit class-scope explicit specialization
3923 // of member class templates.
3924 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3925 assert(ClassTemplate->getDeclContext()->isRecord() &&
3926 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3927 "can only instantiate an explicit specialization "
3928 "for a member class template");
3929
3930 // Lookup the already-instantiated declaration in the instantiation
3931 // of the class template.
3932 ClassTemplateDecl *InstClassTemplate =
3933 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3934 D->getLocation(), ClassTemplate, TemplateArgs));
3935 if (!InstClassTemplate)
3936 return nullptr;
3937
3938 // Substitute into the template arguments of the class template explicit
3939 // specialization.
3940 TemplateArgumentListInfo InstTemplateArgs;
3941 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3942 D->getTemplateArgsAsWritten()) {
3943 InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3944 InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3945
3946 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3947 TemplateArgs, InstTemplateArgs))
3948 return nullptr;
3949 }
3950
3951 // Check that the template argument list is well-formed for this
3952 // class template.
3953 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3954 if (SemaRef.CheckTemplateArgumentList(
3955 InstClassTemplate, D->getLocation(), InstTemplateArgs,
3956 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
3957 /*UpdateArgsWithConversions=*/true))
3958 return nullptr;
3959
3960 // Figure out where to insert this class template explicit specialization
3961 // in the member template's set of class template explicit specializations.
3962 void *InsertPos = nullptr;
3964 InstClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3965
3966 // Check whether we've already seen a conflicting instantiation of this
3967 // declaration (for instance, if there was a prior implicit instantiation).
3968 bool Ignored;
3969 if (PrevDecl &&
3971 D->getSpecializationKind(),
3972 PrevDecl,
3973 PrevDecl->getSpecializationKind(),
3974 PrevDecl->getPointOfInstantiation(),
3975 Ignored))
3976 return nullptr;
3977
3978 // If PrevDecl was a definition and D is also a definition, diagnose.
3979 // This happens in cases like:
3980 //
3981 // template<typename T, typename U>
3982 // struct Outer {
3983 // template<typename X> struct Inner;
3984 // template<> struct Inner<T> {};
3985 // template<> struct Inner<U> {};
3986 // };
3987 //
3988 // Outer<int, int> outer; // error: the explicit specializations of Inner
3989 // // have the same signature.
3990 if (PrevDecl && PrevDecl->getDefinition() &&
3991 D->isThisDeclarationADefinition()) {
3992 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3993 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3994 diag::note_previous_definition);
3995 return nullptr;
3996 }
3997
3998 // Create the class template partial specialization declaration.
4001 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
4002 D->getLocation(), InstClassTemplate, CanonicalConverted, PrevDecl);
4003 InstD->setTemplateArgsAsWritten(InstTemplateArgs);
4004
4005 // Add this partial specialization to the set of class template partial
4006 // specializations.
4007 if (!PrevDecl)
4008 InstClassTemplate->AddSpecialization(InstD, InsertPos);
4009
4010 // Substitute the nested name specifier, if any.
4011 if (SubstQualifier(D, InstD))
4012 return nullptr;
4013
4014 InstD->setAccess(D->getAccess());
4016 InstD->setSpecializationKind(D->getSpecializationKind());
4017 InstD->setExternKeywordLoc(D->getExternKeywordLoc());
4018 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
4019
4020 Owner->addDecl(InstD);
4021
4022 // Instantiate the members of the class-scope explicit specialization eagerly.
4023 // We don't have support for lazy instantiation of an explicit specialization
4024 // yet, and MSVC eagerly instantiates in this case.
4025 // FIXME: This is wrong in standard C++.
4026 if (D->isThisDeclarationADefinition() &&
4027 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
4029 /*Complain=*/true))
4030 return nullptr;
4031
4032 return InstD;
4033}
4034
4037
4038 TemplateArgumentListInfo VarTemplateArgsInfo;
4039 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
4040 assert(VarTemplate &&
4041 "A template specialization without specialized template?");
4042
4043 VarTemplateDecl *InstVarTemplate =
4044 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
4045 D->getLocation(), VarTemplate, TemplateArgs));
4046 if (!InstVarTemplate)
4047 return nullptr;
4048
4049 // Substitute the current template arguments.
4050 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4051 D->getTemplateArgsAsWritten()) {
4052 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4053 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4054
4055 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4056 TemplateArgs, VarTemplateArgsInfo))
4057 return nullptr;
4058 }
4059
4060 // Check that the template argument list is well-formed for this template.
4061 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4062 if (SemaRef.CheckTemplateArgumentList(
4063 InstVarTemplate, D->getLocation(), VarTemplateArgsInfo,
4064 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
4065 /*UpdateArgsWithConversions=*/true))
4066 return nullptr;
4067
4068 // Check whether we've already seen a declaration of this specialization.
4069 void *InsertPos = nullptr;
4071 InstVarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4072
4073 // Check whether we've already seen a conflicting instantiation of this
4074 // declaration (for instance, if there was a prior implicit instantiation).
4075 bool Ignored;
4076 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
4077 D->getLocation(), D->getSpecializationKind(), PrevDecl,
4078 PrevDecl->getSpecializationKind(),
4079 PrevDecl->getPointOfInstantiation(), Ignored))
4080 return nullptr;
4081
4083 InstVarTemplate, D, VarTemplateArgsInfo, CanonicalConverted, PrevDecl);
4084}
4085
4087 VarTemplateDecl *VarTemplate, VarDecl *D,
4088 const TemplateArgumentListInfo &TemplateArgsInfo,
4091
4092 // Do substitution on the type of the declaration
4093 TypeSourceInfo *DI =
4094 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
4095 D->getTypeSpecStartLoc(), D->getDeclName());
4096 if (!DI)
4097 return nullptr;
4098
4099 if (DI->getType()->isFunctionType()) {
4100 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
4101 << D->isStaticDataMember() << DI->getType();
4102 return nullptr;
4103 }
4104
4105 // Build the instantiated declaration
4107 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
4108 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
4109 Var->setTemplateArgsAsWritten(TemplateArgsInfo);
4110 if (!PrevDecl) {
4111 void *InsertPos = nullptr;
4112 VarTemplate->findSpecialization(Converted, InsertPos);
4113 VarTemplate->AddSpecialization(Var, InsertPos);
4114 }
4115
4116 if (SemaRef.getLangOpts().OpenCL)
4117 SemaRef.deduceOpenCLAddressSpace(Var);
4118
4119 // Substitute the nested name specifier, if any.
4120 if (SubstQualifier(D, Var))
4121 return nullptr;
4122
4123 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
4124 StartingScope, false, PrevDecl);
4125
4126 return Var;
4127}
4128
4129Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
4130 llvm_unreachable("@defs is not supported in Objective-C++");
4131}
4132
4133Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
4134 // FIXME: We need to be able to instantiate FriendTemplateDecls.
4135 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
4137 "cannot instantiate %0 yet");
4138 SemaRef.Diag(D->getLocation(), DiagID)
4139 << D->getDeclKindName();
4140
4141 return nullptr;
4142}
4143
4144Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
4145 llvm_unreachable("Concept definitions cannot reside inside a template");
4146}
4147
4148Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4150 llvm_unreachable("Concept specializations cannot reside inside a template");
4151}
4152
4153Decl *
4154TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4156 D->getBeginLoc());
4157}
4158
4160 llvm_unreachable("Unexpected decl");
4161}
4162
4164 const MultiLevelTemplateArgumentList &TemplateArgs) {
4165 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4166 if (D->isInvalidDecl())
4167 return nullptr;
4168
4169 Decl *SubstD;
4171 SubstD = Instantiator.Visit(D);
4172 });
4173 return SubstD;
4174}
4175
4177 FunctionDecl *Orig, QualType &T,
4178 TypeSourceInfo *&TInfo,
4179 DeclarationNameInfo &NameInfo) {
4181
4182 // C++2a [class.compare.default]p3:
4183 // the return type is replaced with bool
4184 auto *FPT = T->castAs<FunctionProtoType>();
4185 T = SemaRef.Context.getFunctionType(
4186 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4187
4188 // Update the return type in the source info too. The most straightforward
4189 // way is to create new TypeSourceInfo for the new type. Use the location of
4190 // the '= default' as the location of the new type.
4191 //
4192 // FIXME: Set the correct return type when we initially transform the type,
4193 // rather than delaying it to now.
4194 TypeSourceInfo *NewTInfo =
4195 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4196 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4197 assert(OldLoc && "type of function is not a function type?");
4198 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4199 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4200 NewLoc.setParam(I, OldLoc.getParam(I));
4201 TInfo = NewTInfo;
4202
4203 // and the declarator-id is replaced with operator==
4204 NameInfo.setName(
4205 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4206}
4207
4209 FunctionDecl *Spaceship) {
4210 if (Spaceship->isInvalidDecl())
4211 return nullptr;
4212
4213 // C++2a [class.compare.default]p3:
4214 // an == operator function is declared implicitly [...] with the same
4215 // access and function-definition and in the same class scope as the
4216 // three-way comparison operator function
4217 MultiLevelTemplateArgumentList NoTemplateArgs;
4219 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4220 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4221 Decl *R;
4222 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4223 R = Instantiator.VisitCXXMethodDecl(
4224 MD, /*TemplateParams=*/nullptr,
4226 } else {
4227 assert(Spaceship->getFriendObjectKind() &&
4228 "defaulted spaceship is neither a member nor a friend");
4229
4230 R = Instantiator.VisitFunctionDecl(
4231 Spaceship, /*TemplateParams=*/nullptr,
4233 if (!R)
4234 return nullptr;
4235
4236 FriendDecl *FD =
4237 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4238 cast<NamedDecl>(R), Spaceship->getBeginLoc());
4239 FD->setAccess(AS_public);
4240 RD->addDecl(FD);
4241 }
4242 return cast_or_null<FunctionDecl>(R);
4243}
4244
4245/// Instantiates a nested template parameter list in the current
4246/// instantiation context.
4247///
4248/// \param L The parameter list to instantiate
4249///
4250/// \returns NULL if there was an error
4253 // Get errors for all the parameters before bailing out.
4254 bool Invalid = false;
4255
4256 unsigned N = L->size();
4257 typedef SmallVector<NamedDecl *, 8> ParamVector;
4258 ParamVector Params;
4259 Params.reserve(N);
4260 for (auto &P : *L) {
4261 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4262 Params.push_back(D);
4263 Invalid = Invalid || !D || D->isInvalidDecl();
4264 }
4265
4266 // Clean up if we had an error.
4267 if (Invalid)
4268 return nullptr;
4269
4270 Expr *InstRequiresClause = L->getRequiresClause();
4271
4274 L->getLAngleLoc(), Params,
4275 L->getRAngleLoc(), InstRequiresClause);
4276 return InstL;
4277}
4278
4281 const MultiLevelTemplateArgumentList &TemplateArgs,
4282 bool EvaluateConstraints) {
4283 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4284 Instantiator.setEvaluateConstraints(EvaluateConstraints);
4285 return Instantiator.SubstTemplateParams(Params);
4286}
4287
4288/// Instantiate the declaration of a class template partial
4289/// specialization.
4290///
4291/// \param ClassTemplate the (instantiated) class template that is partially
4292// specialized by the instantiation of \p PartialSpec.
4293///
4294/// \param PartialSpec the (uninstantiated) class template partial
4295/// specialization that we are instantiating.
4296///
4297/// \returns The instantiated partial specialization, if successful; otherwise,
4298/// NULL to indicate an error.
4301 ClassTemplateDecl *ClassTemplate,
4303 // Create a local instantiation scope for this class template partial
4304 // specialization, which will contain the instantiations of the template
4305 // parameters.
4307
4308 // Substitute into the template parameters of the class template partial
4309 // specialization.
4310 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4311 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4312 if (!InstParams)
4313 return nullptr;
4314
4315 // Substitute into the template arguments of the class template partial
4316 // specialization.
4317 const ASTTemplateArgumentListInfo *TemplArgInfo
4318 = PartialSpec->getTemplateArgsAsWritten();
4319 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4320 TemplArgInfo->RAngleLoc);
4321 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4322 InstTemplateArgs))
4323 return nullptr;
4324
4325 // Check that the template argument list is well-formed for this
4326 // class template.
4327 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4328 if (SemaRef.CheckTemplateArgumentList(
4329 ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4330 /*DefaultArgs=*/{},
4331 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4332 return nullptr;
4333
4334 // Check these arguments are valid for a template partial specialization.
4336 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4337 CanonicalConverted))
4338 return nullptr;
4339
4340 // Figure out where to insert this class template partial specialization
4341 // in the member template's set of class template partial specializations.
4342 void *InsertPos = nullptr;
4344 ClassTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4345 InsertPos);
4346
4347 // Build the canonical type that describes the converted template
4348 // arguments of the class template partial specialization.
4350 TemplateName(ClassTemplate), CanonicalConverted);
4351
4352 // Create the class template partial specialization declaration.
4355 SemaRef.Context, PartialSpec->getTagKind(), Owner,
4356 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4357 ClassTemplate, CanonicalConverted, CanonType,
4358 /*PrevDecl=*/nullptr);
4359
4360 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4361
4362 // Substitute the nested name specifier, if any.
4363 if (SubstQualifier(PartialSpec, InstPartialSpec))
4364 return nullptr;
4365
4366 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4367
4368 if (PrevDecl) {
4369 // We've already seen a partial specialization with the same template
4370 // parameters and template arguments. This can happen, for example, when
4371 // substituting the outer template arguments ends up causing two
4372 // class template partial specializations of a member class template
4373 // to have identical forms, e.g.,
4374 //
4375 // template<typename T, typename U>
4376 // struct Outer {
4377 // template<typename X, typename Y> struct Inner;
4378 // template<typename Y> struct Inner<T, Y>;
4379 // template<typename Y> struct Inner<U, Y>;
4380 // };
4381 //
4382 // Outer<int, int> outer; // error: the partial specializations of Inner
4383 // // have the same signature.
4384 SemaRef.Diag(InstPartialSpec->getLocation(),
4385 diag::err_partial_spec_redeclared)
4386 << InstPartialSpec;
4387 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4388 << SemaRef.Context.getTypeDeclType(PrevDecl);
4389 return nullptr;
4390 }
4391
4392 // Check the completed partial specialization.
4393 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4394
4395 // Add this partial specialization to the set of class template partial
4396 // specializations.
4397 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4398 /*InsertPos=*/nullptr);
4399 return InstPartialSpec;
4400}
4401
4402/// Instantiate the declaration of a variable template partial
4403/// specialization.
4404///
4405/// \param VarTemplate the (instantiated) variable template that is partially
4406/// specialized by the instantiation of \p PartialSpec.
4407///
4408/// \param PartialSpec the (uninstantiated) variable template partial
4409/// specialization that we are instantiating.
4410///
4411/// \returns The instantiated partial specialization, if successful; otherwise,
4412/// NULL to indicate an error.
4415 VarTemplateDecl *VarTemplate,
4417 // Create a local instantiation scope for this variable template partial
4418 // specialization, which will contain the instantiations of the template
4419 // parameters.
4421
4422 // Substitute into the template parameters of the variable template partial
4423 // specialization.
4424 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4425 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4426 if (!InstParams)
4427 return nullptr;
4428
4429 // Substitute into the template arguments of the variable template partial
4430 // specialization.
4431 const ASTTemplateArgumentListInfo *TemplArgInfo
4432 = PartialSpec->getTemplateArgsAsWritten();
4433 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4434 TemplArgInfo->RAngleLoc);
4435 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4436 InstTemplateArgs))
4437 return nullptr;
4438
4439 // Check that the template argument list is well-formed for this
4440 // class template.
4441 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4442 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
4443 InstTemplateArgs, /*DefaultArgs=*/{},
4444 /*PartialTemplateArgs=*/false,
4445 SugaredConverted, CanonicalConverted))
4446 return nullptr;
4447
4448 // Check these arguments are valid for a template partial specialization.
4450 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4451 CanonicalConverted))
4452 return nullptr;
4453
4454 // Figure out where to insert this variable template partial specialization
4455 // in the member template's set of variable template partial specializations.
4456 void *InsertPos = nullptr;
4458 VarTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4459 InsertPos);
4460
4461 // Do substitution on the type of the declaration
4462 TypeSourceInfo *DI = SemaRef.SubstType(
4463 PartialSpec->getTypeSourceInfo(), TemplateArgs,
4464 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4465 if (!DI)
4466 return nullptr;
4467
4468 if (DI->getType()->isFunctionType()) {
4469 SemaRef.Diag(PartialSpec->getLocation(),
4470 diag::err_variable_instantiates_to_function)
4471 << PartialSpec->isStaticDataMember() << DI->getType();
4472 return nullptr;
4473 }
4474
4475 // Create the variable template partial specialization declaration.
4476 VarTemplatePartialSpecializationDecl *InstPartialSpec =
4478 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4479 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4480 DI, PartialSpec->getStorageClass(), CanonicalConverted);
4481
4482 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4483
4484 // Substitute the nested name specifier, if any.
4485 if (SubstQualifier(PartialSpec, InstPartialSpec))
4486 return nullptr;
4487
4488 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4489
4490 if (PrevDecl) {
4491 // We've already seen a partial specialization with the same template
4492 // parameters and template arguments. This can happen, for example, when
4493 // substituting the outer template arguments ends up causing two
4494 // variable template partial specializations of a member variable template
4495 // to have identical forms, e.g.,
4496 //
4497 // template<typename T, typename U>
4498 // struct Outer {
4499 // template<typename X, typename Y> pair<X,Y> p;
4500 // template<typename Y> pair<T, Y> p;
4501 // template<typename Y> pair<U, Y> p;
4502 // };
4503 //
4504 // Outer<int, int> outer; // error: the partial specializations of Inner
4505 // // have the same signature.
4506 SemaRef.Diag(PartialSpec->getLocation(),
4507 diag::err_var_partial_spec_redeclared)
4508 << InstPartialSpec;
4509 SemaRef.Diag(PrevDecl->getLocation(),
4510 diag::note_var_prev_partial_spec_here);
4511 return nullptr;
4512 }
4513 // Check the completed partial specialization.
4514 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4515
4516 // Add this partial specialization to the set of variable template partial
4517 // specializations. The instantiation of the initializer is not necessary.
4518 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4519
4520 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4521 LateAttrs, Owner, StartingScope);
4522
4523 return InstPartialSpec;
4524}
4525
4529 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4530 assert(OldTInfo && "substituting function without type source info");
4531 assert(Params.empty() && "parameter vector is non-empty at start");
4532
4533 CXXRecordDecl *ThisContext = nullptr;
4534 Qualifiers ThisTypeQuals;
4535 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4536 ThisContext = cast<CXXRecordDecl>(Owner);
4537 ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
4538 }
4539
4540 TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
4541 OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
4542 ThisContext, ThisTypeQuals, EvaluateConstraints);
4543 if (!NewTInfo)
4544 return nullptr;
4545
4546 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4547 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4548 if (NewTInfo != OldTInfo) {
4549 // Get parameters from the new type info.
4550 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4551 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4552 unsigned NewIdx = 0;
4553 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4554 OldIdx != NumOldParams; ++OldIdx) {
4555 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4556 if (!OldParam)
4557 return nullptr;
4558
4560
4561 std::optional<unsigned> NumArgumentsInExpansion;
4562 if (OldParam->isParameterPack())
4563 NumArgumentsInExpansion =
4564 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4565 TemplateArgs);
4566 if (!NumArgumentsInExpansion) {
4567 // Simple case: normal parameter, or a parameter pack that's
4568 // instantiated to a (still-dependent) parameter pack.
4569 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4570 Params.push_back(NewParam);
4571 Scope->InstantiatedLocal(OldParam, NewParam);
4572 } else {
4573 // Parameter pack expansion: make the instantiation an argument pack.
4574 Scope->MakeInstantiatedLocalArgPack(OldParam);
4575 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4576 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4577 Params.push_back(NewParam);
4578 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4579 }
4580 }
4581 }
4582 } else {
4583 // The function type itself was not dependent and therefore no
4584 // substitution occurred. However, we still need to instantiate
4585 // the function parameters themselves.
4586 const FunctionProtoType *OldProto =
4587 cast<FunctionProtoType>(OldProtoLoc.getType());
4588 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4589 ++i) {
4590 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4591 if (!OldParam) {
4592 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4593 D, D->getLocation(), OldProto->getParamType(i)));
4594 continue;
4595 }
4596
4597 ParmVarDecl *Parm =
4598 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4599 if (!Parm)
4600 return nullptr;
4601 Params.push_back(Parm);
4602 }
4603 }
4604 } else {
4605 // If the type of this function, after ignoring parentheses, is not
4606 // *directly* a function type, then we're instantiating a function that
4607 // was declared via a typedef or with attributes, e.g.,
4608 //
4609 // typedef int functype(int, int);
4610 // functype func;
4611 // int __cdecl meth(int, int);
4612 //
4613 // In this case, we'll just go instantiate the ParmVarDecls that we
4614 // synthesized in the method declaration.
4615 SmallVector<QualType, 4> ParamTypes;
4616 Sema::ExtParameterInfoBuilder ExtParamInfos;
4617 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4618 TemplateArgs, ParamTypes, &Params,
4619 ExtParamInfos))
4620 return nullptr;
4621 }
4622
4623 return NewTInfo;
4624}
4625
4626void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
4627 const FunctionDecl *PatternDecl,
4629 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(getFunctionScopes().back());
4630
4631 for (auto *decl : PatternDecl->decls()) {
4632 if (!isa<VarDecl>(decl) || isa<ParmVarDecl>(decl))
4633 continue;
4634
4635 VarDecl *VD = cast<VarDecl>(decl);
4636 IdentifierInfo *II = VD->getIdentifier();
4637
4638 auto it = llvm::find_if(Function->decls(), [&](Decl *inst) {
4639 VarDecl *InstVD = dyn_cast<VarDecl>(inst);
4640 return InstVD && InstVD->isLocalVarDecl() &&
4641 InstVD->getIdentifier() == II;
4642 });
4643
4644 if (it == Function->decls().end())
4645 continue;
4646
4647 Scope.InstantiatedLocal(VD, *it);
4648 LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false,
4649 /*isNested=*/false, VD->getLocation(), SourceLocation(),
4650 VD->getType(), /*Invalid=*/false);
4651 }
4652}
4653
4654bool Sema::addInstantiatedParametersToScope(
4655 FunctionDecl *Function, const FunctionDecl *PatternDecl,
4657 const MultiLevelTemplateArgumentList &TemplateArgs) {
4658 unsigned FParamIdx = 0;
4659 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4660 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4661 if (!PatternParam->isParameterPack()) {
4662 // Simple case: not a parameter pack.
4663 assert(FParamIdx < Function->getNumParams());
4664 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4665 FunctionParam->setDeclName(PatternParam->getDeclName());
4666 // If the parameter's type is not dependent, update it to match the type
4667 // in the pattern. They can differ in top-level cv-qualifiers, and we want
4668 // the pattern's type here. If the type is dependent, they can't differ,
4669 // per core issue 1668. Substitute into the type from the pattern, in case
4670 // it's instantiation-dependent.
4671 // FIXME: Updating the type to work around this is at best fragile.
4672 if (!PatternDecl->getType()->isDependentType()) {
4673 QualType T = SubstType(PatternParam->getType(), TemplateArgs,
4674 FunctionParam->getLocation(),
4675 FunctionParam->getDeclName());
4676 if (T.isNull())
4677 return true;
4678 FunctionParam->setType(T);
4679 }
4680
4681 Scope.InstantiatedLocal(PatternParam, FunctionParam);
4682 ++FParamIdx;
4683 continue;
4684 }
4685
4686 // Expand the parameter pack.
4687 Scope.MakeInstantiatedLocalArgPack(PatternParam);
4688 std::optional<unsigned> NumArgumentsInExpansion =
4689 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4690 if (NumArgumentsInExpansion) {
4691 QualType PatternType =
4692 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4693 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4694 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4695 FunctionParam->setDeclName(PatternParam->getDeclName());
4696 if (!PatternDecl->getType()->isDependentType()) {
4697 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
4698 QualType T =
4699 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
4700 FunctionParam->getDeclName());
4701 if (T.isNull())
4702 return true;
4703 FunctionParam->setType(T);
4704 }
4705
4706 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4707 ++FParamIdx;
4708 }
4709 }
4710 }
4711
4712 return false;
4713}
4714
4716 ParmVarDecl *Param) {
4717 assert(Param->hasUninstantiatedDefaultArg());
4718
4719 // FIXME: We don't track member specialization info for non-defining
4720 // friend declarations, so we will not be able to later find the function
4721 // pattern. As a workaround, don't instantiate the default argument in this
4722 // case. This is correct per the standard and only an issue for recovery
4723 // purposes. [dcl.fct.default]p4:
4724 // if a friend declaration D specifies a default argument expression,
4725 // that declaration shall be a definition.
4726 if (FD->getFriendObjectKind() != Decl::FOK_None &&
4728 return true;
4729
4730 // Instantiate the expression.
4731 //
4732 // FIXME: Pass in a correct Pattern argument, otherwise
4733 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4734 //
4735 // template<typename T>
4736 // struct A {
4737 // static int FooImpl();
4738 //
4739 // template<typename Tp>
4740 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4741 // // template argument list [[T], [Tp]], should be [[Tp]].
4742 // friend A<Tp> Foo(int a);
4743 // };
4744 //
4745 // template<typename T>
4746 // A<T> Foo(int a = A<T>::FooImpl());
4748 FD, FD->getLexicalDeclContext(),
4749 /*Final=*/false, /*Innermost=*/std::nullopt,
4750 /*RelativeToPrimary=*/true, /*Pattern=*/nullptr,
4751 /*ForConstraintInstantiation=*/false, /*SkipForSpecialization=*/false,
4752 /*ForDefaultArgumentSubstitution=*/true);
4753
4754 if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
4755 return true;
4756
4758 L->DefaultArgumentInstantiated(Param);
4759
4760 return false;
4761}
4762
4764 FunctionDecl *Decl) {
4765 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4767 return;
4768
4769 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4771 if (Inst.isInvalid()) {
4772 // We hit the instantiation depth limit. Clear the exception specification
4773 // so that our callers don't have to cope with EST_Uninstantiated.
4775 return;
4776 }
4777 if (Inst.isAlreadyInstantiating()) {
4778 // This exception specification indirectly depends on itself. Reject.
4779 // FIXME: Corresponding rule in the standard?
4780 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4782 return;
4783 }
4784
4785 // Enter the scope of this instantiation. We don't use
4786 // PushDeclContext because we don't have a scope.
4787 Sema::ContextRAII savedContext(*this, Decl);
4789
4790 MultiLevelTemplateArgumentList TemplateArgs =
4792 /*Final=*/false, /*Innermost=*/std::nullopt,
4793 /*RelativeToPrimary*/ true);
4794
4795 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4796 // here, because for a non-defining friend declaration in a class template,
4797 // we don't store enough information to map back to the friend declaration in
4798 // the template.
4799 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4800 if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
4802 return;
4803 }
4804
4805 // The noexcept specification could reference any lambda captures. Ensure
4806 // those are added to the LocalInstantiationScope.
4808 *this, Decl, TemplateArgs, Scope,
4809 /*ShouldAddDeclsFromParentScope=*/false);
4810
4812 TemplateArgs);
4813}
4814
4815/// Initializes the common fields of an instantiation function
4816/// declaration (New) from the corresponding fields of its template (Tmpl).
4817///
4818/// \returns true if there was an error
4819bool
4821 FunctionDecl *Tmpl) {
4822 New->setImplicit(Tmpl->isImplicit());
4823
4824 // Forward the mangling number from the template to the instantiated decl.
4825 SemaRef.Context.setManglingNumber(New,
4826 SemaRef.Context.getManglingNumber(Tmpl));
4827
4828 // If we are performing substituting explicitly-specified template arguments
4829 // or deduced template arguments into a function template and we reach this
4830 // point, we are now past the point where SFINAE applies and have committed
4831 // to keeping the new function template specialization. We therefore
4832 // convert the active template instantiation for the function template
4833 // into a template instantiation for this specific function template
4834 // specialization, which is not a SFINAE context, so that we diagnose any
4835 // further errors in the declaration itself.
4836 //
4837 // FIXME: This is a hack.
4838 typedef Sema::CodeSynthesisContext ActiveInstType;
4839 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4840 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4841 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4842 if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
4843 SemaRef.InstantiatingSpecializations.erase(
4844 {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4845 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4846 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4847 ActiveInst.Entity = New;
4848 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4849 }
4850 }
4851
4852 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4853 assert(Proto && "Function template without prototype?");
4854
4855 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4857
4858 // DR1330: In C++11, defer instantiation of a non-trivial
4859 // exception specification.
4860 // DR1484: Local classes and their members are instantiated along with the
4861 // containing function.
4862 if (SemaRef.getLangOpts().CPlusPlus11 &&
4863 EPI.ExceptionSpec.Type != EST_None &&
4867 FunctionDecl *ExceptionSpecTemplate = Tmpl;
4869 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4872 NewEST = EST_Unevaluated;
4873
4874 // Mark the function has having an uninstantiated exception specification.
4875 const FunctionProtoType *NewProto
4876 = New->getType()->getAs<FunctionProtoType>();
4877 assert(NewProto && "Template instantiation without function prototype?");
4878 EPI = NewProto->getExtProtoInfo();
4879 EPI.ExceptionSpec.Type = NewEST;
4880 EPI.ExceptionSpec.SourceDecl = New;
4881 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4882 New->setType(SemaRef.Context.getFunctionType(
4883 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4884 } else {
4885 Sema::ContextRAII SwitchContext(SemaRef, New);
4886 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4887 }
4888 }
4889
4890 // Get the definition. Leaves the variable unchanged if undefined.
4891 const FunctionDecl *Definition = Tmpl;
4892 Tmpl->isDefined(Definition);
4893
4894 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4895 LateAttrs, StartingScope);
4896
4897 return false;
4898}
4899
4900/// Initializes common fields of an instantiated method
4901/// declaration (New) from the corresponding fields of its template
4902/// (Tmpl).
4903///
4904/// \returns true if there was an error
4905bool
4907 CXXMethodDecl *Tmpl) {
4908 if (InitFunctionInstantiation(New, Tmpl))
4909 return true;
4910
4911 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4912 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4913
4914 New->setAccess(Tmpl->getAccess());
4915 if (Tmpl->isVirtualAsWritten())
4916 New->setVirtualAsWritten(true);
4917
4918 // FIXME: New needs a pointer to Tmpl
4919 return false;
4920}
4921
4923 FunctionDecl *Tmpl) {
4924 // Transfer across any unqualified lookups.
4925 if (auto *DFI = Tmpl->getDefalutedOrDeletedInfo()) {
4927 Lookups.reserve(DFI->getUnqualifiedLookups().size());
4928 bool AnyChanged = false;
4929 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4930 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4931 DA.getDecl(), TemplateArgs);
4932 if (!D)
4933 return true;
4934 AnyChanged |= (D != DA.getDecl());
4935 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4936 }
4937
4938 // It's unlikely that substitution will change any declarations. Don't
4939 // store an unnecessary copy in that case.
4942 SemaRef.Context, Lookups)
4943 : DFI);
4944 }
4945
4946 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4947 return false;
4948}
4949
4953 FunctionDecl *FD = FTD->getTemplatedDecl();
4954
4956 InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC, Info);
4957 if (Inst.isInvalid())
4958 return nullptr;
4959
4960 ContextRAII SavedContext(*this, FD);
4961 MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
4962 /*Final=*/false);
4963
4964 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4965}
4966
4969 bool Recursive,
4970 bool DefinitionRequired,
4971 bool AtEndOfTU) {
4972 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
4973 return;
4974
4975 // Never instantiate an explicit specialization except if it is a class scope
4976 // explicit specialization.
4978 Function->getTemplateSpecializationKindForInstantiation();
4979 if (TSK == TSK_ExplicitSpecialization)
4980 return;
4981
4982 // Never implicitly instantiate a builtin; we don't actually need a function
4983 // body.
4984 if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
4985 !DefinitionRequired)
4986 return;
4987
4988 // Don't instantiate a definition if we already have one.
4989 const FunctionDecl *ExistingDefn = nullptr;
4990 if (Function->isDefined(ExistingDefn,
4991 /*CheckForPendingFriendDefinition=*/true)) {
4992 if (ExistingDefn->isThisDeclarationADefinition())
4993 return;
4994
4995 // If we're asked to instantiate a function whose body comes from an
4996 // instantiated friend declaration, attach the instantiated body to the
4997 // corresponding declaration of the function.
4999 Function = const_cast<FunctionDecl*>(ExistingDefn);
5000 }
5001
5002 // Find the function body that we'll be substituting.
5003 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
5004 assert(PatternDecl && "instantiating a non-template");
5005
5006 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
5007 Stmt *Pattern = nullptr;
5008 if (PatternDef) {
5009 Pattern = PatternDef->getBody(PatternDef);
5010 PatternDecl = PatternDef;
5011 if (PatternDef->willHaveBody())
5012 PatternDef = nullptr;
5013 }
5014
5015 // FIXME: We need to track the instantiation stack in order to know which
5016 // definitions should be visible within this instantiation.
5017 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
5018 Function->getInstantiatedFromMemberFunction(),
5019 PatternDecl, PatternDef, TSK,
5020 /*Complain*/DefinitionRequired)) {
5021 if (DefinitionRequired)
5022 Function->setInvalidDecl();
5023 else if (TSK == TSK_ExplicitInstantiationDefinition ||
5024 (Function->isConstexpr() && !Recursive)) {
5025 // Try again at the end of the translation unit (at which point a
5026 // definition will be required).
5027 assert(!Recursive);
5028 Function->setInstantiationIsPending(true);
5029 PendingInstantiations.push_back(
5030 std::make_pair(Function, PointOfInstantiation));
5031
5032 if (llvm::isTimeTraceVerbose()) {
5033 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
5034 std::string Name;
5035 llvm::raw_string_ostream OS(Name);
5036 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5037 /*Qualified=*/true);
5038 return Name;
5039 });
5040 }
5041 } else if (TSK == TSK_ImplicitInstantiation) {
5042 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5043 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5044 Diag(PointOfInstantiation, diag::warn_func_template_missing)
5045 << Function;
5046 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5048 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
5049 << Function;
5050 }
5051 }
5052
5053 return;
5054 }
5055
5056 // Postpone late parsed template instantiations.
5057 if (PatternDecl->isLateTemplateParsed() &&
5059 Function->setInstantiationIsPending(true);
5060 LateParsedInstantiations.push_back(
5061 std::make_pair(Function, PointOfInstantiation));
5062 return;
5063 }
5064
5065 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
5066 llvm::TimeTraceMetadata M;
5067 llvm::raw_string_ostream OS(M.Detail);
5068 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5069 /*Qualified=*/true);
5070 if (llvm::isTimeTraceVerbose()) {
5071 auto Loc = SourceMgr.getExpansionLoc(Function->getLocation());
5072 M.File = SourceMgr.getFilename(Loc);
5074 }
5075 return M;
5076 });
5077
5078 // If we're performing recursive template instantiation, create our own
5079 // queue of pending implicit instantiations that we will instantiate later,
5080 // while we're still within our own instantiation context.
5081 // This has to happen before LateTemplateParser below is called, so that
5082 // it marks vtables used in late parsed templates as used.
5083 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5084 /*Enabled=*/Recursive);
5085 LocalEagerInstantiationScope LocalInstantiations(*this);
5086
5087 // Call the LateTemplateParser callback if there is a need to late parse
5088 // a templated function definition.
5089 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
5091 // FIXME: Optimize to allow individual templates to be deserialized.
5092 if (PatternDecl->isFromASTFile())
5093 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
5094
5095 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
5096 assert(LPTIter != LateParsedTemplateMap.end() &&
5097 "missing LateParsedTemplate");
5098 LateTemplateParser(OpaqueParser, *LPTIter->second);
5099 Pattern = PatternDecl->getBody(PatternDecl);
5101 }
5102
5103 // Note, we should never try to instantiate a deleted function template.
5104 assert((Pattern || PatternDecl->isDefaulted() ||
5105 PatternDecl->hasSkippedBody()) &&
5106 "unexpected kind of function template definition");
5107
5108 // C++1y [temp.explicit]p10:
5109 // Except for inline functions, declarations with types deduced from their
5110 // initializer or return value, and class template specializations, other
5111 // explicit instantiation declarations have the effect of suppressing the
5112 // implicit instantiation of the entity to which they refer.
5114 !PatternDecl->isInlined() &&
5115 !PatternDecl->getReturnType()->getContainedAutoType())
5116 return;
5117
5118 if (PatternDecl->isInlined()) {
5119 // Function, and all later redeclarations of it (from imported modules,
5120 // for instance), are now implicitly inline.
5121 for (auto *D = Function->getMostRecentDecl(); /**/;
5122 D = D->getPreviousDecl()) {
5123 D->setImplicitlyInline();
5124 if (D == Function)
5125 break;
5126 }
5127 }
5128
5129 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
5130 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5131 return;
5133 "instantiating function definition");
5134
5135 // The instantiation is visible here, even if it was first declared in an
5136 // unimported module.
5137 Function->setVisibleDespiteOwningModule();
5138
5139 // Copy the source locations from the pattern.
5140 Function->setLocation(PatternDecl->getLocation());
5141 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
5142 Function->setRangeEnd(PatternDecl->getEndLoc());
5143 Function->setDeclarationNameLoc(PatternDecl->getNameInfo().getInfo());
5144
5147
5148 Qualifiers ThisTypeQuals;
5149 CXXRecordDecl *ThisContext = nullptr;
5150 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5151 ThisContext = Method->getParent();
5152 ThisTypeQuals = Method->getMethodQualifiers();
5153 }
5154 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals);
5155
5156 // Introduce a new scope where local variable instantiations will be
5157 // recorded, unless we're actually a member function within a local
5158 // class, in which case we need to merge our results with the parent
5159 // scope (of the enclosing function). The exception is instantiating
5160 // a function template specialization, since the template to be
5161 // instantiated already has references to locals properly substituted.
5162 bool MergeWithParentScope = false;
5163 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
5164 MergeWithParentScope =
5165 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
5166
5167 LocalInstantiationScope Scope(*this, MergeWithParentScope);
5168 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
5169 // Special members might get their TypeSourceInfo set up w.r.t the
5170 // PatternDecl context, in which case parameters could still be pointing
5171 // back to the original class, make sure arguments are bound to the
5172 // instantiated record instead.
5173 assert(PatternDecl->isDefaulted() &&
5174 "Special member needs to be defaulted");
5175 auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
5176 if (!(PatternSM == CXXSpecialMemberKind::CopyConstructor ||
5180 return;
5181
5182 auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
5183 const auto *PatternRec =
5184 dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
5185 if (!NewRec || !PatternRec)
5186 return;
5187 if (!PatternRec->isLambda())
5188 return;
5189
5190 struct SpecialMemberTypeInfoRebuilder
5191 : TreeTransform<SpecialMemberTypeInfoRebuilder> {
5193 const CXXRecordDecl *OldDecl;
5194 CXXRecordDecl *NewDecl;
5195
5196 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5197 CXXRecordDecl *N)
5198 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5199
5200 bool TransformExceptionSpec(SourceLocation Loc,
5202 SmallVectorImpl<QualType> &Exceptions,
5203 bool &Changed) {
5204 return false;
5205 }
5206
5207 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5208 const RecordType *T = TL.getTypePtr();
5209 RecordDecl *Record = cast_or_null<RecordDecl>(
5210 getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5211 if (Record != OldDecl)
5212 return Base::TransformRecordType(TLB, TL);
5213
5214 QualType Result = getDerived().RebuildRecordType(NewDecl);
5215 if (Result.isNull())
5216 return QualType();
5217
5218 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5219 NewTL.setNameLoc(TL.getNameLoc());
5220 return Result;
5221 }
5222 } IR{*this, PatternRec, NewRec};
5223
5224 TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5225 assert(NewSI && "Type Transform failed?");
5226 Function->setType(NewSI->getType());
5227 Function->setTypeSourceInfo(NewSI);
5228
5229 ParmVarDecl *Parm = Function->getParamDecl(0);
5230 TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5231 assert(NewParmSI && "Type transformation failed.");
5232 Parm->setType(NewParmSI->getType());
5233 Parm->setTypeSourceInfo(NewParmSI);
5234 };
5235
5236 if (PatternDecl->isDefaulted()) {
5237 RebuildTypeSourceInfoForDefaultSpecialMembers();
5238 SetDeclDefaulted(Function, PatternDecl->getLocation());
5239 } else {
5241 Function, Function->getLexicalDeclContext(), /*Final=*/false,
5242 /*Innermost=*/std::nullopt, false, PatternDecl);
5243
5244 // Substitute into the qualifier; we can get a substitution failure here
5245 // through evil use of alias templates.
5246 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5247 // of the) lexical context of the pattern?
5248 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5249
5251
5252 // Enter the scope of this instantiation. We don't use
5253 // PushDeclContext because we don't have a scope.
5254 Sema::ContextRAII savedContext(*this, Function);
5255
5256 FPFeaturesStateRAII SavedFPFeatures(*this);
5258 FpPragmaStack.CurrentValue = FPOptionsOverride();
5259
5260 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5261 TemplateArgs))
5262 return;
5263
5264 StmtResult Body;
5265 if (PatternDecl->hasSkippedBody()) {
5267 Body = nullptr;
5268 } else {
5269 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5270 // If this is a constructor, instantiate the member initializers.
5271 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
5272 TemplateArgs);
5273
5274 // If this is an MS ABI dllexport default constructor, instantiate any
5275 // default arguments.
5277 Ctor->isDefaultConstructor()) {
5279 }
5280 }
5281
5282 // Instantiate the function body.
5283 Body = SubstStmt(Pattern, TemplateArgs);
5284
5285 if (Body.isInvalid())
5286 Function->setInvalidDecl();
5287 }
5288 // FIXME: finishing the function body while in an expression evaluation
5289 // context seems wrong. Investigate more.
5290 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5291
5292 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5293
5294 if (auto *Listener = getASTMutationListener())
5295 Listener->FunctionDefinitionInstantiated(Function);
5296
5297 savedContext.pop();
5298 }
5299
5302
5303 // This class may have local implicit instantiations that need to be
5304 // instantiation within this scope.
5305 LocalInstantiations.perform();
5306 Scope.Exit();
5307 GlobalInstantiations.perform();
5308}
5309
5311 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
5312 const TemplateArgumentList *PartialSpecArgs,
5313 const TemplateArgumentListInfo &TemplateArgsInfo,
5315 SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
5316 LocalInstantiationScope *StartingScope) {
5317 if (FromVar->isInvalidDecl())
5318 return nullptr;
5319
5320 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5321 if (Inst.isInvalid())
5322 return nullptr;
5323
5324 // Instantiate the first declaration of the variable template: for a partial
5325 // specialization of a static data member template, the first declaration may
5326 // or may not be the declaration in the class; if it's in the class, we want
5327 // to instantiate a member in the class (a declaration), and if it's outside,
5328 // we want to instantiate a definition.
5329 //
5330 // If we're instantiating an explicitly-specialized member template or member
5331 // partial specialization, don't do this. The member specialization completely
5332 // replaces the original declaration in this case.
5333 bool IsMemberSpec = false;
5334 MultiLevelTemplateArgumentList MultiLevelList;
5335 if (auto *PartialSpec =
5336 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
5337 assert(PartialSpecArgs);
5338 IsMemberSpec = PartialSpec->isMemberSpecialization();
5339 MultiLevelList.addOuterTemplateArguments(
5340 PartialSpec, PartialSpecArgs->asArray(), /*Final=*/false);
5341 } else {
5342 assert(VarTemplate == FromVar->getDescribedVarTemplate());
5343 IsMemberSpec = VarTemplate->isMemberSpecialization();
5344 MultiLevelList.addOuterTemplateArguments(VarTemplate, Converted,
5345 /*Final=*/false);
5346 }
5347 if (!IsMemberSpec)
5348 FromVar = FromVar->getFirstDecl();
5349
5350 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
5351 MultiLevelList);
5352
5353 // TODO: Set LateAttrs and StartingScope ...
5354
5355 return cast_or_null<VarTemplateSpecializationDecl>(
5357 VarTemplate, FromVar, TemplateArgsInfo, Converted));
5358}
5359
5361 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
5362 const MultiLevelTemplateArgumentList &TemplateArgs) {
5363 assert(PatternDecl->isThisDeclarationADefinition() &&
5364 "don't have a definition to instantiate from");
5365
5366 // Do substitution on the type of the declaration
5367 TypeSourceInfo *DI =
5368 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
5369 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
5370 if (!DI)
5371 return nullptr;
5372
5373 // Update the type of this variable template specialization.
5374 VarSpec->setType(DI->getType());
5375
5376 // Convert the declaration into a definition now.
5377 VarSpec->setCompleteDefinition();
5378
5379 // Instantiate the initializer.
5380 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
5381
5382 if (getLangOpts().OpenCL)
5383 deduceOpenCLAddressSpace(VarSpec);
5384
5385 return VarSpec;
5386}
5387
5389 VarDecl *NewVar, VarDecl *OldVar,
5390 const MultiLevelTemplateArgumentList &TemplateArgs,
5391 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
5392 LocalInstantiationScope *StartingScope,
5393 bool InstantiatingVarTemplate,
5394 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
5395 // Instantiating a partial specialization to produce a partial
5396 // specialization.
5397 bool InstantiatingVarTemplatePartialSpec =
5398 isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
5399 isa<VarTemplatePartialSpecializationDecl>(NewVar);
5400 // Instantiating from a variable template (or partial specialization) to
5401 // produce a variable template specialization.
5402 bool InstantiatingSpecFromTemplate =
5403 isa<VarTemplateSpecializationDecl>(NewVar) &&
5404 (OldVar->getDescribedVarTemplate() ||
5405 isa<VarTemplatePartialSpecializationDecl>(OldVar));
5406
5407 // If we are instantiating a local extern declaration, the
5408 // instantiation belongs lexically to the containing function.
5409 // If we are instantiating a static data member defined
5410 // out-of-line, the instantiation will have the same lexical
5411 // context (which will be a namespace scope) as the template.
5412 if (OldVar->isLocalExternDecl()) {
5413 NewVar->setLocalExternDecl();
5414 NewVar->setLexicalDeclContext(Owner);
5415 } else if (OldVar->isOutOfLine())
5417 NewVar->setTSCSpec(OldVar->getTSCSpec());
5418 NewVar->setInitStyle(OldVar->getInitStyle());
5419 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
5420 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
5421 NewVar->setConstexpr(OldVar->isConstexpr());
5422 NewVar->setInitCapture(OldVar->isInitCapture());
5425 NewVar->setAccess(OldVar->getAccess());
5426
5427 if (!OldVar->isStaticDataMember()) {
5428 if (OldVar->isUsed(false))
5429 NewVar->setIsUsed();
5430 NewVar->setReferenced(OldVar->isReferenced());
5431 }
5432
5433 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
5434
5436 *this, NewVar->getDeclName(), NewVar->getLocation(),
5439 NewVar->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
5441
5442 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
5444 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
5445 // We have a previous declaration. Use that one, so we merge with the
5446 // right type.
5447 if (NamedDecl *NewPrev = FindInstantiatedDecl(
5448 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
5449 Previous.addDecl(NewPrev);
5450 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
5451 OldVar->hasLinkage()) {
5452 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
5453 } else if (PrevDeclForVarTemplateSpecialization) {
5454 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
5455 }
5457
5458 if (!InstantiatingVarTemplate) {
5459 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
5460 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
5461 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
5462 }
5463
5464 if (!OldVar->isOutOfLine()) {
5465 if (NewVar->getDeclContext()->isFunctionOrMethod())
5467 }
5468
5469 // Link instantiations of static data members back to the template from
5470 // which they were instantiated.
5471 //
5472 // Don't do this when instantiating a template (we link the template itself
5473 // back in that case) nor when instantiating a static data member template
5474 // (that's not a member specialization).
5475 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
5476 !InstantiatingSpecFromTemplate)
5479
5480 // If the pattern is an (in-class) explicit specialization, then the result
5481 // is also an explicit specialization.
5482 if (VarTemplateSpecializationDecl *OldVTSD =
5483 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
5484 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
5485 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
5486 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
5488 }
5489
5490 // Forward the mangling number from the template to the instantiated decl.
5493
5494 // Figure out whether to eagerly instantiate the initializer.
5495 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
5496 // We're producing a template. Don't instantiate the initializer yet.
5497 } else if (NewVar->getType()->isUndeducedType()) {
5498 // We need the type to complete the declaration of the variable.
5499 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5500 } else if (InstantiatingSpecFromTemplate ||
5501 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
5502 !NewVar->isThisDeclarationADefinition())) {
5503 // Delay instantiation of the initializer for variable template
5504 // specializations or inline static data members until a definition of the
5505 // variable is needed.
5506 } else {
5507 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5508 }
5509
5510 // Diagnose unused local variables with dependent types, where the diagnostic
5511 // will have been deferred.
5512 if (!NewVar->isInvalidDecl() &&
5513 NewVar->getDeclContext()->isFunctionOrMethod() &&
5514 OldVar->getType()->isDependentType())
5515 DiagnoseUnusedDecl(NewVar);
5516}
5517
5519 VarDecl *Var, VarDecl *OldVar,
5520 const MultiLevelTemplateArgumentList &TemplateArgs) {
5522 L->VariableDefinitionInstantiated(Var);
5523
5524 // We propagate the 'inline' flag with the initializer, because it
5525 // would otherwise imply that the variable is a definition for a
5526 // non-static data member.
5527 if (OldVar->isInlineSpecified())
5528 Var->setInlineSpecified();
5529 else if (OldVar->isInline())
5530 Var->setImplicitlyInline();
5531
5532 if (OldVar->getInit()) {
5535
5540 // Instantiate the initializer.
5542
5543 {
5544 ContextRAII SwitchContext(*this, Var->getDeclContext());
5545 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
5546 OldVar->getInitStyle() == VarDecl::CallInit);
5547 }
5548
5549 if (!Init.isInvalid()) {
5550 Expr *InitExpr = Init.get();
5551
5552 if (Var->hasAttr<DLLImportAttr>() &&
5553 (!InitExpr ||
5554 !InitExpr->isConstantInitializer(getASTContext(), false))) {
5555 // Do not dynamically initialize dllimport variables.
5556 } else if (InitExpr) {
5557 bool DirectInit = OldVar->isDirectInit();
5558 AddInitializerToDecl(Var, InitExpr, DirectInit);
5559 } else
5561 } else {
5562 // FIXME: Not too happy about invalidating the declaration
5563 // because of a bogus initializer.
5564 Var->setInvalidDecl();
5565 }
5566 } else {
5567 // `inline` variables are a definition and declaration all in one; we won't
5568 // pick up an initializer from anywhere else.
5569 if (Var->isStaticDataMember() && !Var->isInline()) {
5570 if (!Var->isOutOfLine())
5571 return;
5572
5573 // If the declaration inside the class had an initializer, don't add
5574 // another one to the out-of-line definition.
5575 if (OldVar->getFirstDecl()->hasInit())
5576 return;
5577 }
5578
5579 // We'll add an initializer to a for-range declaration later.
5580 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
5581 return;
5582
5584 }
5585
5586 if (getLangOpts().CUDA)
5588}
5589
5591 VarDecl *Var, bool Recursive,
5592 bool DefinitionRequired, bool AtEndOfTU) {
5593 if (Var->isInvalidDecl())
5594 return;
5595
5596 // Never instantiate an explicitly-specialized entity.
5599 if (TSK == TSK_ExplicitSpecialization)
5600 return;
5601
5602 // Find the pattern and the arguments to substitute into it.
5603 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
5604 assert(PatternDecl && "no pattern for templated variable");
5605 MultiLevelTemplateArgumentList TemplateArgs =
5607
5609 dyn_cast<VarTemplateSpecializationDecl>(Var);
5610 if (VarSpec) {
5611 // If this is a static data member template, there might be an
5612 // uninstantiated initializer on the declaration. If so, instantiate
5613 // it now.
5614 //
5615 // FIXME: This largely duplicates what we would do below. The difference
5616 // is that along this path we may instantiate an initializer from an
5617 // in-class declaration of the template and instantiate the definition
5618 // from a separate out-of-class definition.
5619 if (PatternDecl->isStaticDataMember() &&
5620 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
5621 !Var->hasInit()) {
5622 // FIXME: Factor out the duplicated instantiation context setup/tear down
5623 // code here.
5624 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5625 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5626 return;
5628 "instantiating variable initializer");
5629
5630 // The instantiation is visible here, even if it was first declared in an
5631 // unimported module.
5633
5634 // If we're performing recursive template instantiation, create our own
5635 // queue of pending implicit instantiations that we will instantiate
5636 // later, while we're still within our own instantiation context.
5637 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5638 /*Enabled=*/Recursive);
5639 LocalInstantiationScope Local(*this);
5640 LocalEagerInstantiationScope LocalInstantiations(*this);
5641
5642 // Enter the scope of this instantiation. We don't use
5643 // PushDeclContext because we don't have a scope.
5644 ContextRAII PreviousContext(*this, Var->getDeclContext());
5645 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
5646 PreviousContext.pop();
5647
5648 // This variable may have local implicit instantiations that need to be
5649 // instantiated within this scope.
5650 LocalInstantiations.perform();
5651 Local.Exit();
5652 GlobalInstantiations.perform();
5653 }
5654 } else {
5655 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
5656 "not a static data member?");
5657 }
5658
5659 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
5660
5661 // If we don't have a definition of the variable template, we won't perform
5662 // any instantiation. Rather, we rely on the user to instantiate this
5663 // definition (or provide a specialization for it) in another translation
5664 // unit.
5665 if (!Def && !DefinitionRequired) {
5667 PendingInstantiations.push_back(
5668 std::make_pair(Var, PointOfInstantiation));
5669 } else if (TSK == TSK_ImplicitInstantiation) {
5670 // Warn about missing definition at the end of translation unit.
5671 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5672 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5673 Diag(PointOfInstantiation, diag::warn_var_template_missing)
5674 << Var;
5675 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5677 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
5678 }
5679 return;
5680 }
5681 }
5682
5683 // FIXME: We need to track the instantiation stack in order to know which
5684 // definitions should be visible within this instantiation.
5685 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
5686 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
5687 /*InstantiatedFromMember*/false,
5688 PatternDecl, Def, TSK,
5689 /*Complain*/DefinitionRequired))
5690 return;
5691
5692 // C++11 [temp.explicit]p10:
5693 // Except for inline functions, const variables of literal types, variables
5694 // of reference types, [...] explicit instantiation declarations
5695 // have the effect of suppressing the implicit instantiation of the entity
5696 // to which they refer.
5697 //
5698 // FIXME: That's not exactly the same as "might be usable in constant
5699 // expressions", which only allows constexpr variables and const integral
5700 // types, not arbitrary const literal types.
5703 return;
5704
5705 // Make sure to pass the instantiated variable to the consumer at the end.
5706 struct PassToConsumerRAII {
5707 ASTConsumer &Consumer;
5708 VarDecl *Var;
5709
5710 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
5711 : Consumer(Consumer), Var(Var) { }
5712
5713 ~PassToConsumerRAII() {
5715 }
5716 } PassToConsumerRAII(Consumer, Var);
5717
5718 // If we already have a definition, we're done.
5719 if (VarDecl *Def = Var->getDefinition()) {
5720 // We may be explicitly instantiating something we've already implicitly
5721 // instantiated.
5723 PointOfInstantiation);
5724 return;
5725 }
5726
5727 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5728 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5729 return;
5731 "instantiating variable definition");
5732
5733 // If we're performing recursive template instantiation, create our own
5734 // queue of pending implicit instantiations that we will instantiate later,
5735 // while we're still within our own instantiation context.
5736 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5737 /*Enabled=*/Recursive);
5738
5739 // Enter the scope of this instantiation. We don't use
5740 // PushDeclContext because we don't have a scope.
5741 ContextRAII PreviousContext(*this, Var->getDeclContext());
5742 LocalInstantiationScope Local(*this);
5743
5744 LocalEagerInstantiationScope LocalInstantiations(*this);
5745
5746 VarDecl *OldVar = Var;
5747 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
5748 // We're instantiating an inline static data member whose definition was
5749 // provided inside the class.
5750 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5751 } else if (!VarSpec) {
5752 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
5753 TemplateArgs));
5754 } else if (Var->isStaticDataMember() &&
5755 Var->getLexicalDeclContext()->isRecord()) {
5756 // We need to instantiate the definition of a static data member template,
5757 // and all we have is the in-class declaration of it. Instantiate a separate
5758 // declaration of the definition.
5759 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
5760 TemplateArgs);
5761
5762 TemplateArgumentListInfo TemplateArgInfo;
5763 if (const ASTTemplateArgumentListInfo *ArgInfo =
5764 VarSpec->getTemplateArgsAsWritten()) {
5765 TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
5766 TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
5767 for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
5768 TemplateArgInfo.addArgument(Arg);
5769 }
5770
5771 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5772 VarSpec->getSpecializedTemplate(), Def, TemplateArgInfo,
5773 VarSpec->getTemplateArgs().asArray(), VarSpec));
5774 if (Var) {
5775 llvm::PointerUnion<VarTemplateDecl *,
5779 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
5780 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
5781 Partial, &VarSpec->getTemplateInstantiationArgs());
5782
5783 // Attach the initializer.
5784 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5785 }
5786 } else
5787 // Complete the existing variable's definition with an appropriately
5788 // substituted type and initializer.
5789 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
5790
5791 PreviousContext.pop();
5792
5793 if (Var) {
5794 PassToConsumerRAII.Var = Var;
5796 OldVar->getPointOfInstantiation());
5797 }
5798
5799 // This variable may have local implicit instantiations that need to be
5800 // instantiated within this scope.
5801 LocalInstantiations.perform();
5802 Local.Exit();
5803 GlobalInstantiations.perform();
5804}
5805
5806void
5808 const CXXConstructorDecl *Tmpl,
5809 const MultiLevelTemplateArgumentList &TemplateArgs) {
5810
5812 bool AnyErrors = Tmpl->isInvalidDecl();
5813
5814 // Instantiate all the initializers.
5815 for (const auto *Init : Tmpl->inits()) {
5816 // Only instantiate written initializers, let Sema re-construct implicit
5817 // ones.
5818 if (!Init->isWritten())
5819 continue;
5820
5821 SourceLocation EllipsisLoc;
5822
5823 if (Init->isPackExpansion()) {
5824 // This is a pack expansion. We should expand it now.
5825 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
5827 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
5828 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
5829 bool ShouldExpand = false;
5830 bool RetainExpansion = false;
5831 std::optional<unsigned> NumExpansions;
5832 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
5833 BaseTL.getSourceRange(),
5834 Unexpanded,
5835 TemplateArgs, ShouldExpand,
5836 RetainExpansion,
5837 NumExpansions)) {
5838 AnyErrors = true;
5839 New->setInvalidDecl();
5840 continue;
5841 }
5842 assert(ShouldExpand && "Partial instantiation of base initializer?");
5843
5844 // Loop over all of the arguments in the argument pack(s),
5845 for (unsigned I = 0; I != *NumExpansions; ++I) {
5846 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
5847
5848 // Instantiate the initializer.
5849 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5850 /*CXXDirectInit=*/true);
5851 if (TempInit.isInvalid()) {
5852 AnyErrors = true;
5853 break;
5854 }
5855
5856 // Instantiate the base type.
5857 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
5858 TemplateArgs,
5859 Init->getSourceLocation(),
5860 New->getDeclName());
5861 if (!BaseTInfo) {
5862 AnyErrors = true;
5863 break;
5864 }
5865
5866 // Build the initializer.
5867 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
5868 BaseTInfo, TempInit.get(),
5869 New->getParent(),
5870 SourceLocation());
5871 if (NewInit.isInvalid()) {
5872 AnyErrors = true;
5873 break;
5874 }
5875
5876 NewInits.push_back(NewInit.get());
5877 }
5878
5879 continue;
5880 }
5881
5882 // Instantiate the initializer.
5883 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5884 /*CXXDirectInit=*/true);
5885 if (TempInit.isInvalid()) {
5886 AnyErrors = true;
5887 continue;
5888 }
5889
5890 MemInitResult NewInit;
5891 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
5892 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
5893 TemplateArgs,
5894 Init->getSourceLocation(),
5895 New->getDeclName());
5896 if (!TInfo) {
5897 AnyErrors = true;
5898 New->setInvalidDecl();
5899 continue;
5900 }
5901
5902 if (Init->isBaseInitializer())
5903 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
5904 New->getParent(), EllipsisLoc);
5905 else
5906 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
5907 cast<CXXRecordDecl>(CurContext->getParent()));
5908 } else if (Init->isMemberInitializer()) {
5909 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
5910 Init->getMemberLocation(),
5911 Init->getMember(),
5912 TemplateArgs));
5913 if (!Member) {
5914 AnyErrors = true;
5915 New->setInvalidDecl();
5916 continue;
5917 }
5918
5919 NewInit = BuildMemberInitializer(Member, TempInit.get(),
5920 Init->getSourceLocation());
5921 } else if (Init->isIndirectMemberInitializer()) {
5922 IndirectFieldDecl *IndirectMember =
5923 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
5924 Init->getMemberLocation(),
5925 Init->getIndirectMember(), TemplateArgs));
5926
5927 if (!IndirectMember) {
5928 AnyErrors = true;
5929 New->setInvalidDecl();
5930 continue;
5931 }
5932
5933 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
5934 Init->getSourceLocation());
5935 }
5936
5937 if (NewInit.isInvalid()) {
5938 AnyErrors = true;
5939 New->setInvalidDecl();
5940 } else {
5941 NewInits.push_back(NewInit.get());
5942 }
5943 }
5944
5945 // Assign all the initializers to the new constructor.
5947 /*FIXME: ColonLoc */
5949 NewInits,
5950 AnyErrors);
5951}
5952
5953// TODO: this could be templated if the various decl types used the
5954// same method name.
5956 ClassTemplateDecl *Instance) {
5957 Pattern = Pattern->getCanonicalDecl();
5958
5959 do {
5960 Instance = Instance->getCanonicalDecl();
5961 if (Pattern == Instance) return true;
5962 Instance = Instance->getInstantiatedFromMemberTemplate();
5963 } while (Instance);
5964
5965 return false;
5966}
5967
5969 FunctionTemplateDecl *Instance) {
5970 Pattern = Pattern->getCanonicalDecl();
5971
5972 do {
5973 Instance = Instance->getCanonicalDecl();
5974 if (Pattern == Instance) return true;
5975 Instance = Instance->getInstantiatedFromMemberTemplate();
5976 } while (Instance);
5977
5978 return false;
5979}
5980
5981static bool
5984 Pattern
5985 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5986 do {
5987 Instance = cast<ClassTemplatePartialSpecializationDecl>(
5988 Instance->getCanonicalDecl());
5989 if (Pattern == Instance)
5990 return true;
5991 Instance = Instance->getInstantiatedFromMember();
5992 } while (Instance);
5993
5994 return false;
5995}
5996
5998 CXXRecordDecl *Instance) {
5999 Pattern = Pattern->getCanonicalDecl();
6000
6001 do {
6002 Instance = Instance->getCanonicalDecl();
6003 if (Pattern == Instance) return true;
6004 Instance = Instance->getInstantiatedFromMemberClass();
6005 } while (Instance);
6006
6007 return false;
6008}
6009
6010static bool isInstantiationOf(FunctionDecl *Pattern,
6011 FunctionDecl *Instance) {
6012 Pattern = Pattern->getCanonicalDecl();
6013
6014 do {
6015 Instance = Instance->getCanonicalDecl();
6016 if (Pattern == Instance) return true;
6017 Instance = Instance->getInstantiatedFromMemberFunction();
6018 } while (Instance);
6019
6020 return false;
6021}
6022
6023static bool isInstantiationOf(EnumDecl *Pattern,
6024 EnumDecl *Instance) {
6025 Pattern = Pattern->getCanonicalDecl();
6026
6027 do {
6028 Instance = Instance->getCanonicalDecl();
6029 if (Pattern == Instance) return true;
6030 Instance = Instance->getInstantiatedFromMemberEnum();
6031 } while (Instance);
6032
6033 return false;
6034}
6035
6037 UsingShadowDecl *Instance,
6038 ASTContext &C) {
6039 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
6040 Pattern);
6041}
6042
6043static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
6044 ASTContext &C) {
6045 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
6046}
6047
6048template<typename T>
6050 ASTContext &Ctx) {
6051 // An unresolved using declaration can instantiate to an unresolved using
6052 // declaration, or to a using declaration or a using declaration pack.
6053 //
6054 // Multiple declarations can claim to be instantiated from an unresolved
6055 // using declaration if it's a pack expansion. We want the UsingPackDecl
6056 // in that case, not the individual UsingDecls within the pack.
6057 bool OtherIsPackExpansion;
6058 NamedDecl *OtherFrom;
6059 if (auto *OtherUUD = dyn_cast<T>(Other)) {
6060 OtherIsPackExpansion = OtherUUD->isPackExpansion();
6061 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
6062 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
6063 OtherIsPackExpansion = true;
6064 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
6065 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
6066 OtherIsPackExpansion = false;
6067 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
6068 } else {
6069 return false;
6070 }
6071 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
6072 declaresSameEntity(OtherFrom, Pattern);
6073}
6074
6076 VarDecl *Instance) {
6077 assert(Instance->isStaticDataMember());
6078
6079 Pattern = Pattern->getCanonicalDecl();
6080
6081 do {
6082 Instance = Instance->getCanonicalDecl();
6083 if (Pattern == Instance) return true;
6084 Instance = Instance->getInstantiatedFromStaticDataMember();
6085 } while (Instance);
6086
6087 return false;
6088}
6089
6090// Other is the prospective instantiation
6091// D is the prospective pattern
6093 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
6095
6096 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
6098
6099 if (D->getKind() != Other->getKind())
6100 return false;
6101
6102 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
6103 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
6104
6105 if (auto *Function = dyn_cast<FunctionDecl>(Other))
6106 return isInstantiationOf(cast<FunctionDecl>(D), Function);
6107
6108 if (auto *Enum = dyn_cast<EnumDecl>(Other))
6109 return isInstantiationOf(cast<EnumDecl>(D), Enum);
6110
6111 if (auto *Var = dyn_cast<VarDecl>(Other))
6112 if (Var->isStaticDataMember())
6113 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
6114
6115 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
6116 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
6117
6118 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
6119 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
6120
6121 if (auto *PartialSpec =
6122 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
6123 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
6124 PartialSpec);
6125
6126 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
6127 if (!Field->getDeclName()) {
6128 // This is an unnamed field.
6130 cast<FieldDecl>(D));
6131 }
6132 }
6133
6134 if (auto *Using = dyn_cast<UsingDecl>(Other))
6135 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
6136
6137 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
6138 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
6139
6140 return D->getDeclName() &&
6141 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
6142}
6143
6144template<typename ForwardIterator>
6146 NamedDecl *D,
6147 ForwardIterator first,
6148 ForwardIterator last) {
6149 for (; first != last; ++first)
6150 if (isInstantiationOf(Ctx, D, *first))
6151 return cast<NamedDecl>(*first);
6152
6153 return nullptr;
6154}
6155
6157 const MultiLevelTemplateArgumentList &TemplateArgs) {
6158 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
6159 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
6160 return cast_or_null<DeclContext>(ID);
6161 } else return DC;
6162}
6163
6164/// Determine whether the given context is dependent on template parameters at
6165/// level \p Level or below.
6166///
6167/// Sometimes we only substitute an inner set of template arguments and leave
6168/// the outer templates alone. In such cases, contexts dependent only on the
6169/// outer levels are not effectively dependent.
6170static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
6171 if (!DC->isDependentContext())
6172 return false;
6173 if (!Level)
6174 return true;
6175 return cast<Decl>(DC)->getTemplateDepth() > Level;
6176}
6177
6179 const MultiLevelTemplateArgumentList &TemplateArgs,
6180 bool FindingInstantiatedContext) {
6181 DeclContext *ParentDC = D->getDeclContext();
6182 // Determine whether our parent context depends on any of the template
6183 // arguments we're currently substituting.
6184 bool ParentDependsOnArgs = isDependentContextAtLevel(
6185 ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6186 // FIXME: Parameters of pointer to functions (y below) that are themselves
6187 // parameters (p below) can have their ParentDC set to the translation-unit
6188 // - thus we can not consistently check if the ParentDC of such a parameter
6189 // is Dependent or/and a FunctionOrMethod.
6190 // For e.g. this code, during Template argument deduction tries to
6191 // find an instantiated decl for (T y) when the ParentDC for y is
6192 // the translation unit.
6193 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6194 // float baz(float(*)()) { return 0.0; }
6195 // Foo(baz);
6196 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6197 // it gets here, always has a FunctionOrMethod as its ParentDC??
6198 // For now:
6199 // - as long as we have a ParmVarDecl whose parent is non-dependent and
6200 // whose type is not instantiation dependent, do nothing to the decl
6201 // - otherwise find its instantiated decl.
6202 if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6203 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6204 return D;
6205 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
6206 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
6207 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6208 isa<OMPDeclareReductionDecl>(ParentDC) ||
6209 isa<OMPDeclareMapperDecl>(ParentDC))) ||
6210 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6211 cast<CXXRecordDecl>(D)->getTemplateDepth() >
6212 TemplateArgs.getNumRetainedOuterLevels())) {
6213 // D is a local of some kind. Look into the map of local
6214 // declarations to their instantiations.
6217 if (Decl *FD = Found->dyn_cast<Decl *>())
6218 return cast<NamedDecl>(FD);
6219
6220 int PackIdx = ArgumentPackSubstitutionIndex;
6221 assert(PackIdx != -1 &&
6222 "found declaration pack but not pack expanding");
6223 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6224 return cast<NamedDecl>((*cast<DeclArgumentPack *>(*Found))[PackIdx]);
6225 }
6226 }
6227
6228 // If we're performing a partial substitution during template argument
6229 // deduction, we may not have values for template parameters yet. They
6230 // just map to themselves.
6231 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
6232 isa<TemplateTemplateParmDecl>(D))
6233 return D;
6234
6235 if (D->isInvalidDecl())
6236 return nullptr;
6237
6238 // Normally this function only searches for already instantiated declaration
6239 // however we have to make an exclusion for local types used before
6240 // definition as in the code:
6241 //
6242 // template<typename T> void f1() {
6243 // void g1(struct x1);
6244 // struct x1 {};
6245 // }
6246 //
6247 // In this case instantiation of the type of 'g1' requires definition of
6248 // 'x1', which is defined later. Error recovery may produce an enum used
6249 // before definition. In these cases we need to instantiate relevant
6250 // declarations here.
6251 bool NeedInstantiate = false;
6252 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6253 NeedInstantiate = RD->isLocalClass();
6254 else if (isa<TypedefNameDecl>(D) &&
6255 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
6256 NeedInstantiate = true;
6257 else
6258 NeedInstantiate = isa<EnumDecl>(D);
6259 if (NeedInstantiate) {
6260 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6262 return cast<TypeDecl>(Inst);
6263 }
6264
6265 // If we didn't find the decl, then we must have a label decl that hasn't
6266 // been found yet. Lazily instantiate it and return it now.
6267 assert(isa<LabelDecl>(D));
6268
6269 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6270 assert(Inst && "Failed to instantiate label??");
6271
6273 return cast<LabelDecl>(Inst);
6274 }
6275
6276 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
6277 if (!Record->isDependentContext())
6278 return D;
6279
6280 // Determine whether this record is the "templated" declaration describing
6281 // a class template or class template specialization.
6282 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
6283 if (ClassTemplate)
6284 ClassTemplate = ClassTemplate->getCanonicalDecl();
6285 else if (ClassTemplateSpecializationDecl *Spec =
6286 dyn_cast<ClassTemplateSpecializationDecl>(Record))
6287 ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl();
6288
6289 // Walk the current context to find either the record or an instantiation of
6290 // it.
6291 DeclContext *DC = CurContext;
6292 while (!DC->isFileContext()) {
6293 // If we're performing substitution while we're inside the template
6294 // definition, we'll find our own context. We're done.
6295 if (DC->Equals(Record))
6296 return Record;
6297
6298 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
6299 // Check whether we're in the process of instantiating a class template
6300 // specialization of the template we're mapping.
6302 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
6303 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
6304 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
6305 return InstRecord;
6306 }
6307
6308 // Check whether we're in the process of instantiating a member class.
6309 if (isInstantiationOf(Record, InstRecord))
6310 return InstRecord;
6311 }
6312
6313 // Move to the outer template scope.
6314 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
6315 if (FD->getFriendObjectKind() &&
6317 DC = FD->getLexicalDeclContext();
6318 continue;
6319 }
6320 // An implicit deduction guide acts as if it's within the class template
6321 // specialization described by its name and first N template params.
6322 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
6323 if (Guide && Guide->isImplicit()) {
6324 TemplateDecl *TD = Guide->getDeducedTemplate();
6325 // Convert the arguments to an "as-written" list.
6327 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
6328 TD->getTemplateParameters()->size())) {
6329 ArrayRef<TemplateArgument> Unpacked(Arg);
6330 if (Arg.getKind() == TemplateArgument::Pack)
6331 Unpacked = Arg.pack_elements();
6332 for (TemplateArgument UnpackedArg : Unpacked)
6333 Args.addArgument(
6334 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
6335 }
6337 // We may get a non-null type with errors, in which case
6338 // `getAsCXXRecordDecl` will return `nullptr`. For instance, this
6339 // happens when one of the template arguments is an invalid
6340 // expression. We return early to avoid triggering the assertion
6341 // about the `CodeSynthesisContext`.
6342 if (T.isNull() || T->containsErrors())
6343 return nullptr;
6344 CXXRecordDecl *SubstRecord = T->getAsCXXRecordDecl();
6345
6346 if (!SubstRecord) {
6347 // T can be a dependent TemplateSpecializationType when performing a
6348 // substitution for building a deduction guide or for template
6349 // argument deduction in the process of rebuilding immediate
6350 // expressions. (Because the default argument that involves a lambda
6351 // is untransformed and thus could be dependent at this point.)
6353 CodeSynthesisContexts.back().Kind ==
6355 // Return a nullptr as a sentinel value, we handle it properly in
6356 // the TemplateInstantiator::TransformInjectedClassNameType
6357 // override, which we transform it to a TemplateSpecializationType.
6358 return nullptr;
6359 }
6360 // Check that this template-id names the primary template and not a
6361 // partial or explicit specialization. (In the latter cases, it's
6362 // meaningless to attempt to find an instantiation of D within the
6363 // specialization.)
6364 // FIXME: The standard doesn't say what should happen here.
6365 if (FindingInstantiatedContext &&
6367 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
6368 Diag(Loc, diag::err_specialization_not_primary_template)
6369 << T << (SubstRecord->getTemplateSpecializationKind() ==
6371 return nullptr;
6372 }
6373 DC = SubstRecord;
6374 continue;
6375 }
6376 }
6377
6378 DC = DC->getParent();
6379 }
6380
6381 // Fall through to deal with other dependent record types (e.g.,
6382 // anonymous unions in class templates).
6383 }
6384
6385 if (!ParentDependsOnArgs)
6386 return D;
6387
6388 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
6389 if (!ParentDC)
6390 return nullptr;
6391
6392 if (ParentDC != D->getDeclContext()) {
6393 // We performed some kind of instantiation in the parent context,
6394 // so now we need to look into the instantiated parent context to
6395 // find the instantiation of the declaration D.
6396
6397 // If our context used to be dependent, we may need to instantiate
6398 // it before performing lookup into that context.
6399 bool IsBeingInstantiated = false;
6400 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
6401 if (!Spec->isDependentContext()) {
6403 const RecordType *Tag = T->getAs<RecordType>();
6404 assert(Tag && "type of non-dependent record is not a RecordType");
6405 if (Tag->isBeingDefined())
6406 IsBeingInstantiated = true;
6407 if (!Tag->isBeingDefined() &&
6408 RequireCompleteType(Loc, T, diag::err_incomplete_type))
6409 return nullptr;
6410
6411 ParentDC = Tag->getDecl();
6412 }
6413 }
6414
6415 NamedDecl *Result = nullptr;
6416 // FIXME: If the name is a dependent name, this lookup won't necessarily
6417 // find it. Does that ever matter?
6418 if (auto Name = D->getDeclName()) {
6419 DeclarationNameInfo NameInfo(Name, D->getLocation());
6420 DeclarationNameInfo NewNameInfo =
6421 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
6422 Name = NewNameInfo.getName();
6423 if (!Name)
6424 return nullptr;
6425 DeclContext::lookup_result Found = ParentDC->lookup(Name);
6426
6427 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
6428 } else {
6429 // Since we don't have a name for the entity we're looking for,
6430 // our only option is to walk through all of the declarations to
6431 // find that name. This will occur in a few cases:
6432 //
6433 // - anonymous struct/union within a template
6434 // - unnamed class/struct/union/enum within a template
6435 //
6436 // FIXME: Find a better way to find these instantiations!
6438 ParentDC->decls_begin(),
6439 ParentDC->decls_end());
6440 }
6441
6442 if (!Result) {
6443 if (isa<UsingShadowDecl>(D)) {
6444 // UsingShadowDecls can instantiate to nothing because of using hiding.
6445 } else if (hasUncompilableErrorOccurred()) {
6446 // We've already complained about some ill-formed code, so most likely
6447 // this declaration failed to instantiate. There's no point in
6448 // complaining further, since this is normal in invalid code.
6449 // FIXME: Use more fine-grained 'invalid' tracking for this.
6450 } else if (IsBeingInstantiated) {
6451 // The class in which this member exists is currently being
6452 // instantiated, and we haven't gotten around to instantiating this
6453 // member yet. This can happen when the code uses forward declarations
6454 // of member classes, and introduces ordering dependencies via
6455 // template instantiation.
6456 Diag(Loc, diag::err_member_not_yet_instantiated)
6457 << D->getDeclName()
6458 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
6459 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
6460 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
6461 // This enumeration constant was found when the template was defined,
6462 // but can't be found in the instantiation. This can happen if an
6463 // unscoped enumeration member is explicitly specialized.
6464 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
6465 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
6466 TemplateArgs));
6467 assert(Spec->getTemplateSpecializationKind() ==
6469 Diag(Loc, diag::err_enumerator_does_not_exist)
6470 << D->getDeclName()
6471 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
6472 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
6473 << Context.getTypeDeclType(Spec);
6474 } else {
6475 // We should have found something, but didn't.
6476 llvm_unreachable("Unable to find instantiation of declaration!");
6477 }
6478 }
6479
6480 D = Result;
6481 }
6482
6483 return D;
6484}
6485
6487 std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
6488 while (!PendingLocalImplicitInstantiations.empty() ||
6489 (!LocalOnly && !PendingInstantiations.empty())) {
6491
6493 Inst = PendingInstantiations.front();
6494 PendingInstantiations.pop_front();
6495 } else {
6498 }
6499
6500 // Instantiate function definitions
6501 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
6502 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
6504 if (Function->isMultiVersion()) {
6506 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
6507 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
6508 DefinitionRequired, true);
6509 if (CurFD->isDefined())
6510 CurFD->setInstantiationIsPending(false);
6511 });
6512 } else {
6513 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
6514 DefinitionRequired, true);
6515 if (Function->isDefined())
6516 Function->setInstantiationIsPending(false);
6517 }
6518 // Definition of a PCH-ed template declaration may be available only in the TU.
6519 if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
6520 TUKind == TU_Prefix && Function->instantiationIsPending())
6521 delayedPCHInstantiations.push_back(Inst);
6522 continue;
6523 }
6524
6525 // Instantiate variable definitions
6526 VarDecl *Var = cast<VarDecl>(Inst.first);
6527
6528 assert((Var->isStaticDataMember() ||
6529 isa<VarTemplateSpecializationDecl>(Var)) &&
6530 "Not a static data member, nor a variable template"
6531 " specialization?");
6532
6533 // Don't try to instantiate declarations if the most recent redeclaration
6534 // is invalid.
6535 if (Var->getMostRecentDecl()->isInvalidDecl())
6536 continue;
6537
6538 // Check if the most recent declaration has changed the specialization kind
6539 // and removed the need for implicit instantiation.
6540 switch (Var->getMostRecentDecl()
6542 case TSK_Undeclared:
6543 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
6546 continue; // No longer need to instantiate this type.
6548 // We only need an instantiation if the pending instantiation *is* the
6549 // explicit instantiation.
6550 if (Var != Var->getMostRecentDecl())
6551 continue;
6552 break;
6554 break;
6555 }
6556
6558 "instantiating variable definition");
6559 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
6561
6562 // Instantiate static data member definitions or variable template
6563 // specializations.
6564 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
6565 DefinitionRequired, true);
6566 }
6567
6568 if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
6569 PendingInstantiations.swap(delayedPCHInstantiations);
6570}
6571
6573 const MultiLevelTemplateArgumentList &TemplateArgs) {
6574 for (auto *DD : Pattern->ddiags()) {
6575 switch (DD->getKind()) {
6577 HandleDependentAccessCheck(*DD, TemplateArgs);
6578 break;
6579 }
6580 }
6581}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
const Decl * D
Expr * E
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
llvm::MachO::Record Record
Definition: MachO.h:31
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis for CUDA constructs.
This file declares semantic analysis for HLSL constructs.
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to Swift.
static void instantiateDependentAMDGPUWavesPerEUAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AMDGPUWavesPerEUAttr &Attr, Decl *New)
static NamedDecl * findInstantiationOf(ASTContext &Ctx, NamedDecl *D, ForwardIterator first, ForwardIterator last)
static void instantiateDependentAMDGPUMaxNumWorkGroupsAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New)
static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New)
static void instantiateDependentDiagnoseIfAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New)
static QualType adjustFunctionTypeForInstantiation(ASTContext &Context, FunctionDecl *D, TypeSourceInfo *TInfo)
Adjust the given function type for an instantiation of the given declaration, to cope with modificati...
static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A)
Determine whether the attribute A might be relevant to the declaration D.
static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level)
Determine whether the given context is dependent on template parameters at level Level or below.
static void instantiateDependentModeAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const ModeAttr &Attr, Decl *New)
static void instantiateDependentCUDALaunchBoundsAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const CUDALaunchBoundsAttr &Attr, Decl *New)
static bool isDeclWithinFunction(const Decl *D)
static void instantiateDependentAssumeAlignedAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AssumeAlignedAttr *Aligned, Decl *New)
static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl, const MultiLevelTemplateArgumentList &TemplateArgs)
static void collectUnexpandedParameterPacks(Sema &S, TemplateParameterList *Params, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
static DeclT * getPreviousDeclForInstantiation(DeclT *D)
Get the previous declaration of a declaration for the purposes of template instantiation.
static Expr * instantiateDependentFunctionAttrCondition(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New)
static bool isInstantiationOf(ClassTemplateDecl *Pattern, ClassTemplateDecl *Instance)
static void instantiateDependentHLSLParamModifierAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const HLSLParamModifierAttr *Attr, Decl *New)
static void instantiateDependentAllocAlignAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AllocAlignAttr *Align, Decl *New)
static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, VarDecl *Instance)
static void instantiateOMPDeclareSimdDeclAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const OMPDeclareSimdDeclAttr &Attr, Decl *New)
Instantiation of 'declare simd' attribute and its arguments.
static void instantiateDependentSYCLKernelAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLKernelAttr &Attr, Decl *New)
static void instantiateDependentAlignValueAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AlignValueAttr *Aligned, Decl *New)
static void instantiateDependentAlignedAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion)
static void instantiateOMPDeclareVariantAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const OMPDeclareVariantAttr &Attr, Decl *New)
Instantiation of 'declare variant' attribute and its arguments.
static void instantiateDependentEnableIfAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New)
static void instantiateDependentAnnotationAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AnnotateAttr *Attr, Decl *New)
static Sema::RetainOwnershipKind attrToRetainOwnershipKind(const Attr *A)
static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other, ASTContext &Ctx)
static bool isInvalid(LocType Loc, bool *Invalid)
Defines the SourceManager interface.
Defines the clang::TypeLoc interface and its subclasses.
StateNode * Previous
#define bool
Definition: amdgpuintrin.h:20
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:34
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *D)
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
Definition: ASTConsumer.h:117
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
QualType getRecordType(const RecordDecl *Decl) const
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2716
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2732
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
unsigned getStaticLocalNumber(const VarDecl *VD) const
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
CanQualType BoolTy
Definition: ASTContext.h:1161
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType IntTy
Definition: ASTContext.h:1169
void setManglingNumber(const NamedDecl *ND, unsigned Number)
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Represents an access specifier followed by colon ':'.
Definition: DeclCXX.h:86
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition: DeclCXX.h:117
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Attr - This represents one attribute.
Definition: Attr.h:43
attr::Kind getKind() const
Definition: Attr.h:89
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition: Attr.h:96
SourceLocation getLoc() const
Represents a C++ declaration that introduces decls from somewhere else.
Definition: DeclCXX.h:3440
A binding in a decomposition declaration.
Definition: DeclCXX.h:4130
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
Definition: DeclCXX.cpp:3426
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2845
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2815
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2885
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:3004
Represents a C++ deduction guide declaration.
Definition: DeclCXX.h:1967
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2250
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2949
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2582
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2368
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2560
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, unsigned DependencyKind, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
Definition: DeclCXX.cpp:147
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:131
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1999
void setInstantiationOfMemberClass(CXXRecordDecl *RD, TemplateSpecializationKind TSK)
Specify that this record is an instantiation of the member class RD.
Definition: DeclCXX.cpp:1982
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1995
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
Declaration of a class template.
void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D, void *InsertPos)
Insert the specified partial specialization knowing that it is not already in.
ClassTemplateDecl * getMostRecentDecl()
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
ClassTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, TemplateParameterList *TPL, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
ClassTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
ClassTemplatePartialSpecializationDecl * findPartialSpecInstantiatedFromMember(ClassTemplatePartialSpecializationDecl *D)
Find a class template partial specialization which was instantiated from the given member partial spe...
void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos)
Insert the specified specialization knowing that it is not already in.
void setCommonPtr(Common *C)
QualType getInjectedClassNameSpecialization()
Retrieve the template specialization type of the injected-class-name for this class template.
Common * getCommonPtr() const
ClassTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
void setInstantiatedFromMember(ClassTemplatePartialSpecializationDecl *PartialSpec)
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, QualType CanonInjectedType, ClassTemplatePartialSpecializationDecl *PrevDecl)
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setExternKeywordLoc(SourceLocation Loc)
Sets the location of the extern keyword.
void setSpecializationKind(TemplateSpecializationKind TSK)
void setTemplateKeywordLoc(SourceLocation Loc)
Sets the location of the template keyword.
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, ClassTemplateSpecializationDecl *PrevDecl)
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Declaration of a C++20 concept.
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:3621
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1368
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2218
bool isFileContext() const
Definition: DeclBase.h:2160
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2045
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
bool isRecord() const
Definition: DeclBase.h:2169
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1990
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1768
decl_iterator decls_end() const
Definition: DeclBase.h:2351
ddiag_range ddiags() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2349
bool isFunctionOrMethod() const
Definition: DeclBase.h:2141
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1742
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1624
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:487
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1050
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:438
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1215
T * getAttr() const
Definition: DeclBase.h:576
void addAttr(Attr *A)
Definition: DeclBase.cpp:1010
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1140
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:99
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:239
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:151
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:882
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1206
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:574
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:293
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition: DeclBase.h:1169
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:786
bool isInLocalScopeForInstantiation() const
Determine whether a substitution into this declaration would occur as part of a substitution into a d...
Definition: DeclBase.cpp:395
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1217
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition: DeclBase.h:1082
bool isInvalidDecl() const
Definition: DeclBase.h:591
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1158
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:562
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:505
SourceLocation getLocation() const
Definition: DeclBase.h:442
const char * getDeclKindName() const
Definition: DeclBase.cpp:142
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
void setImplicit(bool I=true)
Definition: DeclBase.h:597
void setReferenced(bool R=true)
Definition: DeclBase.h:626
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:611
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:549
DeclContext * getDeclContext()
Definition: DeclBase.h:451
attr_range attrs() const
Definition: DeclBase.h:538
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:907
bool hasAttr() const
Definition: DeclBase.h:580
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1224
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:359
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:967
Kind getKind() const
Definition: DeclBase.h:445
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:430
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:859
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
The name of a declaration.
NameKind getNameKind() const
Determine what kind of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:735
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:777
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1977
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:769
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1989
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2023
Represents the type decltype(expr) (C++11).
Definition: Type.h:5879
Expr * getUnderlyingExpr() const
Definition: Type.h:5889
A decomposition declaration.
Definition: DeclCXX.h:4189
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3450
Provides information about a dependent function-template specialization declaration.
Definition: DeclTemplate.h:694
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:7029
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:896
bool hasErrorOccurred() const
Definition: Diagnostic.h:866
RAII object that enters a new expression evaluation context.
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3291
Represents an enum.
Definition: Decl.h:3861
enumerator_range enumerators() const
Definition: Decl.h:3994
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4066
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4877
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition: Decl.h:4037
EnumDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.h:3942
TemplateSpecializationKind getTemplateSpecializationKind() const
If this enumeration is a member of a specialization of a templated class, determine what kind of temp...
Definition: Decl.cpp:4930
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
ExplicitSpecKind getKind() const
Definition: DeclCXX.h:1920
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition: DeclCXX.h:1941
static ExplicitSpecifier Invalid()
Definition: DeclCXX.h:1952
const Expr * getExpr() const
Definition: DeclCXX.h:1921
void setKind(ExplicitSpecKind Kind)
Definition: DeclCXX.h:1945
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition: DeclCXX.cpp:2237
This represents one expression.
Definition: Expr.h:110
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluated - Return true if this expression might be usable in a constant exp...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3097
bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit=nullptr) const
isConstantInitializer - Returns true if this expression can be emitted to IR as a constant,...
Definition: Expr.cpp:3325
QualType getType() const
Definition: Expr.h:142
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:226
Represents difference between two FPOptions values.
Definition: LangOptions.h:978
Represents a member of a struct/union/class.
Definition: Decl.h:3033
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
Definition: DeclFriend.cpp:34
void setUnsupportedFriend(bool Unsupported)
Definition: DeclFriend.h:189
Declaration of a friend template.
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition: Decl.cpp:3103
Represents a function declaration or definition.
Definition: Decl.h:1935
void setInstantiationIsPending(bool IC)
State that the instantiation of this function is pending.
Definition: Decl.h:2441
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3243
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4057
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4052
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2249
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition: Decl.cpp:3124
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2796
void setInstantiationOfMemberFunction(FunctionDecl *FD, TemplateSpecializationKind TSK)
Specify that this record is an instantiation of the member function FD.
Definition: Decl.h:2849
QualType getReturnType() const
Definition: Decl.h:2720
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4123
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3623
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2292
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2284
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2555
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2217
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2791
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2124
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3187
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2153
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2313
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2349
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2279
void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template, TemplateArgumentList *TemplateArgs, void *InsertPos, TemplateSpecializationKind TSK=TSK_ImplicitInstantiation, TemplateArgumentListInfo *TemplateArgsAsWritten=nullptr, SourceLocation PointOfInstantiation=SourceLocation())
Specify that this function declaration is actually a function template specialization.
Definition: Decl.h:2949
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3702
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2146
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3210
DefaultedOrDeletedFunctionInfo * getDefalutedOrDeletedInfo() const
Definition: Decl.cpp:3158
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2680
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2561
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5107
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5387
QualType getParamType(unsigned i) const
Definition: Type.h:5362
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5393
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5371
FunctionDecl * getExceptionSpecTemplate() const
If this function type has an uninstantiated exception specification, this is the function whose excep...
Definition: Type.h:5466
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5367
Declaration of a template function.
Definition: DeclTemplate.h:959
FunctionTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
FunctionTemplateDecl * getPreviousDecl()
Retrieve the previous declaration of this function template, or nullptr if no such declaration exists...
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1537
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1538
ExtInfo getExtInfo() const
Definition: Type.h:4660
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4656
QualType getReturnType() const
Definition: Type.h:4648
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
Definition: Decl.h:4941
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3335
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5506
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2524
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:980
Represents the declaration of a label.
Definition: Decl.h:503
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
Definition: Decl.cpp:5364
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
void InstantiatedLocal(const Decl *D, Decl *Inst)
LocalInstantiationScope * cloneScopes(LocalInstantiationScope *Outermost)
Clone this scope, and all outer scopes, down to the given outermost scope.
Definition: Template.h:465
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationOf(const Decl *D)
Find the instantiation of the declaration D within the current instantiation scope.
Represents the results of name lookup.
Definition: Lookup.h:46
A global _GUID constant.
Definition: DeclCXX.h:4312
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:4258
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:3491
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:620
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:265
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition: Template.h:210
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition: Template.h:123
void setKind(TemplateSubstitutionKind K)
Definition: Template.h:109
unsigned getNumSubstitutedLevels() const
Determine the number of substituted levels in this template argument list.
Definition: Template.h:129
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
unsigned getNumRetainedOuterLevels() const
Definition: Template.h:139
This represents a decl that may have a name.
Definition: Decl.h:253
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1919
void setDeclName(DeclarationName N)
Set the name of this declaration.
Definition: Decl.h:322
Represents a C++ namespace alias.
Definition: DeclCXX.h:3143
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:3129
Represent a C++ namespace.
Definition: Decl.h:551
A C++ nested-name-specifier augmented with source location information.
bool hasQualifier() const
Evaluates true when this nested-name-specifier location is non-empty.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
This represents '#pragma omp allocate ...' directive.
Definition: DeclOpenMP.h:474
Pseudo declaration for capturing expressions.
Definition: DeclOpenMP.h:383
This is a basic class for representing single OpenMP clause.
Definition: OpenMPClause.h:55
This represents '#pragma omp declare mapper ...' directive.
Definition: DeclOpenMP.h:287
This represents '#pragma omp declare reduction ...' directive.
Definition: DeclOpenMP.h:177
This represents '#pragma omp requires...' directive.
Definition: DeclOpenMP.h:417
This represents '#pragma omp threadprivate ...' directive.
Definition: DeclOpenMP.h:110
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
bool anyScoreOrCondition(llvm::function_ref< bool(Expr *&, bool)> Cond)
Represents a field declaration created by an @defs(...).
Definition: DeclObjC.h:2029
Wrapper for void* pointer.
Definition: Ownership.h:50
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(QualType P)
Definition: Ownership.h:60
SourceLocation getEllipsisLoc() const
Definition: TypeLoc.h:2609
TypeLoc getPatternLoc() const
Definition: TypeLoc.h:2625
Represents a pack expansion of types.
Definition: Type.h:7146
std::optional< unsigned > getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: Type.h:7171
Represents a parameter to a function.
Definition: Decl.h:1725
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1858
Represents a #pragma comment line.
Definition: Decl.h:146
Represents a #pragma detect_mismatch line.
Definition: Decl.h:180
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition: Type.h:929
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:8139
The collection of all-type qualifiers we support.
Definition: Type.h:324
Represents a struct/union/class.
Definition: Decl.h:4162
Wrapper for source info for record types.
Definition: TypeLoc.h:741
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6077
void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD)
Definition: DeclTemplate.h:910
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:225
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4995
Represents the body of a requires-expression.
Definition: DeclCXX.h:2047
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition: DeclCXX.cpp:2268
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size attribute to a particular declar...
Definition: SemaAMDGPU.cpp:212
void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a particular declaration.
Definition: SemaAMDGPU.cpp:273
void addAMDGPUMaxNumWorkGroupsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XExpr, Expr *YExpr, Expr *ZExpr)
addAMDGPUMaxNumWorkGroupsAttr - Adds an amdgpu_max_num_work_groups attribute to a particular declarat...
Definition: SemaAMDGPU.cpp:355
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
Sema & SemaRef
Definition: SemaBase.h:40
void checkAllowedInitializer(VarDecl *VD)
Definition: SemaCUDA.cpp:656
QualType getInoutParameterType(QualType Ty)
Definition: SemaHLSL.cpp:2477
bool inferObjCARCLifetime(ValueDecl *decl)
void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, Sema::RetainOwnershipKind K, bool IsTemplateInstantiation)
Definition: SemaObjC.cpp:1740
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid)
Called at the end of '#pragma omp declare reduction'.
void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner)
Finish current declare reduction construct initializer.
ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN)
Build the mapper variable of '#pragma omp declare mapper'.
VarDecl * ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D)
Initialize declare reduction construct initializer.
QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType)
Check if the specified type is allowed to be used in 'omp declare reduction' construct.
DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef< Expr * > VarList, ArrayRef< OMPClause * > Clauses, DeclContext *Owner=nullptr)
Called on well-formed '#pragma omp allocate'.
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef< std::pair< QualType, SourceLocation > > ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope=nullptr)
Called on start of '#pragma omp declare reduction'.
OMPClause * ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc)
Called on well-formed 'allocator' clause.
void EndOpenMPDSABlock(Stmt *CurDirective)
Called on end of data sharing attribute block.
QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType)
Check if the specified type is allowed to be used in 'omp declare mapper' construct.
std::optional< std::pair< FunctionDecl *, Expr * > > checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, OMPTraitInfo &TI, unsigned NumAppendArgs, SourceRange SR)
Checks '#pragma omp declare variant' variant function and original functions after parsing of the ass...
void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D)
Initialize declare reduction construct initializer.
OMPClause * ActOnOpenMPMapClause(Expr *IteratorModifier, ArrayRef< OpenMPMapModifierKind > MapTypeModifiers, ArrayRef< SourceLocation > MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef< Expr * > VarList, const OMPVarListLocTy &Locs, bool NoDiagnose=false, ArrayRef< Expr * > UnresolvedMappers={})
Called on well-formed 'map' clause.
void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc)
Called on start of new data sharing attribute block.
OMPThreadPrivateDecl * CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef< Expr * > VarList)
Builds a new OpenMPThreadPrivateDecl and checks its correctness.
void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, ArrayRef< Expr * > AdjustArgsNothing, ArrayRef< Expr * > AdjustArgsNeedDevicePtr, ArrayRef< OMPInteropInfo > AppendArgs, SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, SourceRange SR)
Called on well-formed '#pragma omp declare variant' after parsing of the associated method/function.
void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm)
Finish current declare reduction construct initializer.
DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef< Expr * > Uniforms, ArrayRef< Expr * > Aligneds, ArrayRef< Expr * > Alignments, ArrayRef< Expr * > Linears, ArrayRef< unsigned > LinModifiers, ArrayRef< Expr * > Steps, SourceRange SR)
Called on well-formed '#pragma omp declare simd' after parsing of the associated method/function.
OMPClause * ActOnOpenMPAlignClause(Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc)
Called on well-formed 'align' clause.
DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Expr *MapperVarRef, ArrayRef< OMPClause * > Clauses, Decl *PrevDeclInScope=nullptr)
Called on start of '#pragma omp declare mapper'.
void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI abi)
Definition: SemaSwift.cpp:715
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:13200
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8048
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3010
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5920
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12614
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition: Sema.h:13569
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:12125
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
SemaAMDGPU & AMDGPU()
Definition: Sema.h:1046
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraint)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13134
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12643
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, std::optional< unsigned > &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8990
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:9017
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:9022
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15838
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, std::optional< unsigned > NumExpansions, bool ExpectParameterPack, bool EvaluateConstraints=true)
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation.
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
RetainOwnershipKind
Definition: Sema.h:4611
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition: Sema.h:1126
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion)
AddAlignedAttr - Adds an aligned attribute to a particular declaration.
AccessResult CheckFriendAccess(NamedDecl *D)
Checks access to the target of a friend declaration.
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:867
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function)
void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE)
AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular declaration.
SemaCUDA & CUDA()
Definition: Sema.h:1071
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition: Sema.h:6447
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:13137
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6840
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:1664
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
void CheckThreadLocalForLargeAlignment(VarDecl *VD)
Definition: SemaDecl.cpp:14619
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition: Sema.h:6459
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:11061
bool SubstExprs(ArrayRef< Expr * > Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< Expr * > &Outputs)
Substitute the given template arguments into a list of expressions, expanding pack expansions if requ...
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs)
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15126
ASTContext & Context
Definition: Sema.h:909
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:529
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
SemaObjC & ObjC()
Definition: Sema.h:1111
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:72
void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19667
ASTContext & getASTContext() const
Definition: Sema.h:532
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition: SemaAttr.cpp:111
NamedDecl * BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists)
Builds a using declaration.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:817
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:11789
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
NamedReturnInfo getNamedReturnInfo(Expr *&E, SimplerImplicitMoveMode Mode=SimplerImplicitMoveMode::Normal)
Determine whether the given expression might be move-eligible or copy-elidable in either a (co_)retur...
Definition: SemaStmt.cpp:3329
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:16831
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition: Sema.h:525
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, QualType ConstrainedType, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation=false)
AddModeAttr - Adds a mode attribute to a particular declaration.
void * OpaqueParser
Definition: Sema.h:953
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
const LangOptions & LangOpts
Definition: Sema.h:907
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
void PerformPendingInstantiations(bool LocalOnly=false)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15314
SemaHLSL & HLSL()
Definition: Sema.h:1076
VarTemplateSpecializationDecl * CompleteVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiates a variable template specialization by completing it with appropriate type information an...
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11924
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
Definition: SemaDecl.cpp:18468
void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst)
Update instantiation attributes after template was late parsed.
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
void InstantiateVariableInitializer(VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the initializer of a variable.
SmallVector< PendingImplicitInstantiation, 1 > LateParsedInstantiations
Queue of implicit template instantiations that cannot be performed eagerly.
Definition: Sema.h:13530
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
SemaSwift & Swift()
Definition: Sema.h:1156
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition: Sema.h:13186
const VarDecl * getCopyElisionCandidate(NamedReturnInfo &Info, QualType ReturnType)
Updates given NamedReturnInfo's move-eligible and copy-elidable statuses, considering the function re...
Definition: SemaStmt.cpp:3407
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr)
AddAllocAlignAttr - Adds an alloc_align attribute to a particular declaration.
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
std::optional< unsigned > getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:8926
int ArgumentPackSubstitutionIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition: Sema.h:13194
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2361
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1044
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
SemaOpenCL & OpenCL()
Definition: Sema.h:1121
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:13543
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
Definition: SemaExpr.cpp:20117
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
SourceManager & getSourceManager() const
Definition: Sema.h:530
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:19993
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15848
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks)
AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular declaration.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
RedeclarationKind forRedeclarationInCurContext() const
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param, const MultiLevelTemplateArgumentList &TemplateArgs, bool ForCallExpr=false)
Substitute the given template arguments into the default argument.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:19524
ASTConsumer & Consumer
Definition: Sema.h:910
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2052
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1686
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:13526
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14582
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9119
LateTemplateParserCB * LateTemplateParser
Definition: Sema.h:951
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr, bool PartialOrderingTTP=false)
Check that the given template arguments can be provided to the given template, converting the argumen...
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition: Sema.h:7767
SourceManager & SourceMgr
Definition: Sema.h:912
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4703
NamedDecl * BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > Expansions)
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
FPOptions CurFPFeatures
Definition: Sema.h:905
NamespaceDecl * getStdNamespace() const
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7265
Attr * CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
Definition: Sema.cpp:2782
@ TPC_ClassTemplate
Definition: Sema.h:11278
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11283
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11284
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2070
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1581
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:13907
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13348
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:564
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:18085
void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate=false, VarTemplateSpecializationDecl *PrevVTSD=nullptr)
BuildVariableInstantiation - Used after a new variable has been created.
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21168
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
void CheckAlignasUnderalignment(Decl *D)
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition: Sema.h:13522
DeclContext * FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs)
Finds the instantiation of the given declaration context within the current instantiation.
bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New)
Definition: SemaDecl.cpp:2437
void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
AddAlignValueAttr - Adds an align_value attribute to a particular declaration.
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition: Sema.h:11053
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
Definition: SemaDecl.cpp:16848
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5332
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:590
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8268
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals, bool EvaluateConstraints=true)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
Encodes a location in the source.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:4081
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:357
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3578
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:3823
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3806
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4753
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4808
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3802
TagKind getTagKind() const
Definition: Decl.h:3773
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
A template argument list.
Definition: DeclTemplate.h:250
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
void setEvaluateConstraints(bool B)
Definition: Template.h:602
Decl * VisitVarDecl(VarDecl *D, bool InstantiatingVarTemplate, ArrayRef< BindingDecl * > *Bindings=nullptr)
bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl)
Initializes common fields of an instantiated method declaration (New) from the corresponding fields o...
bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl)
Initializes the common fields of an instantiation function declaration (New) from the corresponding f...
VarTemplatePartialSpecializationDecl * InstantiateVarTemplatePartialSpecialization(VarTemplateDecl *VarTemplate, VarTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a variable template partial specialization.
void adjustForRewrite(RewriteKind RK, FunctionDecl *Orig, QualType &T, TypeSourceInfo *&TInfo, DeclarationNameInfo &NameInfo)
TypeSourceInfo * SubstFunctionType(FunctionDecl *D, SmallVectorImpl< ParmVarDecl * > &Params)
Decl * VisitVarTemplateSpecializationDecl(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentListInfo &TemplateArgsInfo, ArrayRef< TemplateArgument > Converted, VarTemplateSpecializationDecl *PrevDecl=nullptr)
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
Decl * VisitFunctionDecl(FunctionDecl *D, TemplateParameterList *TemplateParams, RewriteKind RK=RewriteKind::None)
Normal class members are of more specific types and therefore don't make it here.
Decl * VisitCXXMethodDecl(CXXMethodDecl *D, TemplateParameterList *TemplateParams, RewriteKind RK=RewriteKind::None)
Decl * InstantiateTypeAliasTemplateDecl(TypeAliasTemplateDecl *D)
Decl * VisitBaseUsingDecls(BaseUsingDecl *D, BaseUsingDecl *Inst, LookupResult *Lookup)
bool SubstQualifier(const DeclaratorDecl *OldDecl, DeclaratorDecl *NewDecl)
TemplateParameterList * SubstTemplateParams(TemplateParameterList *List)
Instantiates a nested template parameter list in the current instantiation context.
Decl * InstantiateTypedefNameDecl(TypedefNameDecl *D, bool IsTypeAlias)
ClassTemplatePartialSpecializationDecl * InstantiateClassTemplatePartialSpecialization(ClassTemplateDecl *ClassTemplate, ClassTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a class template partial specialization.
bool SubstDefaultedFunction(FunctionDecl *New, FunctionDecl *Tmpl)
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
bool isNull() const
Determine whether this template name is NULL.
A template parameter object.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:183
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:207
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:206
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:142
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:205
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, bool Typename, TemplateParameterList *Params)
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter.
The top declaration context.
Definition: Decl.h:84
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3549
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5578
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:3568
Declaration of an alias template.
static TypeAliasTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:227
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3410
const Type * getTypeForDecl() const
Definition: Decl.h:3409
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3412
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1256
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition: TypeLoc.cpp:749
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2715
A container of type source information.
Definition: Type.h:7907
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7918
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isRValueReferenceType() const
Definition: Type.h:8217
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8805
bool isReferenceType() const
Definition: Type.h:8209
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2811
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isLValueReferenceType() const
Definition: Type.h:8213
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2700
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8649
bool isFunctionType() const
Definition: Type.h:8187
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3528
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5527
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3427
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4369
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition: DeclCXX.h:4063
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition: DeclCXX.cpp:3378
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3982
SourceLocation getTypenameLoc() const
Returns the source location of the 'typename' keyword.
Definition: DeclCXX.h:4012
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3885
Represents a C++ using-declaration.
Definition: DeclCXX.h:3535
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:3264
Represents C++ using-directive.
Definition: DeclCXX.h:3038
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:3051
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3736
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition: DeclCXX.cpp:3285
Represents a pack of using declarations that a single using-declarator pack-expanded into.
Definition: DeclCXX.h:3817
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3343
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
Represents a variable declaration or definition.
Definition: Decl.h:882
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2786
void setObjCForDecl(bool FRD)
Definition: Decl.h:1480
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2140
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1469
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1513
void setInstantiationOfStaticDataMember(VarDecl *VD, TemplateSpecializationKind TSK)
Specify that this variable is an instantiation of the static data member VD.
Definition: Decl.cpp:2911
TLSKind getTLSKind() const
Definition: Decl.cpp:2157
bool hasInit() const
Definition: Decl.cpp:2387
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1396
InitializationStyle getInitStyle() const
The style of initialization for this declaration.
Definition: Decl.h:1410
void setInitCapture(bool IC)
Definition: Decl.h:1525
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2249
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2433
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2246
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1522
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:890
bool isObjCForDecl() const
Determine whether this variable is a for-loop declaration for a for-in statement in Objective-C.
Definition: Decl.h:1476
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1541
bool isInlineSpecified() const
Definition: Decl.h:1498
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
VarDecl * getTemplateInstantiationPattern() const
Retrieve the variable declaration from which this variable could be instantiated, if it is an instant...
Definition: Decl.cpp:2690
bool isCXXForRangeDecl() const
Determine whether this variable is the for-range-declaration in a C++0x for-range statement.
Definition: Decl.h:1466
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2355
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2458
void setInlineSpecified()
Definition: Decl.h:1502
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1159
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2883
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1124
void setNRVOVariable(bool NRVO)
Definition: Decl.h:1459
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1495
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1128
const Expr * getInit() const
Definition: Decl.h:1319
void setConstexpr(bool IC)
Definition: Decl.h:1516
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2791
bool isDirectInit() const
Whether the initializer is a direct-initializer (list or call).
Definition: Decl.h:1415
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1119
void setImplicitlyInline()
Definition: Decl.h:1507
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1536
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2776
TemplateSpecializationKind getTemplateSpecializationKindForInstantiation() const
Get the template specialization kind of this variable for the purposes of template instantiation.
Definition: Decl.cpp:2766
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2755
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2662
Declaration of a variable template.
void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D, void *InsertPos)
Insert the specified partial specialization knowing that it is not already in.
VarTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, TemplateParameterList *TPL, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos)
Insert the specified specialization knowing that it is not already in.
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
VarTemplatePartialSpecializationDecl * findPartialSpecInstantiatedFromMember(VarTemplatePartialSpecializationDecl *D)
Find a variable template partial specialization which was instantiated from the given member partial ...
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
void setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec)
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the variable template specialization.
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate the initializer of the vari...
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
RetTy Visit(PTR(Decl) D)
Definition: DeclVisitor.h:37
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:800
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:737
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1157
Attr * instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
Attr * instantiateTemplateAttributeForDecl(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
The JSON file list parser is used to communicate input to InstallAPI.
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
@ CPlusPlus11
Definition: LangStandard.h:56
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
StorageClass
Storage classes.
Definition: Specifiers.h:248
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
ExprResult ExprEmpty()
Definition: Ownership.h:271
@ Property
The type of a property.
@ Result
The result type of a method or function.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:1102
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1274
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Other
Other implicit parameter.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ EST_Unevaluated
not evaluated yet, for special member function
@ AS_public
Definition: Specifiers.h:124
@ AS_none
Definition: Specifiers.h:127
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
Definition: TemplateBase.h:691
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
Definition: TemplateBase.h:688
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:705
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
const DeclarationNameLoc & getInfo() const
Holds information about the various types of exception specification.
Definition: Type.h:5164
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:5176
FunctionDecl * SourceTemplate
The function template whose exception specification this is instantiated from, for EST_Uninstantiated...
Definition: Type.h:5180
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5166
Extra information about a function prototype.
Definition: Type.h:5192
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5199
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5193
This structure contains most locations needed for by an OMPVarListClause.
Definition: OpenMPClause.h:259
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12660
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:12662
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12767
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12688
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:6373
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition: Sema.h:6376
A stack object to be created when performing template instantiation.
Definition: Sema.h:12845
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:12999
bool isAlreadyInstantiating() const
Determine whether we are already instantiating this specialization in some surrounding active instant...
Definition: Sema.h:13003