clang 24.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"
35#include "llvm/Support/SaveAndRestore.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 UnsignedOrNone NumExpansions = std::nullopt;
133 // FIXME: Use the actual location of the ellipsis.
134 SourceLocation EllipsisLoc = Aligned->getLocation();
135 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
136 Unexpanded, TemplateArgs,
137 /*FailOnPackProducingTemplates=*/true,
138 Expand, RetainExpansion, NumExpansions))
139 return;
140
141 if (!Expand) {
142 Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt);
143 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
144 } else {
145 for (unsigned I = 0; I != *NumExpansions; ++I) {
146 Sema::ArgPackSubstIndexRAII SubstIndex(S, I);
147 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
148 }
149 }
150}
151
153 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
154 const AssumeAlignedAttr *Aligned, Decl *New) {
155 // The alignment expression is a constant expression.
158
159 Expr *E, *OE = nullptr;
160 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
161 if (Result.isInvalid())
162 return;
163 E = Result.getAs<Expr>();
164
165 if (Aligned->getOffset()) {
166 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
167 if (Result.isInvalid())
168 return;
169 OE = Result.getAs<Expr>();
170 }
171
172 S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
173}
174
176 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
177 const AlignValueAttr *Aligned, Decl *New) {
178 // The alignment expression is a constant expression.
181 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
182 if (!Result.isInvalid())
183 S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
184}
185
187 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
188 const AllocAlignAttr *Align, Decl *New) {
190 S.getASTContext(),
191 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
192 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
193 S.AddAllocAlignAttr(New, *Align, Param);
194}
195
197 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
198 const AnnotateAttr *Attr, Decl *New) {
201
202 // If the attribute has delayed arguments it will have to instantiate those
203 // and handle them as new arguments for the attribute.
204 bool HasDelayedArgs = Attr->delayedArgs_size();
205
206 ArrayRef<Expr *> ArgsToInstantiate =
207 HasDelayedArgs
208 ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
209 : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
210
212 if (S.SubstExprs(ArgsToInstantiate,
213 /*IsCall=*/false, TemplateArgs, Args))
214 return;
215
216 StringRef Str = Attr->getAnnotation();
217 if (HasDelayedArgs) {
218 if (Args.size() < 1) {
219 S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
220 << Attr << 1;
221 return;
222 }
223
224 if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
225 return;
226
228 ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
229 std::swap(Args, ActualArgs);
230 }
231 auto *AA = S.CreateAnnotationAttr(*Attr, Str, Args);
232 if (AA) {
233 New->addAttr(AA);
234 }
235}
236
237template <typename Attr>
239 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const Attr *A,
240 Decl *New, ASTContext &C) {
241 Expr *tempInstPriority = nullptr;
242 {
245 ExprResult Result = S.SubstExpr(A->getPriority(), TemplateArgs);
246 if (Result.isInvalid())
247 return;
248 if (Result.isUsable()) {
249 tempInstPriority = Result.get();
250 if (std::optional<llvm::APSInt> CE =
251 tempInstPriority->getIntegerConstantExpr(C)) {
252 // Consistent with non-templated priority arguments, which must fit in a
253 // 32-bit unsigned integer.
254 if (!CE->isIntN(32)) {
255 S.Diag(tempInstPriority->getExprLoc(), diag::err_ice_too_large)
256 << toString(*CE, 10, false) << /*Size=*/32 << /*Unsigned=*/1;
257 return;
258 }
259 }
260 }
261 }
262 New->addAttr(Attr::Create(C, tempInstPriority, *A));
263}
264
266 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
267 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
268 Expr *Cond = nullptr;
269 {
270 Sema::ContextRAII SwitchContext(S, New);
273 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
274 if (Result.isInvalid())
275 return nullptr;
276 Cond = Result.getAs<Expr>();
277 }
278 if (!Cond->isTypeDependent()) {
280 if (Converted.isInvalid())
281 return nullptr;
282 Cond = Converted.get();
283 }
284
286 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
288 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
289 for (const auto &P : Diags)
290 S.Diag(P.first, P.second);
291 return nullptr;
292 }
293 return Cond;
294}
295
297 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
298 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
300 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
301
302 if (Cond)
303 New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
304 Cond, EIA->getMessage()));
305}
306
308 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
309 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
311 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
312
313 if (Cond)
314 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
315 S.getASTContext(), *DIA, Cond, DIA->getMessage(),
316 DIA->getDefaultSeverity(), DIA->getWarningGroup(),
317 DIA->getArgDependent(), New));
318}
319
320// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
321// template A as the base and arguments from TemplateArgs.
323 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
324 const CUDALaunchBoundsAttr &Attr, Decl *New) {
325 // The alignment expression is a constant expression.
328
329 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
330 if (Result.isInvalid())
331 return;
332 Expr *MaxThreads = Result.getAs<Expr>();
333
334 Expr *MinBlocks = nullptr;
335 if (Attr.getMinBlocks()) {
336 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
337 if (Result.isInvalid())
338 return;
339 MinBlocks = Result.getAs<Expr>();
340 }
341
342 Expr *MaxBlocks = nullptr;
343 if (Attr.getMaxBlocks()) {
344 Result = S.SubstExpr(Attr.getMaxBlocks(), TemplateArgs);
345 if (Result.isInvalid())
346 return;
347 MaxBlocks = Result.getAs<Expr>();
348 }
349
350 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks, MaxBlocks);
351}
352
353static void
355 const MultiLevelTemplateArgumentList &TemplateArgs,
356 const ModeAttr &Attr, Decl *New) {
357 S.AddModeAttr(New, Attr, Attr.getMode(),
358 /*InInstantiation=*/true);
359}
360
361/// Instantiation of 'declare simd' attribute and its arguments.
363 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
364 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
365 // Allow 'this' in clauses with varlist.
366 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
367 New = FTD->getTemplatedDecl();
368 auto *FD = cast<FunctionDecl>(New);
369 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
370 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
371 SmallVector<unsigned, 4> LinModifiers;
372
373 auto SubstExpr = [&](Expr *E) -> ExprResult {
374 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
375 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
376 Sema::ContextRAII SavedContext(S, FD);
378 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
379 Local.InstantiatedLocal(
380 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
381 return S.SubstExpr(E, TemplateArgs);
382 }
383 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
384 FD->isCXXInstanceMember());
385 return S.SubstExpr(E, TemplateArgs);
386 };
387
388 // Substitute a single OpenMP clause, which is a potentially-evaluated
389 // full-expression.
390 auto Subst = [&](Expr *E) -> ExprResult {
393 ExprResult Res = SubstExpr(E);
394 if (Res.isInvalid())
395 return Res;
396 return S.ActOnFinishFullExpr(Res.get(), false);
397 };
398
399 ExprResult Simdlen;
400 if (auto *E = Attr.getSimdlen())
401 Simdlen = Subst(E);
402
403 if (Attr.uniforms_size() > 0) {
404 for(auto *E : Attr.uniforms()) {
405 ExprResult Inst = Subst(E);
406 if (Inst.isInvalid())
407 continue;
408 Uniforms.push_back(Inst.get());
409 }
410 }
411
412 auto AI = Attr.alignments_begin();
413 for (auto *E : Attr.aligneds()) {
414 ExprResult Inst = Subst(E);
415 if (Inst.isInvalid())
416 continue;
417 Aligneds.push_back(Inst.get());
418 Inst = ExprEmpty();
419 if (*AI)
420 Inst = S.SubstExpr(*AI, TemplateArgs);
421 Alignments.push_back(Inst.get());
422 ++AI;
423 }
424
425 auto SI = Attr.steps_begin();
426 for (auto *E : Attr.linears()) {
427 ExprResult Inst = Subst(E);
428 if (Inst.isInvalid())
429 continue;
430 Linears.push_back(Inst.get());
431 Inst = ExprEmpty();
432 if (*SI)
433 Inst = S.SubstExpr(*SI, TemplateArgs);
434 Steps.push_back(Inst.get());
435 ++SI;
436 }
437 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
439 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
440 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
441 Attr.getRange());
442}
443
444/// Instantiation of 'declare variant' attribute and its arguments.
446 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
447 const OMPDeclareVariantAttr &Attr, Decl *New) {
448 // Allow 'this' in clauses with varlist.
449 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
450 New = FTD->getTemplatedDecl();
451 auto *FD = cast<FunctionDecl>(New);
452 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
453
454 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
455 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
456 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
457 Sema::ContextRAII SavedContext(S, FD);
459 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
460 Local.InstantiatedLocal(
461 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
462 return S.SubstExpr(E, TemplateArgs);
463 }
464 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
465 FD->isCXXInstanceMember());
466 return S.SubstExpr(E, TemplateArgs);
467 };
468
469 // Substitute a single OpenMP clause, which is a potentially-evaluated
470 // full-expression.
471 auto &&Subst = [&SubstExpr, &S](Expr *E) {
474 ExprResult Res = SubstExpr(E);
475 if (Res.isInvalid())
476 return Res;
477 return S.ActOnFinishFullExpr(Res.get(), false);
478 };
479
480 ExprResult VariantFuncRef;
481 if (Expr *E = Attr.getVariantFuncRef()) {
482 // Do not mark function as is used to prevent its emission if this is the
483 // only place where it is used.
486 VariantFuncRef = Subst(E);
487 }
488
489 // Copy the template version of the OMPTraitInfo and run substitute on all
490 // score and condition expressiosn.
492 TI = *Attr.getTraitInfos();
493
494 // Try to substitute template parameters in score and condition expressions.
495 auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
496 if (E) {
499 ExprResult ER = Subst(E);
500 if (ER.isUsable())
501 E = ER.get();
502 else
503 return true;
504 }
505 return false;
506 };
507 if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
508 return;
509
510 Expr *E = VariantFuncRef.get();
511
512 // Check function/variant ref for `omp declare variant` but not for `omp
513 // begin declare variant` (which use implicit attributes).
514 std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
516 S.ConvertDeclToDeclGroup(New), E, TI, Attr.appendArgs_size(),
517 Attr.getRange());
518
519 if (!DeclVarData)
520 return;
521
522 E = DeclVarData->second;
523 FD = DeclVarData->first;
524
525 if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
526 if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
527 if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
528 if (!VariantFTD->isThisDeclarationADefinition())
529 return;
532 S.Context, TemplateArgs.getInnermost());
533
534 auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
535 New->getLocation());
536 if (!SubstFD)
537 return;
539 SubstFD->getType(), FD->getType(),
540 /* OfBlockPointer */ false,
541 /* Unqualified */ false, /* AllowCXX */ true);
542 if (NewType.isNull())
543 return;
545 New->getLocation(), SubstFD, /* Recursive */ true,
546 /* DefinitionRequired */ false, /* AtEndOfTU */ false);
547 SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
549 SourceLocation(), SubstFD,
550 /* RefersToEnclosingVariableOrCapture */ false,
551 /* NameLoc */ SubstFD->getLocation(),
552 SubstFD->getType(), ExprValueKind::VK_PRValue);
553 }
554 }
555 }
556
559
560 auto SubstAdjustArgsExpr = [&](Expr *&E) {
561 if (!E)
562 return false;
563 ExprResult ER = Subst(E);
564 if (ER.isInvalid())
565 return true;
566 E = ER.get();
567 return false;
568 };
569 for (const OMPAdjustArgsDescriptor *Desc : Attr.adjustArgs()) {
571 for (const OMPAdjustArgsItem &Item : Desc->items()) {
572 OMPAdjustArgsItem NewItem = Item;
573 if (SubstAdjustArgsExpr(NewItem.E) ||
574 SubstAdjustArgsExpr(NewItem.Lower.E) ||
575 SubstAdjustArgsExpr(NewItem.Upper.E))
576 continue;
577 Items.push_back(NewItem);
578 }
579 if (!Items.empty())
581 Desc->AdjustOp, Desc->NeedDevicePtrModifier, Items,
582 Attr.getLocation()))
583 AdjustArgs.push_back(D);
584 }
585 for (OMPInteropInfo &II : Attr.appendArgs()) {
586 OMPInteropInfo Info(II.IsTarget, II.IsTargetSync);
587 Info.HasPreferAttrs = II.HasPreferAttrs;
588 for (const OMPInteropPref &P : II.Prefs) {
589 Expr *SubstFr = nullptr;
590 if (P.Fr) {
591 ExprResult ER = Subst(P.Fr);
592 if (ER.isInvalid())
593 continue;
594 SubstFr = ER.get();
595 }
597 for (Expr *A : P.Attrs) {
598 ExprResult ER = Subst(A);
599 if (!ER.isInvalid())
600 SubstAttrs.push_back(ER.get());
601 }
602 Info.Prefs.emplace_back(SubstFr, std::move(SubstAttrs));
603 }
604 AppendArgs.push_back(Info);
605 }
606
608 FD, E, TI, AdjustArgs, AppendArgs, SourceLocation(), SourceLocation(),
609 Attr.getRange());
610}
611
613 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
614 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
615 // Both min and max expression are constant expressions.
618
619 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
620 if (Result.isInvalid())
621 return;
622 Expr *MinExpr = Result.getAs<Expr>();
623
624 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
625 if (Result.isInvalid())
626 return;
627 Expr *MaxExpr = Result.getAs<Expr>();
628
629 S.AMDGPU().addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
630}
631
633 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
634 const ReqdWorkGroupSizeAttr &Attr, Decl *New) {
635 // Both min and max expression are constant expressions.
638
639 ExprResult Result = S.SubstExpr(Attr.getXDim(), TemplateArgs);
640 if (Result.isInvalid())
641 return;
642 Expr *X = Result.getAs<Expr>();
643
644 Result = S.SubstExpr(Attr.getYDim(), TemplateArgs);
645 if (Result.isInvalid())
646 return;
647 Expr *Y = Result.getAs<Expr>();
648
649 Result = S.SubstExpr(Attr.getZDim(), TemplateArgs);
650 if (Result.isInvalid())
651 return;
652 Expr *Z = Result.getAs<Expr>();
653
654 ASTContext &Context = S.getASTContext();
655 New->addAttr(::new (Context) ReqdWorkGroupSizeAttr(Context, Attr, X, Y, Z));
656}
657
659 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) {
660 if (!ES.getExpr())
661 return ES;
662 Expr *OldCond = ES.getExpr();
663 Expr *Cond = nullptr;
664 {
667 ExprResult SubstResult = SubstExpr(OldCond, TemplateArgs);
668 if (SubstResult.isInvalid()) {
670 }
671 Cond = SubstResult.get();
672 }
673 ExplicitSpecifier Result(Cond, ES.getKind());
674 if (!Cond->isTypeDependent())
676 return Result;
677}
678
680 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
681 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
682 // Both min and max expression are constant expressions.
685
686 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
687 if (Result.isInvalid())
688 return;
689 Expr *MinExpr = Result.getAs<Expr>();
690
691 Expr *MaxExpr = nullptr;
692 if (auto Max = Attr.getMax()) {
693 Result = S.SubstExpr(Max, TemplateArgs);
694 if (Result.isInvalid())
695 return;
696 MaxExpr = Result.getAs<Expr>();
697 }
698
699 S.AMDGPU().addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
700}
701
703 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
704 const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New) {
707
708 Expr *XExpr = nullptr;
709 Expr *YExpr = nullptr;
710 Expr *ZExpr = nullptr;
711
712 if (Attr.getMaxNumWorkGroupsX()) {
713 ExprResult ResultX = S.SubstExpr(Attr.getMaxNumWorkGroupsX(), TemplateArgs);
714 if (ResultX.isUsable())
715 XExpr = ResultX.getAs<Expr>();
716 }
717
718 if (Attr.getMaxNumWorkGroupsY()) {
719 ExprResult ResultY = S.SubstExpr(Attr.getMaxNumWorkGroupsY(), TemplateArgs);
720 if (ResultY.isUsable())
721 YExpr = ResultY.getAs<Expr>();
722 }
723
724 if (Attr.getMaxNumWorkGroupsZ()) {
725 ExprResult ResultZ = S.SubstExpr(Attr.getMaxNumWorkGroupsZ(), TemplateArgs);
726 if (ResultZ.isUsable())
727 ZExpr = ResultZ.getAs<Expr>();
728 }
729
730 if (XExpr)
731 S.AMDGPU().addAMDGPUMaxNumWorkGroupsAttr(New, Attr, XExpr, YExpr, ZExpr);
732}
733
735 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
736 const CUDAClusterDimsAttr &Attr, Decl *New) {
739
740 auto SubstElt = [&S, &TemplateArgs](Expr *E) {
741 return E ? S.SubstExpr(E, TemplateArgs).get() : nullptr;
742 };
743
744 Expr *XExpr = SubstElt(Attr.getX());
745 Expr *YExpr = SubstElt(Attr.getY());
746 Expr *ZExpr = SubstElt(Attr.getZ());
747
748 S.addClusterDimsAttr(New, Attr, XExpr, YExpr, ZExpr);
749}
750
751// This doesn't take any template parameters, but we have a custom action that
752// needs to happen when the kernel itself is instantiated. We need to run the
753// ItaniumMangler to mark the names required to name this kernel.
755 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
756 const SYCLKernelAttr &Attr, Decl *New) {
757 New->addAttr(Attr.clone(S.getASTContext()));
758}
759
760/// Determine whether the attribute A might be relevant to the declaration D.
761/// If not, we can skip instantiating it. The attribute may or may not have
762/// been instantiated yet.
763static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
764 // 'preferred_name' is only relevant to the matching specialization of the
765 // template.
766 if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
767 QualType T = PNA->getTypedefType();
768 const auto *RD = cast<CXXRecordDecl>(D);
769 if (!T->isDependentType() && !RD->isDependentContext() &&
770 !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
771 return false;
772 for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
773 if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
774 PNA->getTypedefType()))
775 return false;
776 return true;
777 }
778
779 if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
780 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
781 switch (BA->getID()) {
782 case Builtin::BIforward:
783 // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
784 // type and returns an lvalue reference type. The library implementation
785 // will produce an error in this case; don't get in its way.
786 if (FD && FD->getNumParams() >= 1 &&
789 return false;
790 }
791 [[fallthrough]];
792 case Builtin::BImove:
793 case Builtin::BImove_if_noexcept:
794 // HACK: Super-old versions of libc++ (3.1 and earlier) provide
795 // std::forward and std::move overloads that sometimes return by value
796 // instead of by reference when building in C++98 mode. Don't treat such
797 // cases as builtins.
798 if (FD && !FD->getReturnType()->isReferenceType())
799 return false;
800 break;
801 }
802 }
803
804 return true;
805}
806
808 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
809 const HLSLParamModifierAttr *Attr, const Decl *Old, Decl *New) {
811 NewParm->addAttr(Attr->clone(S.getASTContext()));
812
813 // If this is groupshared don't change the type because it will assert
814 // below. In this case we might have already produced an error but we
815 // must produce one here again because of all the ways templates can
816 // be used.
817 if (const auto *RT = NewParm->getType()->getAs<LValueReferenceType>()) {
818 if (RT->getPointeeType().getAddressSpace() == LangAS::hlsl_groupshared) {
819 S.Diag(Attr->getLoc(), diag::err_hlsl_attr_incompatible)
820 << Attr << "'groupshared'";
821 return;
822 }
823 }
824
825 const Type *OldParmTy = cast<ParmVarDecl>(Old)->getType().getTypePtr();
826 if (OldParmTy->isDependentType() && Attr->isAnyOut())
827 NewParm->setType(S.HLSL().getInoutParameterType(NewParm->getType()));
828
829 assert(
830 (!Attr->isAnyOut() || (NewParm->getType().isRestrictQualified() &&
831 NewParm->getType()->isReferenceType())) &&
832 "out or inout parameter type must be a reference and restrict qualified");
833}
834
836 const MallocSpanAttr *Attr,
837 Decl *New) {
839 if (!S.CheckSpanLikeType(*Attr, RT))
840 New->addAttr(Attr->clone(S.getASTContext()));
841}
842
844 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
845 Decl *New, LateInstantiatedAttrVec *LateAttrs,
846 LocalInstantiationScope *OuterMostScope) {
847 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
848 // FIXME: This function is called multiple times for the same template
849 // specialization. We should only instantiate attributes that were added
850 // since the previous instantiation.
851 for (const auto *TmplAttr : Tmpl->attrs()) {
852 if (!isRelevantAttr(*this, New, TmplAttr))
853 continue;
854
855 // FIXME: If any of the special case versions from InstantiateAttrs become
856 // applicable to template declaration, we'll need to add them here.
857 CXXThisScopeRAII ThisScope(
858 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
859 Qualifiers(), ND->isCXXInstanceMember());
860
862 TmplAttr, Context, *this, TemplateArgs);
863 if (NewAttr && isRelevantAttr(*this, New, NewAttr) &&
865 New->addAttr(NewAttr);
866 }
867 }
868}
869
872 switch (A->getKind()) {
873 case clang::attr::CFConsumed:
875 case clang::attr::OSConsumed:
877 case clang::attr::NSConsumed:
879 default:
880 llvm_unreachable("Wrong argument supplied");
881 }
882}
883
884/// Instantiate \p TmplAttr for \p New in the current instantiation scope and
885/// attach it, if it is still valid there.
886static void
888 const MultiLevelTemplateArgumentList &TemplateArgs,
889 const Attr *TmplAttr, Decl *New) {
890 // Allow 'this' within late-parsed attributes.
891 auto *ND = cast<NamedDecl>(New);
892 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
893 Qualifiers ThisQuals;
894 bool HasThis = ND->isCXXInstanceMember();
895 // An attribute on a parameter names a member through the 'this' of the
896 // parameter's function, if it has an implicit object parameter; otherwise
897 // there is none, hiding any outer one. A lambda's parameters keep the 'this'
898 // around the lambda.
899 std::optional<llvm::SaveAndRestore<QualType>> NoThis;
900 if (auto *FD = isa<ParmVarDecl>(ND)
901 ? dyn_cast<FunctionDecl>(ND->getDeclContext())
902 : nullptr;
903 FD && !isLambdaCallOperator(FD)) {
904 auto *MD = dyn_cast<CXXMethodDecl>(FD);
905 HasThis = MD && MD->isImplicitObjectMemberFunction();
906 if (HasThis) {
907 ThisContext = MD->getParent();
908 ThisQuals = MD->getMethodQualifiers();
909 } else {
910 NoThis.emplace(S.CXXThisTypeOverride, QualType());
911 }
912 }
913 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisQuals, HasThis);
914
915 Attr *NewAttr =
916 sema::instantiateTemplateAttribute(TmplAttr, S.Context, S, TemplateArgs);
917 if (NewAttr && S.checkInstantiatedThreadSafetyAttrs(New, NewAttr))
918 New->addAttr(NewAttr);
919}
920
921// Implementation is down with the rest of the OpenACC Decl instantiations.
923 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
924 const OpenACCRoutineDeclAttr *OldAttr, const Decl *Old, Decl *New);
925
927 const Decl *Tmpl, Decl *New,
928 LateInstantiatedAttrVec *LateAttrs,
929 LocalInstantiationScope *OuterMostScope) {
930 for (const auto *TmplAttr : Tmpl->attrs()) {
931 if (!isRelevantAttr(*this, New, TmplAttr))
932 continue;
933
934 // FIXME: This should be generalized to more than just the AlignedAttr.
935 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
936 if (Aligned && Aligned->isAlignmentDependent()) {
937 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
938 continue;
939 }
940
941 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
942 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
943 continue;
944 }
945
946 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
947 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
948 continue;
949 }
950
951 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
952 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
953 continue;
954 }
955
956 if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
957 instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
958 continue;
959 }
960
961 if (auto *Constructor = dyn_cast<ConstructorAttr>(TmplAttr)) {
964 continue;
965 }
966
967 if (auto *Destructor = dyn_cast<DestructorAttr>(TmplAttr)) {
970 continue;
971 }
972
973 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
974 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
976 continue;
977 }
978
979 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
980 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
982 continue;
983 }
984
985 if (const auto *CUDALaunchBounds =
986 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
988 *CUDALaunchBounds, New);
989 continue;
990 }
991
992 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
993 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
994 continue;
995 }
996
997 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
998 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
999 continue;
1000 }
1001
1002 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
1003 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
1004 continue;
1005 }
1006
1007 if (const auto *ReqdWorkGroupSize =
1008 dyn_cast<ReqdWorkGroupSizeAttr>(TmplAttr)) {
1010 *ReqdWorkGroupSize, New);
1011 continue;
1012 }
1013
1014 if (const auto *AMDGPUFlatWorkGroupSize =
1015 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
1017 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
1018 continue;
1019 }
1020
1021 if (const auto *AMDGPUFlatWorkGroupSize =
1022 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
1023 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
1024 *AMDGPUFlatWorkGroupSize, New);
1025 continue;
1026 }
1027
1028 if (const auto *AMDGPUMaxNumWorkGroups =
1029 dyn_cast<AMDGPUMaxNumWorkGroupsAttr>(TmplAttr)) {
1031 *this, TemplateArgs, *AMDGPUMaxNumWorkGroups, New);
1032 continue;
1033 }
1034
1035 if (const auto *CUDAClusterDims = dyn_cast<CUDAClusterDimsAttr>(TmplAttr)) {
1036 instantiateDependentCUDAClusterDimsAttr(*this, TemplateArgs,
1037 *CUDAClusterDims, New);
1038 continue;
1039 }
1040
1041 if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(TmplAttr)) {
1042 instantiateDependentHLSLParamModifierAttr(*this, TemplateArgs, ParamAttr,
1043 Tmpl, New);
1044 continue;
1045 }
1046
1047 if (const auto *RoutineAttr = dyn_cast<OpenACCRoutineDeclAttr>(TmplAttr)) {
1049 RoutineAttr, Tmpl, New);
1050 continue;
1051 }
1052
1053 // Existing DLL attribute on the instantiation takes precedence.
1054 if (TmplAttr->getKind() == attr::DLLExport ||
1055 TmplAttr->getKind() == attr::DLLImport) {
1056 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
1057 continue;
1058 }
1059 }
1060
1061 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
1062 Swift().AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
1063 continue;
1064 }
1065
1066 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
1067 isa<CFConsumedAttr>(TmplAttr)) {
1068 ObjC().AddXConsumedAttr(New, *TmplAttr,
1069 attrToRetainOwnershipKind(TmplAttr),
1070 /*template instantiation=*/true);
1071 continue;
1072 }
1073
1074 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
1075 if (!New->hasAttr<PointerAttr>())
1076 New->addAttr(A->clone(Context));
1077 continue;
1078 }
1079
1080 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
1081 if (!New->hasAttr<OwnerAttr>())
1082 New->addAttr(A->clone(Context));
1083 continue;
1084 }
1085
1086 if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
1087 instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
1088 continue;
1089 }
1090
1091 if (auto *A = dyn_cast<CUDAGridConstantAttr>(TmplAttr)) {
1092 if (!New->hasAttr<CUDAGridConstantAttr>())
1093 New->addAttr(A->clone(Context));
1094 continue;
1095 }
1096
1097 if (auto *A = dyn_cast<MallocSpanAttr>(TmplAttr)) {
1099 continue;
1100 }
1101
1102 if (auto *A = dyn_cast<CleanupAttr>(TmplAttr)) {
1103 if (!New->hasAttr<CleanupAttr>()) {
1104 auto *NewAttr = A->clone(Context);
1105 NewAttr->setArgLoc(A->getArgLoc());
1106 New->addAttr(NewAttr);
1107 }
1108 continue;
1109 }
1110
1111 assert(!TmplAttr->isPackExpansion());
1112 if (TmplAttr->isLateParsed() && LateAttrs) {
1113 // A late-parsed attribute may name a declaration that is instantiated
1114 // after the one it is on: a class member's names a later member, and a
1115 // parameter's a later parameter. Defer it, with the scope to instantiate
1116 // it in, until they all are; see InstantiateLateAttrs.
1117 assert(CurrentInstantiationScope && "no scope to defer the attribute in");
1119 CurrentInstantiationScope->cloneScopes(OuterMostScope);
1120 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
1121 } else {
1122 instantiateAttrOnDecl(*this, TemplateArgs, TmplAttr, New);
1123 }
1124 }
1125}
1126
1128 const MultiLevelTemplateArgumentList &TemplateArgs,
1129 LateInstantiatedAttrVec &LateAttrs,
1130 LocalInstantiationScope *OuterMostScope) {
1131 assert(
1132 CurrentInstantiationScope == OuterMostScope &&
1133 "late attributes instantiated outside the scope they were deferred in");
1134 for (const LateInstantiatedAttribute &LA : LateAttrs) {
1135 CurrentInstantiationScope = LA.Scope;
1136 instantiateAttrOnDecl(*this, TemplateArgs, LA.TmplAttr, LA.NewDecl);
1137 // Exiting the saved scopes restores the outermost one.
1138 LocalInstantiationScope::deleteScopes(LA.Scope, OuterMostScope);
1139 assert(CurrentInstantiationScope == OuterMostScope &&
1140 "deferred scope did not extend the outermost scope");
1141 }
1142 LateAttrs.clear();
1143}
1144
1146 for (const auto *Attr : Pattern->attrs()) {
1147 if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
1148 if (!Inst->hasAttr<StrictFPAttr>())
1149 Inst->addAttr(A->clone(getASTContext()));
1150 continue;
1151 }
1152 }
1153}
1154
1155/// Get the previous declaration of a declaration for the purposes of template
1156/// instantiation. If this finds a previous declaration, then the previous
1157/// declaration of the instantiation of D should be an instantiation of the
1158/// result of this function.
1159template<typename DeclT>
1160static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
1161 DeclT *Result = D->getPreviousDecl();
1162
1163 // If the declaration is within a class, and the previous declaration was
1164 // merged from a different definition of that class, then we don't have a
1165 // previous declaration for the purpose of template instantiation.
1166 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
1167 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
1168 return nullptr;
1169
1170 return Result;
1171}
1172
1173Decl *
1174TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
1175 llvm_unreachable("Translation units cannot be instantiated");
1176}
1177
1178Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
1179 llvm_unreachable("HLSL buffer declarations cannot be instantiated");
1180}
1181
1182Decl *TemplateDeclInstantiator::VisitHLSLRootSignatureDecl(
1184 llvm_unreachable("HLSL root signature declarations cannot be instantiated");
1185}
1186
1187Decl *
1188TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
1189 llvm_unreachable("pragma comment cannot be instantiated");
1190}
1191
1192Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
1194 llvm_unreachable("pragma comment cannot be instantiated");
1195}
1196
1197Decl *
1198TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
1199 llvm_unreachable("extern \"C\" context cannot be instantiated");
1200}
1201
1202Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
1203 llvm_unreachable("GUID declaration cannot be instantiated");
1204}
1205
1206Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
1208 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
1209}
1210
1211Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
1213 llvm_unreachable("template parameter objects cannot be instantiated");
1214}
1215
1216Decl *
1217TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
1218 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1219 D->getIdentifier());
1220 SemaRef.InstantiateAttrs(TemplateArgs, D, Inst, LateAttrs, StartingScope);
1221 Owner->addDecl(Inst);
1222 return Inst;
1223}
1224
1225Decl *
1226TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
1227 llvm_unreachable("Namespaces cannot be instantiated");
1228}
1229
1230namespace {
1231class OpenACCDeclClauseInstantiator final
1232 : public OpenACCClauseVisitor<OpenACCDeclClauseInstantiator> {
1233 Sema &SemaRef;
1234 const MultiLevelTemplateArgumentList &MLTAL;
1235 ArrayRef<OpenACCClause *> ExistingClauses;
1236 SemaOpenACC::OpenACCParsedClause &ParsedClause;
1237 OpenACCClause *NewClause = nullptr;
1238
1239public:
1240 OpenACCDeclClauseInstantiator(Sema &S,
1241 const MultiLevelTemplateArgumentList &MLTAL,
1242 ArrayRef<OpenACCClause *> ExistingClauses,
1243 SemaOpenACC::OpenACCParsedClause &ParsedClause)
1244 : SemaRef(S), MLTAL(MLTAL), ExistingClauses(ExistingClauses),
1245 ParsedClause(ParsedClause) {}
1246
1247 OpenACCClause *CreatedClause() { return NewClause; }
1248#define VISIT_CLAUSE(CLAUSE_NAME) \
1249 void Visit##CLAUSE_NAME##Clause(const OpenACC##CLAUSE_NAME##Clause &Clause);
1250#include "clang/Basic/OpenACCClauses.def"
1251
1252 llvm::SmallVector<Expr *> VisitVarList(ArrayRef<Expr *> VarList) {
1253 llvm::SmallVector<Expr *> InstantiatedVarList;
1254 for (Expr *CurVar : VarList) {
1255 ExprResult Res = SemaRef.SubstExpr(CurVar, MLTAL);
1256
1257 if (!Res.isUsable())
1258 continue;
1259
1260 Res = SemaRef.OpenACC().ActOnVar(ParsedClause.getDirectiveKind(),
1261 ParsedClause.getClauseKind(), Res.get());
1262
1263 if (Res.isUsable())
1264 InstantiatedVarList.push_back(Res.get());
1265 }
1266 return InstantiatedVarList;
1267 }
1268};
1269
1270#define CLAUSE_NOT_ON_DECLS(CLAUSE_NAME) \
1271 void OpenACCDeclClauseInstantiator::Visit##CLAUSE_NAME##Clause( \
1272 const OpenACC##CLAUSE_NAME##Clause &) { \
1273 llvm_unreachable("Clause type invalid on declaration construct, or " \
1274 "instantiation not implemented"); \
1275 }
1276
1296CLAUSE_NOT_ON_DECLS(Private)
1303#undef CLAUSE_NOT_ON_DECLS
1304
1305void OpenACCDeclClauseInstantiator::VisitGangClause(
1306 const OpenACCGangClause &C) {
1307 llvm::SmallVector<OpenACCGangKind> TransformedGangKinds;
1308 llvm::SmallVector<Expr *> TransformedIntExprs;
1309 assert(C.getNumExprs() <= 1 &&
1310 "Only 1 expression allowed on gang clause in routine");
1311
1312 if (C.getNumExprs() > 0) {
1313 assert(C.getExpr(0).first == OpenACCGangKind::Dim &&
1314 "Only dim allowed on routine");
1315 ExprResult ER =
1316 SemaRef.SubstExpr(const_cast<Expr *>(C.getExpr(0).second), MLTAL);
1317 if (ER.isUsable()) {
1318 ER = SemaRef.OpenACC().CheckGangExpr(ExistingClauses,
1319 ParsedClause.getDirectiveKind(),
1320 C.getExpr(0).first, ER.get());
1321 if (ER.isUsable()) {
1322 TransformedGangKinds.push_back(OpenACCGangKind::Dim);
1323 TransformedIntExprs.push_back(ER.get());
1324 }
1325 }
1326 }
1327
1328 NewClause = SemaRef.OpenACC().CheckGangClause(
1329 ParsedClause.getDirectiveKind(), ExistingClauses,
1330 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1331 TransformedGangKinds, TransformedIntExprs, ParsedClause.getEndLoc());
1332}
1333
1334void OpenACCDeclClauseInstantiator::VisitSeqClause(const OpenACCSeqClause &C) {
1335 NewClause = OpenACCSeqClause::Create(SemaRef.getASTContext(),
1336 ParsedClause.getBeginLoc(),
1337 ParsedClause.getEndLoc());
1338}
1339void OpenACCDeclClauseInstantiator::VisitNoHostClause(
1340 const OpenACCNoHostClause &C) {
1341 NewClause = OpenACCNoHostClause::Create(SemaRef.getASTContext(),
1342 ParsedClause.getBeginLoc(),
1343 ParsedClause.getEndLoc());
1344}
1345
1346void OpenACCDeclClauseInstantiator::VisitDeviceTypeClause(
1347 const OpenACCDeviceTypeClause &C) {
1348 // Nothing to transform here, just create a new version of 'C'.
1350 SemaRef.getASTContext(), C.getClauseKind(), ParsedClause.getBeginLoc(),
1351 ParsedClause.getLParenLoc(), C.getArchitectures(),
1352 ParsedClause.getEndLoc());
1353}
1354
1355void OpenACCDeclClauseInstantiator::VisitWorkerClause(
1356 const OpenACCWorkerClause &C) {
1357 assert(!C.hasIntExpr() && "Int Expr not allowed on routine 'worker' clause");
1358 NewClause = OpenACCWorkerClause::Create(SemaRef.getASTContext(),
1359 ParsedClause.getBeginLoc(), {},
1360 nullptr, ParsedClause.getEndLoc());
1361}
1362
1363void OpenACCDeclClauseInstantiator::VisitVectorClause(
1364 const OpenACCVectorClause &C) {
1365 assert(!C.hasIntExpr() && "Int Expr not allowed on routine 'vector' clause");
1366 NewClause = OpenACCVectorClause::Create(SemaRef.getASTContext(),
1367 ParsedClause.getBeginLoc(), {},
1368 nullptr, ParsedClause.getEndLoc());
1369}
1370
1371void OpenACCDeclClauseInstantiator::VisitCopyClause(
1372 const OpenACCCopyClause &C) {
1373 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1374 C.getModifierList());
1375 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause, C.getModifierList()))
1376 return;
1377 NewClause = OpenACCCopyClause::Create(
1378 SemaRef.getASTContext(), ParsedClause.getClauseKind(),
1379 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1380 ParsedClause.getModifierList(), ParsedClause.getVarList(),
1381 ParsedClause.getEndLoc());
1382}
1383
1384void OpenACCDeclClauseInstantiator::VisitLinkClause(
1385 const OpenACCLinkClause &C) {
1386 ParsedClause.setVarListDetails(
1387 SemaRef.OpenACC().CheckLinkClauseVarList(VisitVarList(C.getVarList())),
1389
1390 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause,
1392 return;
1393
1394 NewClause = OpenACCLinkClause::Create(
1395 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1396 ParsedClause.getLParenLoc(), ParsedClause.getVarList(),
1397 ParsedClause.getEndLoc());
1398}
1399
1400void OpenACCDeclClauseInstantiator::VisitDeviceResidentClause(
1402 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1404 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause,
1406 return;
1408 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1409 ParsedClause.getLParenLoc(), ParsedClause.getVarList(),
1410 ParsedClause.getEndLoc());
1411}
1412
1413void OpenACCDeclClauseInstantiator::VisitCopyInClause(
1414 const OpenACCCopyInClause &C) {
1415 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1416 C.getModifierList());
1417
1418 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause, C.getModifierList()))
1419 return;
1420 NewClause = OpenACCCopyInClause::Create(
1421 SemaRef.getASTContext(), ParsedClause.getClauseKind(),
1422 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1423 ParsedClause.getModifierList(), ParsedClause.getVarList(),
1424 ParsedClause.getEndLoc());
1425}
1426void OpenACCDeclClauseInstantiator::VisitCopyOutClause(
1427 const OpenACCCopyOutClause &C) {
1428 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1429 C.getModifierList());
1430
1431 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause, C.getModifierList()))
1432 return;
1433 NewClause = OpenACCCopyOutClause::Create(
1434 SemaRef.getASTContext(), ParsedClause.getClauseKind(),
1435 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1436 ParsedClause.getModifierList(), ParsedClause.getVarList(),
1437 ParsedClause.getEndLoc());
1438}
1439void OpenACCDeclClauseInstantiator::VisitCreateClause(
1440 const OpenACCCreateClause &C) {
1441 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1442 C.getModifierList());
1443
1444 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause, C.getModifierList()))
1445 return;
1446 NewClause = OpenACCCreateClause::Create(
1447 SemaRef.getASTContext(), ParsedClause.getClauseKind(),
1448 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1449 ParsedClause.getModifierList(), ParsedClause.getVarList(),
1450 ParsedClause.getEndLoc());
1451}
1452void OpenACCDeclClauseInstantiator::VisitPresentClause(
1453 const OpenACCPresentClause &C) {
1454 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1456 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause,
1458 return;
1459 NewClause = OpenACCPresentClause::Create(
1460 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1461 ParsedClause.getLParenLoc(), ParsedClause.getVarList(),
1462 ParsedClause.getEndLoc());
1463}
1464void OpenACCDeclClauseInstantiator::VisitDevicePtrClause(
1465 const OpenACCDevicePtrClause &C) {
1466 llvm::SmallVector<Expr *> VarList = VisitVarList(C.getVarList());
1467 // Ensure each var is a pointer type.
1468 llvm::erase_if(VarList, [&](Expr *E) {
1469 return SemaRef.OpenACC().CheckVarIsPointerType(OpenACCClauseKind::DevicePtr,
1470 E);
1471 });
1472 ParsedClause.setVarListDetails(VarList, OpenACCModifierKind::Invalid);
1473 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause,
1475 return;
1477 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1478 ParsedClause.getLParenLoc(), ParsedClause.getVarList(),
1479 ParsedClause.getEndLoc());
1480}
1481
1482void OpenACCDeclClauseInstantiator::VisitBindClause(
1483 const OpenACCBindClause &C) {
1484 // Nothing to instantiate, we support only string literal or identifier.
1485 if (C.isStringArgument())
1486 NewClause = OpenACCBindClause::Create(
1487 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1488 ParsedClause.getLParenLoc(), C.getStringArgument(),
1489 ParsedClause.getEndLoc());
1490 else
1491 NewClause = OpenACCBindClause::Create(
1492 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1493 ParsedClause.getLParenLoc(), C.getIdentifierArgument(),
1494 ParsedClause.getEndLoc());
1495}
1496
1497llvm::SmallVector<OpenACCClause *> InstantiateOpenACCClauseList(
1498 Sema &S, const MultiLevelTemplateArgumentList &MLTAL,
1500 llvm::SmallVector<OpenACCClause *> TransformedClauses;
1501
1502 for (const auto *Clause : ClauseList) {
1503 SemaOpenACC::OpenACCParsedClause ParsedClause(DK, Clause->getClauseKind(),
1504 Clause->getBeginLoc());
1505 ParsedClause.setEndLoc(Clause->getEndLoc());
1506 if (const auto *WithParms = dyn_cast<OpenACCClauseWithParams>(Clause))
1507 ParsedClause.setLParenLoc(WithParms->getLParenLoc());
1508
1509 OpenACCDeclClauseInstantiator Instantiator{S, MLTAL, TransformedClauses,
1510 ParsedClause};
1511 Instantiator.Visit(Clause);
1512 if (Instantiator.CreatedClause())
1513 TransformedClauses.push_back(Instantiator.CreatedClause());
1514 }
1515 return TransformedClauses;
1516}
1517
1518} // namespace
1519
1521 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
1522 const OpenACCRoutineDeclAttr *OldAttr, const Decl *OldDecl, Decl *NewDecl) {
1523 OpenACCRoutineDeclAttr *A =
1524 OpenACCRoutineDeclAttr::Create(S.getASTContext(), OldAttr->getLocation());
1525
1526 if (!OldAttr->Clauses.empty()) {
1527 llvm::SmallVector<OpenACCClause *> TransformedClauses =
1528 InstantiateOpenACCClauseList(
1529 S, TemplateArgs, OpenACCDirectiveKind::Routine, OldAttr->Clauses);
1530 A->Clauses.assign(TransformedClauses.begin(), TransformedClauses.end());
1531 }
1532
1533 // We don't end up having to do any magic-static or bind checking here, since
1534 // the first phase should have caught this, since we always apply to the
1535 // functiondecl.
1536 NewDecl->addAttr(A);
1537}
1538
1539Decl *TemplateDeclInstantiator::VisitOpenACCDeclareDecl(OpenACCDeclareDecl *D) {
1540 SemaRef.OpenACC().ActOnConstruct(D->getDirectiveKind(), D->getBeginLoc());
1541 llvm::SmallVector<OpenACCClause *> TransformedClauses =
1542 InstantiateOpenACCClauseList(SemaRef, TemplateArgs, D->getDirectiveKind(),
1543 D->clauses());
1544
1545 if (SemaRef.OpenACC().ActOnStartDeclDirective(
1546 D->getDirectiveKind(), D->getBeginLoc(), TransformedClauses))
1547 return nullptr;
1548
1549 DeclGroupRef Res = SemaRef.OpenACC().ActOnEndDeclDirective(
1550 D->getDirectiveKind(), D->getBeginLoc(), D->getDirectiveLoc(), {}, {},
1551 D->getEndLoc(), TransformedClauses);
1552
1553 if (Res.isNull())
1554 return nullptr;
1555
1556 return Res.getSingleDecl();
1557}
1558
1559Decl *TemplateDeclInstantiator::VisitOpenACCRoutineDecl(OpenACCRoutineDecl *D) {
1560 SemaRef.OpenACC().ActOnConstruct(D->getDirectiveKind(), D->getBeginLoc());
1561 llvm::SmallVector<OpenACCClause *> TransformedClauses =
1562 InstantiateOpenACCClauseList(SemaRef, TemplateArgs, D->getDirectiveKind(),
1563 D->clauses());
1564
1565 ExprResult FuncRef;
1566 if (D->getFunctionReference()) {
1567 FuncRef = SemaRef.SubstCXXIdExpr(D->getFunctionReference(), TemplateArgs);
1568 if (FuncRef.isUsable())
1569 FuncRef = SemaRef.OpenACC().ActOnRoutineName(FuncRef.get());
1570 // We don't return early here, we leave the construct in the AST, even if
1571 // the function decl is empty.
1572 }
1573
1574 if (SemaRef.OpenACC().ActOnStartDeclDirective(
1575 D->getDirectiveKind(), D->getBeginLoc(), TransformedClauses))
1576 return nullptr;
1577
1578 DeclGroupRef Res = SemaRef.OpenACC().ActOnEndRoutineDeclDirective(
1579 D->getBeginLoc(), D->getDirectiveLoc(), D->getLParenLoc(), FuncRef.get(),
1580 D->getRParenLoc(), TransformedClauses, D->getEndLoc(), nullptr);
1581
1582 if (Res.isNull())
1583 return nullptr;
1584
1585 return Res.getSingleDecl();
1586}
1587
1588Decl *
1589TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1590 NamespaceAliasDecl *Inst
1591 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
1592 D->getNamespaceLoc(),
1593 D->getAliasLoc(),
1594 D->getIdentifier(),
1595 D->getQualifierLoc(),
1596 D->getTargetNameLoc(),
1597 D->getNamespace());
1598 Owner->addDecl(Inst);
1599 return Inst;
1600}
1601
1603 bool IsTypeAlias) {
1604 bool Invalid = false;
1606 if (TSI->getType()->isInstantiationDependentType() ||
1607 TSI->getType()->isVariablyModifiedType()) {
1608 TSI = SemaRef.SubstType(TSI, TemplateArgs, D->getLocation(),
1609 D->getDeclName());
1610 if (!TSI) {
1611 Invalid = true;
1612 TSI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
1613 }
1614 } else {
1615 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), TSI->getType());
1616 }
1617
1618 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
1619 // libstdc++ relies upon this bug in its implementation of common_type. If we
1620 // happen to be processing that implementation, fake up the g++ ?:
1621 // semantics. See LWG issue 2141 for more information on the bug. The bugs
1622 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
1623 if (SemaRef.getPreprocessor().NeedsStdLibCxxWorkaroundBefore(2014'04'22)) {
1624 const DecltypeType *DT = TSI->getType()->getAs<DecltypeType>();
1625 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1626 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
1627 DT->isReferenceType() &&
1628 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
1629 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
1630 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
1631 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
1632 // Fold it to the (non-reference) type which g++ would have produced.
1633 TSI = SemaRef.Context.getTrivialTypeSourceInfo(
1634 TSI->getType().getNonReferenceType());
1635 }
1636
1637 // Create the new typedef
1639 if (IsTypeAlias)
1640 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1641 D->getLocation(), D->getIdentifier(), TSI);
1642 else
1643 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1644 D->getLocation(), D->getIdentifier(), TSI);
1645 if (Invalid)
1646 Typedef->setInvalidDecl();
1647
1648 // If the old typedef was the name for linkage purposes of an anonymous
1649 // tag decl, re-establish that relationship for the new typedef.
1650 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1651 TagDecl *oldTag = oldTagType->getDecl();
1652 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1653 TagDecl *newTag = TSI->getType()->castAs<TagType>()->getDecl();
1654 assert(!newTag->hasNameForLinkage());
1656 }
1657 }
1658
1660 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1661 TemplateArgs);
1662 if (!InstPrev)
1663 return nullptr;
1664
1665 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1666
1667 // If the typedef types are not identical, reject them.
1668 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1669
1670 Typedef->setPreviousDecl(InstPrevTypedef);
1671 }
1672
1673 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1674
1675 if (D->getUnderlyingType()->getAs<DependentNameType>())
1676 SemaRef.inferGslPointerAttribute(Typedef);
1677
1678 Typedef->setAccess(D->getAccess());
1679 Typedef->setReferenced(D->isReferenced());
1680
1681 return Typedef;
1682}
1683
1684Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1685 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1686 if (Typedef)
1687 Owner->addDecl(Typedef);
1688 return Typedef;
1689}
1690
1691Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1692 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1693 if (Typedef)
1694 Owner->addDecl(Typedef);
1695 return Typedef;
1696}
1697
1700 // Create a local instantiation scope for this type alias template, which
1701 // will contain the instantiations of the template parameters.
1703
1705 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1706 if (!InstParams)
1707 return nullptr;
1708
1709 // FIXME: This is a hack for instantiating lambdas in the pattern of the
1710 // alias. We are not really instantiating the alias at its template level,
1711 // that only happens in CheckTemplateId, this is only for outer templates
1712 // which contain it. In getTemplateInstantiationArgs, the template arguments
1713 // used here would be used for collating the template arguments needed to
1714 // instantiate the lambda. Pass an empty argument list, so this workaround
1715 // doesn't get confused if there is an outer alias being instantiated.
1716 Sema::InstantiatingTemplate InstTemplate(SemaRef, D->getBeginLoc(), D,
1718 if (InstTemplate.isInvalid())
1719 return nullptr;
1720
1721 TypeAliasDecl *Pattern = D->getTemplatedDecl();
1722 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1724 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1725 if (!Found.empty()) {
1726 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1727 }
1728 }
1729
1730 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1731 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1732 if (!AliasInst)
1733 return nullptr;
1734
1736 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1737 D->getDeclName(), InstParams, AliasInst);
1738 AliasInst->setDescribedAliasTemplate(Inst);
1739 if (PrevAliasTemplate)
1740 Inst->setPreviousDecl(PrevAliasTemplate);
1741
1742 Inst->setAccess(D->getAccess());
1743
1744 if (!PrevAliasTemplate)
1746
1747 return Inst;
1748}
1749
1750Decl *
1751TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1753 if (Inst)
1754 Owner->addDecl(Inst);
1755
1756 return Inst;
1757}
1758
1759Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1760 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1761 D->getIdentifier(), D->getType());
1762 NewBD->setReferenced(D->isReferenced());
1764
1765 return NewBD;
1766}
1767
1768Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1769 // Transform the bindings first.
1770 // The transformed DD will have all of the concrete BindingDecls.
1771 SmallVector<BindingDecl*, 16> NewBindings;
1772 BindingDecl *OldBindingPack = nullptr;
1773 for (auto *OldBD : D->bindings()) {
1774 Expr *BindingExpr = OldBD->getBinding();
1775 if (isa_and_present<FunctionParmPackExpr>(BindingExpr)) {
1776 // We have a resolved pack.
1777 assert(!OldBindingPack && "no more than one pack is allowed");
1778 OldBindingPack = OldBD;
1779 }
1780 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1781 }
1782 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1783
1784 auto *NewDD = cast_if_present<DecompositionDecl>(
1785 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1786
1787 if (!NewDD || NewDD->isInvalidDecl()) {
1788 for (auto *NewBD : NewBindings)
1789 NewBD->setInvalidDecl();
1790 } else if (OldBindingPack) {
1791 // Mark the bindings in the pack as instantiated.
1792 auto Bindings = NewDD->bindings();
1793 BindingDecl *NewBindingPack = *llvm::find_if(
1794 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
1795 assert(NewBindingPack != nullptr && "new bindings should also have a pack");
1796 llvm::ArrayRef<BindingDecl *> OldDecls =
1797 OldBindingPack->getBindingPackDecls();
1798 llvm::ArrayRef<BindingDecl *> NewDecls =
1799 NewBindingPack->getBindingPackDecls();
1800 assert(OldDecls.size() == NewDecls.size());
1801 for (unsigned I = 0; I < OldDecls.size(); I++)
1802 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldDecls[I],
1803 NewDecls[I]);
1804 }
1805
1806 return NewDD;
1807}
1808
1810 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1811}
1812
1814 bool InstantiatingVarTemplate,
1816
1817 // Do substitution on the type of the declaration
1818 TypeSourceInfo *TSI = SemaRef.SubstType(
1819 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1820 D->getDeclName(), /*AllowDeducedTST*/ true);
1821 bool Invalid = false;
1822 if (!TSI) {
1823 if (!InstantiatingVarTemplate)
1824 return nullptr;
1825 TSI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy,
1826 D->getLocation());
1827 Invalid = true;
1828 } else if (TSI->getType()->isFunctionType()) {
1829 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1830 << D->isStaticDataMember() << TSI->getType();
1831 if (!InstantiatingVarTemplate)
1832 return nullptr;
1833 Invalid = true;
1834 }
1835
1836 DeclContext *DC = Owner;
1837 if (D->isLocalExternDecl())
1838 SemaRef.adjustContextForLocalExternDecl(DC);
1839
1840 // Build the instantiated declaration.
1841 VarDecl *Var;
1842 if (Bindings)
1844 SemaRef.Context, DC, D->getInnerLocStart(), D->getLocation(),
1845 D->getEndLoc(), TSI->getType(), TSI, D->getStorageClass(), *Bindings);
1846 else
1847 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1848 D->getLocation(), D->getIdentifier(), TSI->getType(),
1849 TSI, D->getStorageClass());
1850
1851 // In ARC, infer 'retaining' for variables of retainable type.
1852 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1853 SemaRef.ObjC().inferObjCARCLifetime(Var))
1854 Var->setInvalidDecl();
1855
1856 if (SemaRef.getLangOpts().OpenCL)
1857 SemaRef.deduceOpenCLAddressSpace(Var);
1858
1859 // Substitute the nested name specifier, if any.
1860 if (SubstQualifier(D, Var))
1861 return nullptr;
1862
1863 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1864 StartingScope, InstantiatingVarTemplate);
1865 if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1866 QualType RT;
1867 if (auto *F = dyn_cast<FunctionDecl>(DC))
1868 RT = F->getReturnType();
1869 else if (isa<BlockDecl>(DC))
1870 RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1871 ->getReturnType();
1872 else
1873 llvm_unreachable("Unknown context type");
1874
1875 // This is the last chance we have of checking copy elision eligibility
1876 // for functions in dependent contexts. The sema actions for building
1877 // the return statement during template instantiation will have no effect
1878 // regarding copy elision, since NRVO propagation runs on the scope exit
1879 // actions, and these are not run on instantiation.
1880 // This might run through some VarDecls which were returned from non-taken
1881 // 'if constexpr' branches, and these will end up being constructed on the
1882 // return slot even if they will never be returned, as a sort of accidental
1883 // 'optimization'. Notably, functions with 'auto' return types won't have it
1884 // deduced by this point. Coupled with the limitation described
1885 // previously, this makes it very hard to support copy elision for these.
1886 Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1887 bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1888 Var->setNRVOVariable(NRVO);
1889 }
1890
1891 Var->setImplicit(D->isImplicit());
1892
1893 if (Var->isStaticLocal())
1894 SemaRef.CheckStaticLocalForDllExport(Var);
1895
1896 if (Var->getTLSKind())
1897 SemaRef.CheckThreadLocalForLargeAlignment(Var);
1898
1899 if (SemaRef.getLangOpts().OpenACC)
1900 SemaRef.OpenACC().ActOnVariableDeclarator(Var);
1901
1902 if (Invalid)
1903 Var->setInvalidDecl();
1904
1905 return Var;
1906}
1907
1908Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1909 AccessSpecDecl* AD
1910 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1912 Owner->addHiddenDecl(AD);
1913 return AD;
1914}
1915
1916Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1917 bool Invalid = false;
1918 TypeSourceInfo *TSI = D->getTypeSourceInfo();
1919 if (TSI->getType()->isInstantiationDependentType() ||
1920 TSI->getType()->isVariablyModifiedType()) {
1921 TSI = SemaRef.SubstType(TSI, TemplateArgs, D->getLocation(),
1922 D->getDeclName());
1923 if (!TSI) {
1924 TSI = D->getTypeSourceInfo();
1925 Invalid = true;
1926 } else if (TSI->getType()->isFunctionType()) {
1927 // C++ [temp.arg.type]p3:
1928 // If a declaration acquires a function type through a type
1929 // dependent on a template-parameter and this causes a
1930 // declaration that does not use the syntactic form of a
1931 // function declarator to have function type, the program is
1932 // ill-formed.
1933 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1934 << TSI->getType();
1935 Invalid = true;
1936 }
1937 } else {
1938 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), TSI->getType());
1939 }
1940
1941 Expr *BitWidth = D->getBitWidth();
1942 if (Invalid)
1943 BitWidth = nullptr;
1944 else if (BitWidth) {
1945 // The bit-width expression is a constant expression.
1946 EnterExpressionEvaluationContext Unevaluated(
1948
1949 ExprResult InstantiatedBitWidth
1950 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1951 if (InstantiatedBitWidth.isInvalid()) {
1952 Invalid = true;
1953 BitWidth = nullptr;
1954 } else
1955 BitWidth = InstantiatedBitWidth.getAs<Expr>();
1956 }
1957
1958 FieldDecl *Field = SemaRef.CheckFieldDecl(
1959 D->getDeclName(), TSI->getType(), TSI, cast<RecordDecl>(Owner),
1960 D->getLocation(), D->isMutable(), BitWidth, D->getInClassInitStyle(),
1961 D->getInnerLocStart(), D->getAccess(), nullptr);
1962 if (!Field) {
1963 cast<Decl>(Owner)->setInvalidDecl();
1964 return nullptr;
1965 }
1966
1967 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1968
1969 if (Field->hasAttrs())
1970 SemaRef.CheckAlignasUnderalignment(Field);
1971
1972 if (Invalid)
1973 Field->setInvalidDecl();
1974
1975 if (!Field->getDeclName() || Field->isPlaceholderVar(SemaRef.getLangOpts())) {
1976 // Keep track of where this decl came from.
1977 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1978 }
1979 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1980 if (Parent->isAnonymousStructOrUnion() &&
1981 Parent->getRedeclContext()->isFunctionOrMethod())
1982 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1983 }
1984
1985 Field->setImplicit(D->isImplicit());
1986 Field->setAccess(D->getAccess());
1987 Owner->addDecl(Field);
1988
1989 return Field;
1990}
1991
1992Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1993 bool Invalid = false;
1994 TypeSourceInfo *TSI = D->getTypeSourceInfo();
1995
1996 if (TSI->getType()->isVariablyModifiedType()) {
1997 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1998 << D;
1999 Invalid = true;
2000 } else if (TSI->getType()->isInstantiationDependentType()) {
2001 TSI = SemaRef.SubstType(TSI, TemplateArgs, D->getLocation(),
2002 D->getDeclName());
2003 if (!TSI) {
2004 TSI = D->getTypeSourceInfo();
2005 Invalid = true;
2006 } else if (TSI->getType()->isFunctionType()) {
2007 // C++ [temp.arg.type]p3:
2008 // If a declaration acquires a function type through a type
2009 // dependent on a template-parameter and this causes a
2010 // declaration that does not use the syntactic form of a
2011 // function declarator to have function type, the program is
2012 // ill-formed.
2013 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
2014 << TSI->getType();
2015 Invalid = true;
2016 }
2017 } else {
2018 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), TSI->getType());
2019 }
2020
2021 MSPropertyDecl *Property = MSPropertyDecl::Create(
2022 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(),
2023 TSI->getType(), TSI, D->getBeginLoc(), D->getGetterId(),
2024 D->getSetterId());
2025
2026 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
2027 StartingScope);
2028
2029 if (Invalid)
2030 Property->setInvalidDecl();
2031
2032 Property->setAccess(D->getAccess());
2033 Owner->addDecl(Property);
2034
2035 return Property;
2036}
2037
2038Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
2039 NamedDecl **NamedChain =
2040 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
2041
2042 int i = 0;
2043 for (auto *PI : D->chain()) {
2044 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
2045 TemplateArgs);
2046 if (!Next)
2047 return nullptr;
2048
2049 NamedChain[i++] = Next;
2050 }
2051
2052 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
2053 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
2054 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
2055 {NamedChain, D->getChainingSize()});
2056
2057 for (const auto *Attr : D->attrs())
2058 IndirectField->addAttr(Attr->clone(SemaRef.Context));
2059
2060 IndirectField->setImplicit(D->isImplicit());
2061 IndirectField->setAccess(D->getAccess());
2062 Owner->addDecl(IndirectField);
2063 return IndirectField;
2064}
2065
2066static std::optional<TemplateName>
2068 DeclarationName Name, SourceLocation NameLoc,
2069 bool HasTemplateKeyword, bool RequireClassTemplate) {
2070 if (!QualifierLoc)
2071 return TemplateName();
2072
2073 CXXScopeSpec SS;
2074 SS.Adopt(QualifierLoc);
2075
2076 DeclContext *DC = SemaRef.computeDeclContext(SS, /*EnteringContext=*/true);
2077 if (!DC) {
2078 if (QualifierLoc.getNestedNameSpecifier().isDependent())
2079 return TemplateName();
2080 return std::nullopt;
2081 }
2082
2083 bool IsDependentContext = DC->isDependentContext();
2084 if (!IsDependentContext && SemaRef.RequireCompleteDeclContext(SS, DC))
2085 return std::nullopt;
2086
2087 LookupResult Result(SemaRef, Name, NameLoc, Sema::LookupOrdinaryName,
2089 if (!SemaRef.LookupQualifiedName(Result, DC)) {
2090 if (RequireClassTemplate && !IsDependentContext) {
2091 SemaRef.Diag(NameLoc, diag::err_no_member_template)
2092 << Name << DC << QualifierLoc.getSourceRange();
2093 return std::nullopt;
2094 }
2095 return TemplateName();
2096 }
2097
2098 if (Result.isAmbiguous())
2099 return std::nullopt;
2100
2101 auto *CTD = Result.getAsSingle<ClassTemplateDecl>();
2102 if (!CTD) {
2103 if (RequireClassTemplate && !IsDependentContext) {
2104 SemaRef.Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2105 SemaRef.Diag(
2106 Result.getRepresentativeDecl()->getUnderlyingDecl()->getLocation(),
2107 diag::note_previous_definition);
2108 return std::nullopt;
2109 }
2110 return TemplateName();
2111 }
2112
2113 auto *FoundUsingShadow =
2114 dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl());
2115
2116 return SemaRef.Context.getQualifiedTemplateName(
2117 QualifierLoc.getNestedNameSpecifier(), HasTemplateKeyword,
2118 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(CTD));
2119}
2120
2123 const MultiLevelTemplateArgumentList &TemplateArgs,
2124 SourceLocation Loc, DeclarationName Entity) {
2127 NestedNameSpecifierLoc QualifierLoc =
2128 TSTL ? TSTL.getQualifierLoc() : NestedNameSpecifierLoc();
2129 if (!TSTL || !QualifierLoc ||
2130 !QualifierLoc.getNestedNameSpecifier().isDependent())
2131 return SubstType(TSI, TemplateArgs, Loc, Entity);
2132
2133 const auto *FriendTST = TSTL.getTypePtr();
2134 auto *FriendCTD = dyn_cast_or_null<ClassTemplateDecl>(
2135 FriendTST->getTemplateName().getAsTemplateDecl());
2136 if (!FriendCTD)
2137 return SubstType(TSI, TemplateArgs, Loc, Entity);
2138
2139 QualifierLoc = SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2140 if (!QualifierLoc)
2141 return nullptr;
2142
2143 std::optional<TemplateName> InstTemplate = LookupFriendTemplateName(
2144 *this, QualifierLoc, FriendCTD->getDeclName(), TSTL.getTemplateNameLoc(),
2146 /*RequireClassTemplate=*/false);
2147 if (!InstTemplate)
2148 return nullptr;
2149 if (InstTemplate->isNull())
2150 return SubstType(TSI, TemplateArgs, Loc, Entity);
2151
2153 for (unsigned I = 0, N = TSTL.getNumArgs(); I != N; ++I)
2154 FriendArgLocs.push_back(TSTL.getArgLoc(I));
2155
2156 TemplateArgumentListInfo InstArgs(TSTL.getLAngleLoc(), TSTL.getRAngleLoc());
2157 if (SubstTemplateArguments(FriendArgLocs, TemplateArgs, InstArgs))
2158 return nullptr;
2159
2160 QualType InstTy =
2161 CheckTemplateIdType(FriendTST->getKeyword(), *InstTemplate,
2162 TSTL.getTemplateNameLoc(), InstArgs,
2163 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
2164 if (InstTy.isNull())
2165 return nullptr;
2166
2167 TypeLocBuilder TLB;
2168 TLB.push<TemplateSpecializationTypeLoc>(InstTy).set(
2169 TSTL.getElaboratedKeywordLoc(), QualifierLoc,
2170 TSTL.getTemplateKeywordLoc(), TSTL.getTemplateNameLoc(), InstArgs);
2171 return TLB.getTypeSourceInfo(Context, InstTy);
2172}
2173
2177
2178 bool empty() const { return !TypeInfo && Template.isNull(); }
2179};
2180
2181static std::optional<SubstitutedFriend>
2184 const MultiLevelTemplateArgumentList &TemplateArgs,
2185 SourceLocation Loc, DeclarationName Entity) {
2186 NestedNameSpecifierLoc QualifierLoc = TSI->getTypeLoc().getPrefix();
2187 NestedNameSpecifierLoc InstQualifierLoc = QualifierLoc;
2188 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier().isDependent()) {
2189 InstQualifierLoc =
2190 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2191 if (!InstQualifierLoc ||
2192 SemaRef.CheckDependentFriend(Loc, InstQualifierLoc, /*TPLs=*/{},
2193 /*IsInstantiation=*/true))
2194 return std::nullopt;
2195 }
2196
2197 TemplateName InstFriendTemplate;
2198 if (!FriendTemplate.isNull()) {
2199 auto DNTL = TSI->getTypeLoc().getAs<DependentNameTypeLoc>();
2200 assert(DNTL && "friend class template must have a dependent name type");
2201
2202 std::optional<TemplateName> InstTemplate = LookupFriendTemplateName(
2203 SemaRef, InstQualifierLoc, DNTL.getTypePtr()->getIdentifier(),
2204 DNTL.getNameLoc(), /*HasTemplateKeyword=*/false,
2205 /*RequireClassTemplate=*/true);
2206 if (!InstTemplate)
2207 return std::nullopt;
2208 if (!InstTemplate->isNull())
2209 return SubstitutedFriend{nullptr, *InstTemplate};
2210
2211 auto *DTN = FriendTemplate.getAsDependentTemplateName();
2212 assert(DTN && "unresolved friend template must have a dependent name");
2213 InstFriendTemplate = SemaRef.Context.getDependentTemplateName(
2214 {InstQualifierLoc.getNestedNameSpecifier(), DTN->getName(),
2215 DTN->hasTemplateKeyword()});
2216 }
2217
2218 TypeSourceInfo *InstType =
2219 SemaRef.SubstFriendType(TSI, TemplateArgs, Loc, Entity);
2220 if (!InstType)
2221 return std::nullopt;
2222 return SubstitutedFriend{InstType, InstFriendTemplate};
2223}
2224
2226 TypeSourceInfo *TSI = D->getFriendType();
2227 assert(TSI && "friend pack expansion must name a type");
2228
2229 const auto *FTD = dyn_cast<FriendTemplateDecl>(D);
2231 if (FTD)
2232 TPLs = FTD->getTemplateParameterLists();
2233
2235 SemaRef.collectUnexpandedParameterPacks(TSI->getTypeLoc(), Unexpanded);
2236 assert(!Unexpanded.empty() && "Pack expansion without packs");
2237
2238 bool ShouldExpand = true;
2239 bool RetainExpansion = false;
2240 UnsignedOrNone NumExpansions = std::nullopt;
2241 if (SemaRef.CheckParameterPacksForExpansion(
2242 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
2243 /*FailOnPackProducingTemplates=*/true, ShouldExpand, RetainExpansion,
2244 NumExpansions))
2245 return true;
2246
2247 assert(!RetainExpansion &&
2248 "should never retain an expansion for a friend declaration");
2249
2250 if (!ShouldExpand)
2251 return false;
2252
2253 for (unsigned I = 0; I != *NumExpansions; I++) {
2254 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
2255 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
2257 if (SubstTemplateParameterLists(TPLs, InstTPLs))
2258 return true;
2259
2260 std::optional<SubstitutedFriend> InstFriend;
2261 if (FTD)
2262 InstFriend = SubstFriendTemplateType(
2263 SemaRef, TSI, FTD->getFriendTemplateName(), TemplateArgs,
2265 else if (TypeSourceInfo *InstType = SemaRef.SubstFriendType(
2266 TSI, TemplateArgs, D->getEllipsisLoc(), DeclarationName()))
2267 InstFriend = SubstitutedFriend{InstType, {}};
2268 if (!InstFriend || InstFriend->empty())
2269 return true;
2270
2271 FriendDecl *FD;
2272 if (FTD) {
2273 FriendDecl::FriendUnion ToFriend =
2274 InstFriend->TypeInfo ? FriendDecl::FriendUnion(InstFriend->TypeInfo)
2276 FD = FriendTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2277 ToFriend, D->getFriendLoc(), InstTPLs,
2278 /*EllipsisLoc=*/{}, InstFriend->Template);
2279 } else {
2280 assert(InstTPLs.empty() && "unexpected template parameter lists");
2281 assert(InstFriend->Template.isNull() &&
2282 "non-template friend resolved to a class template");
2283 FD = FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2284 InstFriend->TypeInfo, D->getFriendLoc());
2285 }
2286
2287 FD->setAccess(AS_public);
2288 Owner->addDecl(FD);
2289 }
2290
2291 return true;
2292}
2293
2294Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
2295 if (TypeSourceInfo *Ty = D->getFriendType()) {
2297 return nullptr;
2298
2299 TypeSourceInfo *InstTy = SemaRef.SubstFriendType(
2300 Ty, TemplateArgs, D->getLocation(), DeclarationName());
2301 if (!InstTy)
2302 return nullptr;
2303
2305 SemaRef.Context, Owner, D->getLocation(), InstTy, D->getFriendLoc());
2306 FD->setAccess(AS_public);
2307 Owner->addDecl(FD);
2308 return FD;
2309 }
2310
2311 NamedDecl *ND = D->getFriendDecl();
2312 assert(ND && "friend decl must be a decl or a type!");
2313
2314 // All of the Visit implementations for the various potential friend
2315 // declarations have to be carefully written to work for friend
2316 // objects, with the most important detail being that the target
2317 // decl should almost certainly not be placed in Owner.
2318 Decl *NewND = Visit(ND);
2319 if (!NewND) return nullptr;
2320
2321 FriendDecl *FD =
2322 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2323 cast<NamedDecl>(NewND), D->getFriendLoc());
2324 FD->setAccess(AS_public);
2325 Owner->addDecl(FD);
2326 return FD;
2327}
2328
2329Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
2330 Expr *AssertExpr = D->getAssertExpr();
2331
2332 // The expression in a static assertion is a constant expression.
2333 EnterExpressionEvaluationContext Unevaluated(
2335
2336 ExprResult InstantiatedAssertExpr
2337 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
2338 if (InstantiatedAssertExpr.isInvalid())
2339 return nullptr;
2340
2341 ExprResult InstantiatedMessageExpr =
2342 SemaRef.SubstExpr(D->getMessage(), TemplateArgs);
2343 if (InstantiatedMessageExpr.isInvalid())
2344 return nullptr;
2345
2346 return SemaRef.BuildStaticAssertDeclaration(
2347 D->getLocation(), InstantiatedAssertExpr.get(),
2348 InstantiatedMessageExpr.get(), D->getRParenLoc(), D->isFailed());
2349}
2350
2351Decl *TemplateDeclInstantiator::VisitExplicitInstantiationDecl(
2353 // ExplicitInstantiationDecl is a source-info-only node and should not
2354 // appear inside a template pattern. Nothing to instantiate.
2355 llvm_unreachable("ExplicitInstantiationDecl should not be instantiated");
2356}
2357
2358Decl *TemplateDeclInstantiator::VisitCXXExpansionStmtDecl(
2359 CXXExpansionStmtDecl *OldESD) {
2360 Decl *Index = VisitNonTypeTemplateParmDecl(OldESD->getIndexTemplateParm());
2361 CXXExpansionStmtDecl *NewESD = SemaRef.BuildCXXExpansionStmtDecl(
2362 Owner, OldESD->getBeginLoc(), cast<NonTypeTemplateParmDecl>(Index));
2363 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldESD, NewESD);
2364
2365 // If this was already expanded, only instantiate the expansion and
2366 // don't touch the unexpanded expansion statement.
2367 if (CXXExpansionStmtInstantiation *OldInst = OldESD->getInstantiations()) {
2368 StmtResult NewInst = SemaRef.SubstStmt(OldInst, TemplateArgs);
2369 if (NewInst.isInvalid())
2370 return nullptr;
2371
2372 NewESD->setInstantiations(NewInst.getAs<CXXExpansionStmtInstantiation>());
2373 NewESD->setExpansionPattern(OldESD->getExpansionPattern());
2374 return NewESD;
2375 }
2376
2377 // Enter the scope of this expansion statement; don't do this if we've
2378 // already expanded it, as in that case we no longer want to treat its
2379 // content as dependent.
2380 Sema::ContextRAII Context(SemaRef, NewESD, /*NewThis=*/false);
2381
2382 StmtResult Expansion =
2383 SemaRef.SubstStmt(OldESD->getExpansionPattern(), TemplateArgs);
2384 if (Expansion.isInvalid())
2385 return nullptr;
2386
2387 // The code that handles CXXExpansionStmtPattern takes care of calling
2388 // setInstantiation() on the ESD if there was an expansion.
2389 NewESD->setExpansionPattern(cast<CXXExpansionStmtPattern>(Expansion.get()));
2390 return NewESD;
2391}
2392
2393Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
2394 EnumDecl *PrevDecl = nullptr;
2395 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2396 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
2397 PatternPrev,
2398 TemplateArgs);
2399 if (!Prev) return nullptr;
2400 PrevDecl = cast<EnumDecl>(Prev);
2401 }
2402
2403 EnumDecl *Enum =
2404 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
2405 D->getLocation(), D->getIdentifier(), PrevDecl,
2406 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
2407 if (D->isFixed()) {
2408 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
2409 // If we have type source information for the underlying type, it means it
2410 // has been explicitly set by the user. Perform substitution on it before
2411 // moving on.
2412 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
2413 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
2414 DeclarationName());
2415 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
2416 Enum->setIntegerType(SemaRef.Context.IntTy);
2417 else {
2418 // If the underlying type is atomic, we need to adjust the type before
2419 // continuing. See C23 6.7.3.3p5 and Sema::ActOnTag(). FIXME: same as
2420 // within ActOnTag(), it would be nice to have an easy way to get a
2421 // derived TypeSourceInfo which strips qualifiers including the weird
2422 // ones like _Atomic where it forms a different type.
2423 if (NewTI->getType()->isAtomicType())
2424 Enum->setIntegerType(NewTI->getType().getAtomicUnqualifiedType());
2425 else
2426 Enum->setIntegerTypeSourceInfo(NewTI);
2427 }
2428
2429 // C++23 [conv.prom]p4
2430 // if integral promotion can be applied to its underlying type, a prvalue
2431 // of an unscoped enumeration type whose underlying type is fixed can also
2432 // be converted to a prvalue of the promoted underlying type.
2433 //
2434 // FIXME: that logic is already implemented in ActOnEnumBody, factor out
2435 // into (Re)BuildEnumBody.
2436 QualType UnderlyingType = Enum->getIntegerType();
2437 Enum->setPromotionType(
2438 SemaRef.Context.isPromotableIntegerType(UnderlyingType)
2439 ? SemaRef.Context.getPromotedIntegerType(UnderlyingType)
2440 : UnderlyingType);
2441 } else {
2442 assert(!D->getIntegerType()->isDependentType()
2443 && "Dependent type without type source info");
2444 Enum->setIntegerType(D->getIntegerType());
2445 }
2446 }
2447
2448 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
2449
2450 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
2451 Enum->setAccess(D->getAccess());
2452 // Forward the mangling number from the template to the instantiated decl.
2453 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
2454 // See if the old tag was defined along with a declarator.
2455 // If it did, mark the new tag as being associated with that declarator.
2456 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
2457 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
2458 // See if the old tag was defined along with a typedef.
2459 // If it did, mark the new tag as being associated with that typedef.
2460 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
2461 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
2462 if (SubstQualifier(D, Enum)) return nullptr;
2463 Owner->addDecl(Enum);
2464
2465 EnumDecl *Def = D->getDefinition();
2466 if (Def && Def != D) {
2467 // If this is an out-of-line definition of an enum member template, check
2468 // that the underlying types match in the instantiation of both
2469 // declarations.
2470 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
2471 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
2472 QualType DefnUnderlying =
2473 SemaRef.SubstType(TI->getType(), TemplateArgs,
2474 UnderlyingLoc, DeclarationName());
2475 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
2476 DefnUnderlying, /*IsFixed=*/true, Enum);
2477 }
2478 }
2479
2480 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2481 // specialization causes the implicit instantiation of the declarations, but
2482 // not the definitions of scoped member enumerations.
2483 //
2484 // DR1484 clarifies that enumeration definitions inside a template
2485 // declaration aren't considered entities that can be separately instantiated
2486 // from the rest of the entity they are declared inside.
2487 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
2488 // Prevent redundant instantiation of the enumerator-definition if the
2489 // definition has already been instantiated due to a prior
2490 // opaque-enum-declaration.
2491 if (PrevDecl == nullptr) {
2492 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
2494 }
2495 }
2496
2497 return Enum;
2498}
2499
2501 EnumDecl *Enum, EnumDecl *Pattern) {
2502 Enum->startDefinition();
2503
2504 // Update the location to refer to the definition.
2505 Enum->setLocation(Pattern->getLocation());
2506
2507 SmallVector<Decl*, 4> Enumerators;
2508
2509 EnumConstantDecl *LastEnumConst = nullptr;
2510 for (auto *EC : Pattern->enumerators()) {
2511 // The specified value for the enumerator.
2512 ExprResult Value((Expr *)nullptr);
2513 if (Expr *UninstValue = EC->getInitExpr()) {
2514 // The enumerator's value expression is a constant expression.
2517
2518 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
2519 }
2520
2521 // Drop the initial value and continue.
2522 bool isInvalid = false;
2523 if (Value.isInvalid()) {
2524 Value = nullptr;
2525 isInvalid = true;
2526 }
2527
2528 EnumConstantDecl *EnumConst
2529 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
2530 EC->getLocation(), EC->getIdentifier(),
2531 Value.get());
2532
2533 if (isInvalid) {
2534 if (EnumConst)
2535 EnumConst->setInvalidDecl();
2536 Enum->setInvalidDecl();
2537 }
2538
2539 if (EnumConst) {
2540 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
2541
2542 EnumConst->setAccess(Enum->getAccess());
2543 Enum->addDecl(EnumConst);
2544 Enumerators.push_back(EnumConst);
2545 LastEnumConst = EnumConst;
2546
2547 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
2548 !Enum->isScoped()) {
2549 // If the enumeration is within a function or method, record the enum
2550 // constant as a local.
2551 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
2552 }
2553 }
2554 }
2555
2556 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
2557 Enumerators, nullptr, ParsedAttributesView());
2558}
2559
2560Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
2561 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
2562}
2563
2564Decl *
2565TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2566 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
2567}
2568
2569Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2570 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2571
2572 // Create a local instantiation scope for this class template, which
2573 // will contain the instantiations of the template parameters.
2574 LocalInstantiationScope Scope(SemaRef);
2575 TemplateParameterList *TempParams = D->getTemplateParameters();
2576 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2577 if (!InstParams)
2578 return nullptr;
2579
2580 CXXRecordDecl *Pattern = D->getTemplatedDecl();
2581
2582 // Instantiate the qualifier. We have to do this first in case
2583 // we're a friend declaration, because if we are then we need to put
2584 // the new declaration in the appropriate context.
2585 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
2586 if (QualifierLoc) {
2587 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2588 TemplateArgs);
2589 if (!QualifierLoc)
2590 return nullptr;
2591 }
2592
2593 CXXRecordDecl *PrevDecl = nullptr;
2594 ClassTemplateDecl *PrevClassTemplate = nullptr;
2595
2596 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
2597 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
2598 if (!Found.empty()) {
2599 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
2600 if (PrevClassTemplate)
2601 PrevDecl = PrevClassTemplate->getTemplatedDecl();
2602 }
2603 }
2604
2605 // If this isn't a friend, then it's a member template, in which
2606 // case we just want to build the instantiation in the
2607 // specialization. If it is a friend, we want to build it in
2608 // the appropriate context.
2609 DeclContext *DC = Owner;
2610 if (isFriend) {
2611 if (QualifierLoc) {
2612 CXXScopeSpec SS;
2613 SS.Adopt(QualifierLoc);
2614 DC = SemaRef.computeDeclContext(SS);
2615 if (!DC) return nullptr;
2616 } else {
2617 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
2618 Pattern->getDeclContext(),
2619 TemplateArgs);
2620 }
2621
2622 // Look for a previous declaration of the template in the owning
2623 // context.
2624 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
2626 SemaRef.forRedeclarationInCurContext());
2627 SemaRef.LookupQualifiedName(R, DC);
2628
2629 if (R.isSingleResult()) {
2630 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
2631 if (PrevClassTemplate)
2632 PrevDecl = PrevClassTemplate->getTemplatedDecl();
2633 }
2634
2635 if (!PrevClassTemplate && QualifierLoc) {
2636 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
2637 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
2638 << QualifierLoc.getSourceRange();
2639 return nullptr;
2640 }
2641 }
2642
2643 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
2644 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
2645 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl);
2646 if (QualifierLoc)
2647 RecordInst->setQualifierInfo(QualifierLoc);
2648
2649 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
2650 StartingScope);
2651
2652 ClassTemplateDecl *Inst
2653 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
2654 D->getIdentifier(), InstParams, RecordInst);
2655 RecordInst->setDescribedClassTemplate(Inst);
2656
2657 if (isFriend) {
2658 assert(!Owner->isDependentContext());
2659 Inst->setLexicalDeclContext(Owner);
2660 RecordInst->setLexicalDeclContext(Owner);
2661 Inst->setObjectOfFriendDecl();
2662
2663 if (PrevClassTemplate) {
2664 Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
2665 const ClassTemplateDecl *MostRecentPrevCT =
2666 PrevClassTemplate->getMostRecentDecl();
2667 TemplateParameterList *PrevParams =
2668 MostRecentPrevCT->getTemplateParameters();
2669
2670 // Make sure the parameter lists match.
2671 if (!SemaRef.TemplateParameterListsAreEqual(
2672 RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
2673 PrevParams, true, Sema::TPL_TemplateMatch))
2674 return nullptr;
2675
2676 // Do some additional validation, then merge default arguments
2677 // from the existing declarations.
2678 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
2680 return nullptr;
2681
2682 Inst->setAccess(PrevClassTemplate->getAccess());
2683 } else {
2684 Inst->setAccess(D->getAccess());
2685 }
2686
2687 Inst->setObjectOfFriendDecl();
2688 // TODO: do we want to track the instantiation progeny of this
2689 // friend target decl?
2690 } else {
2691 Inst->setAccess(D->getAccess());
2692 if (!PrevClassTemplate)
2694 }
2695
2696 Inst->setPreviousDecl(PrevClassTemplate);
2697
2698 // Finish handling of friends.
2699 if (isFriend) {
2700 DC->makeDeclVisibleInContext(Inst);
2701 return Inst;
2702 }
2703
2704 if (D->isOutOfLine()) {
2707 }
2708
2709 Owner->addDecl(Inst);
2710
2711 if (!PrevClassTemplate) {
2712 // Queue up any out-of-line partial specializations of this member
2713 // class template; the client will force their instantiation once
2714 // the enclosing class has been instantiated.
2715 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2716 D->getPartialSpecializations(PartialSpecs);
2717 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
2718 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
2719 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
2720 }
2721
2722 return Inst;
2723}
2724
2725Decl *
2726TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
2728 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2729
2730 // Lookup the already-instantiated declaration in the instantiation
2731 // of the class template and return that.
2733 = Owner->lookup(ClassTemplate->getDeclName());
2734 if (Found.empty())
2735 return nullptr;
2736
2737 ClassTemplateDecl *InstClassTemplate
2738 = dyn_cast<ClassTemplateDecl>(Found.front());
2739 if (!InstClassTemplate)
2740 return nullptr;
2741
2742 if (ClassTemplatePartialSpecializationDecl *Result
2743 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
2744 return Result;
2745
2746 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
2747}
2748
2749Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
2750 assert(D->getTemplatedDecl()->isStaticDataMember() &&
2751 "Only static data member templates are allowed.");
2752
2753 // Create a local instantiation scope for this variable template, which
2754 // will contain the instantiations of the template parameters.
2755 LocalInstantiationScope Scope(SemaRef);
2756 TemplateParameterList *TempParams = D->getTemplateParameters();
2757 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2758 if (!InstParams)
2759 return nullptr;
2760
2761 VarDecl *Pattern = D->getTemplatedDecl();
2762 VarTemplateDecl *PrevVarTemplate = nullptr;
2763
2764 if (getPreviousDeclForInstantiation(Pattern)) {
2765 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
2766 if (!Found.empty())
2767 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
2768 }
2769
2770 VarDecl *VarInst =
2771 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
2772 /*InstantiatingVarTemplate=*/true));
2773 if (!VarInst) return nullptr;
2774
2775 DeclContext *DC = Owner;
2776
2777 VarTemplateDecl *Inst = VarTemplateDecl::Create(
2778 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
2779 VarInst);
2780 VarInst->setDescribedVarTemplate(Inst);
2781 Inst->setPreviousDecl(PrevVarTemplate);
2782
2783 Inst->setAccess(D->getAccess());
2784 if (!PrevVarTemplate)
2786
2787 if (D->isOutOfLine()) {
2790 }
2791
2792 Owner->addDecl(Inst);
2793 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Inst, LateAttrs,
2794 StartingScope);
2795
2796 if (!PrevVarTemplate) {
2797 // Queue up any out-of-line partial specializations of this member
2798 // variable template; the client will force their instantiation once
2799 // the enclosing class has been instantiated.
2800 SmallVector<VarTemplatePartialSpecializationDecl *, 1> PartialSpecs;
2801 D->getPartialSpecializations(PartialSpecs);
2802 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
2803 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
2804 OutOfLineVarPartialSpecs.push_back(
2805 std::make_pair(Inst, PartialSpecs[I]));
2806 }
2807
2808 return Inst;
2809}
2810
2811Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
2813 assert(D->isStaticDataMember() &&
2814 "Only static data member templates are allowed.");
2815
2816 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2817
2818 // Lookup the already-instantiated declaration and return that.
2819 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
2820 assert(!Found.empty() && "Instantiation found nothing?");
2821
2822 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
2823 assert(InstVarTemplate && "Instantiation did not find a variable template?");
2824
2825 if (VarTemplatePartialSpecializationDecl *Result =
2826 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
2827 return Result;
2828
2829 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
2830}
2831
2832Decl *
2833TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2834 // Create a local instantiation scope for this function template, which
2835 // will contain the instantiations of the template parameters and then get
2836 // merged with the local instantiation scope for the function template
2837 // itself.
2838 LocalInstantiationScope Scope(SemaRef);
2839 llvm::SaveAndRestore RAII(EvaluateConstraints, false);
2840
2841 TemplateParameterList *TempParams = D->getTemplateParameters();
2842 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2843 if (!InstParams)
2844 return nullptr;
2845
2846 FunctionDecl *Instantiated = nullptr;
2847 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
2848 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
2849 InstParams));
2850 else
2851 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
2852 D->getTemplatedDecl(),
2853 InstParams));
2854
2855 if (!Instantiated)
2856 return nullptr;
2857
2858 // Link the instantiated function template declaration to the function
2859 // template from which it was instantiated.
2860 FunctionTemplateDecl *InstTemplate
2861 = Instantiated->getDescribedFunctionTemplate();
2862 InstTemplate->setAccess(D->getAccess());
2863 assert(InstTemplate &&
2864 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
2865
2866 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
2867
2868 // Link the instantiation back to the pattern *unless* this is a
2869 // non-definition friend declaration.
2870 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
2871 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
2872 InstTemplate->setInstantiatedFromMemberTemplate(D);
2873
2874 // Make declarations visible in the appropriate context.
2875 if (!isFriend) {
2876 Owner->addDecl(InstTemplate);
2877 } else if (InstTemplate->getDeclContext()->isRecord() &&
2879 isa<CXXMethodDecl>(InstTemplate->getTemplatedDecl())) {
2880 SemaRef.CheckFriendAccess(InstTemplate);
2881 }
2882
2883 return InstTemplate;
2884}
2885
2886Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
2887 CXXRecordDecl *PrevDecl = nullptr;
2888 if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2889 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
2890 PatternPrev,
2891 TemplateArgs);
2892 if (!Prev) return nullptr;
2893 PrevDecl = cast<CXXRecordDecl>(Prev);
2894 }
2895
2896 CXXRecordDecl *Record = nullptr;
2897 bool IsInjectedClassName = D->isInjectedClassName();
2898 if (D->isLambda())
2900 SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
2903 else
2904 Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
2905 D->getBeginLoc(), D->getLocation(),
2906 D->getIdentifier(), PrevDecl);
2907
2908 Record->setImplicit(D->isImplicit());
2909
2910 // Substitute the nested name specifier, if any.
2911 if (SubstQualifier(D, Record))
2912 return nullptr;
2913
2914 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
2915 StartingScope);
2916
2917 // FIXME: Check against AS_none is an ugly hack to work around the issue that
2918 // the tag decls introduced by friend class declarations don't have an access
2919 // specifier. Remove once this area of the code gets sorted out.
2920 if (D->getAccess() != AS_none)
2921 Record->setAccess(D->getAccess());
2922 if (!IsInjectedClassName)
2923 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2924
2925 // If the original function was part of a friend declaration,
2926 // inherit its namespace state.
2927 if (D->getFriendObjectKind())
2928 Record->setObjectOfFriendDecl();
2929
2930 // Make sure that anonymous structs and unions are recorded.
2931 if (D->isAnonymousStructOrUnion())
2932 Record->setAnonymousStructOrUnion(true);
2933
2934 if (D->isLocalClass())
2935 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
2936
2937 // Forward the mangling number from the template to the instantiated decl.
2938 SemaRef.Context.setManglingNumber(Record,
2939 SemaRef.Context.getManglingNumber(D));
2940
2941 // See if the old tag was defined along with a declarator.
2942 // If it did, mark the new tag as being associated with that declarator.
2943 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
2944 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
2945
2946 // See if the old tag was defined along with a typedef.
2947 // If it did, mark the new tag as being associated with that typedef.
2948 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
2949 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
2950
2951 Owner->addDecl(Record);
2952
2953 // DR1484 clarifies that the members of a local class are instantiated as part
2954 // of the instantiation of their enclosing entity.
2955 if (D->isCompleteDefinition() && D->isLocalClass()) {
2956 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef,
2957 /*AtEndOfTU=*/false);
2958
2959 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
2961 /*Complain=*/true);
2962
2963 // For nested local classes, we will instantiate the members when we
2964 // reach the end of the outermost (non-nested) local class.
2965 if (!D->isCXXClassMember())
2966 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
2968
2969 // This class may have local implicit instantiations that need to be
2970 // performed within this scope.
2971 LocalInstantiations.perform();
2972 }
2973
2974 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
2975
2976 if (IsInjectedClassName)
2977 assert(Record->isInjectedClassName() && "Broken injected-class-name");
2978
2979 return Record;
2980}
2981
2982/// Adjust the given function type for an instantiation of the
2983/// given declaration, to cope with modifications to the function's type that
2984/// aren't reflected in the type-source information.
2985///
2986/// \param D The declaration we're instantiating.
2987/// \param TInfo The already-instantiated type.
2989 FunctionDecl *D,
2990 TypeSourceInfo *TInfo) {
2991 const FunctionProtoType *OrigFunc
2992 = D->getType()->castAs<FunctionProtoType>();
2993 const FunctionProtoType *NewFunc
2994 = TInfo->getType()->castAs<FunctionProtoType>();
2995 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2996 return TInfo->getType();
2997
2998 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2999 NewEPI.ExtInfo = OrigFunc->getExtInfo();
3000 return Context.getFunctionType(NewFunc->getReturnType(),
3001 NewFunc->getParamTypes(), NewEPI);
3002}
3003
3004/// Normal class members are of more specific types and therefore
3005/// don't make it here. This function serves three purposes:
3006/// 1) instantiating function templates
3007/// 2) substituting friend and local function declarations
3008/// 3) substituting deduction guide declarations for nested class templates
3010 FunctionDecl *D, TemplateParameterList *TemplateParams,
3011 RewriteKind FunctionRewriteKind) {
3012 // Check whether there is already a function template specialization for
3013 // this declaration.
3015 bool isFriend;
3016 if (FunctionTemplate)
3017 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
3018 else
3019 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
3020
3021 // Friend function defined withing class template may stop being function
3022 // definition during AST merges from different modules, in this case decl
3023 // with function body should be used for instantiation.
3024 if (ExternalASTSource *Source = SemaRef.Context.getExternalSource()) {
3025 if (isFriend && Source->wasThisDeclarationADefinition(D)) {
3026 const FunctionDecl *Defn = nullptr;
3027 if (D->hasBody(Defn)) {
3028 D = const_cast<FunctionDecl *>(Defn);
3030 }
3031 }
3032 }
3033
3034 if (FunctionTemplate && !TemplateParams) {
3035 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
3036
3037 llvm::FoldingSetInsertToken InsertToken;
3038 FunctionDecl *SpecFunc =
3039 FunctionTemplate->findSpecialization(Innermost, InsertToken);
3040
3041 // If we already have a function template specialization, return it.
3042 if (SpecFunc)
3043 return SpecFunc;
3044 }
3045
3046 bool MergeWithParentScope = (TemplateParams != nullptr) ||
3047 Owner->isFunctionOrMethod() ||
3048 !(isa<Decl>(Owner) &&
3049 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
3050 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
3051
3052 ExplicitSpecifier InstantiatedExplicitSpecifier;
3053 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
3054 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
3055 TemplateArgs, DGuide->getExplicitSpecifier());
3056 if (InstantiatedExplicitSpecifier.isInvalid())
3057 return nullptr;
3058 }
3059
3061 DeferredParamAttrs ParamAttrs(*this);
3062 TypeSourceInfo *TInfo = SubstFunctionType(D, Params, ParamAttrs);
3063 if (!TInfo)
3064 return nullptr;
3065 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
3066
3067 if (TemplateParams && TemplateParams->size()) {
3068 auto *LastParam =
3069 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
3070 if (LastParam && LastParam->isImplicit() &&
3071 LastParam->hasTypeConstraint()) {
3072 // In abbreviated templates, the type-constraints of invented template
3073 // type parameters are instantiated with the function type, invalidating
3074 // the TemplateParameterList which relied on the template type parameter
3075 // not having a type constraint. Recreate the TemplateParameterList with
3076 // the updated parameter list.
3077 TemplateParams = TemplateParameterList::Create(
3078 SemaRef.Context, TemplateParams->getTemplateLoc(),
3079 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
3080 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
3081 }
3082 }
3083
3084 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
3085 if (QualifierLoc) {
3086 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
3087 TemplateArgs);
3088 if (!QualifierLoc)
3089 return nullptr;
3090 }
3091 if (isFriend &&
3092 (FunctionTemplate || !D->getTemplateParameterLists().empty()) &&
3093 D->getQualifier().isDependent() &&
3094 SemaRef.CheckDependentFriend(D->getLocation(), QualifierLoc,
3095 /*TPLs=*/{}, /*IsInstantiation=*/true))
3096 return nullptr;
3097
3098 AssociatedConstraint TrailingRequiresClause = D->getTrailingRequiresClause();
3099
3100 // If we're instantiating a local function declaration, put the result
3101 // in the enclosing namespace; otherwise we need to find the instantiated
3102 // context.
3103 DeclContext *DC;
3104 if (D->isLocalExternDecl()) {
3105 DC = Owner;
3106 SemaRef.adjustContextForLocalExternDecl(DC);
3107 } else if (isFriend && QualifierLoc) {
3108 CXXScopeSpec SS;
3109 SS.Adopt(QualifierLoc);
3110 DC = SemaRef.computeDeclContext(SS);
3111 if (!DC) return nullptr;
3112 } else {
3113 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
3114 TemplateArgs);
3115 }
3116
3117 DeclarationNameInfo NameInfo
3118 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3119
3120 if (FunctionRewriteKind != RewriteKind::None)
3121 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
3122
3124 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
3126 SemaRef.Context, DC, D->getInnerLocStart(),
3127 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
3128 D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
3129 DGuide->getDeductionCandidateKind(), TrailingRequiresClause,
3130 DGuide->getSourceDeductionGuide(),
3131 DGuide->getSourceDeductionGuideKind());
3132 Function->setAccess(D->getAccess());
3133 } else {
3135 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
3138 TrailingRequiresClause);
3139 Function->setFriendConstraintRefersToEnclosingTemplate(
3141 Function->setRangeEnd(D->getSourceRange().getEnd());
3142 }
3143
3144 if (D->isInlined())
3145 Function->setImplicitlyInline();
3146
3147 if (QualifierLoc)
3148 Function->setQualifierInfo(QualifierLoc);
3149
3150 if (D->isLocalExternDecl())
3151 Function->setLocalExternDecl();
3152
3153 DeclContext *LexicalDC = Owner;
3154 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
3155 assert(D->getDeclContext()->isFileContext());
3156 LexicalDC = D->getDeclContext();
3157 }
3158 else if (D->isLocalExternDecl()) {
3159 LexicalDC = SemaRef.CurContext;
3160 }
3161
3162 Function->setIsDestroyingOperatorDelete(D->isDestroyingOperatorDelete());
3163 Function->setIsTypeAwareOperatorNewOrDelete(
3165 Function->setLexicalDeclContext(LexicalDC);
3166
3167 // Attach the parameters
3168 for (unsigned P = 0; P < Params.size(); ++P)
3169 if (Params[P])
3170 Params[P]->setOwningFunction(Function);
3171 Function->setParams(Params);
3172 ParamAttrs.instantiate();
3173
3174 if (TrailingRequiresClause)
3175 Function->setTrailingRequiresClause(TrailingRequiresClause);
3176
3177 if (TemplateParams) {
3178 // Our resulting instantiation is actually a function template, since we
3179 // are substituting only the outer template parameters. For example, given
3180 //
3181 // template<typename T>
3182 // struct X {
3183 // template<typename U> friend void f(T, U);
3184 // };
3185 //
3186 // X<int> x;
3187 //
3188 // We are instantiating the friend function template "f" within X<int>,
3189 // which means substituting int for T, but leaving "f" as a friend function
3190 // template.
3191 // Build the function template itself.
3192 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
3193 Function->getLocation(),
3194 Function->getDeclName(),
3195 TemplateParams, Function);
3196 Function->setDescribedFunctionTemplate(FunctionTemplate);
3197
3198 FunctionTemplate->setLexicalDeclContext(LexicalDC);
3199
3200 if (isFriend && D->isThisDeclarationADefinition()) {
3201 FunctionTemplate->setInstantiatedFromMemberTemplate(
3203 }
3204 } else if (FunctionTemplate &&
3205 SemaRef.CodeSynthesisContexts.back().Kind !=
3207 // Record this function template specialization.
3208 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
3209 Function->setFunctionTemplateSpecialization(
3211 TemplateArgumentList::CreateCopy(SemaRef.Context, Innermost),
3212 /*InsertToken=*/{});
3213 } else if (isFriend && D->isThisDeclarationADefinition()) {
3214 // Do not connect the friend to the template unless it's actually a
3215 // definition. We don't want non-template functions to be marked as being
3216 // template instantiations.
3217 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
3218 } else if (!isFriend) {
3219 // If this is not a function template, and this is not a friend (that is,
3220 // this is a locally declared function), save the instantiation
3221 // relationship for the purposes of constraint instantiation.
3222 Function->setInstantiatedFromDecl(D);
3223 }
3224
3225 if (isFriend) {
3226 Function->setObjectOfFriendDecl();
3227 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
3228 FT->setObjectOfFriendDecl();
3229 }
3230
3232 Function->setInvalidDecl();
3233
3234 bool IsExplicitSpecialization = false;
3235
3237 SemaRef, Function->getDeclName(), SourceLocation(),
3241 : SemaRef.forRedeclarationInCurContext());
3242
3245 assert(isFriend && "dependent specialization info on "
3246 "non-member non-friend function?");
3247
3248 // Instantiate the explicit template arguments.
3249 TemplateArgumentListInfo ExplicitArgs;
3250 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
3251 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
3252 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
3253 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
3254 ExplicitArgs))
3255 return nullptr;
3256 }
3257
3258 // Map the candidates for the primary template to their instantiations.
3259 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
3260 if (NamedDecl *ND =
3261 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
3262 Previous.addDecl(ND);
3263 else
3264 return nullptr;
3265 }
3266
3267 if (SemaRef.CheckFunctionTemplateSpecialization(
3268 Function,
3269 DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
3270 Previous))
3271 Function->setInvalidDecl();
3272
3273 IsExplicitSpecialization = true;
3274 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
3276 // The name of this function was written as a template-id.
3277 SemaRef.LookupQualifiedName(Previous, DC);
3278
3279 // Instantiate the explicit template arguments.
3280 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
3281 ArgsWritten->getRAngleLoc());
3282 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
3283 ExplicitArgs))
3284 return nullptr;
3285
3286 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
3287 &ExplicitArgs,
3288 Previous))
3289 Function->setInvalidDecl();
3290
3291 IsExplicitSpecialization = true;
3292 } else if (TemplateParams || !FunctionTemplate) {
3293 // Look only into the namespace where the friend would be declared to
3294 // find a previous declaration. This is the innermost enclosing namespace,
3295 // as described in ActOnFriendFunctionDecl.
3296 SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
3297
3298 // In C++, the previous declaration we find might be a tag type
3299 // (class or enum). In this case, the new declaration will hide the
3300 // tag type. Note that this does not apply if we're declaring a
3301 // typedef (C++ [dcl.typedef]p4).
3302 if (Previous.isSingleTagDecl())
3303 Previous.clear();
3304
3305 // Filter out previous declarations that don't match the scope. The only
3306 // effect this has is to remove declarations found in inline namespaces
3307 // for friend declarations with unqualified names.
3308 if (isFriend && !QualifierLoc) {
3309 SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
3310 /*ConsiderLinkage=*/ true,
3311 QualifierLoc.hasQualifier());
3312 }
3313 }
3314
3315 // Per [temp.inst], default arguments in function declarations at local scope
3316 // are instantiated along with the enclosing declaration. For example:
3317 //
3318 // template<typename T>
3319 // void ft() {
3320 // void f(int = []{ return T::value; }());
3321 // }
3322 // template void ft<int>(); // error: type 'int' cannot be used prior
3323 // to '::' because it has no members
3324 //
3325 // The error is issued during instantiation of ft<int>() because substitution
3326 // into the default argument fails; the default argument is instantiated even
3327 // though it is never used.
3328 if (Function->isLocalExternDecl()) {
3329 for (ParmVarDecl *PVD : Function->parameters()) {
3330 if (!PVD->hasDefaultArg())
3331 continue;
3332 if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
3333 // If substitution fails, the default argument is set to a
3334 // RecoveryExpr that wraps the uninstantiated default argument so
3335 // that downstream diagnostics are omitted.
3336 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
3337 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
3338 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
3339 { UninstExpr }, UninstExpr->getType());
3340 if (ErrorResult.isUsable())
3341 PVD->setDefaultArg(ErrorResult.get());
3342 }
3343 }
3344 }
3345
3346 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
3347 IsExplicitSpecialization,
3348 Function->isThisDeclarationADefinition());
3349
3350 // Check the template parameter list against the previous declaration. The
3351 // goal here is to pick up default arguments added since the friend was
3352 // declared; we know the template parameter lists match, since otherwise
3353 // we would not have picked this template as the previous declaration.
3354 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
3355 SemaRef.CheckTemplateParameterList(
3356 TemplateParams,
3357 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
3358 Function->isThisDeclarationADefinition()
3361 }
3362
3363 // If we're introducing a friend definition after the first use, trigger
3364 // instantiation.
3365 // FIXME: If this is a friend function template definition, we should check
3366 // to see if any specializations have been used.
3367 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
3368 if (MemberSpecializationInfo *MSInfo =
3369 Function->getMemberSpecializationInfo()) {
3370 if (MSInfo->getPointOfInstantiation().isInvalid()) {
3371 SourceLocation Loc = D->getLocation(); // FIXME
3372 MSInfo->setPointOfInstantiation(Loc);
3373 SemaRef.PendingLocalImplicitInstantiations.emplace_back(Function, Loc);
3374 }
3375 }
3376 }
3377
3378 if (D->isExplicitlyDefaulted()) {
3380 return nullptr;
3381 }
3382 if (D->isDeleted())
3383 SemaRef.SetDeclDeleted(Function, D->getLocation(), D->getDeletedMessage());
3384
3385 NamedDecl *PrincipalDecl =
3386 (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
3387
3388 // If this declaration lives in a different context from its lexical context,
3389 // add it to the corresponding lookup table.
3390 if (isFriend ||
3391 (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
3392 DC->makeDeclVisibleInContext(PrincipalDecl);
3393
3394 if (Function->isOverloadedOperator() && !DC->isRecord() &&
3396 PrincipalDecl->setNonMemberOperator();
3397
3398 return Function;
3399}
3400
3402 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
3403 RewriteKind FunctionRewriteKind) {
3405 if (FunctionTemplate && !TemplateParams) {
3406 // We are creating a function template specialization from a function
3407 // template. Check whether there is already a function template
3408 // specialization for this particular set of template arguments.
3409 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
3410
3411 llvm::FoldingSetInsertToken InsertToken;
3412 FunctionDecl *SpecFunc =
3413 FunctionTemplate->findSpecialization(Innermost, InsertToken);
3414
3415 // If we already have a function template specialization, return it.
3416 if (SpecFunc)
3417 return SpecFunc;
3418 }
3419
3420 bool isFriend;
3421 if (FunctionTemplate)
3422 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
3423 else
3424 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
3425
3426 bool MergeWithParentScope = (TemplateParams != nullptr) ||
3427 !(isa<Decl>(Owner) &&
3428 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
3429 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
3430
3432 SemaRef, D, TemplateArgs, Scope);
3433
3434 // Instantiate enclosing template arguments for friends.
3437 if (isFriend && !TPLs.empty()) {
3438 TempParamLists.resize(TPLs.size());
3439 for (unsigned I = 0; I != TPLs.size(); ++I) {
3440 TemplateParameterList *InstParams = SubstTemplateParams(TPLs[I]);
3441 if (!InstParams)
3442 return nullptr;
3443 TempParamLists[I] = InstParams;
3444 }
3445 }
3446
3447 auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(D);
3448 // deduction guides need this
3449 const bool CouldInstantiate =
3450 InstantiatedExplicitSpecifier.getExpr() == nullptr ||
3451 !InstantiatedExplicitSpecifier.getExpr()->isValueDependent();
3452
3453 // Delay the instantiation of the explicit-specifier until after the
3454 // constraints are checked during template argument deduction.
3455 if (CouldInstantiate ||
3456 SemaRef.CodeSynthesisContexts.back().Kind !=
3458 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
3459 TemplateArgs, InstantiatedExplicitSpecifier);
3460
3461 if (InstantiatedExplicitSpecifier.isInvalid())
3462 return nullptr;
3463 } else {
3464 InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved);
3465 }
3466
3467 // Implicit destructors/constructors created for local classes in
3468 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
3469 // Unfortunately there isn't enough context in those functions to
3470 // conditionally populate the TSI without breaking non-template related use
3471 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
3472 // a proper transformation.
3473 if (isLambdaMethod(D) && !D->getTypeSourceInfo() &&
3475 TypeSourceInfo *TSI =
3476 SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
3477 D->setTypeSourceInfo(TSI);
3478 }
3479
3481 DeferredParamAttrs ParamAttrs(*this);
3482 TypeSourceInfo *TInfo = SubstFunctionType(D, Params, ParamAttrs);
3483 if (!TInfo)
3484 return nullptr;
3485 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
3486
3487 if (TemplateParams && TemplateParams->size()) {
3488 auto *LastParam =
3489 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
3490 if (LastParam && LastParam->isImplicit() &&
3491 LastParam->hasTypeConstraint()) {
3492 // In abbreviated templates, the type-constraints of invented template
3493 // type parameters are instantiated with the function type, invalidating
3494 // the TemplateParameterList which relied on the template type parameter
3495 // not having a type constraint. Recreate the TemplateParameterList with
3496 // the updated parameter list.
3497 TemplateParams = TemplateParameterList::Create(
3498 SemaRef.Context, TemplateParams->getTemplateLoc(),
3499 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
3500 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
3501 }
3502 }
3503
3504 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
3505 if (QualifierLoc) {
3506 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
3507 TemplateArgs);
3508 if (!QualifierLoc)
3509 return nullptr;
3510 }
3511 if (isFriend &&
3512 (FunctionTemplate || !D->getTemplateParameterLists().empty()) &&
3513 D->getQualifier().isDependent() &&
3514 SemaRef.CheckDependentFriend(D->getLocation(), QualifierLoc,
3515 /*TPLs=*/{}, /*IsInstantiation=*/true))
3516 return nullptr;
3517
3518 DeclContext *DC = Owner;
3519 if (isFriend) {
3520 if (QualifierLoc && !QualifierLoc.getNestedNameSpecifier().isDependent()) {
3521 CXXScopeSpec SS;
3522 SS.Adopt(QualifierLoc);
3523 DC = SemaRef.computeDeclContext(SS);
3524
3525 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
3526 return nullptr;
3527 } else if (!QualifierLoc) {
3528 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
3529 D->getDeclContext(),
3530 TemplateArgs);
3531 }
3532 if (!DC) return nullptr;
3533 }
3534
3536 AssociatedConstraint TrailingRequiresClause = D->getTrailingRequiresClause();
3537
3538 DeclarationNameInfo NameInfo
3539 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3540
3541 // Check if the substitution of template args failed
3542 // leading to an empty DeclarationNameInfo.
3543 if (!NameInfo.getName())
3544 return nullptr;
3545
3546 if (FunctionRewriteKind != RewriteKind::None)
3547 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
3548
3549 // Build the instantiated method declaration.
3550 CXXMethodDecl *Method = nullptr;
3551
3552 SourceLocation StartLoc = D->getInnerLocStart();
3553 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
3555 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
3556 InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
3557 Constructor->isInlineSpecified(), false,
3558 Constructor->getConstexprKind(), InheritedConstructor(),
3559 TrailingRequiresClause);
3560 Method->setRangeEnd(Constructor->getEndLoc());
3561 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
3563 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
3564 Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
3565 Destructor->getConstexprKind(), TrailingRequiresClause);
3566 Method->setIneligibleOrNotSelected(true);
3567 Method->setRangeEnd(Destructor->getEndLoc());
3568 Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
3569
3570 SemaRef.Context.getCanonicalTagType(Record)));
3571 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
3573 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
3574 Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
3575 InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
3576 Conversion->getEndLoc(), TrailingRequiresClause);
3577 } else {
3578 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
3580 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
3582 D->getEndLoc(), TrailingRequiresClause);
3583 }
3584
3585 if (D->isInlined())
3586 Method->setImplicitlyInline();
3587
3588 if (QualifierLoc)
3589 Method->setQualifierInfo(QualifierLoc);
3590
3591 if (TemplateParams) {
3592 // Our resulting instantiation is actually a function template, since we
3593 // are substituting only the outer template parameters. For example, given
3594 //
3595 // template<typename T>
3596 // struct X {
3597 // template<typename U> void f(T, U);
3598 // };
3599 //
3600 // X<int> x;
3601 //
3602 // We are instantiating the member template "f" within X<int>, which means
3603 // substituting int for T, but leaving "f" as a member function template.
3604 // Build the function template itself.
3606 Method->getLocation(),
3607 Method->getDeclName(),
3608 TemplateParams, Method);
3609 if (isFriend) {
3610 FunctionTemplate->setLexicalDeclContext(Owner);
3611 FunctionTemplate->setObjectOfFriendDecl();
3612 } else if (D->isOutOfLine())
3613 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
3614 Method->setDescribedFunctionTemplate(FunctionTemplate);
3615 } else if (FunctionTemplate) {
3616 // Record this function template specialization.
3617 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
3618 Method->setFunctionTemplateSpecialization(
3620 TemplateArgumentList::CreateCopy(SemaRef.Context, Innermost),
3621 /*InsertToken=*/{});
3622 } else if (!isFriend) {
3623 // Record that this is an instantiation of a member function.
3624 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
3625 }
3626
3627 // If we are instantiating a member function defined
3628 // out-of-line, the instantiation will have the same lexical
3629 // context (which will be a namespace scope) as the template.
3630 if (isFriend) {
3631 if (!TempParamLists.empty())
3632 Method->setTemplateParameterListsInfo(SemaRef.Context, TempParamLists);
3633
3634 Method->setLexicalDeclContext(Owner);
3635 Method->setObjectOfFriendDecl();
3636 } else if (D->isOutOfLine())
3637 Method->setLexicalDeclContext(D->getLexicalDeclContext());
3638
3639 // Attach the parameters
3640 for (unsigned P = 0; P < Params.size(); ++P)
3641 Params[P]->setOwningFunction(Method);
3642 Method->setParams(Params);
3643 ParamAttrs.instantiate();
3644
3646 Method->setInvalidDecl();
3647
3650
3651 bool IsExplicitSpecialization = false;
3652
3653 // If the name of this function was written as a template-id, instantiate
3654 // the explicit template arguments.
3657 // Instantiate the explicit template arguments.
3658 TemplateArgumentListInfo ExplicitArgs;
3659 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
3660 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
3661 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
3662 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
3663 ExplicitArgs))
3664 return nullptr;
3665 }
3666
3667 // Map the candidates for the primary template to their instantiations.
3668 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
3669 if (NamedDecl *ND =
3670 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
3671 Previous.addDecl(ND);
3672 else
3673 return nullptr;
3674 }
3675
3676 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier().isDependent()) {
3677 if (SemaRef.CheckDependentFunctionTemplateSpecialization(
3678 Method,
3679 DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
3680 Previous))
3681 Method->setInvalidDecl();
3682 } else {
3683 if (Previous.empty())
3684 SemaRef.LookupQualifiedName(Previous, DC);
3685 if (SemaRef.CheckFunctionTemplateSpecialization(
3686 Method,
3687 DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
3688 Previous))
3689 Method->setInvalidDecl();
3690 IsExplicitSpecialization = true;
3691 }
3692 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
3694 SemaRef.LookupQualifiedName(Previous, DC);
3695
3696 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
3697 ArgsWritten->getRAngleLoc());
3698
3699 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
3700 ExplicitArgs))
3701 return nullptr;
3702
3703 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
3704 &ExplicitArgs,
3705 Previous))
3706 Method->setInvalidDecl();
3707
3708 IsExplicitSpecialization = true;
3709 } else if (!FunctionTemplate || TemplateParams || isFriend) {
3710 SemaRef.LookupQualifiedName(Previous, Record);
3711
3712 // In C++, the previous declaration we find might be a tag type
3713 // (class or enum). In this case, the new declaration will hide the
3714 // tag type. Note that this does not apply if we're declaring a
3715 // typedef (C++ [dcl.typedef]p4).
3716 if (Previous.isSingleTagDecl())
3717 Previous.clear();
3718 }
3719
3720 // Per [temp.inst], default arguments in member functions of local classes
3721 // are instantiated along with the member function declaration. For example:
3722 //
3723 // template<typename T>
3724 // void ft() {
3725 // struct lc {
3726 // int operator()(int p = []{ return T::value; }());
3727 // };
3728 // }
3729 // template void ft<int>(); // error: type 'int' cannot be used prior
3730 // to '::'because it has no members
3731 //
3732 // The error is issued during instantiation of ft<int>()::lc::operator()
3733 // because substitution into the default argument fails; the default argument
3734 // is instantiated even though it is never used.
3736 for (unsigned P = 0; P < Params.size(); ++P) {
3737 if (!Params[P]->hasDefaultArg())
3738 continue;
3739 if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
3740 // If substitution fails, the default argument is set to a
3741 // RecoveryExpr that wraps the uninstantiated default argument so
3742 // that downstream diagnostics are omitted.
3743 Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
3744 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
3745 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
3746 { UninstExpr }, UninstExpr->getType());
3747 if (ErrorResult.isUsable())
3748 Params[P]->setDefaultArg(ErrorResult.get());
3749 }
3750 }
3751 }
3752
3753 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
3754 IsExplicitSpecialization,
3755 Method->isThisDeclarationADefinition());
3756
3757 if (D->isPureVirtual())
3758 SemaRef.CheckPureMethod(Method, SourceRange());
3759
3760 // Propagate access. For a non-friend declaration, the access is
3761 // whatever we're propagating from. For a friend, it should be the
3762 // previous declaration we just found.
3763 if (isFriend && Method->getPreviousDecl())
3764 Method->setAccess(Method->getPreviousDecl()->getAccess());
3765 else
3766 Method->setAccess(D->getAccess());
3767 if (FunctionTemplate)
3768 FunctionTemplate->setAccess(Method->getAccess());
3769
3770 SemaRef.CheckOverrideControl(Method);
3771
3772 // If a function is defined as defaulted or deleted, mark it as such now.
3773 if (D->isExplicitlyDefaulted()) {
3775 return nullptr;
3776 }
3777 if (D->isDeletedAsWritten())
3778 SemaRef.SetDeclDeleted(Method, Method->getLocation(),
3779 D->getDeletedMessage());
3780
3781 // If this is an explicit specialization, mark the implicitly-instantiated
3782 // template specialization as being an explicit specialization too.
3783 // FIXME: Is this necessary?
3784 if (IsExplicitSpecialization && !isFriend)
3785 SemaRef.CompleteMemberSpecialization(Method, Previous);
3786
3787 // If the method is a special member function, we need to mark it as
3788 // ineligible so that Owner->addDecl() won't mark the class as non trivial.
3789 // At the end of the class instantiation, we calculate eligibility again and
3790 // then we adjust trivility if needed.
3791 // We need this check to happen only after the method parameters are set,
3792 // because being e.g. a copy constructor depends on the instantiated
3793 // arguments.
3794 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
3795 if (Constructor->isDefaultConstructor() ||
3796 Constructor->isCopyOrMoveConstructor())
3797 Method->setIneligibleOrNotSelected(true);
3798 } else if (Method->isCopyAssignmentOperator() ||
3799 Method->isMoveAssignmentOperator()) {
3800 Method->setIneligibleOrNotSelected(true);
3801 }
3802
3803 // If there's a function template, let our caller handle it.
3804 if (FunctionTemplate) {
3805 // do nothing
3806
3807 // Don't hide a (potentially) valid declaration with an invalid one.
3808 } else if (Method->isInvalidDecl() && !Previous.empty()) {
3809 // do nothing
3810
3811 // Otherwise, check access to friends and make them visible.
3812 } else if (isFriend) {
3813 // We only need to re-check access for methods which we didn't
3814 // manage to match during parsing.
3815 if (!D->getPreviousDecl())
3816 SemaRef.CheckFriendAccess(Method);
3817
3818 Record->makeDeclVisibleInContext(Method);
3819
3820 // Otherwise, add the declaration. We don't need to do this for
3821 // class-scope specializations because we'll have matched them with
3822 // the appropriate template.
3823 } else {
3824 Owner->addDecl(Method);
3825 }
3826
3827 // PR17480: Honor the used attribute to instantiate member function
3828 // definitions
3829 if (Method->hasAttr<UsedAttr>()) {
3830 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
3831 SourceLocation Loc;
3832 if (const MemberSpecializationInfo *MSInfo =
3833 A->getMemberSpecializationInfo())
3834 Loc = MSInfo->getPointOfInstantiation();
3835 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
3836 Loc = Spec->getPointOfInstantiation();
3837 SemaRef.MarkFunctionReferenced(Loc, Method);
3838 }
3839 }
3840
3841 return Method;
3842}
3843
3844Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3845 return VisitCXXMethodDecl(D);
3846}
3847
3848Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3849 return VisitCXXMethodDecl(D);
3850}
3851
3852Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
3853 return VisitCXXMethodDecl(D);
3854}
3855
3856Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
3857 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
3858 std::nullopt,
3859 /*ExpectParameterPack=*/false);
3860}
3861
3862Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
3864 assert(D->getTypeForDecl()->isTemplateTypeParmType());
3865
3866 UnsignedOrNone NumExpanded = std::nullopt;
3867
3868 if (const TypeConstraint *TC = D->getTypeConstraint()) {
3869 if (D->isPackExpansion() && !D->getNumExpansionParameters()) {
3870 assert(TC->getTemplateArgsAsWritten() &&
3871 "type parameter can only be an expansion when explicit arguments "
3872 "are specified");
3873 // The template type parameter pack's type is a pack expansion of types.
3874 // Determine whether we need to expand this parameter pack into separate
3875 // types.
3876 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3877 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
3878 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
3879
3880 // Determine whether the set of unexpanded parameter packs can and should
3881 // be expanded.
3882 bool Expand = true;
3883 bool RetainExpansion = false;
3884 if (SemaRef.CheckParameterPacksForExpansion(
3885 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3886 ->getEllipsisLoc(),
3887 SourceRange(TC->getConceptNameLoc(),
3888 TC->hasExplicitTemplateArgs()
3889 ? TC->getTemplateArgsAsWritten()->getRAngleLoc()
3890 : TC->getConceptNameInfo().getEndLoc()),
3891 Unexpanded, TemplateArgs, /*FailOnPackProducingTemplates=*/true,
3892 Expand, RetainExpansion, NumExpanded))
3893 return nullptr;
3894 }
3895 }
3896
3897 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
3898 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
3899 D->getDepth() - (TemplateArgs.retainInnerDepths()
3900 ? 0
3901 : TemplateArgs.getNumSubstitutedLevels()),
3903 D->isParameterPack(), D->hasTypeConstraint(), NumExpanded);
3904
3905 Inst->setAccess(AS_public);
3906 Inst->setImplicit(D->isImplicit());
3907 if (auto *TC = D->getTypeConstraint()) {
3908 if (!D->isImplicit()) {
3909 // Invented template parameter type constraints will be instantiated
3910 // with the corresponding auto-typed parameter as it might reference
3911 // other parameters.
3912 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
3913 EvaluateConstraints))
3914 return nullptr;
3915 }
3916 }
3918 TemplateArgumentLoc Output;
3919 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3920 Output))
3921 Inst->setDefaultArgument(SemaRef.getASTContext(), Output);
3922 }
3923
3924 // Introduce this template parameter's instantiation into the instantiation
3925 // scope.
3926 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3927
3928 return Inst;
3929}
3930
3931Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
3933 // Substitute into the type of the non-type template parameter.
3934 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
3935 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
3936 SmallVector<QualType, 4> ExpandedParameterPackTypes;
3937 bool IsExpandedParameterPack = false;
3938 TypeSourceInfo *TSI;
3939 QualType T;
3940 bool Invalid = false;
3941
3942 if (D->isExpandedParameterPack()) {
3943 // The non-type template parameter pack is an already-expanded pack
3944 // expansion of types. Substitute into each of the expanded types.
3945 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
3946 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
3947 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
3948 TypeSourceInfo *NewTSI =
3949 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
3950 D->getLocation(), D->getDeclName());
3951 if (!NewTSI)
3952 return nullptr;
3953
3954 QualType NewT =
3955 SemaRef.CheckNonTypeTemplateParameterType(NewTSI, D->getLocation());
3956 if (NewT.isNull())
3957 return nullptr;
3958
3959 ExpandedParameterPackTypesAsWritten.push_back(NewTSI);
3960 ExpandedParameterPackTypes.push_back(NewT);
3961 }
3962
3963 IsExpandedParameterPack = true;
3964 TSI = D->getTypeSourceInfo();
3965 T = TSI->getType();
3966 } else if (D->isPackExpansion()) {
3967 // The non-type template parameter pack's type is a pack expansion of types.
3968 // Determine whether we need to expand this parameter pack into separate
3969 // types.
3970 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
3971 TypeLoc Pattern = Expansion.getPatternLoc();
3972 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3973 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
3974
3975 // Determine whether the set of unexpanded parameter packs can and should
3976 // be expanded.
3977 bool Expand = true;
3978 bool RetainExpansion = false;
3979 UnsignedOrNone OrigNumExpansions =
3980 Expansion.getTypePtr()->getNumExpansions();
3981 UnsignedOrNone NumExpansions = OrigNumExpansions;
3982 if (SemaRef.CheckParameterPacksForExpansion(
3983 Expansion.getEllipsisLoc(), Pattern.getSourceRange(), Unexpanded,
3984 TemplateArgs, /*FailOnPackProducingTemplates=*/true, Expand,
3985 RetainExpansion, NumExpansions))
3986 return nullptr;
3987
3988 if (Expand) {
3989 for (unsigned I = 0; I != *NumExpansions; ++I) {
3990 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
3991 TypeSourceInfo *NewTSI = SemaRef.SubstType(
3992 Pattern, TemplateArgs, D->getLocation(), D->getDeclName());
3993 if (!NewTSI)
3994 return nullptr;
3995
3996 QualType NewT =
3997 SemaRef.CheckNonTypeTemplateParameterType(NewTSI, D->getLocation());
3998 if (NewT.isNull())
3999 return nullptr;
4000
4001 ExpandedParameterPackTypesAsWritten.push_back(NewTSI);
4002 ExpandedParameterPackTypes.push_back(NewT);
4003 }
4004
4005 // Note that we have an expanded parameter pack. The "type" of this
4006 // expanded parameter pack is the original expansion type, but callers
4007 // will end up using the expanded parameter pack types for type-checking.
4008 IsExpandedParameterPack = true;
4009 TSI = D->getTypeSourceInfo();
4010 T = TSI->getType();
4011 } else {
4012 // We cannot fully expand the pack expansion now, so substitute into the
4013 // pattern and create a new pack expansion type.
4014 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, std::nullopt);
4015 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
4016 D->getLocation(),
4017 D->getDeclName());
4018 if (!NewPattern)
4019 return nullptr;
4020
4021 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
4022 TSI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
4023 NumExpansions);
4024 if (!TSI)
4025 return nullptr;
4026
4027 T = TSI->getType();
4028 }
4029 } else {
4030 // Simple case: substitution into a parameter that is not a parameter pack.
4031 TSI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
4032 D->getLocation(), D->getDeclName());
4033 if (!TSI)
4034 return nullptr;
4035
4036 // Check that this type is acceptable for a non-type template parameter.
4037 T = SemaRef.CheckNonTypeTemplateParameterType(TSI, D->getLocation());
4038 if (T.isNull()) {
4039 T = SemaRef.Context.IntTy;
4040 Invalid = true;
4041 }
4042 }
4043
4044 NonTypeTemplateParmDecl *Param;
4045 if (IsExpandedParameterPack)
4047 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
4048 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
4049 D->getPosition(), D->getIdentifier(), T, TSI,
4050 ExpandedParameterPackTypes, ExpandedParameterPackTypesAsWritten);
4051 else
4053 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
4054 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
4055 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), TSI);
4056
4057 if (AutoTypeLoc AutoLoc = TSI->getTypeLoc().getContainedAutoTypeLoc())
4058 if (AutoLoc.isConstrained()) {
4059 SourceLocation EllipsisLoc;
4060 if (IsExpandedParameterPack)
4061 EllipsisLoc =
4062 TSI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
4063 else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
4065 EllipsisLoc = Constraint->getEllipsisLoc();
4066 // Note: We attach the uninstantiated constriant here, so that it can be
4067 // instantiated relative to the top level, like all our other
4068 // constraints.
4069 if (SemaRef.AttachTypeConstraint(AutoLoc, /*NewConstrainedParm=*/Param,
4070 /*OrigConstrainedParm=*/D, EllipsisLoc))
4071 Invalid = true;
4072 }
4073
4074 Param->setAccess(AS_public);
4075 Param->setImplicit(D->isImplicit());
4076 if (Invalid)
4077 Param->setInvalidDecl();
4078
4080 EnterExpressionEvaluationContext ConstantEvaluated(
4082 TemplateArgumentLoc Result;
4083 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
4084 Result))
4085 Param->setDefaultArgument(SemaRef.Context, Result);
4086 }
4087
4088 // Introduce this template parameter's instantiation into the instantiation
4089 // scope.
4090 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
4091 return Param;
4092}
4093
4095 Sema &S,
4096 TemplateParameterList *Params,
4098 for (const auto &P : *Params) {
4099 if (P->isTemplateParameterPack())
4100 continue;
4101 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
4102 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
4103 Unexpanded);
4104 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
4105 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
4106 Unexpanded);
4107 }
4108}
4109
4110Decl *
4111TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
4113 // Instantiate the template parameter list of the template template parameter.
4114 TemplateParameterList *TempParams = D->getTemplateParameters();
4115 TemplateParameterList *InstParams;
4116 SmallVector<TemplateParameterList*, 8> ExpandedParams;
4117
4118 bool IsExpandedParameterPack = false;
4119
4120 if (D->isExpandedParameterPack()) {
4121 // The template template parameter pack is an already-expanded pack
4122 // expansion of template parameters. Substitute into each of the expanded
4123 // parameters.
4124 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
4125 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
4126 I != N; ++I) {
4127 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
4128 TemplateParameterList *Expansion =
4130 if (!Expansion)
4131 return nullptr;
4132 ExpandedParams.push_back(Expansion);
4133 }
4134
4135 IsExpandedParameterPack = true;
4136 InstParams = TempParams;
4137 } else if (D->isPackExpansion()) {
4138 // The template template parameter pack expands to a pack of template
4139 // template parameters. Determine whether we need to expand this parameter
4140 // pack into separate parameters.
4141 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4143 Unexpanded);
4144
4145 // Determine whether the set of unexpanded parameter packs can and should
4146 // be expanded.
4147 bool Expand = true;
4148 bool RetainExpansion = false;
4149 UnsignedOrNone NumExpansions = std::nullopt;
4150 if (SemaRef.CheckParameterPacksForExpansion(
4151 D->getLocation(), TempParams->getSourceRange(), Unexpanded,
4152 TemplateArgs, /*FailOnPackProducingTemplates=*/true, Expand,
4153 RetainExpansion, NumExpansions))
4154 return nullptr;
4155
4156 if (Expand) {
4157 for (unsigned I = 0; I != *NumExpansions; ++I) {
4158 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
4159 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
4160 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
4161 if (!Expansion)
4162 return nullptr;
4163 ExpandedParams.push_back(Expansion);
4164 }
4165
4166 // Note that we have an expanded parameter pack. The "type" of this
4167 // expanded parameter pack is the original expansion type, but callers
4168 // will end up using the expanded parameter pack types for type-checking.
4169 IsExpandedParameterPack = true;
4170 }
4171
4172 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, std::nullopt);
4173
4174 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
4175 InstParams = SubstTemplateParams(TempParams);
4176 if (!InstParams)
4177 return nullptr;
4178 } else {
4179 // Perform the actual substitution of template parameters within a new,
4180 // local instantiation scope.
4181 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
4182 InstParams = SubstTemplateParams(TempParams);
4183 if (!InstParams)
4184 return nullptr;
4185 }
4186
4187 // Build the template template parameter.
4188 TemplateTemplateParmDecl *Param;
4189 if (IsExpandedParameterPack)
4191 SemaRef.Context, Owner, D->getLocation(),
4192 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
4194 D->wasDeclaredWithTypename(), InstParams, ExpandedParams);
4195 else
4197 SemaRef.Context, Owner, D->getLocation(),
4198 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
4199 D->getPosition(), D->isParameterPack(), D->getIdentifier(),
4200 D->templateParameterKind(), D->wasDeclaredWithTypename(), InstParams);
4202 const TemplateArgumentLoc &A = D->getDefaultArgument();
4203 NestedNameSpecifierLoc QualifierLoc = A.getTemplateQualifierLoc();
4204 // FIXME: Pass in the template keyword location.
4205 TemplateName TName = SemaRef.SubstTemplateName(
4206 A.getTemplateKWLoc(), QualifierLoc, A.getArgument().getAsTemplate(),
4207 A.getTemplateNameLoc(), TemplateArgs);
4208 if (!TName.isNull())
4209 Param->setDefaultArgument(
4210 SemaRef.Context,
4211 TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
4212 A.getTemplateKWLoc(), QualifierLoc,
4213 A.getTemplateNameLoc()));
4214 }
4215 Param->setAccess(AS_public);
4216 Param->setImplicit(D->isImplicit());
4217
4218 // Introduce this template parameter's instantiation into the instantiation
4219 // scope.
4220 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
4221
4222 return Param;
4223}
4224
4225Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
4226 // Using directives are never dependent (and never contain any types or
4227 // expressions), so they require no explicit instantiation work.
4228
4229 UsingDirectiveDecl *Inst
4230 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
4232 D->getQualifierLoc(),
4233 D->getIdentLocation(),
4235 D->getCommonAncestor());
4236
4237 // Add the using directive to its declaration context
4238 // only if this is not a function or method.
4239 if (!Owner->isFunctionOrMethod())
4240 Owner->addDecl(Inst);
4241
4242 return Inst;
4243}
4244
4246 BaseUsingDecl *Inst,
4247 LookupResult *Lookup) {
4248
4249 bool isFunctionScope = Owner->isFunctionOrMethod();
4250
4251 for (auto *Shadow : D->shadows()) {
4252 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
4253 // reconstruct it in the case where it matters. Hm, can we extract it from
4254 // the DeclSpec when parsing and save it in the UsingDecl itself?
4255 NamedDecl *OldTarget = Shadow->getTargetDecl();
4256 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
4257 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
4258 OldTarget = BaseShadow;
4259
4260 NamedDecl *InstTarget = nullptr;
4261 if (auto *EmptyD =
4262 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
4264 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
4265 } else {
4266 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
4267 Shadow->getLocation(), OldTarget, TemplateArgs));
4268 }
4269 if (!InstTarget)
4270 return nullptr;
4271
4272 UsingShadowDecl *PrevDecl = nullptr;
4273 if (Lookup &&
4274 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
4275 continue;
4276
4277 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
4278 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
4279 Shadow->getLocation(), OldPrev, TemplateArgs));
4280
4281 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
4282 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
4283 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
4284
4285 if (isFunctionScope)
4286 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
4287 }
4288
4289 return Inst;
4290}
4291
4292Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
4293
4294 // The nested name specifier may be dependent, for example
4295 // template <typename T> struct t {
4296 // struct s1 { T f1(); };
4297 // struct s2 : s1 { using s1::f1; };
4298 // };
4299 // template struct t<int>;
4300 // Here, in using s1::f1, s1 refers to t<T>::s1;
4301 // we need to substitute for t<int>::s1.
4302 NestedNameSpecifierLoc QualifierLoc
4304 TemplateArgs);
4305 if (!QualifierLoc)
4306 return nullptr;
4307
4308 // For an inheriting constructor declaration, the name of the using
4309 // declaration is the name of a constructor in this class, not in the
4310 // base class.
4311 DeclarationNameInfo NameInfo = D->getNameInfo();
4313 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
4315 SemaRef.Context.getCanonicalTagType(RD)));
4316
4317 // We only need to do redeclaration lookups if we're in a class scope (in
4318 // fact, it's not really even possible in non-class scopes).
4319 bool CheckRedeclaration = Owner->isRecord();
4320 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
4322
4323 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
4324 D->getUsingLoc(),
4325 QualifierLoc,
4326 NameInfo,
4327 D->hasTypename());
4328
4329 CXXScopeSpec SS;
4330 SS.Adopt(QualifierLoc);
4331 if (CheckRedeclaration) {
4332 Prev.setHideTags(false);
4333 SemaRef.LookupQualifiedName(Prev, Owner);
4334
4335 // Check for invalid redeclarations.
4337 D->hasTypename(), SS,
4338 D->getLocation(), Prev))
4339 NewUD->setInvalidDecl();
4340 }
4341
4342 if (!NewUD->isInvalidDecl() &&
4343 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
4344 NameInfo, D->getLocation(), nullptr, D))
4345 NewUD->setInvalidDecl();
4346
4347 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
4348 NewUD->setAccess(D->getAccess());
4349 Owner->addDecl(NewUD);
4350
4351 // Don't process the shadow decls for an invalid decl.
4352 if (NewUD->isInvalidDecl())
4353 return NewUD;
4354
4355 // If the using scope was dependent, or we had dependent bases, we need to
4356 // recheck the inheritance
4359
4360 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
4361}
4362
4363Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
4364 // Cannot be a dependent type, but still could be an instantiation
4365 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
4366 D->getLocation(), D->getEnumDecl(), TemplateArgs));
4367
4368 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
4369 return nullptr;
4370
4371 TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
4372 D->getLocation(), D->getDeclName());
4373
4374 if (!TSI)
4375 return nullptr;
4376
4377 UsingEnumDecl *NewUD =
4378 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
4379 D->getEnumLoc(), D->getLocation(), TSI);
4380
4381 SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
4382 NewUD->setAccess(D->getAccess());
4383 Owner->addDecl(NewUD);
4384
4385 // Don't process the shadow decls for an invalid decl.
4386 if (NewUD->isInvalidDecl())
4387 return NewUD;
4388
4389 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
4390 // cannot be dependent, and will therefore have been checked during template
4391 // definition.
4392
4393 return VisitBaseUsingDecls(D, NewUD, nullptr);
4394}
4395
4396Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
4397 // Ignore these; we handle them in bulk when processing the UsingDecl.
4398 return nullptr;
4399}
4400
4401Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
4403 // Ignore these; we handle them in bulk when processing the UsingDecl.
4404 return nullptr;
4405}
4406
4407template <typename T>
4408Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
4409 T *D, bool InstantiatingPackElement) {
4410 // If this is a pack expansion, expand it now.
4411 if (D->isPackExpansion() && !InstantiatingPackElement) {
4412 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4413 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
4414 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
4415
4416 // Determine whether the set of unexpanded parameter packs can and should
4417 // be expanded.
4418 bool Expand = true;
4419 bool RetainExpansion = false;
4420 UnsignedOrNone NumExpansions = std::nullopt;
4421 if (SemaRef.CheckParameterPacksForExpansion(
4422 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
4423 /*FailOnPackProducingTemplates=*/true, Expand, RetainExpansion,
4424 NumExpansions))
4425 return nullptr;
4426
4427 // This declaration cannot appear within a function template signature,
4428 // so we can't have a partial argument list for a parameter pack.
4429 assert(!RetainExpansion &&
4430 "should never need to retain an expansion for UsingPackDecl");
4431
4432 if (!Expand) {
4433 // We cannot fully expand the pack expansion now, so substitute into the
4434 // pattern and create a new pack expansion.
4435 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, std::nullopt);
4436 return instantiateUnresolvedUsingDecl(D, true);
4437 }
4438
4439 // Within a function, we don't have any normal way to check for conflicts
4440 // between shadow declarations from different using declarations in the
4441 // same pack expansion, but this is always ill-formed because all expansions
4442 // must produce (conflicting) enumerators.
4443 //
4444 // Sadly we can't just reject this in the template definition because it
4445 // could be valid if the pack is empty or has exactly one expansion.
4446 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
4447 SemaRef.Diag(D->getEllipsisLoc(),
4448 diag::err_using_decl_redeclaration_expansion);
4449 return nullptr;
4450 }
4451
4452 // Instantiate the slices of this pack and build a UsingPackDecl.
4453 SmallVector<NamedDecl*, 8> Expansions;
4454 for (unsigned I = 0; I != *NumExpansions; ++I) {
4455 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
4456 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
4457 if (!Slice)
4458 return nullptr;
4459 // Note that we can still get unresolved using declarations here, if we
4460 // had arguments for all packs but the pattern also contained other
4461 // template arguments (this only happens during partial substitution, eg
4462 // into the body of a generic lambda in a function template).
4463 Expansions.push_back(cast<NamedDecl>(Slice));
4464 }
4465
4466 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
4467 if (isDeclWithinFunction(D))
4468 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
4469 return NewD;
4470 }
4471
4472 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
4473 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
4474
4475 NestedNameSpecifierLoc QualifierLoc
4476 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
4477 TemplateArgs);
4478 if (!QualifierLoc)
4479 return nullptr;
4480
4481 CXXScopeSpec SS;
4482 SS.Adopt(QualifierLoc);
4483
4484 DeclarationNameInfo NameInfo
4485 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
4486
4487 // Produce a pack expansion only if we're not instantiating a particular
4488 // slice of a pack expansion.
4489 bool InstantiatingSlice =
4490 D->getEllipsisLoc().isValid() && SemaRef.ArgPackSubstIndex;
4491 SourceLocation EllipsisLoc =
4492 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
4493
4494 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
4495 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
4496 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
4497 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
4498 ParsedAttributesView(),
4499 /*IsInstantiation*/ true, IsUsingIfExists);
4500 if (UD) {
4501 SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
4502 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
4503 }
4504
4505 return UD;
4506}
4507
4508Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
4510 return instantiateUnresolvedUsingDecl(D);
4511}
4512
4513Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
4515 return instantiateUnresolvedUsingDecl(D);
4516}
4517
4518Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
4520 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
4521}
4522
4523Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
4524 SmallVector<NamedDecl*, 8> Expansions;
4525 for (auto *UD : D->expansions()) {
4526 if (NamedDecl *NewUD =
4527 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
4528 Expansions.push_back(NewUD);
4529 else
4530 return nullptr;
4531 }
4532
4533 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
4534 if (isDeclWithinFunction(D))
4535 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
4536 return NewD;
4537}
4538
4539Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
4541 SmallVector<Expr *, 5> Vars;
4542 for (auto *I : D->varlist()) {
4543 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
4544 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
4545 Vars.push_back(Var);
4546 }
4547
4548 OMPThreadPrivateDecl *TD =
4549 SemaRef.OpenMP().CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
4550
4551 TD->setAccess(AS_public);
4552 Owner->addDecl(TD);
4553
4554 return TD;
4555}
4556
4557Decl *
4558TemplateDeclInstantiator::VisitOMPGroupPrivateDecl(OMPGroupPrivateDecl *D) {
4559 SmallVector<Expr *, 5> Vars;
4560 for (auto *I : D->varlist()) {
4561 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
4562 assert(isa<DeclRefExpr>(Var) && "groupprivate arg is not a DeclRefExpr");
4563 Vars.push_back(Var);
4564 }
4565
4566 OMPGroupPrivateDecl *TD =
4567 SemaRef.OpenMP().CheckOMPGroupPrivateDecl(D->getLocation(), Vars);
4568
4569 TD->setAccess(AS_public);
4570 Owner->addDecl(TD);
4571
4572 return TD;
4573}
4574
4575Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
4576 SmallVector<Expr *, 5> Vars;
4577 for (auto *I : D->varlist()) {
4578 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
4579 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
4580 Vars.push_back(Var);
4581 }
4582 SmallVector<OMPClause *, 4> Clauses;
4583 // Copy map clauses from the original mapper.
4584 for (OMPClause *C : D->clauselists()) {
4585 OMPClause *IC = nullptr;
4586 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
4587 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
4588 if (!NewE.isUsable())
4589 continue;
4590 IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause(
4591 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
4592 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
4593 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
4594 if (!NewE.isUsable())
4595 continue;
4596 IC = SemaRef.OpenMP().ActOnOpenMPAlignClause(
4597 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
4598 // If align clause value ends up being invalid, this can end up null.
4599 if (!IC)
4600 continue;
4601 }
4602 Clauses.push_back(IC);
4603 }
4604
4605 Sema::DeclGroupPtrTy Res = SemaRef.OpenMP().ActOnOpenMPAllocateDirective(
4606 D->getLocation(), Vars, Clauses, Owner);
4607 if (Res.get().isNull())
4608 return nullptr;
4609 return Res.get().getSingleDecl();
4610}
4611
4612Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
4613 llvm_unreachable(
4614 "Requires directive cannot be instantiated within a dependent context");
4615}
4616
4617Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
4619 // Instantiate type and check if it is allowed.
4620 const bool RequiresInstantiation =
4621 D->getType()->isDependentType() ||
4624 QualType SubstReductionType;
4625 if (RequiresInstantiation) {
4626 QualType T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
4627 DeclarationName());
4628 if (T.isNull())
4629 return nullptr;
4630 SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType(
4631 D->getLocation(), ParsedType::make(T));
4632 } else {
4633 SubstReductionType = D->getType();
4634 }
4635 if (SubstReductionType.isNull())
4636 return nullptr;
4637 Expr *Combiner = D->getCombiner();
4638 Expr *Init = D->getInitializer();
4639 bool IsCorrect = true;
4640 // Create instantiated copy.
4641 std::pair<QualType, SourceLocation> ReductionTypes[] = {
4642 std::make_pair(SubstReductionType, D->getLocation())};
4643 auto *PrevDeclInScope = D->getPrevDeclInScope();
4644 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
4645 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
4646 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
4647 PrevDeclInScope)));
4648 }
4649 auto DRD = SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveStart(
4650 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
4651 PrevDeclInScope);
4652 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
4653 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
4654 Expr *SubstCombiner = nullptr;
4655 Expr *SubstInitializer = nullptr;
4656 // Combiners instantiation sequence.
4657 if (Combiner) {
4658 SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerStart(
4659 /*S=*/nullptr, NewDRD);
4660 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4661 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
4662 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
4663 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4664 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
4665 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
4666 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
4667 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
4668 ThisContext);
4669 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
4670 SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerEnd(NewDRD,
4671 SubstCombiner);
4672 }
4673 // Initializers instantiation sequence.
4674 if (Init) {
4675 VarDecl *OmpPrivParm =
4676 SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerStart(
4677 /*S=*/nullptr, NewDRD);
4678 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4679 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
4680 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
4681 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4682 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
4683 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
4685 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
4686 } else {
4687 auto *OldPrivParm =
4689 IsCorrect = IsCorrect && OldPrivParm->hasInit();
4690 if (IsCorrect)
4691 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
4692 TemplateArgs);
4693 }
4694 SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerEnd(
4695 NewDRD, SubstInitializer, OmpPrivParm);
4696 }
4697 IsCorrect = IsCorrect && SubstCombiner &&
4698 (!Init ||
4700 SubstInitializer) ||
4702 !SubstInitializer));
4703
4704 (void)SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveEnd(
4705 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
4706
4707 return NewDRD;
4708}
4709
4710Decl *
4711TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
4712 // Instantiate type and check if it is allowed.
4713 const bool RequiresInstantiation =
4714 D->getType()->isDependentType() ||
4717 QualType SubstMapperTy;
4718 DeclarationName VN = D->getVarName();
4719 if (RequiresInstantiation) {
4720 QualType T =
4721 SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(), VN);
4722 if (T.isNull())
4723 return nullptr;
4724 SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType(
4725 D->getLocation(), ParsedType::make(T));
4726 } else {
4727 SubstMapperTy = D->getType();
4728 }
4729 if (SubstMapperTy.isNull())
4730 return nullptr;
4731 // Create an instantiated copy of mapper.
4732 auto *PrevDeclInScope = D->getPrevDeclInScope();
4733 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
4734 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
4735 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
4736 PrevDeclInScope)));
4737 }
4738 bool IsCorrect = true;
4739 SmallVector<OMPClause *, 6> Clauses;
4740 // Instantiate the mapper variable.
4741 DeclarationNameInfo DirName;
4742 SemaRef.OpenMP().StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
4743 /*S=*/nullptr,
4744 (*D->clauselist_begin())->getBeginLoc());
4745 ExprResult MapperVarRef =
4746 SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirectiveVarDecl(
4747 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
4748 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4749 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
4750 cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
4751 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
4752 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
4753 ThisContext);
4754 // Instantiate map clauses.
4755 for (OMPClause *C : D->clauselists()) {
4756 auto *OldC = cast<OMPMapClause>(C);
4757 SmallVector<Expr *, 4> NewVars;
4758 for (Expr *OE : OldC->varlist()) {
4759 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
4760 if (!NE) {
4761 IsCorrect = false;
4762 break;
4763 }
4764 NewVars.push_back(NE);
4765 }
4766 if (!IsCorrect)
4767 break;
4768 NestedNameSpecifierLoc NewQualifierLoc =
4769 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
4770 TemplateArgs);
4771 CXXScopeSpec SS;
4772 SS.Adopt(NewQualifierLoc);
4773 DeclarationNameInfo NewNameInfo =
4774 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
4775 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
4776 OldC->getEndLoc());
4777 OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause(
4778 OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
4779 OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
4780 OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
4781 NewVars, Locs);
4782 Clauses.push_back(NewC);
4783 }
4784 SemaRef.OpenMP().EndOpenMPDSABlock(nullptr);
4785 if (!IsCorrect)
4786 return nullptr;
4787 Sema::DeclGroupPtrTy DG = SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirective(
4788 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
4789 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
4790 Decl *NewDMD = DG.get().getSingleDecl();
4791 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
4792 return NewDMD;
4793}
4794
4795Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
4796 OMPCapturedExprDecl * /*D*/) {
4797 llvm_unreachable("Should not be met in templates");
4798}
4799
4801 return VisitFunctionDecl(D, nullptr);
4802}
4803
4804Decl *
4805TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
4806 Decl *Inst = VisitFunctionDecl(D, nullptr);
4807 if (Inst && !D->getDescribedFunctionTemplate())
4808 Owner->addDecl(Inst);
4809 return Inst;
4810}
4811
4813 return VisitCXXMethodDecl(D, nullptr);
4814}
4815
4816Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
4817 llvm_unreachable("There are only CXXRecordDecls in C++");
4818}
4819
4820Decl *
4821TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
4823 // As a MS extension, we permit class-scope explicit specialization
4824 // of member class templates.
4825 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
4826 assert(ClassTemplate->getDeclContext()->isRecord() &&
4828 "can only instantiate an explicit specialization "
4829 "for a member class template");
4830
4831 // Lookup the already-instantiated declaration in the instantiation
4832 // of the class template.
4833 ClassTemplateDecl *InstClassTemplate =
4834 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
4835 D->getLocation(), ClassTemplate, TemplateArgs));
4836 if (!InstClassTemplate)
4837 return nullptr;
4838
4839 // Substitute into the template arguments of the class template explicit
4840 // specialization.
4841 TemplateArgumentListInfo InstTemplateArgs;
4842 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4844 InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4845 InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4846
4847 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4848 TemplateArgs, InstTemplateArgs))
4849 return nullptr;
4850 }
4851
4852 // Check that the template argument list is well-formed for this
4853 // class template.
4854 Sema::CheckTemplateArgumentInfo CTAI;
4855 if (SemaRef.CheckTemplateArgumentList(
4856 InstClassTemplate, D->getLocation(), InstTemplateArgs,
4857 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4858 /*UpdateArgsWithConversions=*/true))
4859 return nullptr;
4860
4861 // Figure out where to insert this class template explicit specialization
4862 // in the member template's set of class template explicit specializations.
4863 llvm::FoldingSetInsertToken InsertToken;
4864 ClassTemplateSpecializationDecl *PrevDecl =
4865 InstClassTemplate->findSpecialization(CTAI.CanonicalConverted,
4866 InsertToken);
4867
4868 // Check whether we've already seen a conflicting instantiation of this
4869 // declaration (for instance, if there was a prior implicit instantiation).
4870 bool Ignored;
4871 if (PrevDecl &&
4872 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
4874 PrevDecl,
4875 PrevDecl->getSpecializationKind(),
4876 PrevDecl->getPointOfInstantiation(),
4877 Ignored))
4878 return nullptr;
4879
4880 // If PrevDecl was a definition and D is also a definition, diagnose.
4881 // This happens in cases like:
4882 //
4883 // template<typename T, typename U>
4884 // struct Outer {
4885 // template<typename X> struct Inner;
4886 // template<> struct Inner<T> {};
4887 // template<> struct Inner<U> {};
4888 // };
4889 //
4890 // Outer<int, int> outer; // error: the explicit specializations of Inner
4891 // // have the same signature.
4892 if (PrevDecl && PrevDecl->getDefinition() &&
4894 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
4895 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
4896 diag::note_previous_definition);
4897 return nullptr;
4898 }
4899
4900 // Create the class template partial specialization declaration.
4901 ClassTemplateSpecializationDecl *InstD =
4903 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
4904 D->getLocation(), InstClassTemplate, CTAI.CanonicalConverted,
4905 CTAI.StrictPackMatch, PrevDecl);
4906 InstD->setTemplateArgsAsWritten(InstTemplateArgs);
4907
4908 // Add this partial specialization to the set of class template partial
4909 // specializations.
4910 if (!PrevDecl)
4911 InstClassTemplate->AddSpecialization(InstD, InsertToken);
4912
4913 // Substitute the nested name specifier, if any.
4914 if (SubstQualifier(D, InstD))
4915 return nullptr;
4916
4917 InstD->setAccess(D->getAccess());
4922
4923 Owner->addDecl(InstD);
4924
4925 // Instantiate the members of the class-scope explicit specialization eagerly.
4926 // We don't have support for lazy instantiation of an explicit specialization
4927 // yet, and MSVC eagerly instantiates in this case.
4928 // FIXME: This is wrong in standard C++.
4930 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
4932 /*Complain=*/true))
4933 return nullptr;
4934
4935 return InstD;
4936}
4937
4940
4941 TemplateArgumentListInfo VarTemplateArgsInfo;
4943 assert(VarTemplate &&
4944 "A template specialization without specialized template?");
4945
4946 VarTemplateDecl *InstVarTemplate =
4947 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
4948 D->getLocation(), VarTemplate, TemplateArgs));
4949 if (!InstVarTemplate)
4950 return nullptr;
4951
4952 // Substitute the current template arguments.
4953 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4955 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4956 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4957
4958 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4959 TemplateArgs, VarTemplateArgsInfo))
4960 return nullptr;
4961 }
4962
4963 // Check that the template argument list is well-formed for this template.
4965 if (SemaRef.CheckTemplateArgumentList(
4966 InstVarTemplate, D->getLocation(), VarTemplateArgsInfo,
4967 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4968 /*UpdateArgsWithConversions=*/true))
4969 return nullptr;
4970
4971 // Check whether we've already seen a declaration of this specialization.
4972 llvm::FoldingSetInsertToken InsertToken;
4974 InstVarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
4975
4976 // Check whether we've already seen a conflicting instantiation of this
4977 // declaration (for instance, if there was a prior implicit instantiation).
4978 bool Ignored;
4979 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
4980 D->getLocation(), D->getSpecializationKind(), PrevDecl,
4981 PrevDecl->getSpecializationKind(),
4982 PrevDecl->getPointOfInstantiation(), Ignored))
4983 return nullptr;
4984
4986 InstVarTemplate, D, CTAI.CanonicalConverted, PrevDecl)) {
4987 VTSD->setTemplateArgsAsWritten(VarTemplateArgsInfo);
4988 return VTSD;
4989 }
4990 return nullptr;
4991}
4992
4998
4999 // Do substitution on the type of the declaration
5000 TypeSourceInfo *TSI =
5001 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
5002 D->getTypeSpecStartLoc(), D->getDeclName());
5003 if (!TSI)
5004 return nullptr;
5005
5006 if (TSI->getType()->isFunctionType()) {
5007 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
5008 << D->isStaticDataMember() << TSI->getType();
5009 return nullptr;
5010 }
5011
5012 // Build the instantiated declaration
5014 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
5015 VarTemplate, TSI->getType(), TSI, D->getStorageClass(), Converted);
5016 if (!PrevDecl) {
5017 llvm::FoldingSetInsertToken InsertToken;
5018 VarTemplate->findSpecialization(Converted, InsertToken);
5019 VarTemplate->AddSpecialization(Var, InsertToken);
5020 }
5021
5022 if (SemaRef.getLangOpts().OpenCL)
5023 SemaRef.deduceOpenCLAddressSpace(Var);
5024
5025 // Substitute the nested name specifier, if any.
5026 if (SubstQualifier(D, Var))
5027 return nullptr;
5028
5029 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
5030 StartingScope, false, PrevDecl);
5031
5032 return Var;
5033}
5034
5035Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
5036 llvm_unreachable("@defs is not supported in Objective-C++");
5037}
5038
5039Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
5040 ArrayRef<TemplateParameterList *> FriendTPLs = D->getTemplateParameterLists();
5041
5042 TypeSourceInfo *FriendTSI = D->getFriendType();
5043 if (FriendTSI && D->isPackExpansion() && InstantiateFriendPackExpansion(D))
5044 return nullptr;
5045
5046 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
5047 SmallVector<TemplateParameterList *, 1> InstTPLs;
5048 if (SubstTemplateParameterLists(FriendTPLs, InstTPLs))
5049 return nullptr;
5050
5051 FriendDecl::FriendUnion ToFriend;
5052 TemplateName ToTemplate;
5053 if (FriendTSI) {
5054 std::optional<SubstitutedFriend> Substituted = SubstFriendTemplateType(
5055 SemaRef, FriendTSI, D->getFriendTemplateName(), TemplateArgs,
5056 D->getLocation(), DeclarationName());
5057 if (!Substituted || Substituted->empty())
5058 return nullptr;
5059 ToFriend = Substituted->TypeInfo;
5060 ToTemplate = Substituted->Template;
5061 } else if (!D->getFriendTemplateName().isNull()) {
5062 if (auto *InstTemplate =
5063 cast_or_null<TemplateDecl>(Visit(D->getFriendDecl())))
5064 ToTemplate = TemplateName(InstTemplate);
5065 else
5066 return nullptr;
5067 } else {
5068 if (auto *InstFriendDecl =
5069 cast_or_null<NamedDecl>(Visit(D->getFriendDecl())))
5070 ToFriend = InstFriendDecl;
5071 else
5072 return nullptr;
5073 }
5074
5075 FriendTemplateDecl *InstFriend = FriendTemplateDecl::Create(
5076 SemaRef.Context, Owner, D->getLocation(), ToFriend, D->getFriendLoc(),
5077 InstTPLs, /*EllipsisLoc=*/{}, ToTemplate);
5078
5079 InstFriend->setAccess(AS_public);
5080 Owner->addDecl(InstFriend);
5081 return InstFriend;
5082}
5083
5084Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
5085 llvm_unreachable("Concept definitions cannot reside inside a template");
5086}
5087
5088Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
5090 llvm_unreachable("Concept specializations cannot reside inside a template");
5091}
5092
5093Decl *
5094TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
5095 return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
5096 D->getBeginLoc());
5097}
5098
5100 llvm_unreachable("Unexpected decl");
5101}
5102
5104 const MultiLevelTemplateArgumentList &TemplateArgs) {
5105 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
5106 if (D->isInvalidDecl())
5107 return nullptr;
5108
5109 Decl *SubstD;
5111 SubstD = Instantiator.Visit(D);
5112 });
5113 return SubstD;
5114}
5115
5117 FunctionDecl *Orig, QualType &T,
5118 TypeSourceInfo *&TInfo,
5119 DeclarationNameInfo &NameInfo) {
5121
5122 // C++2a [class.compare.default]p3:
5123 // the return type is replaced with bool
5124 auto *FPT = T->castAs<FunctionProtoType>();
5125 T = SemaRef.Context.getFunctionType(
5126 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
5127
5128 // Update the return type in the source info too. The most straightforward
5129 // way is to create new TypeSourceInfo for the new type. Use the location of
5130 // the '= default' as the location of the new type.
5131 //
5132 // FIXME: Set the correct return type when we initially transform the type,
5133 // rather than delaying it to now.
5134 TypeSourceInfo *NewTInfo =
5135 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
5136 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
5137 assert(OldLoc && "type of function is not a function type?");
5138 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
5139 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
5140 NewLoc.setParam(I, OldLoc.getParam(I));
5141 TInfo = NewTInfo;
5142
5143 // and the declarator-id is replaced with operator==
5144 NameInfo.setName(
5145 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
5146}
5147
5149 FunctionDecl *Spaceship) {
5150 if (Spaceship->isInvalidDecl())
5151 return nullptr;
5152
5153 // C++2a [class.compare.default]p3:
5154 // an == operator function is declared implicitly [...] with the same
5155 // access and function-definition and in the same class scope as the
5156 // three-way comparison operator function
5157 MultiLevelTemplateArgumentList NoTemplateArgs;
5159 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
5160 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
5161 Decl *R;
5162 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
5163 R = Instantiator.VisitCXXMethodDecl(
5164 MD, /*TemplateParams=*/nullptr,
5166 } else {
5167 assert(Spaceship->getFriendObjectKind() &&
5168 "defaulted spaceship is neither a member nor a friend");
5169
5170 R = Instantiator.VisitFunctionDecl(
5171 Spaceship, /*TemplateParams=*/nullptr,
5173 if (!R)
5174 return nullptr;
5175
5176 FriendDecl *FD =
5177 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
5178 cast<NamedDecl>(R), Spaceship->getBeginLoc());
5179 FD->setAccess(AS_public);
5180 RD->addDecl(FD);
5181 }
5182 return cast_or_null<FunctionDecl>(R);
5183}
5184
5185/// Instantiates a nested template parameter list in the current
5186/// instantiation context.
5187///
5188/// \param L The parameter list to instantiate
5189///
5190/// \returns NULL if there was an error
5193 // Get errors for all the parameters before bailing out.
5194 bool Invalid = false;
5195
5196 unsigned N = L->size();
5197 typedef SmallVector<NamedDecl *, 8> ParamVector;
5198 ParamVector Params;
5199 Params.reserve(N);
5200 for (auto &P : *L) {
5201 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
5202 Params.push_back(D);
5203 Invalid = Invalid || !D || D->isInvalidDecl();
5204 }
5205
5206 // Clean up if we had an error.
5207 if (Invalid)
5208 return nullptr;
5209
5210 Expr *InstRequiresClause = L->getRequiresClause();
5211 if (InstRequiresClause && EvaluateConstraints) {
5212 ExprResult E =
5213 SemaRef.SubstConstraintExpr(InstRequiresClause, TemplateArgs);
5214 if (E.isInvalid())
5215 return nullptr;
5216 InstRequiresClause = E.get();
5217 }
5218
5220 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
5221 L->getLAngleLoc(), Params,
5222 L->getRAngleLoc(), InstRequiresClause);
5223 return InstL;
5224}
5225
5229 llvm::SaveAndRestore RAII(EvaluateConstraints, false);
5230 for (TemplateParameterList *L : TPLs) {
5232 if (!InstParams)
5233 return true;
5234
5235 if (Expr *RequiresClause = L->getRequiresClause()) {
5236 ExprResult InstRequiresClause =
5237 SemaRef.SubstConstraintExprWithoutSatisfaction(RequiresClause,
5238 TemplateArgs);
5239 if (!InstRequiresClause.isUsable())
5240 return true;
5241
5242 InstParams = TemplateParameterList::Create(
5243 SemaRef.Context, InstParams->getTemplateLoc(),
5244 InstParams->getLAngleLoc(), InstParams->asArray(),
5245 InstParams->getRAngleLoc(), InstRequiresClause.get());
5246 }
5247
5248 InstTPLs.push_back(InstParams);
5249 }
5250 return false;
5251}
5252
5255 const MultiLevelTemplateArgumentList &TemplateArgs,
5256 bool EvaluateConstraints) {
5257 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
5258 Instantiator.setEvaluateConstraints(EvaluateConstraints);
5259 return Instantiator.SubstTemplateParams(Params);
5260}
5261
5262/// Instantiate the declaration of a class template partial
5263/// specialization.
5264///
5265/// \param ClassTemplate the (instantiated) class template that is partially
5266// specialized by the instantiation of \p PartialSpec.
5267///
5268/// \param PartialSpec the (uninstantiated) class template partial
5269/// specialization that we are instantiating.
5270///
5271/// \returns The instantiated partial specialization, if successful; otherwise,
5272/// NULL to indicate an error.
5275 ClassTemplateDecl *ClassTemplate,
5277 // Create a local instantiation scope for this class template partial
5278 // specialization, which will contain the instantiations of the template
5279 // parameters.
5281
5282 // Substitute into the template parameters of the class template partial
5283 // specialization.
5284 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
5285 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
5286 if (!InstParams)
5287 return nullptr;
5288
5289 // Substitute into the template arguments of the class template partial
5290 // specialization.
5291 const ASTTemplateArgumentListInfo *TemplArgInfo
5292 = PartialSpec->getTemplateArgsAsWritten();
5293 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
5294 TemplArgInfo->RAngleLoc);
5295 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
5296 InstTemplateArgs))
5297 return nullptr;
5298
5299 // Check that the template argument list is well-formed for this
5300 // class template.
5302 if (SemaRef.CheckTemplateArgumentList(
5303 ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
5304 /*DefaultArgs=*/{},
5305 /*PartialTemplateArgs=*/false, CTAI))
5306 return nullptr;
5307
5308 // Check these arguments are valid for a template partial specialization.
5309 if (SemaRef.CheckTemplatePartialSpecializationArgs(
5310 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
5311 CTAI.CanonicalConverted))
5312 return nullptr;
5313
5314 // Figure out where to insert this class template partial specialization
5315 // in the member template's set of class template partial specializations.
5316 llvm::FoldingSetInsertToken InsertToken;
5319 InstParams, InsertToken);
5320
5321 // Create the class template partial specialization declaration.
5324 SemaRef.Context, PartialSpec->getTagKind(), Owner,
5325 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
5326 ClassTemplate, CTAI.CanonicalConverted,
5327 /*CanonInjectedTST=*/CanQualType(),
5328 /*PrevDecl=*/nullptr);
5329
5330 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
5331
5332 // Substitute the nested name specifier, if any.
5333 if (SubstQualifier(PartialSpec, InstPartialSpec))
5334 return nullptr;
5335
5336 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
5337
5338 if (PrevDecl) {
5339 // We've already seen a partial specialization with the same template
5340 // parameters and template arguments. This can happen, for example, when
5341 // substituting the outer template arguments ends up causing two
5342 // class template partial specializations of a member class template
5343 // to have identical forms, e.g.,
5344 //
5345 // template<typename T, typename U>
5346 // struct Outer {
5347 // template<typename X, typename Y> struct Inner;
5348 // template<typename Y> struct Inner<T, Y>;
5349 // template<typename Y> struct Inner<U, Y>;
5350 // };
5351 //
5352 // Outer<int, int> outer; // error: the partial specializations of Inner
5353 // // have the same signature.
5354 SemaRef.Diag(InstPartialSpec->getLocation(),
5355 diag::err_partial_spec_redeclared)
5356 << InstPartialSpec;
5357 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
5358 << SemaRef.Context.getCanonicalTagType(PrevDecl);
5359 return nullptr;
5360 }
5361
5362 // Check the completed partial specialization.
5363 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
5364
5365 // Add this partial specialization to the set of class template partial
5366 // specializations.
5367 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
5368 /*InsertToken=*/{});
5369 return InstPartialSpec;
5370}
5371
5372/// Instantiate the declaration of a variable template partial
5373/// specialization.
5374///
5375/// \param VarTemplate the (instantiated) variable template that is partially
5376/// specialized by the instantiation of \p PartialSpec.
5377///
5378/// \param PartialSpec the (uninstantiated) variable template partial
5379/// specialization that we are instantiating.
5380///
5381/// \returns The instantiated partial specialization, if successful; otherwise,
5382/// NULL to indicate an error.
5387 // Create a local instantiation scope for this variable template partial
5388 // specialization, which will contain the instantiations of the template
5389 // parameters.
5391
5392 // Substitute into the template parameters of the variable template partial
5393 // specialization.
5394 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
5395 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
5396 if (!InstParams)
5397 return nullptr;
5398
5399 // Substitute into the template arguments of the variable template partial
5400 // specialization.
5401 const ASTTemplateArgumentListInfo *TemplArgInfo
5402 = PartialSpec->getTemplateArgsAsWritten();
5403 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
5404 TemplArgInfo->RAngleLoc);
5405 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
5406 InstTemplateArgs))
5407 return nullptr;
5408
5409 // Check that the template argument list is well-formed for this
5410 // class template.
5412 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
5413 InstTemplateArgs, /*DefaultArgs=*/{},
5414 /*PartialTemplateArgs=*/false, CTAI))
5415 return nullptr;
5416
5417 // Check these arguments are valid for a template partial specialization.
5418 if (SemaRef.CheckTemplatePartialSpecializationArgs(
5419 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
5420 CTAI.CanonicalConverted))
5421 return nullptr;
5422
5423 // Figure out where to insert this variable template partial specialization
5424 // in the member template's set of variable template partial specializations.
5425 llvm::FoldingSetInsertToken InsertToken;
5427 VarTemplate->findPartialSpecialization(CTAI.CanonicalConverted,
5428 InstParams, InsertToken);
5429
5430 // Do substitution on the type of the declaration
5431 TypeSourceInfo *TSI = SemaRef.SubstType(
5432 PartialSpec->getTypeSourceInfo(), TemplateArgs,
5433 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
5434 if (!TSI)
5435 return nullptr;
5436
5437 if (TSI->getType()->isFunctionType()) {
5438 SemaRef.Diag(PartialSpec->getLocation(),
5439 diag::err_variable_instantiates_to_function)
5440 << PartialSpec->isStaticDataMember() << TSI->getType();
5441 return nullptr;
5442 }
5443
5444 // Create the variable template partial specialization declaration.
5445 VarTemplatePartialSpecializationDecl *InstPartialSpec =
5447 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
5448 PartialSpec->getLocation(), InstParams, VarTemplate, TSI->getType(),
5449 TSI, PartialSpec->getStorageClass(), CTAI.CanonicalConverted);
5450
5451 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
5452
5453 // Substitute the nested name specifier, if any.
5454 if (SubstQualifier(PartialSpec, InstPartialSpec))
5455 return nullptr;
5456
5457 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
5458
5459 if (PrevDecl) {
5460 // We've already seen a partial specialization with the same template
5461 // parameters and template arguments. This can happen, for example, when
5462 // substituting the outer template arguments ends up causing two
5463 // variable template partial specializations of a member variable template
5464 // to have identical forms, e.g.,
5465 //
5466 // template<typename T, typename U>
5467 // struct Outer {
5468 // template<typename X, typename Y> pair<X,Y> p;
5469 // template<typename Y> pair<T, Y> p;
5470 // template<typename Y> pair<U, Y> p;
5471 // };
5472 //
5473 // Outer<int, int> outer; // error: the partial specializations of Inner
5474 // // have the same signature.
5475 SemaRef.Diag(PartialSpec->getLocation(),
5476 diag::err_var_partial_spec_redeclared)
5477 << InstPartialSpec;
5478 SemaRef.Diag(PrevDecl->getLocation(),
5479 diag::note_var_prev_partial_spec_here);
5480 return nullptr;
5481 }
5482 // Check the completed partial specialization.
5483 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
5484
5485 // Add this partial specialization to the set of variable template partial
5486 // specializations. The instantiation of the initializer is not necessary.
5487 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertToken=*/{});
5488
5489 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
5490 LateAttrs, Owner, StartingScope);
5491
5492 return InstPartialSpec;
5493}
5494
5500
5502 if (!Instantiator.LateAttrs) {
5503 Instantiator.SemaRef.InstantiateLateAttrs(Instantiator.TemplateArgs, Attrs,
5504 Outer);
5505 return;
5506 }
5507 for (const Sema::LateInstantiatedAttribute &LA : Attrs)
5508 Instantiator.LateAttrs->push_back(Sema::LateInstantiatedAttribute(
5509 LA.TmplAttr, LA.Scope->cloneScopes(Instantiator.StartingScope),
5510 LA.NewDecl));
5511 discard();
5512}
5513
5516 DeferredParamAttrs &ParamAttrs) {
5517 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
5518 assert(OldTInfo && "substituting function without type source info");
5519 assert(Params.empty() && "parameter vector is non-empty at start");
5520
5521 CXXRecordDecl *ThisContext = nullptr;
5522 Qualifiers ThisTypeQuals;
5523 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5524 ThisContext = cast<CXXRecordDecl>(Owner);
5525 ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
5526 }
5527
5528 TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
5529 OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
5530 ThisContext, ThisTypeQuals, EvaluateConstraints, D, &ParamAttrs.Attrs);
5531 if (!NewTInfo)
5532 return nullptr;
5533
5534 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
5535 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
5536 if (NewTInfo != OldTInfo) {
5537 // Get parameters from the new type info.
5538 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
5539 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
5540 unsigned NewIdx = 0;
5541 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
5542 OldIdx != NumOldParams; ++OldIdx) {
5543 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
5544 if (!OldParam)
5545 return nullptr;
5546
5547 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
5548
5549 UnsignedOrNone NumArgumentsInExpansion = std::nullopt;
5550 if (OldParam->isParameterPack())
5551 NumArgumentsInExpansion =
5552 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
5553 TemplateArgs);
5554 if (!NumArgumentsInExpansion) {
5555 // Simple case: normal parameter, or a parameter pack that's
5556 // instantiated to a (still-dependent) parameter pack.
5557 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
5558 Params.push_back(NewParam);
5559 Scope->InstantiatedLocal(OldParam, NewParam);
5560 } else {
5561 // Parameter pack expansion: make the instantiation an argument pack.
5562 Scope->MakeInstantiatedLocalArgPack(OldParam);
5563 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
5564 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
5565 Params.push_back(NewParam);
5566 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
5567 }
5568 }
5569 }
5570 } else {
5571 // The function type itself was not dependent and therefore no
5572 // substitution occurred. However, we still need to instantiate
5573 // the function parameters themselves.
5574 const FunctionProtoType *OldProto =
5575 cast<FunctionProtoType>(OldProtoLoc.getType());
5576 SmallVector<QualType, 4> ParamTypes;
5577 Sema::ExtParameterInfoBuilder ExtParamInfos;
5578 if (SemaRef.SubstParmTypes(D->getLocation(), OldProtoLoc.getParams(),
5579 nullptr, TemplateArgs, ParamTypes, &Params,
5580 ExtParamInfos, OldProto->param_type_begin(),
5581 EvaluateConstraints))
5582 return nullptr;
5583 // Declare a parameter that was only a type in the prototype. A function
5584 // declared through a typedef with an attribute that rewrites the
5585 // function type in place, such as noreturn, gets a prototype whose
5586 // parameters have no ParmVarDecl, so no attribute of the typedef's
5587 // parameters reaches it; see TypeSpecLocFiller in SemaType.
5588 // FIXME: Keep the typedef's parameters there instead. The dependent
5589 // branch above returns null for such a prototype, dropping the member.
5590 assert(Params.size() == ParamTypes.size());
5591 for (unsigned i = 0, i_end = Params.size(); i != i_end; ++i)
5592 if (!Params[i])
5593 Params[i] = SemaRef.BuildParmVarDeclForTypedef(D, D->getLocation(),
5594 ParamTypes[i]);
5595 }
5596 } else {
5597 // If the type of this function, after ignoring parentheses, is not
5598 // *directly* a function type, then we're instantiating a function that
5599 // was declared via a typedef or with attributes, e.g.,
5600 //
5601 // typedef int functype(int, int);
5602 // functype func;
5603 // int __cdecl meth(int, int);
5604 //
5605 // In this case, we'll just go instantiate the ParmVarDecls that we
5606 // synthesized in the method declaration.
5607 //
5608 // The late-parsed attributes of the parameters that substituting the type
5609 // created, if it did, are not the function's; defer those of its own
5610 // parameters instead.
5611 ParamAttrs.discard();
5612 SmallVector<QualType, 4> ParamTypes;
5613 Sema::ExtParameterInfoBuilder ExtParamInfos;
5614 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
5615 TemplateArgs, ParamTypes, &Params, ExtParamInfos,
5616 /*OldParamTypes=*/nullptr, EvaluateConstraints,
5617 D, &ParamAttrs.Attrs))
5618 return nullptr;
5619 }
5620
5621 return NewTInfo;
5622}
5623
5624void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
5625 const FunctionDecl *PatternDecl,
5627 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(getFunctionScopes().back());
5628
5629 for (auto *decl : PatternDecl->decls()) {
5631 continue;
5632
5633 VarDecl *VD = cast<VarDecl>(decl);
5634 IdentifierInfo *II = VD->getIdentifier();
5635
5636 auto it = llvm::find_if(Function->decls(), [&](Decl *inst) {
5637 VarDecl *InstVD = dyn_cast<VarDecl>(inst);
5638 return InstVD && InstVD->isLocalVarDecl() &&
5639 InstVD->getIdentifier() == II;
5640 });
5641
5642 if (it == Function->decls().end())
5643 continue;
5644
5645 Scope.InstantiatedLocal(VD, *it);
5646 LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false,
5647 /*isNested=*/false, VD->getLocation(), SourceLocation(),
5648 VD->getType(), /*Invalid=*/false);
5649 }
5650}
5651
5652bool Sema::addInstantiatedParametersToScope(
5653 FunctionDecl *Function, const FunctionDecl *PatternDecl,
5654 LocalInstantiationScope &Scope,
5655 const MultiLevelTemplateArgumentList &TemplateArgs) {
5656 unsigned FParamIdx = 0;
5657 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
5658 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
5659 if (!PatternParam->isParameterPack()) {
5660 // Simple case: not a parameter pack.
5661 assert(FParamIdx < Function->getNumParams());
5662 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
5663 FunctionParam->setDeclName(PatternParam->getDeclName());
5664 // If the parameter's type is not dependent, update it to match the type
5665 // in the pattern. They can differ in top-level cv-qualifiers, and we want
5666 // the pattern's type here. If the type is dependent, they can't differ,
5667 // per core issue 1668. Substitute into the type from the pattern, in case
5668 // it's instantiation-dependent.
5669 // FIXME: Updating the type to work around this is at best fragile.
5670 if (!PatternDecl->getType()->isDependentType()) {
5671 QualType T = SubstType(PatternParam->getType(), TemplateArgs,
5672 FunctionParam->getLocation(),
5673 FunctionParam->getDeclName());
5674 if (T.isNull())
5675 return true;
5676 FunctionParam->setType(T);
5677 }
5678
5679 Scope.InstantiatedLocal(PatternParam, FunctionParam);
5680 ++FParamIdx;
5681 continue;
5682 }
5683
5684 // Expand the parameter pack.
5685 Scope.MakeInstantiatedLocalArgPack(PatternParam);
5686 UnsignedOrNone NumArgumentsInExpansion =
5687 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
5688 if (NumArgumentsInExpansion) {
5689 QualType PatternType =
5690 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
5691 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
5692 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
5693 FunctionParam->setDeclName(PatternParam->getDeclName());
5694 if (!PatternDecl->getType()->isDependentType()) {
5695 Sema::ArgPackSubstIndexRAII SubstIndex(*this, Arg);
5696 QualType T =
5697 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
5698 FunctionParam->getDeclName());
5699 if (T.isNull())
5700 return true;
5701 FunctionParam->setType(T);
5702 }
5703
5704 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
5705 ++FParamIdx;
5706 }
5707 }
5708 }
5709
5710 return false;
5711}
5712
5714 ParmVarDecl *Param) {
5715 assert(Param->hasUninstantiatedDefaultArg());
5716
5717 // FIXME: We don't track member specialization info for non-defining
5718 // friend declarations, so we will not be able to later find the function
5719 // pattern. As a workaround, don't instantiate the default argument in this
5720 // case. This is correct per the standard and only an issue for recovery
5721 // purposes. [dcl.fct.default]p4:
5722 // if a friend declaration D specifies a default argument expression,
5723 // that declaration shall be a definition.
5724 if (FD->getFriendObjectKind() != Decl::FOK_None &&
5726 return true;
5727
5728 // Instantiate the expression.
5729 //
5730 // FIXME: Pass in a correct Pattern argument, otherwise
5731 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
5732 //
5733 // template<typename T>
5734 // struct A {
5735 // static int FooImpl();
5736 //
5737 // template<typename Tp>
5738 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
5739 // // template argument list [[T], [Tp]], should be [[Tp]].
5740 // friend A<Tp> Foo(int a);
5741 // };
5742 //
5743 // template<typename T>
5744 // A<T> Foo(int a = A<T>::FooImpl());
5746 FD, FD->getLexicalDeclContext(),
5747 /*Final=*/false, /*Innermost=*/std::nullopt,
5748 /*RelativeToPrimary=*/true, /*Pattern=*/nullptr,
5749 /*ForConstraintInstantiation=*/false, /*SkipForSpecialization=*/false,
5750 /*ForDefaultArgumentSubstitution=*/true);
5751
5752 if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
5753 return true;
5754
5756 L->DefaultArgumentInstantiated(Param);
5757
5758 return false;
5759}
5760
5762 FunctionDecl *Decl) {
5763 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
5765 return;
5766
5767 RecursiveInstGuard AlreadyInstantiating(
5769 if (AlreadyInstantiating) {
5770 // This exception specification indirectly depends on itself. Reject.
5771 // FIXME: Corresponding rule in the standard?
5772 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
5774 return;
5775 }
5776
5777 NonSFINAEContext _(*this);
5778 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
5780 if (Inst.isInvalid()) {
5781 // We hit the instantiation depth limit. Clear the exception specification
5782 // so that our callers don't have to cope with EST_Uninstantiated.
5784 return;
5785 }
5786
5787 // Enter the scope of this instantiation. We don't use
5788 // PushDeclContext because we don't have a scope.
5789 Sema::ContextRAII savedContext(*this, Decl);
5791
5792 MultiLevelTemplateArgumentList TemplateArgs =
5794 /*Final=*/false, /*Innermost=*/std::nullopt,
5795 /*RelativeToPrimary*/ true);
5796
5797 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
5798 // here, because for a non-defining friend declaration in a class template,
5799 // we don't store enough information to map back to the friend declaration in
5800 // the template.
5802 if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
5804 return;
5805 }
5806
5807 // The noexcept specification could reference any lambda captures. Ensure
5808 // those are added to the LocalInstantiationScope.
5810 *this, Decl, TemplateArgs, Scope,
5811 /*ShouldAddDeclsFromParentScope=*/false);
5812
5813 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
5814 TemplateArgs);
5815}
5816
5817/// Initializes the common fields of an instantiation function
5818/// declaration (New) from the corresponding fields of its template (Tmpl).
5819///
5820/// \returns true if there was an error
5821bool
5823 FunctionDecl *Tmpl) {
5824 New->setImplicit(Tmpl->isImplicit());
5825
5826 // Forward the mangling number from the template to the instantiated decl.
5827 SemaRef.Context.setManglingNumber(New,
5828 SemaRef.Context.getManglingNumber(Tmpl));
5829
5830 // If we are performing substituting explicitly-specified template arguments
5831 // or deduced template arguments into a function template and we reach this
5832 // point, we are now past the point where SFINAE applies and have committed
5833 // to keeping the new function template specialization. We therefore
5834 // convert the active template instantiation for the function template
5835 // into a template instantiation for this specific function template
5836 // specialization, which is not a SFINAE context, so that we diagnose any
5837 // further errors in the declaration itself.
5838 //
5839 // FIXME: This is a hack.
5840 typedef Sema::CodeSynthesisContext ActiveInstType;
5841 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
5842 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
5843 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
5844 if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
5845 SemaRef.CurrentSFINAEContext = nullptr;
5846 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
5847 ActiveInst.Entity = New;
5848 }
5849 }
5850
5851 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
5852 assert(Proto && "Function template without prototype?");
5853
5854 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
5856
5857 // DR1330: In C++11, defer instantiation of a non-trivial
5858 // exception specification.
5859 // DR1484: Local classes and their members are instantiated along with the
5860 // containing function.
5861 if (SemaRef.getLangOpts().CPlusPlus11 &&
5862 EPI.ExceptionSpec.Type != EST_None &&
5866 FunctionDecl *ExceptionSpecTemplate = Tmpl;
5868 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
5871 NewEST = EST_Unevaluated;
5872
5873 // Mark the function has having an uninstantiated exception specification.
5874 const FunctionProtoType *NewProto
5875 = New->getType()->getAs<FunctionProtoType>();
5876 assert(NewProto && "Template instantiation without function prototype?");
5877 EPI = NewProto->getExtProtoInfo();
5878 EPI.ExceptionSpec.Type = NewEST;
5880 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
5881 New->setType(SemaRef.Context.getFunctionType(
5882 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
5883 } else {
5884 Sema::ContextRAII SwitchContext(SemaRef, New);
5885 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
5886 }
5887 }
5888
5889 // Get the definition. Leaves the variable unchanged if undefined.
5890 const FunctionDecl *Definition = Tmpl;
5891 Tmpl->isDefined(Definition);
5892
5893 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
5894 LateAttrs, StartingScope);
5895
5896 SemaRef.inferLifetimeBoundAttribute(New);
5897
5898 return false;
5899}
5900
5901/// Initializes common fields of an instantiated method
5902/// declaration (New) from the corresponding fields of its template
5903/// (Tmpl).
5904///
5905/// \returns true if there was an error
5906bool
5908 CXXMethodDecl *Tmpl) {
5909 if (InitFunctionInstantiation(New, Tmpl))
5910 return true;
5911
5912 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
5913 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
5914
5915 New->setAccess(Tmpl->getAccess());
5916 if (Tmpl->isVirtualAsWritten())
5917 New->setVirtualAsWritten(true);
5918
5919 // FIXME: New needs a pointer to Tmpl
5920 return false;
5921}
5922
5924 FunctionDecl *Tmpl) {
5925 // Transfer across any unqualified lookups.
5926 if (auto *DFI = Tmpl->getDefaultedOrDeletedInfo()) {
5928 Lookups.reserve(DFI->getUnqualifiedLookups().size());
5929 bool AnyChanged = false;
5930 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
5931 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
5932 DA.getDecl(), TemplateArgs);
5933 if (!D)
5934 return true;
5935 AnyChanged |= (D != DA.getDecl());
5936 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
5937 }
5938
5939 New->setDefaultedOrDeletedInfo(
5941 SemaRef.Context, Lookups, DFI->getFPFeatures(),
5942 DFI->getDeletedMessage())
5943 : DFI);
5944 }
5945
5946 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
5947 return false;
5948}
5949
5953 FunctionDecl *FD = FTD->getTemplatedDecl();
5954
5955 InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC);
5956 if (Inst.isInvalid())
5957 return nullptr;
5958
5959 ContextRAII SavedContext(*this, FD);
5960 MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
5961 /*Final=*/false);
5962
5963 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
5964}
5965
5968 bool Recursive,
5969 bool DefinitionRequired,
5970 bool AtEndOfTU) {
5971 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
5972 return;
5973
5974 // Never instantiate an explicit specialization except if it is a class scope
5975 // explicit specialization.
5977 Function->getTemplateSpecializationKindForInstantiation();
5978 if (TSK == TSK_ExplicitSpecialization)
5979 return;
5980
5981 // Never implicitly instantiate a builtin; we don't actually need a function
5982 // body.
5983 if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
5984 !DefinitionRequired)
5985 return;
5986
5987 // Don't instantiate a definition if we already have one.
5988 const FunctionDecl *ExistingDefn = nullptr;
5989 if (Function->isDefined(ExistingDefn,
5990 /*CheckForPendingFriendDefinition=*/true)) {
5991 if (ExistingDefn->isThisDeclarationADefinition())
5992 return;
5993
5994 // If we're asked to instantiate a function whose body comes from an
5995 // instantiated friend declaration, attach the instantiated body to the
5996 // corresponding declaration of the function.
5998 Function = const_cast<FunctionDecl*>(ExistingDefn);
5999 }
6000
6001#ifndef NDEBUG
6002 RecursiveInstGuard AlreadyInstantiating(*this, Function,
6004 assert(!AlreadyInstantiating && "should have been caught by caller");
6005#endif
6006
6007 // Find the function body that we'll be substituting.
6008 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
6009 assert(PatternDecl && "instantiating a non-template");
6010
6011 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
6012 Stmt *Pattern = nullptr;
6013 if (PatternDef) {
6014 Pattern = PatternDef->getBody(PatternDef);
6015 PatternDecl = PatternDef;
6016 if (PatternDef->willHaveBody())
6017 PatternDef = nullptr;
6018 }
6019
6020 // True is the template definition is unreachable, otherwise false.
6021 bool Unreachable = false;
6022 // FIXME: We need to track the instantiation stack in order to know which
6023 // definitions should be visible within this instantiation.
6025 PointOfInstantiation, Function,
6026 Function->getInstantiatedFromMemberFunction(), PatternDecl,
6027 PatternDef, TSK,
6028 /*Complain*/ DefinitionRequired, &Unreachable)) {
6029 if (DefinitionRequired)
6030 Function->setInvalidDecl();
6031 else if (TSK == TSK_ExplicitInstantiationDefinition ||
6032 (Function->isConstexpr() && !Recursive)) {
6033 // Try again at the end of the translation unit (at which point a
6034 // definition will be required).
6035 assert(!Recursive);
6036 Function->setInstantiationIsPending(true);
6037 PendingInstantiations.emplace_back(Function, PointOfInstantiation);
6038
6039 if (llvm::isTimeTraceVerbose()) {
6040 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
6041 std::string Name;
6042 llvm::raw_string_ostream OS(Name);
6043 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
6044 /*Qualified=*/true);
6045 return Name;
6046 });
6047 }
6048 } else if (TSK == TSK_ImplicitInstantiation) {
6049 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
6050 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
6051 Diag(PointOfInstantiation, diag::warn_func_template_missing)
6052 << Function;
6053 if (Unreachable) {
6054 // FIXME: would be nice to mention which module the function template
6055 // comes from.
6056 Diag(PatternDecl->getLocation(),
6057 diag::note_unreachable_template_decl);
6058 } else {
6059 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
6061 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
6062 << Function;
6063 }
6064 }
6065 }
6066
6067 return;
6068 }
6069
6070 // Postpone late parsed template instantiations.
6071 if (PatternDecl->isLateTemplateParsed() &&
6073 Function->setInstantiationIsPending(true);
6074 LateParsedInstantiations.push_back(
6075 std::make_pair(Function, PointOfInstantiation));
6076 return;
6077 }
6078
6079 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
6080 llvm::TimeTraceMetadata M;
6081 llvm::raw_string_ostream OS(M.Detail);
6082 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
6083 /*Qualified=*/true);
6084 if (llvm::isTimeTraceVerbose()) {
6085 auto Loc = SourceMgr.getExpansionLoc(Function->getLocation());
6086 M.File = SourceMgr.getFilename(Loc);
6087 M.Line = SourceMgr.getExpansionLineNumber(Loc);
6088 }
6089 return M;
6090 });
6091
6092 // If we're performing recursive template instantiation, create our own
6093 // queue of pending implicit instantiations that we will instantiate later,
6094 // while we're still within our own instantiation context.
6095 // This has to happen before LateTemplateParser below is called, so that
6096 // it marks vtables used in late parsed templates as used.
6097 GlobalEagerInstantiationScope GlobalInstantiations(*this,
6098 /*Enabled=*/Recursive,
6099 /*AtEndOfTU=*/AtEndOfTU);
6100 LocalEagerInstantiationScope LocalInstantiations(*this,
6101 /*AtEndOfTU=*/AtEndOfTU);
6102
6103 // Call the LateTemplateParser callback if there is a need to late parse
6104 // a templated function definition.
6105 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
6107 // FIXME: Optimize to allow individual templates to be deserialized.
6108 if (PatternDecl->isFromASTFile())
6109 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
6110
6111 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
6112 assert(LPTIter != LateParsedTemplateMap.end() &&
6113 "missing LateParsedTemplate");
6114 LateTemplateParser(OpaqueParser, *LPTIter->second);
6115 Pattern = PatternDecl->getBody(PatternDecl);
6117 }
6118
6119 // Note, we should never try to instantiate a deleted function template.
6120 assert((Pattern || PatternDecl->isDefaulted() ||
6121 PatternDecl->hasSkippedBody()) &&
6122 "unexpected kind of function template definition");
6123
6124 // C++1y [temp.explicit]p10:
6125 // Except for inline functions, declarations with types deduced from their
6126 // initializer or return value, and class template specializations, other
6127 // explicit instantiation declarations have the effect of suppressing the
6128 // implicit instantiation of the entity to which they refer.
6130 !PatternDecl->isInlined() &&
6131 !PatternDecl->getReturnType()->getContainedAutoType())
6132 return;
6133
6134 if (PatternDecl->isInlined()) {
6135 // Function, and all later redeclarations of it (from imported modules,
6136 // for instance), are now implicitly inline.
6137 for (auto *D = Function->getMostRecentDecl(); /**/;
6138 D = D->getPreviousDecl()) {
6139 D->setImplicitlyInline();
6140 if (D == Function)
6141 break;
6142 }
6143 }
6144
6145 NonSFINAEContext _(*this);
6146 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
6147 if (Inst.isInvalid())
6148 return;
6150 "instantiating function definition");
6151
6152 // The instantiation is visible here, even if it was first declared in an
6153 // unimported module.
6154 Function->setVisibleDespiteOwningModule();
6155
6156 // Copy the source locations from the pattern.
6157 Function->setLocation(PatternDecl->getLocation());
6158 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
6159 Function->setRangeEnd(PatternDecl->getEndLoc());
6160 // Let the instantiation use the Pattern's DeclarationNameLoc, due to the
6161 // following awkwardness:
6162 //
6163 // 1. There are out-of-tree users of getNameInfo().getSourceRange(), who
6164 // expect the source range of the instantiated declaration to be set to
6165 // point to the definition.
6166 //
6167 // 2. That getNameInfo().getSourceRange() might return the TypeLocInfo's
6168 // location it tracked.
6169 //
6170 // 3. Function might come from an (implicit) declaration, while the pattern
6171 // comes from a definition. In these cases, we need the PatternDecl's source
6172 // location.
6173 //
6174 // To that end, we need to more or less tweak the DeclarationNameLoc. However,
6175 // we can't blindly copy the DeclarationNameLoc from the PatternDecl to the
6176 // function, since it contains associated TypeLocs that should have already
6177 // been transformed. So, we rebuild the TypeLoc for that purpose. Technically,
6178 // we should create a new function declaration and assign everything we need,
6179 // but InstantiateFunctionDefinition updates the declaration in place.
6180 auto NameLocPointsToPattern = [&] {
6181 DeclarationNameInfo PatternName = PatternDecl->getNameInfo();
6182 DeclarationNameLoc PatternNameLoc = PatternName.getInfo();
6183 switch (PatternName.getName().getNameKind()) {
6187 break;
6188 default:
6189 // Cases where DeclarationNameLoc doesn't matter, as it merely contains a
6190 // source range.
6191 return PatternNameLoc;
6192 }
6193
6194 TypeSourceInfo *TSI = Function->getNameInfo().getNamedTypeInfo();
6195 // TSI might be null if the function is named by a constructor template id.
6196 // E.g. S<T>() {} for class template S with a template parameter T.
6197 if (!TSI) {
6198 // We don't care about the DeclarationName of the instantiated function,
6199 // but only the DeclarationNameLoc. So if the TypeLoc is absent, we do
6200 // nothing.
6201 return PatternNameLoc;
6202 }
6203
6204 QualType InstT = TSI->getType();
6205 // We want to use a TypeLoc that reflects the transformed type while
6206 // preserving the source location from the pattern.
6207 TypeLocBuilder TLB;
6208 TypeSourceInfo *PatternTSI = PatternName.getNamedTypeInfo();
6209 assert(PatternTSI && "Pattern is supposed to have an associated TSI");
6210 // FIXME: PatternTSI is not trivial. We should copy the source location
6211 // along the TypeLoc chain. However a trivial TypeLoc is sufficient for
6212 // getNameInfo().getSourceRange().
6213 TLB.pushTrivial(Context, InstT, PatternTSI->getTypeLoc().getBeginLoc());
6215 TLB.getTypeSourceInfo(Context, InstT));
6216 };
6217 Function->setDeclarationNameLoc(NameLocPointsToPattern());
6218
6221
6222 Qualifiers ThisTypeQuals;
6223 CXXRecordDecl *ThisContext = nullptr;
6224 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6225 ThisContext = Method->getParent();
6226 ThisTypeQuals = Method->getMethodQualifiers();
6227 }
6228 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals);
6229
6230 // Introduce a new scope where local variable instantiations will be
6231 // recorded, unless we're actually a member function within a local
6232 // class, in which case we need to merge our results with the parent
6233 // scope (of the enclosing function). The exception is instantiating
6234 // a function template specialization, since the template to be
6235 // instantiated already has references to locals properly substituted.
6236 bool MergeWithParentScope = false;
6237 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
6238 MergeWithParentScope =
6239 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
6240
6241 LocalInstantiationScope Scope(*this, MergeWithParentScope);
6242 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
6243 // Special members might get their TypeSourceInfo set up w.r.t the
6244 // PatternDecl context, in which case parameters could still be pointing
6245 // back to the original class, make sure arguments are bound to the
6246 // instantiated record instead.
6247 assert(PatternDecl->isDefaulted() &&
6248 "Special member needs to be defaulted");
6249 auto PatternSM = PatternDecl->getDefaultedFunctionKind().asSpecialMember();
6250 if (!(PatternSM == CXXSpecialMemberKind::CopyConstructor ||
6254 return;
6255
6256 auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
6257 const auto *PatternRec =
6258 dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
6259 if (!NewRec || !PatternRec)
6260 return;
6261 if (!PatternRec->isLambda())
6262 return;
6263
6264 struct SpecialMemberTypeInfoRebuilder
6265 : TreeTransform<SpecialMemberTypeInfoRebuilder> {
6267 const CXXRecordDecl *OldDecl;
6268 CXXRecordDecl *NewDecl;
6269
6270 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
6271 CXXRecordDecl *N)
6272 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
6273
6274 bool TransformExceptionSpec(SourceLocation Loc,
6276 SmallVectorImpl<QualType> &Exceptions,
6277 bool &Changed) {
6278 return false;
6279 }
6280
6281 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
6282 const RecordType *T = TL.getTypePtr();
6283 RecordDecl *Record = cast_or_null<RecordDecl>(
6284 getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
6285 if (Record != OldDecl)
6286 return Base::TransformRecordType(TLB, TL);
6287
6288 // FIXME: transform the rest of the record type.
6289 QualType Result = getDerived().RebuildTagType(
6290 ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt, NewDecl);
6291 if (Result.isNull())
6292 return QualType();
6293
6294 TagTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
6297 NewTL.setNameLoc(TL.getNameLoc());
6298 return Result;
6299 }
6300 } IR{*this, PatternRec, NewRec};
6301
6302 TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
6303 assert(NewSI && "Type Transform failed?");
6304 Function->setType(NewSI->getType());
6305 Function->setTypeSourceInfo(NewSI);
6306
6307 ParmVarDecl *Parm = Function->getParamDecl(0);
6308 TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
6309 assert(NewParmSI && "Type transformation failed.");
6310 Parm->setType(NewParmSI->getType());
6311 Parm->setTypeSourceInfo(NewParmSI);
6312 };
6313
6314 if (PatternDecl->isDefaulted()) {
6315 RebuildTypeSourceInfoForDefaultSpecialMembers();
6316 // A function defaulted outside its class was not defaulted when its
6317 // declaration was instantiated, so transfer the info recorded at its
6318 // definition now: the floating-point features in effect there, and any
6319 // unqualified lookups, which were performed from namespace scope and so
6320 // don't need to be instantiated.
6321 if (!Function->getDefaultedOrDeletedInfo())
6322 if (auto *DFI = PatternDecl->getDefaultedOrDeletedInfo())
6323 Function->setDefaultedOrDeletedInfo(DFI);
6324 SetDeclDefaulted(Function, PatternDecl->getLocation());
6325 } else {
6326 DeclContext *DC = Function->getLexicalDeclContext();
6327 std::optional<ArrayRef<TemplateArgument>> Innermost;
6328 if (auto *Primary = Function->getPrimaryTemplate();
6329 Primary &&
6331 Function->getTemplateSpecializationKind() !=
6333 auto It = llvm::find_if(Primary->redecls(),
6334 [](const RedeclarableTemplateDecl *RTD) {
6335 return cast<FunctionTemplateDecl>(RTD)
6336 ->isCompatibleWithDefinition();
6337 });
6338 assert(It != Primary->redecls().end() &&
6339 "Should't get here without a definition");
6341 ->getTemplatedDecl()
6342 ->getDefinition())
6343 DC = Def->getLexicalDeclContext();
6344 else
6345 DC = (*It)->getLexicalDeclContext();
6346 Innermost.emplace(Function->getTemplateSpecializationArgs()->asArray());
6347 }
6349 Function, DC, /*Final=*/false, Innermost, false, PatternDecl);
6350
6351 // Substitute into the qualifier; we can get a substitution failure here
6352 // through evil use of alias templates.
6353 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
6354 // of the) lexical context of the pattern?
6355 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
6356
6358
6359 // Enter the scope of this instantiation. We don't use
6360 // PushDeclContext because we don't have a scope.
6361 Sema::ContextRAII savedContext(*this, Function);
6362
6363 FPFeaturesStateRAII SavedFPFeatures(*this);
6365 FpPragmaStack.CurrentValue = FPOptionsOverride();
6366
6367 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
6368 TemplateArgs))
6369 return;
6370
6371 StmtResult Body;
6372 if (PatternDecl->hasSkippedBody()) {
6374 Body = nullptr;
6375 } else {
6376 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
6377 // If this is a constructor, instantiate the member initializers.
6379 TemplateArgs);
6380
6381 // If this is an MS ABI dllexport default constructor, instantiate any
6382 // default arguments.
6383 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6384 Ctor->isDefaultConstructor()) {
6385 if (DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>())
6387 }
6388 }
6389
6390 // Instantiate the function body.
6391 Body = SubstStmt(Pattern, TemplateArgs);
6392
6393 if (Body.isInvalid())
6394 Function->setInvalidDecl();
6395 }
6396 // FIXME: finishing the function body while in an expression evaluation
6397 // context seems wrong. Investigate more.
6398 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
6399
6401
6402 checkReferenceToTULocalFromOtherTU(Function, PointOfInstantiation);
6403
6404 if (PatternDecl->isDependentContext())
6405 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
6406
6407 if (auto *Listener = getASTMutationListener())
6408 Listener->FunctionDefinitionInstantiated(Function);
6409
6410 savedContext.pop();
6411 }
6412
6413 // We never need to emit the code for a lambda in unevaluated context.
6414 // We also can't mangle a lambda in the require clause of a function template
6415 // during constraint checking as the MSI ABI would need to mangle the (not yet
6416 // specialized) enclosing declaration
6417 // FIXME: Should we try to skip this for non-lambda functions too?
6418 bool ShouldSkipCG = [&] {
6419 auto *RD = dyn_cast<CXXRecordDecl>(Function->getParent());
6420 if (!RD || !RD->isLambda())
6421 return false;
6422
6423 return llvm::any_of(ExprEvalContexts, [](auto &Context) {
6424 return Context.isUnevaluated() || Context.isImmediateFunctionContext();
6425 });
6426 }();
6427 if (!ShouldSkipCG) {
6429 Consumer.HandleTopLevelDecl(DG);
6430 }
6431
6432 // This class may have local implicit instantiations that need to be
6433 // instantiation within this scope.
6434 LocalInstantiations.perform();
6435 Scope.Exit();
6436 GlobalInstantiations.perform();
6437}
6438
6441 const TemplateArgumentList *PartialSpecArgs,
6443 SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
6444 LocalInstantiationScope *StartingScope) {
6445 if (FromVar->isInvalidDecl())
6446 return nullptr;
6447
6448 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
6449 if (Inst.isInvalid())
6450 return nullptr;
6451
6452 // A variable template specialization is never a local declaration, so it
6453 // must not see the locals of whatever instantiation we are currently in.
6455
6456 // Instantiate the first declaration of the variable template: for a partial
6457 // specialization of a static data member template, the first declaration may
6458 // or may not be the declaration in the class; if it's in the class, we want
6459 // to instantiate a member in the class (a declaration), and if it's outside,
6460 // we want to instantiate a definition.
6461 //
6462 // If we're instantiating an explicitly-specialized member template or member
6463 // partial specialization, don't do this. The member specialization completely
6464 // replaces the original declaration in this case.
6465 bool IsMemberSpec = false;
6466 MultiLevelTemplateArgumentList MultiLevelList;
6467 if (auto *PartialSpec =
6468 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
6469 assert(PartialSpecArgs);
6470 IsMemberSpec = PartialSpec->isMemberSpecialization();
6471 MultiLevelList.addOuterTemplateArguments(
6472 PartialSpec, PartialSpecArgs->asArray(), /*Final=*/false);
6473 } else {
6474 assert(VarTemplate == FromVar->getDescribedVarTemplate());
6475 IsMemberSpec = VarTemplate->isMemberSpecialization();
6476 MultiLevelList.addOuterTemplateArguments(VarTemplate, Converted,
6477 /*Final=*/false);
6478 }
6479 if (!IsMemberSpec)
6480 FromVar = FromVar->getFirstDecl();
6481
6482 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
6483 MultiLevelList);
6484
6485 // TODO: Set LateAttrs and StartingScope ...
6486
6487 return Instantiator.VisitVarTemplateSpecializationDecl(VarTemplate, FromVar,
6488 Converted);
6489}
6490
6492 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
6493 const MultiLevelTemplateArgumentList &TemplateArgs) {
6494 assert(PatternDecl->isThisDeclarationADefinition() &&
6495 "don't have a definition to instantiate from");
6496
6497 // Do substitution on the type of the declaration
6498 TypeSourceInfo *TSI =
6499 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
6500 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
6501 if (!TSI)
6502 return nullptr;
6503
6504 // Update the type of this variable template specialization.
6505 VarSpec->setType(TSI->getType());
6506
6507 // Convert the declaration into a definition now.
6508 VarSpec->setCompleteDefinition();
6509
6510 // Instantiate the initializer.
6511 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
6512
6513 if (getLangOpts().OpenCL)
6514 deduceOpenCLAddressSpace(VarSpec);
6515
6516 return VarSpec;
6517}
6518
6520 VarDecl *NewVar, VarDecl *OldVar,
6521 const MultiLevelTemplateArgumentList &TemplateArgs,
6522 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
6523 LocalInstantiationScope *StartingScope,
6524 bool InstantiatingVarTemplate,
6525 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
6526 // Instantiating a partial specialization to produce a partial
6527 // specialization.
6528 bool InstantiatingVarTemplatePartialSpec =
6531 // Instantiating from a variable template (or partial specialization) to
6532 // produce a variable template specialization.
6533 bool InstantiatingSpecFromTemplate =
6535 (OldVar->getDescribedVarTemplate() ||
6537
6538 // If we are instantiating a local extern declaration, the
6539 // instantiation belongs lexically to the containing function.
6540 // If we are instantiating a static data member defined
6541 // out-of-line, the instantiation will have the same lexical
6542 // context (which will be a namespace scope) as the template.
6543 if (OldVar->isLocalExternDecl()) {
6544 NewVar->setLocalExternDecl();
6545 NewVar->setLexicalDeclContext(Owner);
6546 } else if (OldVar->isOutOfLine())
6548 NewVar->setTSCSpec(OldVar->getTSCSpec());
6549 NewVar->setInitStyle(OldVar->getInitStyle());
6550 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
6551 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
6552 NewVar->setConstexpr(OldVar->isConstexpr());
6553 NewVar->setInitCapture(OldVar->isInitCapture());
6556 NewVar->setAccess(OldVar->getAccess());
6557
6558 if (!OldVar->isStaticDataMember()) {
6559 if (OldVar->isUsed(false))
6560 NewVar->setIsUsed();
6561 NewVar->setReferenced(OldVar->isReferenced());
6562 }
6563
6564 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
6565
6567 *this, NewVar->getDeclName(), NewVar->getLocation(),
6572
6573 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
6575 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
6576 // We have a previous declaration. Use that one, so we merge with the
6577 // right type.
6578 if (NamedDecl *NewPrev = FindInstantiatedDecl(
6579 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
6580 Previous.addDecl(NewPrev);
6581 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
6582 OldVar->hasLinkage()) {
6583 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
6584 } else if (PrevDeclForVarTemplateSpecialization) {
6585 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
6586 }
6588
6589 if (!InstantiatingVarTemplate) {
6590 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
6591 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
6592 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
6593 }
6594
6595 if (!OldVar->isOutOfLine()) {
6596 if (NewVar->getDeclContext()->isFunctionOrMethod())
6597 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
6598 }
6599
6600 // Link instantiations of static data members back to the template from
6601 // which they were instantiated.
6602 //
6603 // Don't do this when instantiating a template (we link the template itself
6604 // back in that case) nor when instantiating a static data member template
6605 // (that's not a member specialization).
6606 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
6607 !InstantiatingSpecFromTemplate)
6610
6611 // If the pattern is an (in-class) explicit specialization, then the result
6612 // is also an explicit specialization.
6613 if (VarTemplateSpecializationDecl *OldVTSD =
6614 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
6615 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
6617 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
6619 }
6620
6621 // Forward the mangling number from the template to the instantiated decl.
6622 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
6623 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
6624
6625 // Figure out whether to eagerly instantiate the initializer.
6626 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
6627 // We're producing a template. Don't instantiate the initializer yet.
6628 } else if (NewVar->getType()->isUndeducedType()) {
6629 // We need the type to complete the declaration of the variable.
6630 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
6631 } else if (InstantiatingSpecFromTemplate ||
6632 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
6633 !NewVar->isThisDeclarationADefinition())) {
6634 // Delay instantiation of the initializer for variable template
6635 // specializations or inline static data members until a definition of the
6636 // variable is needed.
6637 } else {
6638 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
6639 }
6640
6641 // Diagnose unused local variables with dependent types, where the diagnostic
6642 // will have been deferred.
6643 if (!NewVar->isInvalidDecl() &&
6644 NewVar->getDeclContext()->isFunctionOrMethod() &&
6645 OldVar->getType()->isDependentType())
6646 DiagnoseUnusedDecl(NewVar);
6647}
6648
6650 VarDecl *Var, VarDecl *OldVar,
6651 const MultiLevelTemplateArgumentList &TemplateArgs) {
6653 L->VariableDefinitionInstantiated(Var);
6654
6655 // We propagate the 'inline' flag with the initializer, because it
6656 // would otherwise imply that the variable is a definition for a
6657 // non-static data member.
6658 if (OldVar->isInlineSpecified())
6659 Var->setInlineSpecified();
6660 else if (OldVar->isInline())
6661 Var->setImplicitlyInline();
6662
6663 ContextRAII SwitchContext(*this, Var->getDeclContext());
6664
6668 currentEvaluationContext().InLifetimeExtendingContext =
6669 parentEvaluationContext().InLifetimeExtendingContext;
6670 currentEvaluationContext().RebuildDefaultArgOrDefaultInit =
6671 parentEvaluationContext().RebuildDefaultArgOrDefaultInit;
6672
6673 // Set DeclForInitializer for this variable so DiagIfReachable can properly
6674 // suppress runtime diagnostics for constexpr/static member variables
6675 currentEvaluationContext().DeclForInitializer = Var;
6676
6677 if (OldVar->getInit()) {
6678 // Instantiate the initializer.
6680 SubstInitializer(OldVar->getInit(), TemplateArgs,
6681 OldVar->getInitStyle() == VarDecl::CallInit);
6682
6683 if (!Init.isInvalid()) {
6684 Expr *InitExpr = Init.get();
6685
6686 if (Var->hasAttr<DLLImportAttr>() &&
6687 (!InitExpr || !InitExpr->isConstantInitializer(getASTContext()))) {
6688 // Do not dynamically initialize dllimport variables.
6689 } else if (InitExpr) {
6690 bool DirectInit = OldVar->isDirectInit();
6691 AddInitializerToDecl(Var, InitExpr, DirectInit);
6692 } else
6694 } else {
6695 // FIXME: Not too happy about invalidating the declaration
6696 // because of a bogus initializer.
6697 Var->setInvalidDecl();
6698 }
6699 } else {
6700 // `inline` variables are a definition and declaration all in one; we won't
6701 // pick up an initializer from anywhere else.
6702 if (Var->isStaticDataMember() && !Var->isInline()) {
6703 if (!Var->isOutOfLine())
6704 return;
6705
6706 // If the declaration inside the class had an initializer, don't add
6707 // another one to the out-of-line definition.
6708 if (OldVar->getFirstDecl()->hasInit())
6709 return;
6710 }
6711
6712 // We'll add an initializer to a for-range declaration later.
6713 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
6714 return;
6715
6717 }
6718
6719 if (getLangOpts().CUDA)
6720 CUDA().checkAllowedInitializer(Var);
6721}
6722
6724 VarDecl *Var, bool Recursive,
6725 bool DefinitionRequired, bool AtEndOfTU) {
6726 if (Var->isInvalidDecl())
6727 return;
6728
6729 // Never instantiate an explicitly-specialized entity.
6732 if (TSK == TSK_ExplicitSpecialization)
6733 return;
6734
6735 RecursiveInstGuard AlreadyInstantiating(*this, Var,
6737 if (AlreadyInstantiating)
6738 return;
6739
6740 // Find the pattern and the arguments to substitute into it.
6741 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
6742 assert(PatternDecl && "no pattern for templated variable");
6743 MultiLevelTemplateArgumentList TemplateArgs =
6745
6747 dyn_cast<VarTemplateSpecializationDecl>(Var);
6748 if (VarSpec) {
6749 // If this is a static data member template, there might be an
6750 // uninstantiated initializer on the declaration. If so, instantiate
6751 // it now.
6752 //
6753 // FIXME: This largely duplicates what we would do below. The difference
6754 // is that along this path we may instantiate an initializer from an
6755 // in-class declaration of the template and instantiate the definition
6756 // from a separate out-of-class definition.
6757 if (PatternDecl->isStaticDataMember() &&
6758 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
6759 !Var->hasInit()) {
6760 // FIXME: Factor out the duplicated instantiation context setup/tear down
6761 // code here.
6762 NonSFINAEContext _(*this);
6763 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
6764 if (Inst.isInvalid())
6765 return;
6767 "instantiating variable initializer");
6768
6769 // The instantiation is visible here, even if it was first declared in an
6770 // unimported module.
6772
6773 // If we're performing recursive template instantiation, create our own
6774 // queue of pending implicit instantiations that we will instantiate
6775 // later, while we're still within our own instantiation context.
6776 GlobalEagerInstantiationScope GlobalInstantiations(
6777 *this,
6778 /*Enabled=*/Recursive, /*AtEndOfTU=*/AtEndOfTU);
6780 LocalEagerInstantiationScope LocalInstantiations(*this,
6781 /*AtEndOfTU=*/AtEndOfTU);
6782
6783 // Enter the scope of this instantiation. We don't use
6784 // PushDeclContext because we don't have a scope.
6785 ContextRAII PreviousContext(*this, Var->getDeclContext());
6786 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
6787 PreviousContext.pop();
6788
6789 // This variable may have local implicit instantiations that need to be
6790 // instantiated within this scope.
6791 LocalInstantiations.perform();
6792 Local.Exit();
6793 GlobalInstantiations.perform();
6794 }
6795 } else {
6796 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
6797 "not a static data member?");
6798 }
6799
6800 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
6801
6802 // If we don't have a definition of the variable template, we won't perform
6803 // any instantiation. Rather, we rely on the user to instantiate this
6804 // definition (or provide a specialization for it) in another translation
6805 // unit.
6806 if (!Def && !DefinitionRequired) {
6808 PendingInstantiations.emplace_back(Var, PointOfInstantiation);
6809 } else if (TSK == TSK_ImplicitInstantiation) {
6810 // Warn about missing definition at the end of translation unit.
6811 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
6812 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
6813 Diag(PointOfInstantiation, diag::warn_var_template_missing)
6814 << Var;
6815 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
6817 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
6818 }
6819 return;
6820 }
6821 }
6822
6823 // FIXME: We need to track the instantiation stack in order to know which
6824 // definitions should be visible within this instantiation.
6825 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
6826 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
6827 /*InstantiatedFromMember*/false,
6828 PatternDecl, Def, TSK,
6829 /*Complain*/DefinitionRequired))
6830 return;
6831
6832 // C++11 [temp.explicit]p10:
6833 // Except for inline functions, const variables of literal types, variables
6834 // of reference types, [...] explicit instantiation declarations
6835 // have the effect of suppressing the implicit instantiation of the entity
6836 // to which they refer.
6837 //
6838 // FIXME: That's not exactly the same as "might be usable in constant
6839 // expressions", which only allows constexpr variables and const integral
6840 // types, not arbitrary const literal types.
6843 return;
6844
6845 // Make sure to pass the instantiated variable to the consumer at the end.
6846 struct PassToConsumerRAII {
6848 VarDecl *Var;
6849
6850 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
6851 : Consumer(Consumer), Var(Var) { }
6852
6853 ~PassToConsumerRAII() {
6854 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
6855 }
6856 } PassToConsumerRAII(Consumer, Var);
6857
6858 // If we already have a definition, we're done.
6859 if (VarDecl *Def = Var->getDefinition()) {
6860 // We may be explicitly instantiating something we've already implicitly
6861 // instantiated.
6863 PointOfInstantiation);
6864 return;
6865 }
6866
6867 NonSFINAEContext _(*this);
6868 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
6869 if (Inst.isInvalid())
6870 return;
6872 "instantiating variable definition");
6873
6874 // If we're performing recursive template instantiation, create our own
6875 // queue of pending implicit instantiations that we will instantiate later,
6876 // while we're still within our own instantiation context.
6877 GlobalEagerInstantiationScope GlobalInstantiations(*this,
6878 /*Enabled=*/Recursive,
6879 /*AtEndOfTU=*/AtEndOfTU);
6880
6881 // Enter the scope of this instantiation. We don't use
6882 // PushDeclContext because we don't have a scope.
6883 ContextRAII PreviousContext(*this, Var->getDeclContext());
6885
6886 LocalEagerInstantiationScope LocalInstantiations(*this,
6887 /*AtEndOfTU=*/AtEndOfTU);
6888
6889 VarDecl *OldVar = Var;
6890 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
6891 // We're instantiating an inline static data member whose definition was
6892 // provided inside the class.
6893 InstantiateVariableInitializer(Var, Def, TemplateArgs);
6894 } else if (!VarSpec) {
6895 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
6896 TemplateArgs));
6897 } else if (Var->isStaticDataMember() &&
6898 Var->getLexicalDeclContext()->isRecord()) {
6899 // We need to instantiate the definition of a static data member template,
6900 // and all we have is the in-class declaration of it. Instantiate a separate
6901 // declaration of the definition.
6902 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
6903 TemplateArgs);
6904
6905 TemplateArgumentListInfo TemplateArgInfo;
6906 if (const ASTTemplateArgumentListInfo *ArgInfo =
6907 VarSpec->getTemplateArgsAsWritten()) {
6908 TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
6909 TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
6910 for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
6911 TemplateArgInfo.addArgument(Arg);
6912 }
6913
6916 VarSpec->getSpecializedTemplate(), Def,
6917 VarSpec->getTemplateArgs().asArray(), VarSpec);
6918 Var = VTSD;
6919
6920 if (Var) {
6921 VTSD->setTemplateArgsAsWritten(TemplateArgInfo);
6922
6923 llvm::PointerUnion<VarTemplateDecl *,
6927 dyn_cast<VarTemplatePartialSpecializationDecl *>(PatternPtr))
6928 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
6929 Partial, &VarSpec->getTemplateInstantiationArgs());
6930
6931 // Attach the initializer.
6932 InstantiateVariableInitializer(Var, Def, TemplateArgs);
6933 }
6934 } else
6935 // Complete the existing variable's definition with an appropriately
6936 // substituted type and initializer.
6937 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
6938
6939 PreviousContext.pop();
6940
6941 if (Var) {
6942 PassToConsumerRAII.Var = Var;
6944 OldVar->getPointOfInstantiation());
6945 // Emit any deferred warnings for the variable's initializer
6946 AnalysisWarnings.issueWarningsForRegisteredVarDecl(Var);
6947 }
6948
6949 // This variable may have local implicit instantiations that need to be
6950 // instantiated within this scope.
6951 LocalInstantiations.perform();
6952 Local.Exit();
6953 GlobalInstantiations.perform();
6954}
6955
6956void
6958 const CXXConstructorDecl *Tmpl,
6959 const MultiLevelTemplateArgumentList &TemplateArgs) {
6960
6962 bool AnyErrors = Tmpl->isInvalidDecl();
6963
6964 // Instantiate all the initializers.
6965 for (const auto *Init : Tmpl->inits()) {
6966 // Only instantiate written initializers, let Sema re-construct implicit
6967 // ones.
6968 if (!Init->isWritten())
6969 continue;
6970
6971 SourceLocation EllipsisLoc;
6972
6973 if (Init->isPackExpansion()) {
6974 // This is a pack expansion. We should expand it now.
6975 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
6977 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
6978 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
6979 bool ShouldExpand = false;
6980 bool RetainExpansion = false;
6981 UnsignedOrNone NumExpansions = std::nullopt;
6983 Init->getEllipsisLoc(), BaseTL.getSourceRange(), Unexpanded,
6984 TemplateArgs, /*FailOnPackProducingTemplates=*/true, ShouldExpand,
6985 RetainExpansion, NumExpansions)) {
6986 AnyErrors = true;
6987 New->setInvalidDecl();
6988 continue;
6989 }
6990 assert(ShouldExpand && "Partial instantiation of base initializer?");
6991
6992 // Loop over all of the arguments in the argument pack(s),
6993 for (unsigned I = 0; I != *NumExpansions; ++I) {
6994 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
6995
6996 // Instantiate the initializer.
6997 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
6998 /*CXXDirectInit=*/true);
6999 if (TempInit.isInvalid()) {
7000 AnyErrors = true;
7001 break;
7002 }
7003
7004 // Instantiate the base type.
7005 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
7006 TemplateArgs,
7007 Init->getSourceLocation(),
7008 New->getDeclName());
7009 if (!BaseTInfo) {
7010 AnyErrors = true;
7011 break;
7012 }
7013
7014 // Build the initializer.
7015 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
7016 BaseTInfo, TempInit.get(),
7017 New->getParent(),
7018 SourceLocation());
7019 if (NewInit.isInvalid()) {
7020 AnyErrors = true;
7021 break;
7022 }
7023
7024 NewInits.push_back(NewInit.get());
7025 }
7026
7027 continue;
7028 }
7029
7030 // Instantiate the initializer.
7031 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
7032 /*CXXDirectInit=*/true);
7033 if (TempInit.isInvalid()) {
7034 AnyErrors = true;
7035 continue;
7036 }
7037
7038 MemInitResult NewInit;
7039 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
7040 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
7041 TemplateArgs,
7042 Init->getSourceLocation(),
7043 New->getDeclName());
7044 if (!TInfo) {
7045 AnyErrors = true;
7046 New->setInvalidDecl();
7047 continue;
7048 }
7049
7050 if (Init->isBaseInitializer())
7051 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
7052 New->getParent(), EllipsisLoc);
7053 else
7054 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
7055 cast<CXXRecordDecl>(CurContext->getParent()));
7056 } else if (Init->isMemberInitializer()) {
7057 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
7058 Init->getMemberLocation(),
7059 Init->getMember(),
7060 TemplateArgs));
7061 if (!Member) {
7062 AnyErrors = true;
7063 New->setInvalidDecl();
7064 continue;
7065 }
7066
7067 NewInit = BuildMemberInitializer(Member, TempInit.get(),
7068 Init->getSourceLocation());
7069 } else if (Init->isIndirectMemberInitializer()) {
7070 IndirectFieldDecl *IndirectMember =
7071 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
7072 Init->getMemberLocation(),
7073 Init->getIndirectMember(), TemplateArgs));
7074
7075 if (!IndirectMember) {
7076 AnyErrors = true;
7077 New->setInvalidDecl();
7078 continue;
7079 }
7080
7081 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
7082 Init->getSourceLocation());
7083 }
7084
7085 if (NewInit.isInvalid()) {
7086 AnyErrors = true;
7087 New->setInvalidDecl();
7088 } else {
7089 NewInits.push_back(NewInit.get());
7090 }
7091 }
7092
7093 // Assign all the initializers to the new constructor.
7095 /*FIXME: ColonLoc */
7097 NewInits,
7098 AnyErrors);
7099}
7100
7101// TODO: this could be templated if the various decl types used the
7102// same method name.
7104 RedeclarableTemplateDecl *Instance) {
7105 Pattern = Pattern->getCanonicalDecl();
7106
7107 do {
7108 Instance = Instance->getCanonicalDecl();
7109 if (Pattern == Instance) return true;
7110 Instance = Instance->getInstantiatedFromMemberTemplate();
7111 } while (Instance);
7112
7113 return false;
7114}
7115
7116static bool
7119 Pattern
7121 do {
7123 Instance->getCanonicalDecl());
7124 if (Pattern == Instance)
7125 return true;
7126 Instance = Instance->getInstantiatedFromMember();
7127 } while (Instance);
7128
7129 return false;
7130}
7131
7133 CXXRecordDecl *Instance) {
7134 Pattern = Pattern->getCanonicalDecl();
7135
7136 do {
7137 Instance = Instance->getCanonicalDecl();
7138 if (Pattern == Instance) return true;
7139 Instance = Instance->getInstantiatedFromMemberClass();
7140 } while (Instance);
7141
7142 return false;
7143}
7144
7145static bool isInstantiationOf(FunctionDecl *Pattern,
7146 FunctionDecl *Instance) {
7147 Pattern = Pattern->getCanonicalDecl();
7148
7149 do {
7150 Instance = Instance->getCanonicalDecl();
7151 if (Pattern == Instance) return true;
7152 Instance = Instance->getInstantiatedFromMemberFunction();
7153 } while (Instance);
7154
7155 return false;
7156}
7157
7158static bool isInstantiationOf(EnumDecl *Pattern,
7159 EnumDecl *Instance) {
7160 Pattern = Pattern->getCanonicalDecl();
7161
7162 do {
7163 Instance = Instance->getCanonicalDecl();
7164 if (Pattern == Instance) return true;
7165 Instance = Instance->getInstantiatedFromMemberEnum();
7166 } while (Instance);
7167
7168 return false;
7169}
7170
7172 UsingShadowDecl *Instance,
7173 ASTContext &C) {
7174 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
7175 Pattern);
7176}
7177
7178static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
7179 ASTContext &C) {
7180 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
7181}
7182
7183template<typename T>
7185 ASTContext &Ctx) {
7186 // An unresolved using declaration can instantiate to an unresolved using
7187 // declaration, or to a using declaration or a using declaration pack.
7188 //
7189 // Multiple declarations can claim to be instantiated from an unresolved
7190 // using declaration if it's a pack expansion. We want the UsingPackDecl
7191 // in that case, not the individual UsingDecls within the pack.
7192 bool OtherIsPackExpansion;
7193 NamedDecl *OtherFrom;
7194 if (auto *OtherUUD = dyn_cast<T>(Other)) {
7195 OtherIsPackExpansion = OtherUUD->isPackExpansion();
7196 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
7197 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
7198 OtherIsPackExpansion = true;
7199 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
7200 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
7201 OtherIsPackExpansion = false;
7202 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
7203 } else {
7204 return false;
7205 }
7206 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
7207 declaresSameEntity(OtherFrom, Pattern);
7208}
7209
7211 VarDecl *Instance) {
7212 assert(Instance->isStaticDataMember());
7213
7214 Pattern = Pattern->getCanonicalDecl();
7215
7216 do {
7217 Instance = Instance->getCanonicalDecl();
7218 if (Pattern == Instance) return true;
7219 Instance = Instance->getInstantiatedFromStaticDataMember();
7220 } while (Instance);
7221
7222 return false;
7223}
7224
7225// Other is the prospective instantiation
7226// D is the prospective pattern
7228 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
7230
7231 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
7233
7234 if (D->getKind() != Other->getKind())
7235 return false;
7236
7237 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
7239
7240 if (auto *Function = dyn_cast<FunctionDecl>(Other))
7241 return isInstantiationOf(cast<FunctionDecl>(D), Function);
7242
7243 if (auto *Enum = dyn_cast<EnumDecl>(Other))
7245
7246 if (auto *Var = dyn_cast<VarDecl>(Other))
7247 if (Var->isStaticDataMember())
7249
7250 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
7252
7253 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
7255
7256 if (auto *PartialSpec =
7257 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
7259 PartialSpec);
7260
7261 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
7262 if (!Field->getDeclName()) {
7263 // This is an unnamed field.
7265 cast<FieldDecl>(D));
7266 }
7267 }
7268
7269 if (auto *Using = dyn_cast<UsingDecl>(Other))
7270 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
7271
7272 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
7273 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
7274
7275 return D->getDeclName() &&
7276 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
7277}
7278
7279template<typename ForwardIterator>
7281 NamedDecl *D,
7282 ForwardIterator first,
7283 ForwardIterator last) {
7284 for (; first != last; ++first)
7285 if (isInstantiationOf(Ctx, D, *first))
7286 return cast<NamedDecl>(*first);
7287
7288 return nullptr;
7289}
7290
7292 const MultiLevelTemplateArgumentList &TemplateArgs) {
7293 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
7294 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
7295 return cast_or_null<DeclContext>(ID);
7296 } else return DC;
7297}
7298
7299/// Determine whether the given context is dependent on template parameters at
7300/// level \p Level or below.
7301///
7302/// Sometimes we only substitute an inner set of template arguments and leave
7303/// the outer templates alone. In such cases, contexts dependent only on the
7304/// outer levels are not effectively dependent.
7305static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
7306 if (!DC->isDependentContext())
7307 return false;
7308 if (!Level)
7309 return true;
7310 return cast<Decl>(DC)->getTemplateDepth() > Level;
7311}
7312
7314 const MultiLevelTemplateArgumentList &TemplateArgs,
7315 bool FindingInstantiatedContext) {
7316 DeclContext *ParentDC = D->getDeclContext();
7317 // Determine whether our parent context depends on any of the template
7318 // arguments we're currently substituting.
7319 bool ParentDependsOnArgs = isDependentContextAtLevel(
7320 ParentDC, TemplateArgs.getNumRetainedOuterLevels());
7321 // FIXME: Parameters of pointer to functions (y below) that are themselves
7322 // parameters (p below) can have their ParentDC set to the translation-unit
7323 // - thus we can not consistently check if the ParentDC of such a parameter
7324 // is Dependent or/and a FunctionOrMethod.
7325 // For e.g. this code, during Template argument deduction tries to
7326 // find an instantiated decl for (T y) when the ParentDC for y is
7327 // the translation unit.
7328 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
7329 // float baz(float(*)()) { return 0.0; }
7330 // Foo(baz);
7331 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
7332 // it gets here, always has a FunctionOrMethod as its ParentDC??
7333 // For now:
7334 // - as long as we have a ParmVarDecl whose parent is non-dependent and
7335 // whose type is not instantiation dependent, do nothing to the decl
7336 // - otherwise find its instantiated decl.
7337 if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
7338 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
7339 return D;
7342 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
7343 isa<OMPDeclareReductionDecl>(ParentDC) ||
7344 isa<OMPDeclareMapperDecl>(ParentDC))) ||
7345 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
7346 cast<CXXRecordDecl>(D)->getTemplateDepth() >
7347 TemplateArgs.getNumRetainedOuterLevels())) {
7348 // D is a local of some kind. Look into the map of local
7349 // declarations to their instantiations.
7351 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
7352 if (Decl *FD = dyn_cast<Decl *>(*Found)) {
7353 if (auto *BD = dyn_cast<BindingDecl>(FD);
7354 BD && BD->isParameterPack() && ArgPackSubstIndex) {
7355 return BD->getBindingPackDecls()[*ArgPackSubstIndex];
7356 }
7357 return cast<NamedDecl>(FD);
7358 }
7359
7360 assert(ArgPackSubstIndex &&
7361 "found declaration pack but not pack expanding");
7362 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
7363 return cast<NamedDecl>(
7365 }
7366 }
7367
7368 // If we're performing a partial substitution during template argument
7369 // deduction, we may not have values for template parameters yet. They
7370 // just map to themselves.
7373 return D;
7374
7375 if (D->isInvalidDecl())
7376 return nullptr;
7377
7378 // Normally this function only searches for already instantiated declaration
7379 // however we have to make an exclusion for local types used before
7380 // definition as in the code:
7381 //
7382 // template<typename T> void f1() {
7383 // void g1(struct x1);
7384 // struct x1 {};
7385 // }
7386 //
7387 // In this case instantiation of the type of 'g1' requires definition of
7388 // 'x1', which is defined later. Error recovery may produce an enum used
7389 // before definition. In these cases we need to instantiate relevant
7390 // declarations here.
7391 bool NeedInstantiate = false;
7392 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
7393 NeedInstantiate = RD->isLocalClass();
7394 else if (isa<TypedefNameDecl>(D) &&
7396 NeedInstantiate = true;
7397 else
7398 NeedInstantiate = isa<EnumDecl>(D);
7399 if (NeedInstantiate) {
7400 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
7401 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
7402 return cast<TypeDecl>(Inst);
7403 }
7404
7405 // If we didn't find the decl, then we must have a label decl that hasn't
7406 // been found yet. Lazily instantiate it and return it now.
7407 assert(isa<LabelDecl>(D));
7408
7409 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
7410 assert(Inst && "Failed to instantiate label??");
7411
7412 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
7413 return cast<LabelDecl>(Inst);
7414 }
7415
7416 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
7417 if (!Record->isDependentContext())
7418 return D;
7419
7420 // Determine whether this record is the "templated" declaration describing
7421 // a class template or class template specialization.
7422 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
7423 if (ClassTemplate)
7424 ClassTemplate = ClassTemplate->getCanonicalDecl();
7425 else if (ClassTemplateSpecializationDecl *Spec =
7426 dyn_cast<ClassTemplateSpecializationDecl>(Record))
7427 ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl();
7428
7429 // Walk the current context to find either the record or an instantiation of
7430 // it.
7431 DeclContext *DC = CurContext;
7432 while (!DC->isFileContext()) {
7433 // If we're performing substitution while we're inside the template
7434 // definition, we'll find our own context. We're done.
7435 if (DC->Equals(Record))
7436 return Record;
7437
7438 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
7439 // Check whether we're in the process of instantiating a class template
7440 // specialization of the template we're mapping.
7442 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
7443 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
7444 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
7445 return InstRecord;
7446 }
7447
7448 // Check whether we're in the process of instantiating a member class.
7449 if (isInstantiationOf(Record, InstRecord))
7450 return InstRecord;
7451 }
7452
7453 // Move to the outer template scope.
7454 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
7455 if (FD->getFriendObjectKind() &&
7457 DC = FD->getLexicalDeclContext();
7458 continue;
7459 }
7460 // An implicit deduction guide acts as if it's within the class template
7461 // specialization described by its name and first N template params.
7462 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
7463 if (Guide && Guide->isImplicit()) {
7464 TemplateDecl *TD = Guide->getDeducedTemplate();
7465 // Convert the arguments to an "as-written" list.
7466 TemplateArgumentListInfo Args(Loc, Loc);
7467 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
7468 TD->getTemplateParameters()->size())) {
7469 ArrayRef<TemplateArgument> Unpacked(Arg);
7470 if (Arg.getKind() == TemplateArgument::Pack)
7471 Unpacked = Arg.pack_elements();
7472 for (TemplateArgument UnpackedArg : Unpacked)
7473 Args.addArgument(
7474 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
7475 }
7478 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
7479 // We may get a non-null type with errors, in which case
7480 // `getAsCXXRecordDecl` will return `nullptr`. For instance, this
7481 // happens when one of the template arguments is an invalid
7482 // expression. We return early to avoid triggering the assertion
7483 // about the `CodeSynthesisContext`.
7484 if (T.isNull() || T->containsErrors())
7485 return nullptr;
7486 CXXRecordDecl *SubstRecord = T->getAsCXXRecordDecl();
7487
7488 if (!SubstRecord) {
7489 // T can be a dependent TemplateSpecializationType when performing a
7490 // substitution for building a deduction guide or for template
7491 // argument deduction in the process of rebuilding immediate
7492 // expressions. (Because the default argument that involves a lambda
7493 // is untransformed and thus could be dependent at this point.)
7494 assert(SemaRef.RebuildingImmediateInvocation ||
7495 CodeSynthesisContexts.back().Kind ==
7497 // Return a nullptr as a sentinel value, we handle it properly in
7498 // the TemplateInstantiator::TransformInjectedClassNameType
7499 // override, which we transform it to a TemplateSpecializationType.
7500 return nullptr;
7501 }
7502 // Check that this template-id names the primary template and not a
7503 // partial or explicit specialization. (In the latter cases, it's
7504 // meaningless to attempt to find an instantiation of D within the
7505 // specialization.)
7506 // FIXME: The standard doesn't say what should happen here.
7507 if (FindingInstantiatedContext &&
7509 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
7510 Diag(Loc, diag::err_specialization_not_primary_template)
7511 << T << (SubstRecord->getTemplateSpecializationKind() ==
7513 return nullptr;
7514 }
7515 DC = SubstRecord;
7516 continue;
7517 }
7518 }
7519
7520 DC = DC->getParent();
7521 }
7522
7523 // Fall through to deal with other dependent record types (e.g.,
7524 // anonymous unions in class templates).
7525 }
7526
7528 if (auto Found = CurrentInstantiationScope->getInstantiationOfIfExists(D))
7529 if (auto *FD = dyn_cast<NamedDecl>(cast<Decl *>(*Found)))
7530 return FD;
7531 }
7532
7533 if (!ParentDependsOnArgs)
7534 return D;
7535
7536 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
7537 if (!ParentDC)
7538 return nullptr;
7539
7540 if (ParentDC != D->getDeclContext()) {
7541 // We performed some kind of instantiation in the parent context,
7542 // so now we need to look into the instantiated parent context to
7543 // find the instantiation of the declaration D.
7544
7545 // If our context used to be dependent, we may need to instantiate
7546 // it before performing lookup into that context.
7547 bool IsBeingInstantiated = false;
7548 if (auto *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
7549 if (!Spec->isDependentContext()) {
7550 if (Spec->isEntityBeingDefined())
7551 IsBeingInstantiated = true;
7552 else if (RequireCompleteType(Loc, Context.getCanonicalTagType(Spec),
7553 diag::err_incomplete_type))
7554 return nullptr;
7555
7556 ParentDC = Spec->getDefinitionOrSelf();
7557 }
7558 }
7559
7560 NamedDecl *Result = nullptr;
7561 // FIXME: If the name is a dependent name, this lookup won't necessarily
7562 // find it. Does that ever matter?
7563 if (auto Name = D->getDeclName()) {
7564 DeclarationNameInfo NameInfo(Name, D->getLocation());
7565 DeclarationNameInfo NewNameInfo =
7566 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
7567 Name = NewNameInfo.getName();
7568 if (!Name)
7569 return nullptr;
7570 DeclContext::lookup_result Found = ParentDC->lookup(Name);
7571
7572 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
7573 } else {
7574 // Since we don't have a name for the entity we're looking for,
7575 // our only option is to walk through all of the declarations to
7576 // find that name. This will occur in a few cases:
7577 //
7578 // - anonymous struct/union within a template
7579 // - unnamed class/struct/union/enum within a template
7580 //
7581 // FIXME: Find a better way to find these instantiations!
7583 ParentDC->decls_begin(),
7584 ParentDC->decls_end());
7585 }
7586
7587 if (!Result) {
7588 if (isa<UsingShadowDecl>(D)) {
7589 // UsingShadowDecls can instantiate to nothing because of using hiding.
7590 } else if (hasUncompilableErrorOccurred()) {
7591 // We've already complained about some ill-formed code, so most likely
7592 // this declaration failed to instantiate. There's no point in
7593 // complaining further, since this is normal in invalid code.
7594 // FIXME: Use more fine-grained 'invalid' tracking for this.
7595 } else if (IsBeingInstantiated) {
7596 // The class in which this member exists is currently being
7597 // instantiated, and we haven't gotten around to instantiating this
7598 // member yet. This can happen when the code uses forward declarations
7599 // of member classes, and introduces ordering dependencies via
7600 // template instantiation.
7601 Diag(Loc, diag::err_member_not_yet_instantiated)
7602 << D->getDeclName()
7603 << Context.getCanonicalTagType(cast<CXXRecordDecl>(ParentDC));
7604 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
7605 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
7606 // This enumeration constant was found when the template was defined,
7607 // but can't be found in the instantiation. This can happen if an
7608 // unscoped enumeration member is explicitly specialized.
7609 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
7611 TemplateArgs));
7612 assert(Spec->getTemplateSpecializationKind() ==
7614 Diag(Loc, diag::err_enumerator_does_not_exist)
7615 << D->getDeclName()
7616 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
7617 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
7618 << Context.getCanonicalTagType(Spec);
7619 } else {
7620 // We should have found something, but didn't.
7621 llvm_unreachable("Unable to find instantiation of declaration!");
7622 }
7623 }
7624
7625 D = Result;
7626 }
7627
7628 return D;
7629}
7630
7631void Sema::PerformPendingInstantiations(bool LocalOnly, bool AtEndOfTU) {
7632 std::deque<PendingImplicitInstantiation> DelayedImplicitInstantiations;
7633 while (!PendingLocalImplicitInstantiations.empty() ||
7634 (!LocalOnly && !PendingInstantiations.empty())) {
7636
7637 bool LocalInstantiation = false;
7639 Inst = PendingInstantiations.front();
7640 PendingInstantiations.pop_front();
7641 } else {
7644 LocalInstantiation = true;
7645 }
7646
7647 // Instantiate function definitions
7648 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
7649 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
7651 if (Function->isMultiVersion()) {
7652 getASTContext().forEachMultiversionedFunctionVersion(
7653 Function,
7654 [this, Inst, DefinitionRequired, AtEndOfTU](FunctionDecl *CurFD) {
7655 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
7656 DefinitionRequired, AtEndOfTU);
7657 if (CurFD->isDefined())
7658 CurFD->setInstantiationIsPending(false);
7659 });
7660 } else {
7661 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
7662 DefinitionRequired, AtEndOfTU);
7663 if (Function->isDefined())
7664 Function->setInstantiationIsPending(false);
7665 }
7666 // Definition of a PCH-ed template declaration may be available only in the TU.
7667 if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
7668 TUKind == TU_Prefix && Function->instantiationIsPending())
7669 DelayedImplicitInstantiations.push_back(Inst);
7670 else if (!AtEndOfTU && Function->instantiationIsPending() &&
7671 !LocalInstantiation)
7672 DelayedImplicitInstantiations.push_back(Inst);
7673 continue;
7674 }
7675
7676 // Instantiate variable definitions
7677 VarDecl *Var = cast<VarDecl>(Inst.first);
7678
7679 assert((Var->isStaticDataMember() ||
7681 "Not a static data member, nor a variable template"
7682 " specialization?");
7683
7684 // Don't try to instantiate declarations if the most recent redeclaration
7685 // is invalid.
7686 if (Var->getMostRecentDecl()->isInvalidDecl())
7687 continue;
7688
7689 // Check if the most recent declaration has changed the specialization kind
7690 // and removed the need for implicit instantiation.
7691 switch (Var->getMostRecentDecl()
7693 case TSK_Undeclared:
7694 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
7697 continue; // No longer need to instantiate this type.
7699 // We only need an instantiation if the pending instantiation *is* the
7700 // explicit instantiation.
7701 if (Var != Var->getMostRecentDecl())
7702 continue;
7703 break;
7705 break;
7706 }
7707
7709 "instantiating variable definition");
7710 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
7712
7713 // Instantiate static data member definitions or variable template
7714 // specializations.
7715 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
7716 DefinitionRequired, AtEndOfTU);
7717 }
7718
7719 if (!DelayedImplicitInstantiations.empty())
7720 PendingInstantiations.swap(DelayedImplicitInstantiations);
7721}
7722
7724 const MultiLevelTemplateArgumentList &TemplateArgs) {
7725 for (auto *DD : Pattern->ddiags()) {
7726 switch (DD->getKind()) {
7728 HandleDependentAccessCheck(*DD, TemplateArgs);
7729 break;
7730 }
7731 }
7732}
Defines the clang::ASTContext interface.
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:187
This file declares semantic analysis for CUDA constructs.
static const NamedDecl * getDefinition(const Decl *D)
This file declares semantic analysis for HLSL constructs.
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 instantiateDependentCUDAClusterDimsAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const CUDAClusterDimsAttr &Attr, Decl *New)
static void sharedInstantiateConstructorDestructorAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const Attr *A, Decl *New, ASTContext &C)
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 std::optional< SubstitutedFriend > SubstFriendTemplateType(Sema &SemaRef, TypeSourceInfo *TSI, TemplateName FriendTemplate, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity)
static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A)
Determine whether the attribute A might be relevant to the declaration D.
static std::optional< TemplateName > LookupFriendTemplateName(Sema &SemaRef, NestedNameSpecifierLoc QualifierLoc, DeclarationName Name, SourceLocation NameLoc, bool HasTemplateKeyword, bool RequireClassTemplate)
static void instantiateDependentReqdWorkGroupSizeAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const ReqdWorkGroupSizeAttr &Attr, Decl *New)
#define CLAUSE_NOT_ON_DECLS(CLAUSE_NAME)
static void instantiateDependentMallocSpanAttr(Sema &S, const MallocSpanAttr *Attr, Decl *New)
static void instantiateAttrOnDecl(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const Attr *TmplAttr, Decl *New)
Instantiate TmplAttr for New in the current instantiation scope and attach it, if it is still valid t...
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 void instantiateDependentHLSLParamModifierAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const HLSLParamModifierAttr *Attr, const Decl *Old, Decl *New)
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 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 bool isInstantiationOf(RedeclarableTemplateDecl *Pattern, RedeclarableTemplateDecl *Instance)
static void instantiateDependentAnnotationAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AnnotateAttr *Attr, Decl *New)
static Sema::RetainOwnershipKind attrToRetainOwnershipKind(const Attr *A)
static void instantiateDependentOpenACCRoutineDeclAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const OpenACCRoutineDeclAttr *OldAttr, const Decl *Old, Decl *New)
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.
bool anyScoreOrCondition(llvm::function_ref< bool(Expr *&, bool)> Cond)
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:35
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:246
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:866
TemplateName getDependentTemplateName(const DependentTemplateStorage &Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template operat...
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
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
CanQualType UnsignedLongLongTy
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
CanQualType getCanonicalTagType(const TagDecl *TD) const
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
SourceLocation getColonLoc() const
The location of the colon following the access specifier.
Definition DeclCXX.h:108
SourceLocation getAccessSpecifierLoc() const
The location of the access specifier.
Definition DeclCXX.h:102
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Attr - This represents one attribute.
Definition Attr.h:47
attr::Kind getKind() const
Definition Attr.h:93
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition Attr.h:100
SourceLocation getLoc() const
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3543
shadow_range shadows() const
Definition DeclCXX.h:3609
A binding in a decomposition declaration.
Definition DeclCXX.h:4232
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T)
Definition DeclCXX.cpp:3707
ArrayRef< BindingDecl * > getBindingPackDecls() const
Definition DeclCXX.cpp:3731
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:2645
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(), const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3018
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2994
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3283
Represents a C++ deduction guide declaration.
Definition DeclCXX.h:2001
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, const AssociatedConstraint &TrailingRequiresClause={}, const CXXDeductionGuideDecl *SourceDG=nullptr, SourceDeductionGuideKind SK=SourceDeductionGuideKind::None)
Definition DeclCXX.cpp:2383
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3158
Represents a C++26 expansion statement declaration.
CXXExpansionStmtPattern * getExpansionPattern()
CXXExpansionStmtInstantiation * getInstantiations()
void setInstantiations(CXXExpansionStmtInstantiation *S)
NonTypeTemplateParmDecl * getIndexTemplateParm()
void setExpansionPattern(CXXExpansionStmtPattern *S)
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2504
bool isStatic() const
Definition DeclCXX.cpp:2417
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1681
unsigned getLambdaDependencyKind() const
Definition DeclCXX.h:1879
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1578
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1028
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, unsigned DependencyKind, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
Definition DeclCXX.cpp:142
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2062
TypeSourceInfo * getLambdaTypeInfo() const
Definition DeclCXX.h:1885
void setInstantiationOfMemberClass(CXXRecordDecl *RD, TemplateSpecializationKind TSK)
Specify that this record is an instantiation of the member class RD.
Definition DeclCXX.cpp:2045
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2154
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition DeclCXX.h:1069
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2058
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:523
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Declaration of a class template.
ClassTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, TemplateParameterList *TPL, llvm::FoldingSetInsertToken &InsertToken)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
ClassTemplateDecl * getMostRecentDecl()
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
llvm::FoldingSetVector< ClassTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
ClassTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, llvm::FoldingSetInsertToken &InsertToken)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
ClassTemplatePartialSpecializationDecl * findPartialSpecInstantiatedFromMember(ClassTemplatePartialSpecializationDecl *D)
Find a class template partial specialization which was instantiated from the given member partial spe...
void AddSpecialization(ClassTemplateSpecializationDecl *D, llvm::FoldingSetInsertToken InsertToken)
Insert the specified specialization knowing that it is not already in.
void setCommonPtr(Common *C)
void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D, llvm::FoldingSetInsertToken InsertToken)
Insert the specified partial specialization knowing that it is not already in.
Common * getCommonPtr() const
void setInstantiatedFromMember(ClassTemplatePartialSpecializationDecl *PartialSpec)
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, CanQualType CanonInjectedTST, 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.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, bool StrictPackMatch, ClassTemplateSpecializationDecl *PrevDecl)
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)
SourceLocation getExternKeywordLoc() const
Gets the location of the extern keyword, if present.
SourceLocation getTemplateKeywordLoc() const
Gets the location of the template keyword, if present.
void setTemplateKeywordLoc(SourceLocation Loc)
Sets the location of the template keyword.
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:433
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition DeclCXX.h:3724
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2110
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2263
bool isFileContext() const
Definition DeclBase.h:2201
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2611
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isRecord() const
Definition DeclBase.h:2210
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
decl_iterator decls_end() const
Definition DeclBase.h:2409
ddiag_range ddiags() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2407
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2165
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
decl_iterator decls_begin() const
Decl * getSingleDecl()
Definition DeclGroup.h:72
bool isNull() const
Definition DeclGroup.h:68
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:498
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:1079
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:444
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1244
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition DeclBase.h:1169
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:101
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:911
@ FOK_None
Not a friend object.
Definition DeclBase.h:1235
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:612
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition DeclBase.cpp:320
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:1198
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition DeclBase.h:806
bool isInLocalScopeForInstantiation() const
Determine whether a substitution into this declaration would occur as part of a substitution into a d...
Definition DeclBase.cpp:426
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
bool isInvalidDecl() const
Definition DeclBase.h:597
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1187
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:568
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:511
SourceLocation getLocation() const
Definition DeclBase.h:448
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
void setImplicit(bool I=true)
Definition DeclBase.h:603
void setReferenced(bool R=true)
Definition DeclBase.h:632
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition DeclBase.h:617
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:587
DeclContext * getDeclContext()
Definition DeclBase.h:457
attr_range attrs() const
Definition DeclBase.h:544
AccessSpecifier getAccess() const
Definition DeclBase.h:516
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:440
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:936
bool hasAttr() const
Definition DeclBase.h:586
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1253
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
Kind getKind() const
Definition DeclBase.h:451
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:883
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeNamedTypeLoc(TypeSourceInfo *TInfo)
Construct location information for a constructor, destructor or conversion operator.
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:782
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:824
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2007
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:833
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:857
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:816
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
Definition Decl.h:864
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition Decl.h:847
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:839
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:811
A decomposition declaration.
Definition DeclCXX.h:4296
ArrayRef< BindingDecl * > bindings() const
Definition DeclCXX.h:4336
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, SourceLocation RSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3742
Provides information about a dependent function-template specialization declaration.
RAII object that enters a new function expression evaluation context.
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:3604
Represents an enum.
Definition Decl.h:4192
enumerator_range enumerators() const
Definition Decl.h:4338
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4410
bool isScopedUsingClassTag() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4413
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5185
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition Decl.h:4381
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4419
EnumDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.h:4282
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4365
EnumDecl * getDefinition() const
Definition Decl.h:4304
TemplateSpecializationKind getTemplateSpecializationKind() const
If this enumeration is a member of a specialization of a templated class, determine what kind of temp...
Definition Decl.cpp:5232
Represents an explicit instantiation of a template entity in source code.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1949
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1957
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition DeclCXX.h:1978
static ExplicitSpecifier Invalid()
Definition DeclCXX.h:1986
const Expr * getExpr() const
Definition DeclCXX.h:1958
static ExplicitSpecifier getFromDecl(const FunctionDecl *Function)
Definition DeclCXX.cpp:2370
This represents one expression.
Definition Expr.h:114
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:179
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
bool isConstantInitializer(ASTContext &Ctx, bool ForRef=false, const Expr **Culprit=nullptr) const
Returns true if this expression can be emitted to IR as a constant, and thus can be used as a constan...
Definition Expr.cpp:3387
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:249
Abstract interface for external sources of AST nodes.
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3341
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition Decl.h:3441
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3515
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3457
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:46
llvm::PointerUnion< NamedDecl *, TypeSourceInfo * > FriendUnion
Definition DeclFriend.h:50
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
SourceLocation getFriendLoc() const
Definition DeclFriend.h:109
SourceLocation getEllipsisLoc() const
Retrieves the location of the '...', if present.
Definition DeclFriend.h:107
virtual NamedDecl * getFriendDecl() const
If this friend declaration doesn't name a type, return the inner declaration.
Definition DeclFriend.h:102
TypeSourceInfo * getFriendType() const
If this friend declaration names an (untemplated but possibly dependent) type, return the type; other...
Definition DeclFriend.h:96
bool isPackExpansion() const
Definition DeclFriend.h:113
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend, SourceLocation FriendL, SourceLocation EllipsisLoc={})
Declaration of a friend template.
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, FriendUnion Friend, SourceLocation FriendLoc, ArrayRef< TemplateParameterList * > FriendTPLists, SourceLocation EllipsisLoc={}, TemplateName Template={})
NamedDecl * getFriendDecl() const override
If this friend declaration doesn't name a type, return the inner declaration.
TemplateName getFriendTemplateName() const
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
CXXSpecialMemberKind asSpecialMember() const
Definition Decl.h:2188
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, FPOptionsOverride FPFeatures, StringLiteral *DeletedMessage=nullptr)
Definition Decl.cpp:3146
Represents a function declaration or definition.
Definition Decl.h:2082
void setInstantiationIsPending(bool IC)
State that the instantiation of this function is pending.
Definition Decl.h:2682
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2345
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2974
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3287
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2645
DefaultedOrDeletedFunctionInfo * getDefaultedOrDeletedInfo() const
Definition Decl.cpp:3202
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4271
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2470
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3627
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition Decl.h:2931
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3098
bool UsesFPIntrin() const
Determine whether the function was declared in source context that requires constrained FP intrinsics...
Definition Decl.h:3086
QualType getReturnType() const
Definition Decl.h:3022
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2947
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:4342
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2558
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2617
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3823
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition Decl.cpp:4467
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2709
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:3065
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4625
bool FriendConstraintRefersToEnclosingTemplate() const
Definition Decl.h:2880
bool isDeletedAsWritten() const
Definition Decl.h:2713
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2522
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2526
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2852
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2438
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3635
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3231
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2554
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4648
DefaultedFunctionKind getDefaultedFunctionKind() const
Determine the kind of defaulting that would be done for a given function.
Definition Decl.cpp:3307
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2513
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3902
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2367
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3207
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:3254
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition Decl.h:3076
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2858
const ASTTemplateArgumentListInfo * getTemplateSpecializationArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
Definition Decl.cpp:4417
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5650
param_type_iterator param_type_begin() const
Definition TypeBase.h:6094
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5957
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5963
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5939
FunctionDecl * getExceptionSpecTemplate() const
If this function type has an uninstantiated exception specification, this is the function whose excep...
Definition TypeBase.h:6036
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5935
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
void setInstantiatedFromMemberTemplate(FunctionTemplateDecl *D)
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:1753
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1754
ExtInfo getExtInfo() const
Definition TypeBase.h:5202
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:5194
QualType getReturnType() const
Definition TypeBase.h:5186
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
Definition Decl.h:5381
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:3648
unsigned getChainingSize() const
Definition Decl.h:3673
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5853
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3669
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2616
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
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:985
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3716
Represents the declaration of a label.
Definition Decl.h:526
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
Definition Decl.cpp:5665
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:377
SmallVector< ValueDecl *, 4 > DeclArgumentPack
A set of declarations.
Definition Template.h:380
static void deleteScopes(LocalInstantiationScope *Scope, LocalInstantiationScope *Outermost)
deletes the given scope, and all outer scopes, down to the given outermost scope.
Definition Template.h:517
void InstantiatedLocal(const Decl *D, Decl *Inst)
void InstantiatedLocalPackArg(const Decl *D, VarDecl *Inst)
Represents the results of name lookup.
Definition Lookup.h:147
A global _GUID constant.
Definition DeclCXX.h:4468
An instance of this class represents the declaration of a property member.
Definition DeclCXX.h:4414
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition DeclCXX.cpp:3839
IdentifierInfo * getGetterId() const
Definition DeclCXX.h:4436
IdentifierInfo * getSetterId() const
Definition DeclCXX.h:4438
Provides information a specialization of a member of a class template, which may be a member function...
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:277
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:218
void setKind(TemplateSubstitutionKind K)
Definition Template.h:111
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:272
unsigned getNumRetainedOuterLevels() const
Definition Template.h:145
This represents a decl that may have a name.
Definition Decl.h:276
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1947
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:399
Represents a C++ namespace alias.
Definition DeclCXX.h:3248
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name of the namespace, with source-location inf...
Definition DeclCXX.h:3309
SourceLocation getAliasLoc() const
Returns the location of the alias name, i.e.
Definition DeclCXX.h:3331
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamespaceBaseDecl *Namespace)
Definition DeclCXX.cpp:3414
SourceLocation getNamespaceLoc() const
Returns the location of the namespace keyword.
Definition DeclCXX.h:3334
SourceLocation getTargetNameLoc() const
Returns the location of the identifier in the named namespace.
Definition DeclCXX.h:3337
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition DeclCXX.h:3318
Represent a C++ namespace.
Definition Decl.h:594
A C++ nested-name-specifier augmented with source location information.
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
bool hasQualifier() const
Evaluates true when this nested-name-specifier location is non-empty.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, int D, int P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool defaultArgumentWasInherited() const
Determines whether the default argument was inherited from a previous declaration of this template.
TypeSourceInfo * getExpansionTypeSourceInfo(unsigned I) const
Retrieve a particular expansion type source info within an expanded parameter pack.
unsigned getNumExpansionTypes() const
Retrieves the number of expansion types in an expanded parameter pack.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Expr * getPlaceholderTypeConstraint() const
Return the constraint introduced by the placeholder type of this non-type template parameter (if any)...
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
Describes the source-level contents of one OpenMP 'adjust_args' clause.
This represents 'pragma omp allocate ...' directive.
Definition DeclOpenMP.h:536
clauselist_range clauselists()
Definition DeclOpenMP.h:589
varlist_range varlist()
Definition DeclOpenMP.h:578
Pseudo declaration for capturing expressions.
Definition DeclOpenMP.h:445
This represents 'pragma omp declare mapper ...' directive.
Definition DeclOpenMP.h:349
OMPDeclareMapperDecl * getPrevDeclInScope()
Get reference to previous declare mapper construct in the same scope with the same name.
clauselist_iterator clauselist_begin()
Definition DeclOpenMP.h:401
clauselist_range clauselists()
Definition DeclOpenMP.h:395
DeclarationName getVarName()
Get the name of the variable declared in the mapper.
Definition DeclOpenMP.h:421
Expr * getMapperVarRef()
Get the variable declared in the mapper.
Definition DeclOpenMP.h:411
This represents 'pragma omp declare reduction ...' directive.
Definition DeclOpenMP.h:239
Expr * getInitializer()
Get initializer expression (if specified) of the declare reduction construct.
Definition DeclOpenMP.h:300
Expr * getInitPriv()
Get Priv variable of the initializer.
Definition DeclOpenMP.h:311
Expr * getCombinerOut()
Get Out variable of the combiner.
Definition DeclOpenMP.h:288
Expr * getCombinerIn()
Get In variable of the combiner.
Definition DeclOpenMP.h:285
Expr * getCombiner()
Get combiner expression of the declare reduction construct.
Definition DeclOpenMP.h:282
OMPDeclareReductionDecl * getPrevDeclInScope()
Get reference to previous declare reduction construct in the same scope with the same name.
Expr * getInitOrig()
Get Orig variable of the initializer.
Definition DeclOpenMP.h:308
OMPDeclareReductionInitKind getInitializerKind() const
Get initializer kind.
Definition DeclOpenMP.h:303
This represents 'pragma omp groupprivate ...' directive.
Definition DeclOpenMP.h:173
varlist_range varlist()
Definition DeclOpenMP.h:208
This represents 'pragma omp requires...' directive.
Definition DeclOpenMP.h:479
This represents 'pragma omp threadprivate ...' directive.
Definition DeclOpenMP.h:110
Represents a field declaration created by an @defs(...).
Definition DeclObjC.h:2036
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(QualType P)
Definition Ownership.h:61
static OpenACCBindClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, const IdentifierInfo *ID, SourceLocation EndLoc)
OpenACCDirectiveKind getDirectiveKind() const
Definition DeclOpenACC.h:56
ArrayRef< const OpenACCClause * > clauses() const
Definition DeclOpenACC.h:62
SourceLocation getDirectiveLoc() const
Definition DeclOpenACC.h:57
static OpenACCCopyClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyInClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyOutClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCreateClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDevicePtrClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceResidentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
A 'device_type' or 'dtype' clause, takes a list of either an 'asterisk' or an identifier.
static OpenACCDeviceTypeClause * Create(const ASTContext &C, OpenACCClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< DeviceTypeArgument > Archs, SourceLocation EndLoc)
static OpenACCLinkClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCNoHostClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCPresentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
SourceLocation getRParenLoc() const
const Expr * getFunctionReference() const
SourceLocation getLParenLoc() const
static OpenACCSeqClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCVectorClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCWorkerClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
SourceLocation getEllipsisLoc() const
Definition TypeLoc.h:2752
TypeLoc getPatternLoc() const
Definition TypeLoc.h:2768
Represents a parameter to a function.
Definition Decl.h:1832
Represents a #pragma comment line.
Definition Decl.h:169
Represents a #pragma detect_mismatch line.
Definition Decl.h:203
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8758
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8865
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1853
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
Represents a struct/union/class.
Definition Decl.h:4506
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4558
Wrapper for source info for record types.
Definition TypeLoc.h:855
Declaration of a redeclarable template.
RedeclarableTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD)
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5517
Represents the body of a requires-expression.
Definition DeclCXX.h:2122
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition DeclCXX.cpp:2405
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...
void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a particular declaration.
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...
Sema & SemaRef
Definition SemaBase.h:49
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
QualType getInoutParameterType(QualType Ty)
void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, Sema::RetainOwnershipKind K, bool IsTemplateInstantiation)
A type to represent all the data for an OpenACC Clause that has been parsed, but not yet created/sema...
OpenACCDirectiveKind getDirectiveKind() const
OpenACCClauseKind getClauseKind() const
OMPAdjustArgsDescriptor * ActOnOpenMPAdjustArgsClause(OpenMPAdjustArgsOpKind AdjustOp, OpenMPNeedDevicePtrModifier NeedDevicePtrModifier, ArrayRef< OMPAdjustArgsItem > Items, SourceLocation Loc)
Called on well-formed 'adjust_args' clause of a '#pragma omp declare variant' directive.
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 ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, ArrayRef< OMPAdjustArgsDescriptor * > AdjustArgs, ArrayRef< OMPInteropInfo > AppendArgs, SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, SourceRange SR)
Called on well-formed '#pragma omp declare variant' after parsing of the associated method/function.
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.
void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI abi)
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:14010
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8717
A RAII object to temporarily push a declaration context.
Definition Sema.h:3683
A helper class for building up ExtParameterInfos.
Definition Sema.h:13379
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition Sema.h:14438
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12838
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
SemaAMDGPU & AMDGPU()
Definition Sema.h:1493
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13957
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13408
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...
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9614
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9641
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9646
Decl * ActOnSkippedFunctionBody(Decl *Decl)
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation.
void deduceOpenCLAddressSpace(VarDecl *decl)
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
RetainOwnershipKind
Definition Sema.h:5306
TypeSourceInfo * SubstFriendType(TypeSourceInfo *TSI, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity)
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition Sema.h:1578
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion)
AddAlignedAttr - Adds an aligned attribute to a particular declaration.
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1293
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:1518
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7156
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2125
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...
void InstantiateLateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec &LateAttrs, LocalInstantiationScope *OuterMostScope)
Instantiate the attributes that InstantiateAttrs deferred to LateAttrs, and attach them to their decl...
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)
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation=false, bool RetainFunctionScopeInfo=false)
Performs semantic analysis at the end of a function body.
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:7168
LateParsedTemplateMapT LateParsedTemplateMap
Definition Sema.h:11707
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...
StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTContext & Context
Definition Sema.h:1339
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool FailOnPackProducingTemplates, bool &ShouldExpand, bool &RetainExpansion, UnsignedOrNone &NumExpansions, bool Diagnose=true)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
SemaObjC & ObjC()
Definition Sema.h:1563
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:83
void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs)
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc, Scope *S=nullptr)
Mark the given declaration as explicitly defaulted.
void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Name, bool InInstantiation=false)
AddModeAttr - Adds a mode attribute to a particular declaration.
ASTContext & getASTContext() const
Definition Sema.h:935
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.
SmallVector< LateInstantiatedAttribute, 1 > LateInstantiatedAttrVec
Definition Sema.h:14122
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1243
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:12492
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:277
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition Sema.h:928
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:243
void * OpaqueParser
Definition Sema.h:1385
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor, bool IsCopy=false)
const LangOptions & LangOpts
Definition Sema.h:1337
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1528
VarTemplateSpecializationDecl * CompleteVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiates a variable template specialization by completing it with appropriate type information an...
void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst)
Update instantiation attributes after template was late parsed.
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:14390
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
SemaSwift & Swift()
Definition Sema.h:1608
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)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1491
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:1573
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition Sema.h:14403
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
SourceManager & getSourceManager() const
Definition Sema.h:933
QualType CXXThisTypeOverride
When non-NULL, the C++ 'this' expression is allowed despite the current context not being a non-stati...
Definition Sema.h:8713
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
void PerformPendingInstantiations(bool LocalOnly=false, bool AtEndOfTU=true)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
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.
UnsignedOrNone ArgPackSubstIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition Sema.h:14004
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
RedeclarationKind forRedeclarationInCurContext() const
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)
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1629
ASTConsumer & Consumer
Definition Sema.h:1340
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1379
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1911
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14386
bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A)
Recheck instantiated thread-safety attributes that could not be validated on the dependent pattern de...
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X, Expr *Y, Expr *Z)
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6957
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6967
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6936
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.
LateTemplateParserCB * LateTemplateParser
Definition Sema.h:1384
bool CheckDependentFriend(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc, ArrayRef< TemplateParameterList * > TPLs, bool IsInstantiation)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8582
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true, bool *Unreachable=nullptr)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
SourceManager & SourceMgr
Definition Sema.h:1342
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
FPOptions CurFPFeatures
Definition Sema.h:1335
Attr * CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
Definition Sema.cpp:3213
@ TPC_FriendFunctionTemplate
Definition Sema.h:11925
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11926
void DiagnoseUnusedDecl(const NamedDecl *ND)
void ActOnUninitializedDecl(Decl *dcl)
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:648
bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty)
Check that the type is a plain record with one field being a pointer type and the other field being a...
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.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:14382
DeclContext * FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs)
Finds the instantiation of the given declaration context within the current instantiation.
void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
AddAlignValueAttr - Adds an align_value attribute to a particular declaration.
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1330
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:674
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8930
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
Represents a C++11 static_assert declaration.
Definition DeclCXX.h:4183
bool isFailed() const
Definition DeclCXX.h:4212
SourceLocation getRParenLoc() const
Definition DeclCXX.h:4214
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3898
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:3994
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3999
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition Decl.h:4152
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:4135
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:5012
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:5054
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:4131
TagKind getTagKind() const
Definition Decl.h:4098
SourceLocation getNameLoc() const
Definition TypeLoc.h:822
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:816
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:824
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
A template argument list.
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.
Location wrapper for a TemplateArgument.
const TemplateArgument & getArgument() const
SourceLocation getTemplateNameLoc() const
SourceLocation getTemplateKWLoc() const
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Represents a template argument.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
@ Pack
The template argument is actually a parameter pack.
Container for the late-parsed attributes of a function's parameters, which SubstFunctionType defers u...
Definition Template.h:727
void discard()
Free the attributes without instantiating them.
void instantiate()
Instantiate the attributes, once the function is declared.
bool SubstTemplateParameterLists(ArrayRef< TemplateParameterList * > TPLs, SmallVectorImpl< TemplateParameterList * > &InstTPLs)
void setEvaluateConstraints(bool B)
Definition Template.h:621
TypeSourceInfo * SubstFunctionType(FunctionDecl *D, SmallVectorImpl< ParmVarDecl * > &Params, DeferredParamAttrs &ParamAttrs)
VarTemplateSpecializationDecl * VisitVarTemplateSpecializationDecl(VarTemplateDecl *VarTemplate, VarDecl *FromVar, ArrayRef< TemplateArgument > Converted, VarTemplateSpecializationDecl *PrevDecl=nullptr)
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)
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.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
bool isNull() const
Determine whether this template name is NULL.
@ Template
A single template declaration.
A template parameter object.
Stores a list of template parameters for a TemplateDecl and its derived classes.
SourceRange getSourceRange() const LLVM_READONLY
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.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
ArrayRef< NamedDecl * > asArray()
SourceLocation getTemplateLoc() const
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:1938
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition TypeLoc.h:1948
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:1953
SourceLocation getTemplateNameLoc() const
Definition TypeLoc.h:1936
SourceLocation getTemplateKeywordLoc() const
Definition TypeLoc.h:1932
NestedNameSpecifierLoc getQualifierLoc() const
Definition TypeLoc.h:1922
SourceLocation getElaboratedKeywordLoc() const
Definition TypeLoc.h:1918
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
bool wasDeclaredWithTypename() const
Whether this template template parameter was declared with the 'typename' keyword.
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
unsigned getNumExpansionTemplateParameters() const
Retrieves the number of expansion template parameters in an expanded parameter pack.
TemplateNameKind templateParameterKind() const
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
bool defaultArgumentWasInherited() const
Determines whether the default argument was inherited from a previous declaration of this template.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, int D, int P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
bool wasDeclaredWithTypename() const
Whether this template type parameter was declared with the 'typename' keyword.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
unsigned getIndex() const
Retrieve the index of the template parameter.
bool hasTypeConstraint() const
Determine whether this template parameter has a type-constraint.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
const TypeConstraint * getTypeConstraint() const
Returns the type constraint associated with this template parameter (if any).
UnsignedOrNone getNumExpansionParameters() const
Whether this parameter is a template type parameter pack that has a known list of different type-cons...
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool defaultArgumentWasInherited() const
Determines whether the default argument was inherited from a previous declaration of this template.
bool isParameterPack() const
Returns whether this is a parameter pack.
unsigned getDepth() const
Retrieve the depth of the template parameter.
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
The top declaration context.
Definition Decl.h:107
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:3869
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5927
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition Decl.h:3888
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.
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
const Type * getTypeForDecl() const
Definition Decl.h:3719
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3728
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
void pushTrivial(ASTContext &Context, QualType T, SourceLocation Loc)
Pushes 'T' with all locations pointing to 'Loc'.
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
NestedNameSpecifierLoc getPrefix() const
If this type represents a qualified-id, this returns it's nested name specifier.
Definition TypeLoc.cpp:478
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1468
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:154
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:892
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2858
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8651
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8662
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isRValueReferenceType() const
Definition TypeBase.h:8949
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9604
bool isReferenceType() const
Definition TypeBase.h:8941
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2981
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2872
bool isLValueReferenceType() const
Definition TypeBase.h:8945
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2864
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2469
bool isTemplateTypeParmType() const
Definition TypeBase.h:9271
bool isAtomicType() const
Definition TypeBase.h:9113
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2882
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9453
bool isFunctionType() const
Definition TypeBase.h:8913
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9537
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3848
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5876
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3743
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3793
QualType getUnderlyingType() const
Definition Decl.h:3798
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4525
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition DeclCXX.h:4165
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition DeclCXX.cpp:3659
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4084
SourceLocation getTypenameLoc() const
Returns the source location of the 'typename' keyword.
Definition DeclCXX.h:4114
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3987
Represents a C++ using-declaration.
Definition DeclCXX.h:3638
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition DeclCXX.h:3687
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name, with source-location information.
Definition DeclCXX.h:3672
DeclarationNameInfo getNameInfo() const
Definition DeclCXX.h:3679
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition DeclCXX.cpp:3547
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition DeclCXX.h:3665
Represents C++ using-directive.
Definition DeclCXX.h:3143
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition DeclCXX.cpp:3330
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition DeclCXX.cpp:3357
DeclContext * getCommonAncestor()
Returns the common ancestor context of this using-directive and its nominated namespace.
Definition DeclCXX.h:3210
SourceLocation getNamespaceKeyLocation() const
Returns the location of the namespace keyword.
Definition DeclCXX.h:3218
SourceLocation getIdentLocation() const
Returns the location of this using declaration's identifier.
Definition DeclCXX.h:3221
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name of the namespace, with source-location inf...
Definition DeclCXX.h:3188
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3839
SourceLocation getEnumLoc() const
The source location of the 'enum' keyword.
Definition DeclCXX.h:3863
EnumDecl * getEnumDecl() const
Definition DeclCXX.h:3881
TypeSourceInfo * getEnumType() const
Definition DeclCXX.h:3875
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition DeclCXX.cpp:3568
SourceLocation getUsingLoc() const
The source location of the 'using' keyword.
Definition DeclCXX.h:3859
Represents a pack of using declarations that a single using-declarator pack-expanded into.
Definition DeclCXX.h:3920
ArrayRef< NamedDecl * > expansions() const
Get the set of using declarations that this pack expanded into.
Definition DeclCXX.h:3953
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3446
void setType(QualType newType)
Definition Decl.h:726
QualType getType() const
Definition Decl.h:725
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5703
Represents a variable declaration or definition.
Definition Decl.h:934
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2804
void setObjCForDecl(bool FRD)
Definition Decl.h:1573
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2134
void setCXXForRangeDecl(bool FRD)
Definition Decl.h:1562
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1606
void setInstantiationOfStaticDataMember(VarDecl *VD, TemplateSpecializationKind TSK)
Specify that this variable is an instantiation of the static data member VD.
Definition Decl.cpp:2927
TLSKind getTLSKind() const
Definition Decl.cpp:2151
bool hasInit() const
Definition Decl.cpp:2402
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1489
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
InitializationStyle getInitStyle() const
The style of initialization for this declaration.
Definition Decl.h:1503
void setInitCapture(bool IC)
Definition Decl.h:1618
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2258
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:2465
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2240
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1615
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:942
bool isObjCForDecl() const
Determine whether this variable is a for-loop declaration for a for-in statement in Objective-C.
Definition Decl.h:1569
void setPreviousDeclInSameBlockScope(bool Same)
Definition Decl.h:1630
bool isInlineSpecified() const
Definition Decl.h:1591
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1308
VarDecl * getTemplateInstantiationPattern() const
Retrieve the variable declaration from which this variable could be instantiated, if it is an instant...
Definition Decl.cpp:2721
bool isCXXForRangeDecl() const
Determine whether this variable is the for-range-declaration in a C++0x for-range statement.
Definition Decl.h:1559
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2370
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:2481
bool isNRVOVariable() const
Determine whether this local variable can be used with the named return value optimization (NRVO).
Definition Decl.h:1549
void setInlineSpecified()
Definition Decl.h:1595
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1216
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:2899
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition Decl.h:1181
void setNRVOVariable(bool NRVO)
Definition Decl.h:1552
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1588
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1185
const Expr * getInit() const
Definition Decl.h:1393
void setConstexpr(bool IC)
Definition Decl.h:1609
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition Decl.cpp:2809
bool isDirectInit() const
Whether the initializer is a direct-initializer (list or call).
Definition Decl.h:1508
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1176
void setImplicitlyInline()
Definition Decl.h:1600
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition Decl.h:1625
VarDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
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:2794
TemplateSpecializationKind getTemplateSpecializationKindForInstantiation() const
Get the template specialization kind of this variable for the purposes of template instantiation.
Definition Decl.cpp:2784
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:2773
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, llvm::FoldingSetInsertToken &InsertToken)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
llvm::FoldingSetVector< VarTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
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.
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:745
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1498
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Attr * instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
Attr * instantiateTemplateAttributeForDecl(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OpenACCDirectiveKind
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus11
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
Definition Template.h:54
QualType getFunctionOrMethodResultType(const Decl *D)
Definition Attr.h:136
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ DevicePtr
'deviceptr' clause, allowed on Compute and Combined Constructs, plus 'data' and 'declare'.
@ VectorLength
'vector_length' clause, allowed on 'parallel', 'kernels', 'parallel loop', and 'kernels loop' constru...
@ Async
'async' clause, allowed on Compute, Data, 'update', 'wait', and Combined constructs.
@ Collapse
'collapse' clause, allowed on 'loop' and Combined constructs.
@ DeviceNum
'device_num' clause, allowed on 'init', 'shutdown', and 'set' constructs.
@ DefaultAsync
'default_async' clause, allowed on 'set' construct.
@ Attach
'attach' clause, allowed on Compute and Combined constructs, plus 'data' and 'enter data'.
@ NumGangs
'num_gangs' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs.
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ UseDevice
'use_device' clause, allowed on 'host_data' construct.
@ NoCreate
'no_create' clause, allowed on allowed on Compute and Combined constructs, plus 'data'.
@ Reduction
'reduction' clause, allowed on Parallel, Serial, Loop, and the combined constructs.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ FirstPrivate
'firstprivate' clause, allowed on 'parallel', 'serial', 'parallel loop', and 'serial loop' constructs...
@ Tile
'tile' clause, allowed on 'loop' and Combined constructs.
@ Independent
'independent' clause, allowed on 'loop' directives.
@ NumWorkers
'num_workers' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs...
@ IfPresent
'if_present' clause, allowed on 'host_data' and 'update' directives.
@ Detach
'detach' clause, allowed on the 'exit data' construct.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ Finalize
'finalize' clause, allowed on 'exit data' directive.
@ AS_public
Definition Specifiers.h:128
@ AS_none
Definition Specifiers.h:131
StorageClass
Storage classes.
Definition Specifiers.h:252
@ SC_Static
Definition Specifiers.h:256
@ SC_None
Definition Specifiers.h:254
ExprResult ExprEmpty()
Definition Ownership.h:272
bool isGenericLambdaCallOperatorOrStaticInvokerSpecialization(const DeclContext *DC)
Definition ASTLambda.h:89
@ Default
Set to the current date and time.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Property
The type of a property.
Definition TypeBase.h:912
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
OptionalUnsigned< unsigned > UnsignedOrNone
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:581
@ VarTemplate
The name was classified as a variable template name.
Definition Sema.h:579
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1306
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:192
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:210
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:206
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:195
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6269
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6262
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ EST_Unevaluated
not evaluated yet, for special member function
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
ArrayRef< TemplateArgumentLoc > arguments() const
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
TypeSourceInfo * getNamedTypeInfo() const
Holds information about the various types of exception specification.
Definition TypeBase.h:5707
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition TypeBase.h:5719
FunctionDecl * SourceTemplate
The function template whose exception specification this is instantiated from, for EST_Uninstantiated...
Definition TypeBase.h:5723
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5709
Extra information about a function prototype.
Definition TypeBase.h:5735
Expr * E
The bound expression, or the logical offset for a NumArgs bound.
One item in an OpenMP 'adjust_args' parameter list.
Expr * E
A named parameter or positional expression for a Single item.
llvm::SmallVector< OMPInteropPref, 4 > Prefs
One entry of a prefer_type list.
llvm::SmallVector< Expr *, 2 > Attrs
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12343
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12329
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13459
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:13461
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13563
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13487
A stack object to be created when performing template instantiation.
Definition Sema.h:13653
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13806
An attribute whose instantiation is deferred, together with the instantiation scope to instantiate it...
Definition Sema.h:14113