clang 23.0.0git
SemaTemplateInstantiateDecl.cpp
Go to the documentation of this file.
1//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===/
7//
8// This file implements C++ template instantiation for declarations.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
21#include "clang/AST/TypeLoc.h"
26#include "clang/Sema/Lookup.h"
29#include "clang/Sema/SemaCUDA.h"
30#include "clang/Sema/SemaHLSL.h"
31#include "clang/Sema/SemaObjC.h"
34#include "clang/Sema/Template.h"
36#include "llvm/Support/TimeProfiler.h"
37#include <optional>
38
39using namespace clang;
40
41static bool isDeclWithinFunction(const Decl *D) {
42 const DeclContext *DC = D->getDeclContext();
43 if (DC->isFunctionOrMethod())
44 return true;
45
46 if (DC->isRecord())
47 return cast<CXXRecordDecl>(DC)->isLocalClass();
48
49 return false;
50}
51
52template<typename DeclT>
53static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
54 const MultiLevelTemplateArgumentList &TemplateArgs) {
55 if (!OldDecl->getQualifierLoc())
56 return false;
57
58 assert((NewDecl->getFriendObjectKind() ||
59 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
60 "non-friend with qualified name defined in dependent context");
61 Sema::ContextRAII SavedContext(
62 SemaRef,
63 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
64 ? NewDecl->getLexicalDeclContext()
65 : OldDecl->getLexicalDeclContext()));
66
67 NestedNameSpecifierLoc NewQualifierLoc
68 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
69 TemplateArgs);
70
71 if (!NewQualifierLoc)
72 return true;
73
74 NewDecl->setQualifierInfo(NewQualifierLoc);
75 return false;
76}
77
79 DeclaratorDecl *NewDecl) {
80 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
81}
82
84 TagDecl *NewDecl) {
85 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
86}
87
88// Include attribute instantiation code.
89#include "clang/Sema/AttrTemplateInstantiate.inc"
90
92 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
93 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
94 if (Aligned->isAlignmentExpr()) {
95 // The alignment expression is a constant expression.
98 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
99 if (!Result.isInvalid())
100 S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
101 } else {
103 S.SubstType(Aligned->getAlignmentType(), TemplateArgs,
104 Aligned->getLocation(), DeclarationName())) {
105 if (!S.CheckAlignasTypeArgument(Aligned->getSpelling(), Result,
106 Aligned->getLocation(),
107 Result->getTypeLoc().getSourceRange()))
108 S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
109 }
110 }
111}
112
114 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
115 const AlignedAttr *Aligned, Decl *New) {
116 if (!Aligned->isPackExpansion()) {
117 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
118 return;
119 }
120
122 if (Aligned->isAlignmentExpr())
123 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
124 Unexpanded);
125 else
126 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
127 Unexpanded);
128 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
129
130 // Determine whether we can expand this attribute pack yet.
131 bool Expand = true, RetainExpansion = false;
132 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
557 SmallVector<Expr *, 8> NothingExprs;
558 SmallVector<Expr *, 8> NeedDevicePtrExprs;
559 SmallVector<Expr *, 8> NeedDeviceAddrExprs;
561
562 for (Expr *E : Attr.adjustArgsNothing()) {
563 ExprResult ER = Subst(E);
564 if (ER.isInvalid())
565 continue;
566 NothingExprs.push_back(ER.get());
567 }
568 for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
569 ExprResult ER = Subst(E);
570 if (ER.isInvalid())
571 continue;
572 NeedDevicePtrExprs.push_back(ER.get());
573 }
574 for (Expr *E : Attr.adjustArgsNeedDeviceAddr()) {
575 ExprResult ER = Subst(E);
576 if (ER.isInvalid())
577 continue;
578 NeedDeviceAddrExprs.push_back(ER.get());
579 }
580 for (OMPInteropInfo &II : Attr.appendArgs()) {
581 // When prefer_type is implemented for append_args handle them here too.
582 AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
583 }
584
586 FD, E, TI, NothingExprs, NeedDevicePtrExprs, NeedDeviceAddrExprs,
587 AppendArgs, SourceLocation(), SourceLocation(), Attr.getRange());
588}
589
591 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
592 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
593 // Both min and max expression are constant expressions.
596
597 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
598 if (Result.isInvalid())
599 return;
600 Expr *MinExpr = Result.getAs<Expr>();
601
602 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
603 if (Result.isInvalid())
604 return;
605 Expr *MaxExpr = Result.getAs<Expr>();
606
607 S.AMDGPU().addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
608}
609
611 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
612 const ReqdWorkGroupSizeAttr &Attr, Decl *New) {
613 // Both min and max expression are constant expressions.
616
617 ExprResult Result = S.SubstExpr(Attr.getXDim(), TemplateArgs);
618 if (Result.isInvalid())
619 return;
620 Expr *X = Result.getAs<Expr>();
621
622 Result = S.SubstExpr(Attr.getYDim(), TemplateArgs);
623 if (Result.isInvalid())
624 return;
625 Expr *Y = Result.getAs<Expr>();
626
627 Result = S.SubstExpr(Attr.getZDim(), TemplateArgs);
628 if (Result.isInvalid())
629 return;
630 Expr *Z = Result.getAs<Expr>();
631
632 ASTContext &Context = S.getASTContext();
633 New->addAttr(::new (Context) ReqdWorkGroupSizeAttr(Context, Attr, X, Y, Z));
634}
635
637 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) {
638 if (!ES.getExpr())
639 return ES;
640 Expr *OldCond = ES.getExpr();
641 Expr *Cond = nullptr;
642 {
645 ExprResult SubstResult = SubstExpr(OldCond, TemplateArgs);
646 if (SubstResult.isInvalid()) {
648 }
649 Cond = SubstResult.get();
650 }
652 if (!Cond->isTypeDependent())
654 return Result;
655}
656
658 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
659 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
660 // Both min and max expression are constant expressions.
663
664 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
665 if (Result.isInvalid())
666 return;
667 Expr *MinExpr = Result.getAs<Expr>();
668
669 Expr *MaxExpr = nullptr;
670 if (auto Max = Attr.getMax()) {
671 Result = S.SubstExpr(Max, TemplateArgs);
672 if (Result.isInvalid())
673 return;
674 MaxExpr = Result.getAs<Expr>();
675 }
676
677 S.AMDGPU().addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
678}
679
681 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
682 const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New) {
685
686 Expr *XExpr = nullptr;
687 Expr *YExpr = nullptr;
688 Expr *ZExpr = nullptr;
689
690 if (Attr.getMaxNumWorkGroupsX()) {
691 ExprResult ResultX = S.SubstExpr(Attr.getMaxNumWorkGroupsX(), TemplateArgs);
692 if (ResultX.isUsable())
693 XExpr = ResultX.getAs<Expr>();
694 }
695
696 if (Attr.getMaxNumWorkGroupsY()) {
697 ExprResult ResultY = S.SubstExpr(Attr.getMaxNumWorkGroupsY(), TemplateArgs);
698 if (ResultY.isUsable())
699 YExpr = ResultY.getAs<Expr>();
700 }
701
702 if (Attr.getMaxNumWorkGroupsZ()) {
703 ExprResult ResultZ = S.SubstExpr(Attr.getMaxNumWorkGroupsZ(), TemplateArgs);
704 if (ResultZ.isUsable())
705 ZExpr = ResultZ.getAs<Expr>();
706 }
707
708 if (XExpr)
709 S.AMDGPU().addAMDGPUMaxNumWorkGroupsAttr(New, Attr, XExpr, YExpr, ZExpr);
710}
711
713 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
714 const CUDAClusterDimsAttr &Attr, Decl *New) {
717
718 auto SubstElt = [&S, &TemplateArgs](Expr *E) {
719 return E ? S.SubstExpr(E, TemplateArgs).get() : nullptr;
720 };
721
722 Expr *XExpr = SubstElt(Attr.getX());
723 Expr *YExpr = SubstElt(Attr.getY());
724 Expr *ZExpr = SubstElt(Attr.getZ());
725
726 S.addClusterDimsAttr(New, Attr, XExpr, YExpr, ZExpr);
727}
728
729// This doesn't take any template parameters, but we have a custom action that
730// needs to happen when the kernel itself is instantiated. We need to run the
731// ItaniumMangler to mark the names required to name this kernel.
733 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
734 const SYCLKernelAttr &Attr, Decl *New) {
735 New->addAttr(Attr.clone(S.getASTContext()));
736}
737
738/// Determine whether the attribute A might be relevant to the declaration D.
739/// If not, we can skip instantiating it. The attribute may or may not have
740/// been instantiated yet.
741static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
742 // 'preferred_name' is only relevant to the matching specialization of the
743 // template.
744 if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
745 QualType T = PNA->getTypedefType();
746 const auto *RD = cast<CXXRecordDecl>(D);
747 if (!T->isDependentType() && !RD->isDependentContext() &&
748 !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
749 return false;
750 for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
751 if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
752 PNA->getTypedefType()))
753 return false;
754 return true;
755 }
756
757 if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
758 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
759 switch (BA->getID()) {
760 case Builtin::BIforward:
761 // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
762 // type and returns an lvalue reference type. The library implementation
763 // will produce an error in this case; don't get in its way.
764 if (FD && FD->getNumParams() >= 1 &&
767 return false;
768 }
769 [[fallthrough]];
770 case Builtin::BImove:
771 case Builtin::BImove_if_noexcept:
772 // HACK: Super-old versions of libc++ (3.1 and earlier) provide
773 // std::forward and std::move overloads that sometimes return by value
774 // instead of by reference when building in C++98 mode. Don't treat such
775 // cases as builtins.
776 if (FD && !FD->getReturnType()->isReferenceType())
777 return false;
778 break;
779 }
780 }
781
782 return true;
783}
784
786 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
787 const HLSLParamModifierAttr *Attr, const Decl *Old, Decl *New) {
789 NewParm->addAttr(Attr->clone(S.getASTContext()));
790
791 // If this is groupshared don't change the type because it will assert
792 // below. In this case we might have already produced an error but we
793 // must produce one here again because of all the ways templates can
794 // be used.
795 if (const auto *RT = NewParm->getType()->getAs<LValueReferenceType>()) {
796 if (RT->getPointeeType().getAddressSpace() == LangAS::hlsl_groupshared) {
797 S.Diag(Attr->getLoc(), diag::err_hlsl_attr_incompatible)
798 << Attr << "'groupshared'";
799 return;
800 }
801 }
802
803 const Type *OldParmTy = cast<ParmVarDecl>(Old)->getType().getTypePtr();
804 if (OldParmTy->isDependentType() && Attr->isAnyOut())
805 NewParm->setType(S.HLSL().getInoutParameterType(NewParm->getType()));
806
807 assert(
808 (!Attr->isAnyOut() || (NewParm->getType().isRestrictQualified() &&
809 NewParm->getType()->isReferenceType())) &&
810 "out or inout parameter type must be a reference and restrict qualified");
811}
812
814 const MallocSpanAttr *Attr,
815 Decl *New) {
817 if (!S.CheckSpanLikeType(*Attr, RT))
818 New->addAttr(Attr->clone(S.getASTContext()));
819}
820
822 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
823 Decl *New, LateInstantiatedAttrVec *LateAttrs,
824 LocalInstantiationScope *OuterMostScope) {
825 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
826 // FIXME: This function is called multiple times for the same template
827 // specialization. We should only instantiate attributes that were added
828 // since the previous instantiation.
829 for (const auto *TmplAttr : Tmpl->attrs()) {
830 if (!isRelevantAttr(*this, New, TmplAttr))
831 continue;
832
833 // FIXME: If any of the special case versions from InstantiateAttrs become
834 // applicable to template declaration, we'll need to add them here.
835 CXXThisScopeRAII ThisScope(
836 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
837 Qualifiers(), ND->isCXXInstanceMember());
838
840 TmplAttr, Context, *this, TemplateArgs);
841 if (NewAttr && isRelevantAttr(*this, New, NewAttr) &&
843 New->addAttr(NewAttr);
844 }
845 }
846}
847
850 switch (A->getKind()) {
851 case clang::attr::CFConsumed:
853 case clang::attr::OSConsumed:
855 case clang::attr::NSConsumed:
857 default:
858 llvm_unreachable("Wrong argument supplied");
859 }
860}
861
862// Implementation is down with the rest of the OpenACC Decl instantiations.
864 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
865 const OpenACCRoutineDeclAttr *OldAttr, const Decl *Old, Decl *New);
866
868 const Decl *Tmpl, Decl *New,
869 LateInstantiatedAttrVec *LateAttrs,
870 LocalInstantiationScope *OuterMostScope) {
871 for (const auto *TmplAttr : Tmpl->attrs()) {
872 if (!isRelevantAttr(*this, New, TmplAttr))
873 continue;
874
875 // FIXME: This should be generalized to more than just the AlignedAttr.
876 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
877 if (Aligned && Aligned->isAlignmentDependent()) {
878 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
879 continue;
880 }
881
882 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
883 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
884 continue;
885 }
886
887 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
888 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
889 continue;
890 }
891
892 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
893 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
894 continue;
895 }
896
897 if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
898 instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
899 continue;
900 }
901
902 if (auto *Constructor = dyn_cast<ConstructorAttr>(TmplAttr)) {
905 continue;
906 }
907
908 if (auto *Destructor = dyn_cast<DestructorAttr>(TmplAttr)) {
911 continue;
912 }
913
914 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
915 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
917 continue;
918 }
919
920 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
921 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
923 continue;
924 }
925
926 if (const auto *CUDALaunchBounds =
927 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
929 *CUDALaunchBounds, New);
930 continue;
931 }
932
933 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
934 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
935 continue;
936 }
937
938 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
939 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
940 continue;
941 }
942
943 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
944 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
945 continue;
946 }
947
948 if (const auto *ReqdWorkGroupSize =
949 dyn_cast<ReqdWorkGroupSizeAttr>(TmplAttr)) {
951 *ReqdWorkGroupSize, New);
952 }
953
954 if (const auto *AMDGPUFlatWorkGroupSize =
955 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
957 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
958 }
959
960 if (const auto *AMDGPUFlatWorkGroupSize =
961 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
963 *AMDGPUFlatWorkGroupSize, New);
964 }
965
966 if (const auto *AMDGPUMaxNumWorkGroups =
967 dyn_cast<AMDGPUMaxNumWorkGroupsAttr>(TmplAttr)) {
969 *this, TemplateArgs, *AMDGPUMaxNumWorkGroups, New);
970 }
971
972 if (const auto *CUDAClusterDims = dyn_cast<CUDAClusterDimsAttr>(TmplAttr)) {
973 instantiateDependentCUDAClusterDimsAttr(*this, TemplateArgs,
974 *CUDAClusterDims, New);
975 }
976
977 if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(TmplAttr)) {
978 instantiateDependentHLSLParamModifierAttr(*this, TemplateArgs, ParamAttr,
979 Tmpl, New);
980 continue;
981 }
982
983 if (const auto *RoutineAttr = dyn_cast<OpenACCRoutineDeclAttr>(TmplAttr)) {
985 RoutineAttr, Tmpl, New);
986 continue;
987 }
988
989 // Existing DLL attribute on the instantiation takes precedence.
990 if (TmplAttr->getKind() == attr::DLLExport ||
991 TmplAttr->getKind() == attr::DLLImport) {
992 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
993 continue;
994 }
995 }
996
997 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
998 Swift().AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
999 continue;
1000 }
1001
1002 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
1003 isa<CFConsumedAttr>(TmplAttr)) {
1004 ObjC().AddXConsumedAttr(New, *TmplAttr,
1005 attrToRetainOwnershipKind(TmplAttr),
1006 /*template instantiation=*/true);
1007 continue;
1008 }
1009
1010 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
1011 if (!New->hasAttr<PointerAttr>())
1012 New->addAttr(A->clone(Context));
1013 continue;
1014 }
1015
1016 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
1017 if (!New->hasAttr<OwnerAttr>())
1018 New->addAttr(A->clone(Context));
1019 continue;
1020 }
1021
1022 if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
1023 instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
1024 continue;
1025 }
1026
1027 if (auto *A = dyn_cast<CUDAGridConstantAttr>(TmplAttr)) {
1028 if (!New->hasAttr<CUDAGridConstantAttr>())
1029 New->addAttr(A->clone(Context));
1030 continue;
1031 }
1032
1033 if (auto *A = dyn_cast<MallocSpanAttr>(TmplAttr)) {
1035 continue;
1036 }
1037
1038 if (auto *A = dyn_cast<CleanupAttr>(TmplAttr)) {
1039 if (!New->hasAttr<CleanupAttr>()) {
1040 auto *NewAttr = A->clone(Context);
1041 NewAttr->setArgLoc(A->getArgLoc());
1042 New->addAttr(NewAttr);
1043 }
1044 continue;
1045 }
1046
1047 if (auto *A = dyn_cast<HLSLMatrixLayoutAttr>(TmplAttr)) {
1048 if (!HLSL().diagnoseInstantiatedMatrixLayoutAttr(New, A) &&
1049 !New->hasAttr<HLSLMatrixLayoutAttr>())
1050 New->addAttr(A->clone(Context));
1051 continue;
1052 }
1053
1054 assert(!TmplAttr->isPackExpansion());
1055 if (TmplAttr->isLateParsed() && LateAttrs) {
1056 // Late parsed attributes must be instantiated and attached after the
1057 // enclosing class has been instantiated. See Sema::InstantiateClass.
1058 LocalInstantiationScope *Saved = nullptr;
1060 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
1061 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
1062 } else {
1063 // Allow 'this' within late-parsed attributes.
1064 auto *ND = cast<NamedDecl>(New);
1065 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
1066 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
1067 ND->isCXXInstanceMember());
1068
1069 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
1070 *this, TemplateArgs);
1071 if (NewAttr && isRelevantAttr(*this, New, TmplAttr) &&
1073 New->addAttr(NewAttr);
1074 }
1075 }
1076}
1077
1079 for (const auto *Attr : Pattern->attrs()) {
1080 if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
1081 if (!Inst->hasAttr<StrictFPAttr>())
1082 Inst->addAttr(A->clone(getASTContext()));
1083 continue;
1084 }
1085 }
1086}
1087
1089 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
1090 Ctor->isDefaultConstructor());
1091 unsigned NumParams = Ctor->getNumParams();
1092 if (NumParams == 0)
1093 return;
1094 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
1095 if (!Attr)
1096 return;
1097 for (unsigned I = 0; I != NumParams; ++I) {
1099 Ctor->getParamDecl(I));
1101 }
1102}
1103
1104/// Get the previous declaration of a declaration for the purposes of template
1105/// instantiation. If this finds a previous declaration, then the previous
1106/// declaration of the instantiation of D should be an instantiation of the
1107/// result of this function.
1108template<typename DeclT>
1109static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
1110 DeclT *Result = D->getPreviousDecl();
1111
1112 // If the declaration is within a class, and the previous declaration was
1113 // merged from a different definition of that class, then we don't have a
1114 // previous declaration for the purpose of template instantiation.
1115 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
1116 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
1117 return nullptr;
1118
1119 return Result;
1120}
1121
1122Decl *
1123TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
1124 llvm_unreachable("Translation units cannot be instantiated");
1125}
1126
1127Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
1128 llvm_unreachable("HLSL buffer declarations cannot be instantiated");
1129}
1130
1131Decl *TemplateDeclInstantiator::VisitHLSLRootSignatureDecl(
1133 llvm_unreachable("HLSL root signature declarations cannot be instantiated");
1134}
1135
1136Decl *
1137TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
1138 llvm_unreachable("pragma comment cannot be instantiated");
1139}
1140
1141Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
1143 llvm_unreachable("pragma comment cannot be instantiated");
1144}
1145
1146Decl *
1147TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
1148 llvm_unreachable("extern \"C\" context cannot be instantiated");
1149}
1150
1151Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
1152 llvm_unreachable("GUID declaration cannot be instantiated");
1153}
1154
1155Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
1157 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
1158}
1159
1160Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
1162 llvm_unreachable("template parameter objects cannot be instantiated");
1163}
1164
1165Decl *
1166TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
1167 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1168 D->getIdentifier());
1169 SemaRef.InstantiateAttrs(TemplateArgs, D, Inst, LateAttrs, StartingScope);
1170 Owner->addDecl(Inst);
1171 return Inst;
1172}
1173
1174Decl *
1175TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
1176 llvm_unreachable("Namespaces cannot be instantiated");
1177}
1178
1179namespace {
1180class OpenACCDeclClauseInstantiator final
1181 : public OpenACCClauseVisitor<OpenACCDeclClauseInstantiator> {
1182 Sema &SemaRef;
1183 const MultiLevelTemplateArgumentList &MLTAL;
1184 ArrayRef<OpenACCClause *> ExistingClauses;
1185 SemaOpenACC::OpenACCParsedClause &ParsedClause;
1186 OpenACCClause *NewClause = nullptr;
1187
1188public:
1189 OpenACCDeclClauseInstantiator(Sema &S,
1190 const MultiLevelTemplateArgumentList &MLTAL,
1191 ArrayRef<OpenACCClause *> ExistingClauses,
1192 SemaOpenACC::OpenACCParsedClause &ParsedClause)
1193 : SemaRef(S), MLTAL(MLTAL), ExistingClauses(ExistingClauses),
1194 ParsedClause(ParsedClause) {}
1195
1196 OpenACCClause *CreatedClause() { return NewClause; }
1197#define VISIT_CLAUSE(CLAUSE_NAME) \
1198 void Visit##CLAUSE_NAME##Clause(const OpenACC##CLAUSE_NAME##Clause &Clause);
1199#include "clang/Basic/OpenACCClauses.def"
1200
1201 llvm::SmallVector<Expr *> VisitVarList(ArrayRef<Expr *> VarList) {
1202 llvm::SmallVector<Expr *> InstantiatedVarList;
1203 for (Expr *CurVar : VarList) {
1204 ExprResult Res = SemaRef.SubstExpr(CurVar, MLTAL);
1205
1206 if (!Res.isUsable())
1207 continue;
1208
1209 Res = SemaRef.OpenACC().ActOnVar(ParsedClause.getDirectiveKind(),
1210 ParsedClause.getClauseKind(), Res.get());
1211
1212 if (Res.isUsable())
1213 InstantiatedVarList.push_back(Res.get());
1214 }
1215 return InstantiatedVarList;
1216 }
1217};
1218
1219#define CLAUSE_NOT_ON_DECLS(CLAUSE_NAME) \
1220 void OpenACCDeclClauseInstantiator::Visit##CLAUSE_NAME##Clause( \
1221 const OpenACC##CLAUSE_NAME##Clause &) { \
1222 llvm_unreachable("Clause type invalid on declaration construct, or " \
1223 "instantiation not implemented"); \
1224 }
1225
1245CLAUSE_NOT_ON_DECLS(Private)
1252#undef CLAUSE_NOT_ON_DECLS
1253
1254void OpenACCDeclClauseInstantiator::VisitGangClause(
1255 const OpenACCGangClause &C) {
1256 llvm::SmallVector<OpenACCGangKind> TransformedGangKinds;
1257 llvm::SmallVector<Expr *> TransformedIntExprs;
1258 assert(C.getNumExprs() <= 1 &&
1259 "Only 1 expression allowed on gang clause in routine");
1260
1261 if (C.getNumExprs() > 0) {
1262 assert(C.getExpr(0).first == OpenACCGangKind::Dim &&
1263 "Only dim allowed on routine");
1264 ExprResult ER =
1265 SemaRef.SubstExpr(const_cast<Expr *>(C.getExpr(0).second), MLTAL);
1266 if (ER.isUsable()) {
1267 ER = SemaRef.OpenACC().CheckGangExpr(ExistingClauses,
1268 ParsedClause.getDirectiveKind(),
1269 C.getExpr(0).first, ER.get());
1270 if (ER.isUsable()) {
1271 TransformedGangKinds.push_back(OpenACCGangKind::Dim);
1272 TransformedIntExprs.push_back(ER.get());
1273 }
1274 }
1275 }
1276
1277 NewClause = SemaRef.OpenACC().CheckGangClause(
1278 ParsedClause.getDirectiveKind(), ExistingClauses,
1279 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1280 TransformedGangKinds, TransformedIntExprs, ParsedClause.getEndLoc());
1281}
1282
1283void OpenACCDeclClauseInstantiator::VisitSeqClause(const OpenACCSeqClause &C) {
1284 NewClause = OpenACCSeqClause::Create(SemaRef.getASTContext(),
1285 ParsedClause.getBeginLoc(),
1286 ParsedClause.getEndLoc());
1287}
1288void OpenACCDeclClauseInstantiator::VisitNoHostClause(
1289 const OpenACCNoHostClause &C) {
1290 NewClause = OpenACCNoHostClause::Create(SemaRef.getASTContext(),
1291 ParsedClause.getBeginLoc(),
1292 ParsedClause.getEndLoc());
1293}
1294
1295void OpenACCDeclClauseInstantiator::VisitDeviceTypeClause(
1296 const OpenACCDeviceTypeClause &C) {
1297 // Nothing to transform here, just create a new version of 'C'.
1299 SemaRef.getASTContext(), C.getClauseKind(), ParsedClause.getBeginLoc(),
1300 ParsedClause.getLParenLoc(), C.getArchitectures(),
1301 ParsedClause.getEndLoc());
1302}
1303
1304void OpenACCDeclClauseInstantiator::VisitWorkerClause(
1305 const OpenACCWorkerClause &C) {
1306 assert(!C.hasIntExpr() && "Int Expr not allowed on routine 'worker' clause");
1307 NewClause = OpenACCWorkerClause::Create(SemaRef.getASTContext(),
1308 ParsedClause.getBeginLoc(), {},
1309 nullptr, ParsedClause.getEndLoc());
1310}
1311
1312void OpenACCDeclClauseInstantiator::VisitVectorClause(
1313 const OpenACCVectorClause &C) {
1314 assert(!C.hasIntExpr() && "Int Expr not allowed on routine 'vector' clause");
1315 NewClause = OpenACCVectorClause::Create(SemaRef.getASTContext(),
1316 ParsedClause.getBeginLoc(), {},
1317 nullptr, ParsedClause.getEndLoc());
1318}
1319
1320void OpenACCDeclClauseInstantiator::VisitCopyClause(
1321 const OpenACCCopyClause &C) {
1322 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1323 C.getModifierList());
1324 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause, C.getModifierList()))
1325 return;
1326 NewClause = OpenACCCopyClause::Create(
1327 SemaRef.getASTContext(), ParsedClause.getClauseKind(),
1328 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1329 ParsedClause.getModifierList(), ParsedClause.getVarList(),
1330 ParsedClause.getEndLoc());
1331}
1332
1333void OpenACCDeclClauseInstantiator::VisitLinkClause(
1334 const OpenACCLinkClause &C) {
1335 ParsedClause.setVarListDetails(
1336 SemaRef.OpenACC().CheckLinkClauseVarList(VisitVarList(C.getVarList())),
1338
1339 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause,
1341 return;
1342
1343 NewClause = OpenACCLinkClause::Create(
1344 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1345 ParsedClause.getLParenLoc(), ParsedClause.getVarList(),
1346 ParsedClause.getEndLoc());
1347}
1348
1349void OpenACCDeclClauseInstantiator::VisitDeviceResidentClause(
1351 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1353 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause,
1355 return;
1357 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1358 ParsedClause.getLParenLoc(), ParsedClause.getVarList(),
1359 ParsedClause.getEndLoc());
1360}
1361
1362void OpenACCDeclClauseInstantiator::VisitCopyInClause(
1363 const OpenACCCopyInClause &C) {
1364 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1365 C.getModifierList());
1366
1367 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause, C.getModifierList()))
1368 return;
1369 NewClause = OpenACCCopyInClause::Create(
1370 SemaRef.getASTContext(), ParsedClause.getClauseKind(),
1371 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1372 ParsedClause.getModifierList(), ParsedClause.getVarList(),
1373 ParsedClause.getEndLoc());
1374}
1375void OpenACCDeclClauseInstantiator::VisitCopyOutClause(
1376 const OpenACCCopyOutClause &C) {
1377 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1378 C.getModifierList());
1379
1380 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause, C.getModifierList()))
1381 return;
1382 NewClause = OpenACCCopyOutClause::Create(
1383 SemaRef.getASTContext(), ParsedClause.getClauseKind(),
1384 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1385 ParsedClause.getModifierList(), ParsedClause.getVarList(),
1386 ParsedClause.getEndLoc());
1387}
1388void OpenACCDeclClauseInstantiator::VisitCreateClause(
1389 const OpenACCCreateClause &C) {
1390 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1391 C.getModifierList());
1392
1393 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause, C.getModifierList()))
1394 return;
1395 NewClause = OpenACCCreateClause::Create(
1396 SemaRef.getASTContext(), ParsedClause.getClauseKind(),
1397 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1398 ParsedClause.getModifierList(), ParsedClause.getVarList(),
1399 ParsedClause.getEndLoc());
1400}
1401void OpenACCDeclClauseInstantiator::VisitPresentClause(
1402 const OpenACCPresentClause &C) {
1403 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1405 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause,
1407 return;
1408 NewClause = OpenACCPresentClause::Create(
1409 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1410 ParsedClause.getLParenLoc(), ParsedClause.getVarList(),
1411 ParsedClause.getEndLoc());
1412}
1413void OpenACCDeclClauseInstantiator::VisitDevicePtrClause(
1414 const OpenACCDevicePtrClause &C) {
1415 llvm::SmallVector<Expr *> VarList = VisitVarList(C.getVarList());
1416 // Ensure each var is a pointer type.
1417 llvm::erase_if(VarList, [&](Expr *E) {
1418 return SemaRef.OpenACC().CheckVarIsPointerType(OpenACCClauseKind::DevicePtr,
1419 E);
1420 });
1421 ParsedClause.setVarListDetails(VarList, OpenACCModifierKind::Invalid);
1422 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause,
1424 return;
1426 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1427 ParsedClause.getLParenLoc(), ParsedClause.getVarList(),
1428 ParsedClause.getEndLoc());
1429}
1430
1431void OpenACCDeclClauseInstantiator::VisitBindClause(
1432 const OpenACCBindClause &C) {
1433 // Nothing to instantiate, we support only string literal or identifier.
1434 if (C.isStringArgument())
1435 NewClause = OpenACCBindClause::Create(
1436 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1437 ParsedClause.getLParenLoc(), C.getStringArgument(),
1438 ParsedClause.getEndLoc());
1439 else
1440 NewClause = OpenACCBindClause::Create(
1441 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1442 ParsedClause.getLParenLoc(), C.getIdentifierArgument(),
1443 ParsedClause.getEndLoc());
1444}
1445
1446llvm::SmallVector<OpenACCClause *> InstantiateOpenACCClauseList(
1447 Sema &S, const MultiLevelTemplateArgumentList &MLTAL,
1449 llvm::SmallVector<OpenACCClause *> TransformedClauses;
1450
1451 for (const auto *Clause : ClauseList) {
1452 SemaOpenACC::OpenACCParsedClause ParsedClause(DK, Clause->getClauseKind(),
1453 Clause->getBeginLoc());
1454 ParsedClause.setEndLoc(Clause->getEndLoc());
1455 if (const auto *WithParms = dyn_cast<OpenACCClauseWithParams>(Clause))
1456 ParsedClause.setLParenLoc(WithParms->getLParenLoc());
1457
1458 OpenACCDeclClauseInstantiator Instantiator{S, MLTAL, TransformedClauses,
1459 ParsedClause};
1460 Instantiator.Visit(Clause);
1461 if (Instantiator.CreatedClause())
1462 TransformedClauses.push_back(Instantiator.CreatedClause());
1463 }
1464 return TransformedClauses;
1465}
1466
1467} // namespace
1468
1470 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
1471 const OpenACCRoutineDeclAttr *OldAttr, const Decl *OldDecl, Decl *NewDecl) {
1472 OpenACCRoutineDeclAttr *A =
1473 OpenACCRoutineDeclAttr::Create(S.getASTContext(), OldAttr->getLocation());
1474
1475 if (!OldAttr->Clauses.empty()) {
1476 llvm::SmallVector<OpenACCClause *> TransformedClauses =
1477 InstantiateOpenACCClauseList(
1478 S, TemplateArgs, OpenACCDirectiveKind::Routine, OldAttr->Clauses);
1479 A->Clauses.assign(TransformedClauses.begin(), TransformedClauses.end());
1480 }
1481
1482 // We don't end up having to do any magic-static or bind checking here, since
1483 // the first phase should have caught this, since we always apply to the
1484 // functiondecl.
1485 NewDecl->addAttr(A);
1486}
1487
1488Decl *TemplateDeclInstantiator::VisitOpenACCDeclareDecl(OpenACCDeclareDecl *D) {
1489 SemaRef.OpenACC().ActOnConstruct(D->getDirectiveKind(), D->getBeginLoc());
1490 llvm::SmallVector<OpenACCClause *> TransformedClauses =
1491 InstantiateOpenACCClauseList(SemaRef, TemplateArgs, D->getDirectiveKind(),
1492 D->clauses());
1493
1494 if (SemaRef.OpenACC().ActOnStartDeclDirective(
1495 D->getDirectiveKind(), D->getBeginLoc(), TransformedClauses))
1496 return nullptr;
1497
1498 DeclGroupRef Res = SemaRef.OpenACC().ActOnEndDeclDirective(
1499 D->getDirectiveKind(), D->getBeginLoc(), D->getDirectiveLoc(), {}, {},
1500 D->getEndLoc(), TransformedClauses);
1501
1502 if (Res.isNull())
1503 return nullptr;
1504
1505 return Res.getSingleDecl();
1506}
1507
1508Decl *TemplateDeclInstantiator::VisitOpenACCRoutineDecl(OpenACCRoutineDecl *D) {
1509 SemaRef.OpenACC().ActOnConstruct(D->getDirectiveKind(), D->getBeginLoc());
1510 llvm::SmallVector<OpenACCClause *> TransformedClauses =
1511 InstantiateOpenACCClauseList(SemaRef, TemplateArgs, D->getDirectiveKind(),
1512 D->clauses());
1513
1514 ExprResult FuncRef;
1515 if (D->getFunctionReference()) {
1516 FuncRef = SemaRef.SubstCXXIdExpr(D->getFunctionReference(), TemplateArgs);
1517 if (FuncRef.isUsable())
1518 FuncRef = SemaRef.OpenACC().ActOnRoutineName(FuncRef.get());
1519 // We don't return early here, we leave the construct in the AST, even if
1520 // the function decl is empty.
1521 }
1522
1523 if (SemaRef.OpenACC().ActOnStartDeclDirective(
1524 D->getDirectiveKind(), D->getBeginLoc(), TransformedClauses))
1525 return nullptr;
1526
1527 DeclGroupRef Res = SemaRef.OpenACC().ActOnEndRoutineDeclDirective(
1528 D->getBeginLoc(), D->getDirectiveLoc(), D->getLParenLoc(), FuncRef.get(),
1529 D->getRParenLoc(), TransformedClauses, D->getEndLoc(), nullptr);
1530
1531 if (Res.isNull())
1532 return nullptr;
1533
1534 return Res.getSingleDecl();
1535}
1536
1537Decl *
1538TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1539 NamespaceAliasDecl *Inst
1540 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
1541 D->getNamespaceLoc(),
1542 D->getAliasLoc(),
1543 D->getIdentifier(),
1544 D->getQualifierLoc(),
1545 D->getTargetNameLoc(),
1546 D->getNamespace());
1547 Owner->addDecl(Inst);
1548 return Inst;
1549}
1550
1552 bool IsTypeAlias) {
1553 bool Invalid = false;
1555 if (TSI->getType()->isInstantiationDependentType() ||
1556 TSI->getType()->isVariablyModifiedType()) {
1557 TSI = SemaRef.SubstType(TSI, TemplateArgs, D->getLocation(),
1558 D->getDeclName());
1559 if (!TSI) {
1560 Invalid = true;
1561 TSI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
1562 }
1563 } else {
1564 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), TSI->getType());
1565 }
1566
1567 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
1568 // libstdc++ relies upon this bug in its implementation of common_type. If we
1569 // happen to be processing that implementation, fake up the g++ ?:
1570 // semantics. See LWG issue 2141 for more information on the bug. The bugs
1571 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
1572 if (SemaRef.getPreprocessor().NeedsStdLibCxxWorkaroundBefore(2014'04'22)) {
1573 const DecltypeType *DT = TSI->getType()->getAs<DecltypeType>();
1574 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1575 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
1576 DT->isReferenceType() &&
1577 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
1578 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
1579 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
1580 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
1581 // Fold it to the (non-reference) type which g++ would have produced.
1582 TSI = SemaRef.Context.getTrivialTypeSourceInfo(
1583 TSI->getType().getNonReferenceType());
1584 }
1585
1586 // Create the new typedef
1588 if (IsTypeAlias)
1589 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1590 D->getLocation(), D->getIdentifier(), TSI);
1591 else
1592 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1593 D->getLocation(), D->getIdentifier(), TSI);
1594 if (Invalid)
1595 Typedef->setInvalidDecl();
1596
1597 // If the old typedef was the name for linkage purposes of an anonymous
1598 // tag decl, re-establish that relationship for the new typedef.
1599 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1600 TagDecl *oldTag = oldTagType->getDecl();
1601 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1602 TagDecl *newTag = TSI->getType()->castAs<TagType>()->getDecl();
1603 assert(!newTag->hasNameForLinkage());
1605 }
1606 }
1607
1609 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1610 TemplateArgs);
1611 if (!InstPrev)
1612 return nullptr;
1613
1614 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1615
1616 // If the typedef types are not identical, reject them.
1617 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1618
1619 Typedef->setPreviousDecl(InstPrevTypedef);
1620 }
1621
1622 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1623
1624 if (D->getUnderlyingType()->getAs<DependentNameType>())
1625 SemaRef.inferGslPointerAttribute(Typedef);
1626
1627 Typedef->setAccess(D->getAccess());
1628 Typedef->setReferenced(D->isReferenced());
1629
1630 return Typedef;
1631}
1632
1633Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1634 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1635 if (Typedef)
1636 Owner->addDecl(Typedef);
1637 return Typedef;
1638}
1639
1640Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1641 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1642 if (Typedef)
1643 Owner->addDecl(Typedef);
1644 return Typedef;
1645}
1646
1649 // Create a local instantiation scope for this type alias template, which
1650 // will contain the instantiations of the template parameters.
1652
1654 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1655 if (!InstParams)
1656 return nullptr;
1657
1658 // FIXME: This is a hack for instantiating lambdas in the pattern of the
1659 // alias. We are not really instantiating the alias at its template level,
1660 // that only happens in CheckTemplateId, this is only for outer templates
1661 // which contain it. In getTemplateInstantiationArgs, the template arguments
1662 // used here would be used for collating the template arguments needed to
1663 // instantiate the lambda. Pass an empty argument list, so this workaround
1664 // doesn't get confused if there is an outer alias being instantiated.
1665 Sema::InstantiatingTemplate InstTemplate(SemaRef, D->getBeginLoc(), D,
1667 if (InstTemplate.isInvalid())
1668 return nullptr;
1669
1670 TypeAliasDecl *Pattern = D->getTemplatedDecl();
1671 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1673 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1674 if (!Found.empty()) {
1675 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1676 }
1677 }
1678
1679 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1680 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1681 if (!AliasInst)
1682 return nullptr;
1683
1685 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1686 D->getDeclName(), InstParams, AliasInst);
1687 AliasInst->setDescribedAliasTemplate(Inst);
1688 if (PrevAliasTemplate)
1689 Inst->setPreviousDecl(PrevAliasTemplate);
1690
1691 Inst->setAccess(D->getAccess());
1692
1693 if (!PrevAliasTemplate)
1695
1696 return Inst;
1697}
1698
1699Decl *
1700TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1702 if (Inst)
1703 Owner->addDecl(Inst);
1704
1705 return Inst;
1706}
1707
1708Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1709 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1710 D->getIdentifier(), D->getType());
1711 NewBD->setReferenced(D->isReferenced());
1713
1714 return NewBD;
1715}
1716
1717Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1718 // Transform the bindings first.
1719 // The transformed DD will have all of the concrete BindingDecls.
1720 SmallVector<BindingDecl*, 16> NewBindings;
1721 BindingDecl *OldBindingPack = nullptr;
1722 for (auto *OldBD : D->bindings()) {
1723 Expr *BindingExpr = OldBD->getBinding();
1724 if (isa_and_present<FunctionParmPackExpr>(BindingExpr)) {
1725 // We have a resolved pack.
1726 assert(!OldBindingPack && "no more than one pack is allowed");
1727 OldBindingPack = OldBD;
1728 }
1729 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1730 }
1731 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1732
1733 auto *NewDD = cast_if_present<DecompositionDecl>(
1734 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1735
1736 if (!NewDD || NewDD->isInvalidDecl()) {
1737 for (auto *NewBD : NewBindings)
1738 NewBD->setInvalidDecl();
1739 } else if (OldBindingPack) {
1740 // Mark the bindings in the pack as instantiated.
1741 auto Bindings = NewDD->bindings();
1742 BindingDecl *NewBindingPack = *llvm::find_if(
1743 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
1744 assert(NewBindingPack != nullptr && "new bindings should also have a pack");
1745 llvm::ArrayRef<BindingDecl *> OldDecls =
1746 OldBindingPack->getBindingPackDecls();
1747 llvm::ArrayRef<BindingDecl *> NewDecls =
1748 NewBindingPack->getBindingPackDecls();
1749 assert(OldDecls.size() == NewDecls.size());
1750 for (unsigned I = 0; I < OldDecls.size(); I++)
1751 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldDecls[I],
1752 NewDecls[I]);
1753 }
1754
1755 return NewDD;
1756}
1757
1759 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1760}
1761
1763 bool InstantiatingVarTemplate,
1765
1766 // Do substitution on the type of the declaration
1767 TypeSourceInfo *TSI = SemaRef.SubstType(
1768 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1769 D->getDeclName(), /*AllowDeducedTST*/ true);
1770 if (!TSI)
1771 return nullptr;
1772
1773 if (TSI->getType()->isFunctionType()) {
1774 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1775 << D->isStaticDataMember() << TSI->getType();
1776 return nullptr;
1777 }
1778
1779 DeclContext *DC = Owner;
1780 if (D->isLocalExternDecl())
1782
1783 // Build the instantiated declaration.
1784 VarDecl *Var;
1785 if (Bindings)
1786 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1787 D->getLocation(), TSI->getType(), TSI,
1788 D->getStorageClass(), *Bindings);
1789 else
1790 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1791 D->getLocation(), D->getIdentifier(), TSI->getType(),
1792 TSI, D->getStorageClass());
1793
1794 // In ARC, infer 'retaining' for variables of retainable type.
1795 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1796 SemaRef.ObjC().inferObjCARCLifetime(Var))
1797 Var->setInvalidDecl();
1798
1799 if (SemaRef.getLangOpts().OpenCL)
1800 SemaRef.deduceOpenCLAddressSpace(Var);
1801
1802 // Substitute the nested name specifier, if any.
1803 if (SubstQualifier(D, Var))
1804 return nullptr;
1805
1806 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1807 StartingScope, InstantiatingVarTemplate);
1808 if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1809 QualType RT;
1810 if (auto *F = dyn_cast<FunctionDecl>(DC))
1811 RT = F->getReturnType();
1812 else if (isa<BlockDecl>(DC))
1814 ->getReturnType();
1815 else
1816 llvm_unreachable("Unknown context type");
1817
1818 // This is the last chance we have of checking copy elision eligibility
1819 // for functions in dependent contexts. The sema actions for building
1820 // the return statement during template instantiation will have no effect
1821 // regarding copy elision, since NRVO propagation runs on the scope exit
1822 // actions, and these are not run on instantiation.
1823 // This might run through some VarDecls which were returned from non-taken
1824 // 'if constexpr' branches, and these will end up being constructed on the
1825 // return slot even if they will never be returned, as a sort of accidental
1826 // 'optimization'. Notably, functions with 'auto' return types won't have it
1827 // deduced by this point. Coupled with the limitation described
1828 // previously, this makes it very hard to support copy elision for these.
1829 Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1830 bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1831 Var->setNRVOVariable(NRVO);
1832 }
1833
1834 Var->setImplicit(D->isImplicit());
1835
1836 if (Var->isStaticLocal())
1837 SemaRef.CheckStaticLocalForDllExport(Var);
1838
1839 if (Var->getTLSKind())
1840 SemaRef.CheckThreadLocalForLargeAlignment(Var);
1841
1842 if (SemaRef.getLangOpts().OpenACC)
1843 SemaRef.OpenACC().ActOnVariableDeclarator(Var);
1844
1845 return Var;
1846}
1847
1848Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1849 AccessSpecDecl* AD
1850 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1852 Owner->addHiddenDecl(AD);
1853 return AD;
1854}
1855
1856Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1857 bool Invalid = false;
1858 TypeSourceInfo *TSI = D->getTypeSourceInfo();
1859 if (TSI->getType()->isInstantiationDependentType() ||
1860 TSI->getType()->isVariablyModifiedType()) {
1861 TSI = SemaRef.SubstType(TSI, TemplateArgs, D->getLocation(),
1862 D->getDeclName());
1863 if (!TSI) {
1864 TSI = D->getTypeSourceInfo();
1865 Invalid = true;
1866 } else if (TSI->getType()->isFunctionType()) {
1867 // C++ [temp.arg.type]p3:
1868 // If a declaration acquires a function type through a type
1869 // dependent on a template-parameter and this causes a
1870 // declaration that does not use the syntactic form of a
1871 // function declarator to have function type, the program is
1872 // ill-formed.
1873 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1874 << TSI->getType();
1875 Invalid = true;
1876 }
1877 } else {
1878 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), TSI->getType());
1879 }
1880
1881 Expr *BitWidth = D->getBitWidth();
1882 if (Invalid)
1883 BitWidth = nullptr;
1884 else if (BitWidth) {
1885 // The bit-width expression is a constant expression.
1886 EnterExpressionEvaluationContext Unevaluated(
1888
1889 ExprResult InstantiatedBitWidth
1890 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1891 if (InstantiatedBitWidth.isInvalid()) {
1892 Invalid = true;
1893 BitWidth = nullptr;
1894 } else
1895 BitWidth = InstantiatedBitWidth.getAs<Expr>();
1896 }
1897
1898 FieldDecl *Field = SemaRef.CheckFieldDecl(
1899 D->getDeclName(), TSI->getType(), TSI, cast<RecordDecl>(Owner),
1900 D->getLocation(), D->isMutable(), BitWidth, D->getInClassInitStyle(),
1901 D->getInnerLocStart(), D->getAccess(), nullptr);
1902 if (!Field) {
1903 cast<Decl>(Owner)->setInvalidDecl();
1904 return nullptr;
1905 }
1906
1907 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1908
1909 if (Field->hasAttrs())
1910 SemaRef.CheckAlignasUnderalignment(Field);
1911
1912 if (Invalid)
1913 Field->setInvalidDecl();
1914
1915 if (!Field->getDeclName() || Field->isPlaceholderVar(SemaRef.getLangOpts())) {
1916 // Keep track of where this decl came from.
1917 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1918 }
1919 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1920 if (Parent->isAnonymousStructOrUnion() &&
1921 Parent->getRedeclContext()->isFunctionOrMethod())
1922 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1923 }
1924
1925 Field->setImplicit(D->isImplicit());
1926 Field->setAccess(D->getAccess());
1927 Owner->addDecl(Field);
1928
1929 return Field;
1930}
1931
1932Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1933 bool Invalid = false;
1934 TypeSourceInfo *TSI = D->getTypeSourceInfo();
1935
1936 if (TSI->getType()->isVariablyModifiedType()) {
1937 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1938 << D;
1939 Invalid = true;
1940 } else if (TSI->getType()->isInstantiationDependentType()) {
1941 TSI = SemaRef.SubstType(TSI, TemplateArgs, D->getLocation(),
1942 D->getDeclName());
1943 if (!TSI) {
1944 TSI = D->getTypeSourceInfo();
1945 Invalid = true;
1946 } else if (TSI->getType()->isFunctionType()) {
1947 // C++ [temp.arg.type]p3:
1948 // If a declaration acquires a function type through a type
1949 // dependent on a template-parameter and this causes a
1950 // declaration that does not use the syntactic form of a
1951 // function declarator to have function type, the program is
1952 // ill-formed.
1953 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1954 << TSI->getType();
1955 Invalid = true;
1956 }
1957 } else {
1958 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), TSI->getType());
1959 }
1960
1961 MSPropertyDecl *Property = MSPropertyDecl::Create(
1962 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(),
1963 TSI->getType(), TSI, D->getBeginLoc(), D->getGetterId(),
1964 D->getSetterId());
1965
1966 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1967 StartingScope);
1968
1969 if (Invalid)
1970 Property->setInvalidDecl();
1971
1972 Property->setAccess(D->getAccess());
1973 Owner->addDecl(Property);
1974
1975 return Property;
1976}
1977
1978Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1979 NamedDecl **NamedChain =
1980 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1981
1982 int i = 0;
1983 for (auto *PI : D->chain()) {
1984 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1985 TemplateArgs);
1986 if (!Next)
1987 return nullptr;
1988
1989 NamedChain[i++] = Next;
1990 }
1991
1992 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1993 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1994 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1995 {NamedChain, D->getChainingSize()});
1996
1997 for (const auto *Attr : D->attrs())
1998 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1999
2000 IndirectField->setImplicit(D->isImplicit());
2001 IndirectField->setAccess(D->getAccess());
2002 Owner->addDecl(IndirectField);
2003 return IndirectField;
2004}
2005
2006Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
2007 // Handle friend type expressions by simply substituting template
2008 // parameters into the pattern type and checking the result.
2009 if (TypeSourceInfo *Ty = D->getFriendType()) {
2010 TypeSourceInfo *InstTy;
2011 // If this is an unsupported friend, don't bother substituting template
2012 // arguments into it. The actual type referred to won't be used by any
2013 // parts of Clang, and may not be valid for instantiating. Just use the
2014 // same info for the instantiated friend.
2015 if (D->isUnsupportedFriend()) {
2016 InstTy = Ty;
2017 } else {
2018 if (D->isPackExpansion()) {
2019 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2020 SemaRef.collectUnexpandedParameterPacks(Ty->getTypeLoc(), Unexpanded);
2021 assert(!Unexpanded.empty() && "Pack expansion without packs");
2022
2023 bool ShouldExpand = true;
2024 bool RetainExpansion = false;
2025 UnsignedOrNone NumExpansions = std::nullopt;
2026 if (SemaRef.CheckParameterPacksForExpansion(
2027 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded,
2028 TemplateArgs, /*FailOnPackProducingTemplates=*/true,
2029 ShouldExpand, RetainExpansion, NumExpansions))
2030 return nullptr;
2031
2032 assert(!RetainExpansion &&
2033 "should never retain an expansion for a variadic friend decl");
2034
2035 if (ShouldExpand) {
2036 SmallVector<FriendDecl *> Decls;
2037 for (unsigned I = 0; I != *NumExpansions; I++) {
2038 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
2039 TypeSourceInfo *TSI = SemaRef.SubstType(
2040 Ty, TemplateArgs, D->getEllipsisLoc(), DeclarationName());
2041 if (!TSI)
2042 return nullptr;
2043
2044 auto FD =
2045 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2046 TSI, D->getFriendLoc());
2047
2048 FD->setAccess(AS_public);
2049 Owner->addDecl(FD);
2050 Decls.push_back(FD);
2051 }
2052
2053 // Just drop this node; we have no use for it anymore.
2054 return nullptr;
2055 }
2056 }
2057
2058 InstTy = SemaRef.SubstType(Ty, TemplateArgs, D->getLocation(),
2059 DeclarationName());
2060 }
2061 if (!InstTy)
2062 return nullptr;
2063
2064 FriendDecl *FD = FriendDecl::Create(
2065 SemaRef.Context, Owner, D->getLocation(), InstTy, D->getFriendLoc());
2066 FD->setAccess(AS_public);
2068 Owner->addDecl(FD);
2069 return FD;
2070 }
2071
2072 NamedDecl *ND = D->getFriendDecl();
2073 assert(ND && "friend decl must be a decl or a type!");
2074
2075 // All of the Visit implementations for the various potential friend
2076 // declarations have to be carefully written to work for friend
2077 // objects, with the most important detail being that the target
2078 // decl should almost certainly not be placed in Owner.
2079 Decl *NewND = Visit(ND);
2080 if (!NewND) return nullptr;
2081
2082 FriendDecl *FD =
2083 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2084 cast<NamedDecl>(NewND), D->getFriendLoc());
2085 FD->setAccess(AS_public);
2087 Owner->addDecl(FD);
2088 return FD;
2089}
2090
2091Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
2092 Expr *AssertExpr = D->getAssertExpr();
2093
2094 // The expression in a static assertion is a constant expression.
2095 EnterExpressionEvaluationContext Unevaluated(
2097
2098 ExprResult InstantiatedAssertExpr
2099 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
2100 if (InstantiatedAssertExpr.isInvalid())
2101 return nullptr;
2102
2103 ExprResult InstantiatedMessageExpr =
2104 SemaRef.SubstExpr(D->getMessage(), TemplateArgs);
2105 if (InstantiatedMessageExpr.isInvalid())
2106 return nullptr;
2107
2108 return SemaRef.BuildStaticAssertDeclaration(
2109 D->getLocation(), InstantiatedAssertExpr.get(),
2110 InstantiatedMessageExpr.get(), D->getRParenLoc(), D->isFailed());
2111}
2112
2113Decl *TemplateDeclInstantiator::VisitExplicitInstantiationDecl(
2115 // ExplicitInstantiationDecl is a source-info-only node and should not
2116 // appear inside a template pattern. Nothing to instantiate.
2117 llvm_unreachable("ExplicitInstantiationDecl should not be instantiated");
2118}
2119
2120Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
2121 EnumDecl *PrevDecl = nullptr;
2122 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2123 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
2124 PatternPrev,
2125 TemplateArgs);
2126 if (!Prev) return nullptr;
2127 PrevDecl = cast<EnumDecl>(Prev);
2128 }
2129
2130 EnumDecl *Enum =
2131 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
2132 D->getLocation(), D->getIdentifier(), PrevDecl,
2133 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
2134 if (D->isFixed()) {
2135 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
2136 // If we have type source information for the underlying type, it means it
2137 // has been explicitly set by the user. Perform substitution on it before
2138 // moving on.
2139 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
2140 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
2141 DeclarationName());
2142 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
2143 Enum->setIntegerType(SemaRef.Context.IntTy);
2144 else {
2145 // If the underlying type is atomic, we need to adjust the type before
2146 // continuing. See C23 6.7.3.3p5 and Sema::ActOnTag(). FIXME: same as
2147 // within ActOnTag(), it would be nice to have an easy way to get a
2148 // derived TypeSourceInfo which strips qualifiers including the weird
2149 // ones like _Atomic where it forms a different type.
2150 if (NewTI->getType()->isAtomicType())
2151 Enum->setIntegerType(NewTI->getType().getAtomicUnqualifiedType());
2152 else
2153 Enum->setIntegerTypeSourceInfo(NewTI);
2154 }
2155
2156 // C++23 [conv.prom]p4
2157 // if integral promotion can be applied to its underlying type, a prvalue
2158 // of an unscoped enumeration type whose underlying type is fixed can also
2159 // be converted to a prvalue of the promoted underlying type.
2160 //
2161 // FIXME: that logic is already implemented in ActOnEnumBody, factor out
2162 // into (Re)BuildEnumBody.
2163 QualType UnderlyingType = Enum->getIntegerType();
2164 Enum->setPromotionType(
2165 SemaRef.Context.isPromotableIntegerType(UnderlyingType)
2166 ? SemaRef.Context.getPromotedIntegerType(UnderlyingType)
2167 : UnderlyingType);
2168 } else {
2169 assert(!D->getIntegerType()->isDependentType()
2170 && "Dependent type without type source info");
2171 Enum->setIntegerType(D->getIntegerType());
2172 }
2173 }
2174
2175 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
2176
2177 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
2178 Enum->setAccess(D->getAccess());
2179 // Forward the mangling number from the template to the instantiated decl.
2180 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
2181 // See if the old tag was defined along with a declarator.
2182 // If it did, mark the new tag as being associated with that declarator.
2183 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
2184 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
2185 // See if the old tag was defined along with a typedef.
2186 // If it did, mark the new tag as being associated with that typedef.
2187 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
2188 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
2189 if (SubstQualifier(D, Enum)) return nullptr;
2190 Owner->addDecl(Enum);
2191
2192 EnumDecl *Def = D->getDefinition();
2193 if (Def && Def != D) {
2194 // If this is an out-of-line definition of an enum member template, check
2195 // that the underlying types match in the instantiation of both
2196 // declarations.
2197 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
2198 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
2199 QualType DefnUnderlying =
2200 SemaRef.SubstType(TI->getType(), TemplateArgs,
2201 UnderlyingLoc, DeclarationName());
2202 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
2203 DefnUnderlying, /*IsFixed=*/true, Enum);
2204 }
2205 }
2206
2207 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2208 // specialization causes the implicit instantiation of the declarations, but
2209 // not the definitions of scoped member enumerations.
2210 //
2211 // DR1484 clarifies that enumeration definitions inside a template
2212 // declaration aren't considered entities that can be separately instantiated
2213 // from the rest of the entity they are declared inside.
2214 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
2215 // Prevent redundant instantiation of the enumerator-definition if the
2216 // definition has already been instantiated due to a prior
2217 // opaque-enum-declaration.
2218 if (PrevDecl == nullptr) {
2219 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
2221 }
2222 }
2223
2224 return Enum;
2225}
2226
2228 EnumDecl *Enum, EnumDecl *Pattern) {
2229 Enum->startDefinition();
2230
2231 // Update the location to refer to the definition.
2232 Enum->setLocation(Pattern->getLocation());
2233
2234 SmallVector<Decl*, 4> Enumerators;
2235
2236 EnumConstantDecl *LastEnumConst = nullptr;
2237 for (auto *EC : Pattern->enumerators()) {
2238 // The specified value for the enumerator.
2239 ExprResult Value((Expr *)nullptr);
2240 if (Expr *UninstValue = EC->getInitExpr()) {
2241 // The enumerator's value expression is a constant expression.
2244
2245 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
2246 }
2247
2248 // Drop the initial value and continue.
2249 bool isInvalid = false;
2250 if (Value.isInvalid()) {
2251 Value = nullptr;
2252 isInvalid = true;
2253 }
2254
2255 EnumConstantDecl *EnumConst
2256 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
2257 EC->getLocation(), EC->getIdentifier(),
2258 Value.get());
2259
2260 if (isInvalid) {
2261 if (EnumConst)
2262 EnumConst->setInvalidDecl();
2263 Enum->setInvalidDecl();
2264 }
2265
2266 if (EnumConst) {
2267 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
2268
2269 EnumConst->setAccess(Enum->getAccess());
2270 Enum->addDecl(EnumConst);
2271 Enumerators.push_back(EnumConst);
2272 LastEnumConst = EnumConst;
2273
2274 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
2275 !Enum->isScoped()) {
2276 // If the enumeration is within a function or method, record the enum
2277 // constant as a local.
2278 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
2279 }
2280 }
2281 }
2282
2283 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
2284 Enumerators, nullptr, ParsedAttributesView());
2285}
2286
2287Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
2288 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
2289}
2290
2291Decl *
2292TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2293 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
2294}
2295
2296Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2297 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2298
2299 // Create a local instantiation scope for this class template, which
2300 // will contain the instantiations of the template parameters.
2301 LocalInstantiationScope Scope(SemaRef);
2302 TemplateParameterList *TempParams = D->getTemplateParameters();
2303 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2304 if (!InstParams)
2305 return nullptr;
2306
2307 CXXRecordDecl *Pattern = D->getTemplatedDecl();
2308
2309 // Instantiate the qualifier. We have to do this first in case
2310 // we're a friend declaration, because if we are then we need to put
2311 // the new declaration in the appropriate context.
2312 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
2313 if (QualifierLoc) {
2314 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2315 TemplateArgs);
2316 if (!QualifierLoc)
2317 return nullptr;
2318 }
2319
2320 CXXRecordDecl *PrevDecl = nullptr;
2321 ClassTemplateDecl *PrevClassTemplate = nullptr;
2322
2323 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
2324 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
2325 if (!Found.empty()) {
2326 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
2327 if (PrevClassTemplate)
2328 PrevDecl = PrevClassTemplate->getTemplatedDecl();
2329 }
2330 }
2331
2332 // If this isn't a friend, then it's a member template, in which
2333 // case we just want to build the instantiation in the
2334 // specialization. If it is a friend, we want to build it in
2335 // the appropriate context.
2336 DeclContext *DC = Owner;
2337 if (isFriend) {
2338 if (QualifierLoc) {
2339 CXXScopeSpec SS;
2340 SS.Adopt(QualifierLoc);
2341 DC = SemaRef.computeDeclContext(SS);
2342 if (!DC) return nullptr;
2343 } else {
2344 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
2345 Pattern->getDeclContext(),
2346 TemplateArgs);
2347 }
2348
2349 // Look for a previous declaration of the template in the owning
2350 // context.
2351 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
2353 SemaRef.forRedeclarationInCurContext());
2354 SemaRef.LookupQualifiedName(R, DC);
2355
2356 if (R.isSingleResult()) {
2357 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
2358 if (PrevClassTemplate)
2359 PrevDecl = PrevClassTemplate->getTemplatedDecl();
2360 }
2361
2362 if (!PrevClassTemplate && QualifierLoc) {
2363 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
2364 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
2365 << QualifierLoc.getSourceRange();
2366 return nullptr;
2367 }
2368 }
2369
2370 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
2371 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
2372 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl);
2373 if (QualifierLoc)
2374 RecordInst->setQualifierInfo(QualifierLoc);
2375
2376 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
2377 StartingScope);
2378
2379 ClassTemplateDecl *Inst
2380 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
2381 D->getIdentifier(), InstParams, RecordInst);
2382 RecordInst->setDescribedClassTemplate(Inst);
2383
2384 if (isFriend) {
2385 assert(!Owner->isDependentContext());
2386 Inst->setLexicalDeclContext(Owner);
2387 RecordInst->setLexicalDeclContext(Owner);
2388 Inst->setObjectOfFriendDecl();
2389
2390 if (PrevClassTemplate) {
2391 Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
2392 const ClassTemplateDecl *MostRecentPrevCT =
2393 PrevClassTemplate->getMostRecentDecl();
2394 TemplateParameterList *PrevParams =
2395 MostRecentPrevCT->getTemplateParameters();
2396
2397 // Make sure the parameter lists match.
2398 if (!SemaRef.TemplateParameterListsAreEqual(
2399 RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
2400 PrevParams, true, Sema::TPL_TemplateMatch))
2401 return nullptr;
2402
2403 // Do some additional validation, then merge default arguments
2404 // from the existing declarations.
2405 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
2407 return nullptr;
2408
2409 Inst->setAccess(PrevClassTemplate->getAccess());
2410 } else {
2411 Inst->setAccess(D->getAccess());
2412 }
2413
2414 Inst->setObjectOfFriendDecl();
2415 // TODO: do we want to track the instantiation progeny of this
2416 // friend target decl?
2417 } else {
2418 Inst->setAccess(D->getAccess());
2419 if (!PrevClassTemplate)
2421 }
2422
2423 Inst->setPreviousDecl(PrevClassTemplate);
2424
2425 // Finish handling of friends.
2426 if (isFriend) {
2427 DC->makeDeclVisibleInContext(Inst);
2428 return Inst;
2429 }
2430
2431 if (D->isOutOfLine()) {
2434 }
2435
2436 Owner->addDecl(Inst);
2437
2438 if (!PrevClassTemplate) {
2439 // Queue up any out-of-line partial specializations of this member
2440 // class template; the client will force their instantiation once
2441 // the enclosing class has been instantiated.
2442 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2443 D->getPartialSpecializations(PartialSpecs);
2444 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
2445 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
2446 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
2447 }
2448
2449 return Inst;
2450}
2451
2452Decl *
2453TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
2455 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2456
2457 // Lookup the already-instantiated declaration in the instantiation
2458 // of the class template and return that.
2460 = Owner->lookup(ClassTemplate->getDeclName());
2461 if (Found.empty())
2462 return nullptr;
2463
2464 ClassTemplateDecl *InstClassTemplate
2465 = dyn_cast<ClassTemplateDecl>(Found.front());
2466 if (!InstClassTemplate)
2467 return nullptr;
2468
2469 if (ClassTemplatePartialSpecializationDecl *Result
2470 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
2471 return Result;
2472
2473 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
2474}
2475
2476Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
2477 assert(D->getTemplatedDecl()->isStaticDataMember() &&
2478 "Only static data member templates are allowed.");
2479
2480 // Create a local instantiation scope for this variable template, which
2481 // will contain the instantiations of the template parameters.
2482 LocalInstantiationScope Scope(SemaRef);
2483 TemplateParameterList *TempParams = D->getTemplateParameters();
2484 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2485 if (!InstParams)
2486 return nullptr;
2487
2488 VarDecl *Pattern = D->getTemplatedDecl();
2489 VarTemplateDecl *PrevVarTemplate = nullptr;
2490
2491 if (getPreviousDeclForInstantiation(Pattern)) {
2492 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
2493 if (!Found.empty())
2494 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
2495 }
2496
2497 VarDecl *VarInst =
2498 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
2499 /*InstantiatingVarTemplate=*/true));
2500 if (!VarInst) return nullptr;
2501
2502 DeclContext *DC = Owner;
2503
2504 VarTemplateDecl *Inst = VarTemplateDecl::Create(
2505 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
2506 VarInst);
2507 VarInst->setDescribedVarTemplate(Inst);
2508 Inst->setPreviousDecl(PrevVarTemplate);
2509
2510 Inst->setAccess(D->getAccess());
2511 if (!PrevVarTemplate)
2513
2514 if (D->isOutOfLine()) {
2517 }
2518
2519 Owner->addDecl(Inst);
2520
2521 if (!PrevVarTemplate) {
2522 // Queue up any out-of-line partial specializations of this member
2523 // variable template; the client will force their instantiation once
2524 // the enclosing class has been instantiated.
2525 SmallVector<VarTemplatePartialSpecializationDecl *, 1> PartialSpecs;
2526 D->getPartialSpecializations(PartialSpecs);
2527 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
2528 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
2529 OutOfLineVarPartialSpecs.push_back(
2530 std::make_pair(Inst, PartialSpecs[I]));
2531 }
2532
2533 return Inst;
2534}
2535
2536Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
2538 assert(D->isStaticDataMember() &&
2539 "Only static data member templates are allowed.");
2540
2541 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2542
2543 // Lookup the already-instantiated declaration and return that.
2544 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
2545 assert(!Found.empty() && "Instantiation found nothing?");
2546
2547 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
2548 assert(InstVarTemplate && "Instantiation did not find a variable template?");
2549
2550 if (VarTemplatePartialSpecializationDecl *Result =
2551 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
2552 return Result;
2553
2554 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
2555}
2556
2557Decl *
2558TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2559 // Create a local instantiation scope for this function template, which
2560 // will contain the instantiations of the template parameters and then get
2561 // merged with the local instantiation scope for the function template
2562 // itself.
2563 LocalInstantiationScope Scope(SemaRef);
2564 Sema::ConstraintEvalRAII<TemplateDeclInstantiator> RAII(*this);
2565
2566 TemplateParameterList *TempParams = D->getTemplateParameters();
2567 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2568 if (!InstParams)
2569 return nullptr;
2570
2571 FunctionDecl *Instantiated = nullptr;
2572 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
2573 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
2574 InstParams));
2575 else
2576 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
2577 D->getTemplatedDecl(),
2578 InstParams));
2579
2580 if (!Instantiated)
2581 return nullptr;
2582
2583 // Link the instantiated function template declaration to the function
2584 // template from which it was instantiated.
2585 FunctionTemplateDecl *InstTemplate
2586 = Instantiated->getDescribedFunctionTemplate();
2587 InstTemplate->setAccess(D->getAccess());
2588 assert(InstTemplate &&
2589 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
2590
2591 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
2592
2593 // Link the instantiation back to the pattern *unless* this is a
2594 // non-definition friend declaration.
2595 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
2596 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
2597 InstTemplate->setInstantiatedFromMemberTemplate(D);
2598
2599 // Make declarations visible in the appropriate context.
2600 if (!isFriend) {
2601 Owner->addDecl(InstTemplate);
2602 } else if (InstTemplate->getDeclContext()->isRecord() &&
2604 SemaRef.CheckFriendAccess(InstTemplate);
2605 }
2606
2607 return InstTemplate;
2608}
2609
2610Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
2611 CXXRecordDecl *PrevDecl = nullptr;
2612 if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2613 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
2614 PatternPrev,
2615 TemplateArgs);
2616 if (!Prev) return nullptr;
2617 PrevDecl = cast<CXXRecordDecl>(Prev);
2618 }
2619
2620 CXXRecordDecl *Record = nullptr;
2621 bool IsInjectedClassName = D->isInjectedClassName();
2622 if (D->isLambda())
2624 SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
2627 else
2628 Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
2629 D->getBeginLoc(), D->getLocation(),
2630 D->getIdentifier(), PrevDecl);
2631
2632 Record->setImplicit(D->isImplicit());
2633
2634 // Substitute the nested name specifier, if any.
2635 if (SubstQualifier(D, Record))
2636 return nullptr;
2637
2638 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
2639 StartingScope);
2640
2641 // FIXME: Check against AS_none is an ugly hack to work around the issue that
2642 // the tag decls introduced by friend class declarations don't have an access
2643 // specifier. Remove once this area of the code gets sorted out.
2644 if (D->getAccess() != AS_none)
2645 Record->setAccess(D->getAccess());
2646 if (!IsInjectedClassName)
2647 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2648
2649 // If the original function was part of a friend declaration,
2650 // inherit its namespace state.
2651 if (D->getFriendObjectKind())
2652 Record->setObjectOfFriendDecl();
2653
2654 // Make sure that anonymous structs and unions are recorded.
2655 if (D->isAnonymousStructOrUnion())
2656 Record->setAnonymousStructOrUnion(true);
2657
2658 if (D->isLocalClass())
2659 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
2660
2661 // Forward the mangling number from the template to the instantiated decl.
2662 SemaRef.Context.setManglingNumber(Record,
2663 SemaRef.Context.getManglingNumber(D));
2664
2665 // See if the old tag was defined along with a declarator.
2666 // If it did, mark the new tag as being associated with that declarator.
2667 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
2668 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
2669
2670 // See if the old tag was defined along with a typedef.
2671 // If it did, mark the new tag as being associated with that typedef.
2672 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
2673 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
2674
2675 Owner->addDecl(Record);
2676
2677 // DR1484 clarifies that the members of a local class are instantiated as part
2678 // of the instantiation of their enclosing entity.
2679 if (D->isCompleteDefinition() && D->isLocalClass()) {
2680 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef,
2681 /*AtEndOfTU=*/false);
2682
2683 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
2685 /*Complain=*/true);
2686
2687 // For nested local classes, we will instantiate the members when we
2688 // reach the end of the outermost (non-nested) local class.
2689 if (!D->isCXXClassMember())
2690 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
2692
2693 // This class may have local implicit instantiations that need to be
2694 // performed within this scope.
2695 LocalInstantiations.perform();
2696 }
2697
2698 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
2699
2700 if (IsInjectedClassName)
2701 assert(Record->isInjectedClassName() && "Broken injected-class-name");
2702
2703 return Record;
2704}
2705
2706/// Adjust the given function type for an instantiation of the
2707/// given declaration, to cope with modifications to the function's type that
2708/// aren't reflected in the type-source information.
2709///
2710/// \param D The declaration we're instantiating.
2711/// \param TInfo The already-instantiated type.
2713 FunctionDecl *D,
2714 TypeSourceInfo *TInfo) {
2715 const FunctionProtoType *OrigFunc
2716 = D->getType()->castAs<FunctionProtoType>();
2717 const FunctionProtoType *NewFunc
2718 = TInfo->getType()->castAs<FunctionProtoType>();
2719 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2720 return TInfo->getType();
2721
2722 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2723 NewEPI.ExtInfo = OrigFunc->getExtInfo();
2724 return Context.getFunctionType(NewFunc->getReturnType(),
2725 NewFunc->getParamTypes(), NewEPI);
2726}
2727
2728/// Normal class members are of more specific types and therefore
2729/// don't make it here. This function serves three purposes:
2730/// 1) instantiating function templates
2731/// 2) substituting friend and local function declarations
2732/// 3) substituting deduction guide declarations for nested class templates
2734 FunctionDecl *D, TemplateParameterList *TemplateParams,
2735 RewriteKind FunctionRewriteKind) {
2736 // Check whether there is already a function template specialization for
2737 // this declaration.
2739 bool isFriend;
2740 if (FunctionTemplate)
2741 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2742 else
2743 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2744
2745 // Friend function defined withing class template may stop being function
2746 // definition during AST merges from different modules, in this case decl
2747 // with function body should be used for instantiation.
2748 if (ExternalASTSource *Source = SemaRef.Context.getExternalSource()) {
2749 if (isFriend && Source->wasThisDeclarationADefinition(D)) {
2750 const FunctionDecl *Defn = nullptr;
2751 if (D->hasBody(Defn)) {
2752 D = const_cast<FunctionDecl *>(Defn);
2754 }
2755 }
2756 }
2757
2758 if (FunctionTemplate && !TemplateParams) {
2759 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2760
2761 void *InsertPos = nullptr;
2762 FunctionDecl *SpecFunc
2763 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2764
2765 // If we already have a function template specialization, return it.
2766 if (SpecFunc)
2767 return SpecFunc;
2768 }
2769
2770 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2771 Owner->isFunctionOrMethod() ||
2772 !(isa<Decl>(Owner) &&
2773 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2774 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2775
2776 ExplicitSpecifier InstantiatedExplicitSpecifier;
2777 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2778 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2779 TemplateArgs, DGuide->getExplicitSpecifier());
2780 if (InstantiatedExplicitSpecifier.isInvalid())
2781 return nullptr;
2782 }
2783
2785 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2786 if (!TInfo)
2787 return nullptr;
2788 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2789
2790 if (TemplateParams && TemplateParams->size()) {
2791 auto *LastParam =
2792 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2793 if (LastParam && LastParam->isImplicit() &&
2794 LastParam->hasTypeConstraint()) {
2795 // In abbreviated templates, the type-constraints of invented template
2796 // type parameters are instantiated with the function type, invalidating
2797 // the TemplateParameterList which relied on the template type parameter
2798 // not having a type constraint. Recreate the TemplateParameterList with
2799 // the updated parameter list.
2800 TemplateParams = TemplateParameterList::Create(
2801 SemaRef.Context, TemplateParams->getTemplateLoc(),
2802 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2803 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2804 }
2805 }
2806
2807 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2808 if (QualifierLoc) {
2809 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2810 TemplateArgs);
2811 if (!QualifierLoc)
2812 return nullptr;
2813 }
2814
2815 AssociatedConstraint TrailingRequiresClause = D->getTrailingRequiresClause();
2816
2817 // If we're instantiating a local function declaration, put the result
2818 // in the enclosing namespace; otherwise we need to find the instantiated
2819 // context.
2820 DeclContext *DC;
2821 if (D->isLocalExternDecl()) {
2822 DC = Owner;
2823 SemaRef.adjustContextForLocalExternDecl(DC);
2824 } else if (isFriend && QualifierLoc) {
2825 CXXScopeSpec SS;
2826 SS.Adopt(QualifierLoc);
2827 DC = SemaRef.computeDeclContext(SS);
2828 if (!DC) return nullptr;
2829 } else {
2830 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2831 TemplateArgs);
2832 }
2833
2834 DeclarationNameInfo NameInfo
2835 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2836
2837 if (FunctionRewriteKind != RewriteKind::None)
2838 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2839
2841 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2843 SemaRef.Context, DC, D->getInnerLocStart(),
2844 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2845 D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
2846 DGuide->getDeductionCandidateKind(), TrailingRequiresClause,
2847 DGuide->getSourceDeductionGuide(),
2848 DGuide->getSourceDeductionGuideKind());
2849 Function->setAccess(D->getAccess());
2850 } else {
2852 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2855 TrailingRequiresClause);
2856 Function->setFriendConstraintRefersToEnclosingTemplate(
2858 Function->setRangeEnd(D->getSourceRange().getEnd());
2859 }
2860
2861 if (D->isInlined())
2862 Function->setImplicitlyInline();
2863
2864 if (QualifierLoc)
2865 Function->setQualifierInfo(QualifierLoc);
2866
2867 if (D->isLocalExternDecl())
2868 Function->setLocalExternDecl();
2869
2870 DeclContext *LexicalDC = Owner;
2871 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2872 assert(D->getDeclContext()->isFileContext());
2873 LexicalDC = D->getDeclContext();
2874 }
2875 else if (D->isLocalExternDecl()) {
2876 LexicalDC = SemaRef.CurContext;
2877 }
2878
2879 Function->setIsDestroyingOperatorDelete(D->isDestroyingOperatorDelete());
2880 Function->setIsTypeAwareOperatorNewOrDelete(
2882 Function->setLexicalDeclContext(LexicalDC);
2883
2884 // Attach the parameters
2885 for (unsigned P = 0; P < Params.size(); ++P)
2886 if (Params[P])
2887 Params[P]->setOwningFunction(Function);
2888 Function->setParams(Params);
2889
2890 if (TrailingRequiresClause)
2891 Function->setTrailingRequiresClause(TrailingRequiresClause);
2892
2893 if (TemplateParams) {
2894 // Our resulting instantiation is actually a function template, since we
2895 // are substituting only the outer template parameters. For example, given
2896 //
2897 // template<typename T>
2898 // struct X {
2899 // template<typename U> friend void f(T, U);
2900 // };
2901 //
2902 // X<int> x;
2903 //
2904 // We are instantiating the friend function template "f" within X<int>,
2905 // which means substituting int for T, but leaving "f" as a friend function
2906 // template.
2907 // Build the function template itself.
2908 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2909 Function->getLocation(),
2910 Function->getDeclName(),
2911 TemplateParams, Function);
2912 Function->setDescribedFunctionTemplate(FunctionTemplate);
2913
2914 FunctionTemplate->setLexicalDeclContext(LexicalDC);
2915
2916 if (isFriend && D->isThisDeclarationADefinition()) {
2917 FunctionTemplate->setInstantiatedFromMemberTemplate(
2919 }
2920 } else if (FunctionTemplate &&
2921 SemaRef.CodeSynthesisContexts.back().Kind !=
2923 // Record this function template specialization.
2924 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2925 Function->setFunctionTemplateSpecialization(FunctionTemplate,
2926 TemplateArgumentList::CreateCopy(SemaRef.Context,
2927 Innermost),
2928 /*InsertPos=*/nullptr);
2929 } else if (FunctionRewriteKind == RewriteKind::None) {
2930 if (isFriend && D->isThisDeclarationADefinition()) {
2931 // Do not connect the friend to the template unless it's actually a
2932 // definition. We don't want non-template functions to be marked as being
2933 // template instantiations.
2934 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2935 } else if (!isFriend) {
2936 // If this is not a function template, and this is not a friend (that is,
2937 // this is a locally declared function), save the instantiation
2938 // relationship for the purposes of constraint instantiation.
2939 Function->setInstantiatedFromDecl(D);
2940 }
2941 }
2942
2943 if (isFriend) {
2944 Function->setObjectOfFriendDecl();
2945 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2946 FT->setObjectOfFriendDecl();
2947 }
2948
2950 Function->setInvalidDecl();
2951
2952 bool IsExplicitSpecialization = false;
2953
2955 SemaRef, Function->getDeclName(), SourceLocation(),
2959 : SemaRef.forRedeclarationInCurContext());
2960
2963 assert(isFriend && "dependent specialization info on "
2964 "non-member non-friend function?");
2965
2966 // Instantiate the explicit template arguments.
2967 TemplateArgumentListInfo ExplicitArgs;
2968 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2969 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2970 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2971 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2972 ExplicitArgs))
2973 return nullptr;
2974 }
2975
2976 // Map the candidates for the primary template to their instantiations.
2977 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2978 if (NamedDecl *ND =
2979 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2980 Previous.addDecl(ND);
2981 else
2982 return nullptr;
2983 }
2984
2985 if (SemaRef.CheckFunctionTemplateSpecialization(
2986 Function,
2987 DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2988 Previous))
2989 Function->setInvalidDecl();
2990
2991 IsExplicitSpecialization = true;
2992 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2994 // The name of this function was written as a template-id.
2995 SemaRef.LookupQualifiedName(Previous, DC);
2996
2997 // Instantiate the explicit template arguments.
2998 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2999 ArgsWritten->getRAngleLoc());
3000 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
3001 ExplicitArgs))
3002 return nullptr;
3003
3004 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
3005 &ExplicitArgs,
3006 Previous))
3007 Function->setInvalidDecl();
3008
3009 IsExplicitSpecialization = true;
3010 } else if (TemplateParams || !FunctionTemplate) {
3011 // Look only into the namespace where the friend would be declared to
3012 // find a previous declaration. This is the innermost enclosing namespace,
3013 // as described in ActOnFriendFunctionDecl.
3014 SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
3015
3016 // In C++, the previous declaration we find might be a tag type
3017 // (class or enum). In this case, the new declaration will hide the
3018 // tag type. Note that this does not apply if we're declaring a
3019 // typedef (C++ [dcl.typedef]p4).
3020 if (Previous.isSingleTagDecl())
3021 Previous.clear();
3022
3023 // Filter out previous declarations that don't match the scope. The only
3024 // effect this has is to remove declarations found in inline namespaces
3025 // for friend declarations with unqualified names.
3026 if (isFriend && !QualifierLoc) {
3027 SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
3028 /*ConsiderLinkage=*/ true,
3029 QualifierLoc.hasQualifier());
3030 }
3031 }
3032
3033 // Per [temp.inst], default arguments in function declarations at local scope
3034 // are instantiated along with the enclosing declaration. For example:
3035 //
3036 // template<typename T>
3037 // void ft() {
3038 // void f(int = []{ return T::value; }());
3039 // }
3040 // template void ft<int>(); // error: type 'int' cannot be used prior
3041 // to '::' because it has no members
3042 //
3043 // The error is issued during instantiation of ft<int>() because substitution
3044 // into the default argument fails; the default argument is instantiated even
3045 // though it is never used.
3046 if (Function->isLocalExternDecl()) {
3047 for (ParmVarDecl *PVD : Function->parameters()) {
3048 if (!PVD->hasDefaultArg())
3049 continue;
3050 if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
3051 // If substitution fails, the default argument is set to a
3052 // RecoveryExpr that wraps the uninstantiated default argument so
3053 // that downstream diagnostics are omitted.
3054 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
3055 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
3056 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
3057 { UninstExpr }, UninstExpr->getType());
3058 if (ErrorResult.isUsable())
3059 PVD->setDefaultArg(ErrorResult.get());
3060 }
3061 }
3062 }
3063
3064 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
3065 IsExplicitSpecialization,
3066 Function->isThisDeclarationADefinition());
3067
3068 // Check the template parameter list against the previous declaration. The
3069 // goal here is to pick up default arguments added since the friend was
3070 // declared; we know the template parameter lists match, since otherwise
3071 // we would not have picked this template as the previous declaration.
3072 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
3073 SemaRef.CheckTemplateParameterList(
3074 TemplateParams,
3075 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
3076 Function->isThisDeclarationADefinition()
3079 }
3080
3081 // If we're introducing a friend definition after the first use, trigger
3082 // instantiation.
3083 // FIXME: If this is a friend function template definition, we should check
3084 // to see if any specializations have been used.
3085 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
3086 if (MemberSpecializationInfo *MSInfo =
3087 Function->getMemberSpecializationInfo()) {
3088 if (MSInfo->getPointOfInstantiation().isInvalid()) {
3089 SourceLocation Loc = D->getLocation(); // FIXME
3090 MSInfo->setPointOfInstantiation(Loc);
3091 SemaRef.PendingLocalImplicitInstantiations.emplace_back(Function, Loc);
3092 }
3093 }
3094 }
3095
3096 if (D->isExplicitlyDefaulted()) {
3098 return nullptr;
3099 }
3100 if (D->isDeleted())
3101 SemaRef.SetDeclDeleted(Function, D->getLocation(), D->getDeletedMessage());
3102
3103 NamedDecl *PrincipalDecl =
3104 (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
3105
3106 // If this declaration lives in a different context from its lexical context,
3107 // add it to the corresponding lookup table.
3108 if (isFriend ||
3109 (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
3110 DC->makeDeclVisibleInContext(PrincipalDecl);
3111
3112 if (Function->isOverloadedOperator() && !DC->isRecord() &&
3114 PrincipalDecl->setNonMemberOperator();
3115
3116 return Function;
3117}
3118
3120 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
3121 RewriteKind FunctionRewriteKind) {
3123 if (FunctionTemplate && !TemplateParams) {
3124 // We are creating a function template specialization from a function
3125 // template. Check whether there is already a function template
3126 // specialization for this particular set of template arguments.
3127 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
3128
3129 void *InsertPos = nullptr;
3130 FunctionDecl *SpecFunc
3131 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
3132
3133 // If we already have a function template specialization, return it.
3134 if (SpecFunc)
3135 return SpecFunc;
3136 }
3137
3138 bool isFriend;
3139 if (FunctionTemplate)
3140 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
3141 else
3142 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
3143
3144 bool MergeWithParentScope = (TemplateParams != nullptr) ||
3145 !(isa<Decl>(Owner) &&
3146 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
3147 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
3148
3150 SemaRef, D, TemplateArgs, Scope);
3151
3152 // Instantiate enclosing template arguments for friends.
3155 if (isFriend && !TPLs.empty()) {
3156 TempParamLists.resize(TPLs.size());
3157 for (unsigned I = 0; I != TPLs.size(); ++I) {
3158 TemplateParameterList *InstParams = SubstTemplateParams(TPLs[I]);
3159 if (!InstParams)
3160 return nullptr;
3161 TempParamLists[I] = InstParams;
3162 }
3163 }
3164
3165 auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(D);
3166 // deduction guides need this
3167 const bool CouldInstantiate =
3168 InstantiatedExplicitSpecifier.getExpr() == nullptr ||
3169 !InstantiatedExplicitSpecifier.getExpr()->isValueDependent();
3170
3171 // Delay the instantiation of the explicit-specifier until after the
3172 // constraints are checked during template argument deduction.
3173 if (CouldInstantiate ||
3174 SemaRef.CodeSynthesisContexts.back().Kind !=
3176 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
3177 TemplateArgs, InstantiatedExplicitSpecifier);
3178
3179 if (InstantiatedExplicitSpecifier.isInvalid())
3180 return nullptr;
3181 } else {
3182 InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved);
3183 }
3184
3185 // Implicit destructors/constructors created for local classes in
3186 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
3187 // Unfortunately there isn't enough context in those functions to
3188 // conditionally populate the TSI without breaking non-template related use
3189 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
3190 // a proper transformation.
3191 if (isLambdaMethod(D) && !D->getTypeSourceInfo() &&
3193 TypeSourceInfo *TSI =
3194 SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
3195 D->setTypeSourceInfo(TSI);
3196 }
3197
3199 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
3200 if (!TInfo)
3201 return nullptr;
3202 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
3203
3204 if (TemplateParams && TemplateParams->size()) {
3205 auto *LastParam =
3206 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
3207 if (LastParam && LastParam->isImplicit() &&
3208 LastParam->hasTypeConstraint()) {
3209 // In abbreviated templates, the type-constraints of invented template
3210 // type parameters are instantiated with the function type, invalidating
3211 // the TemplateParameterList which relied on the template type parameter
3212 // not having a type constraint. Recreate the TemplateParameterList with
3213 // the updated parameter list.
3214 TemplateParams = TemplateParameterList::Create(
3215 SemaRef.Context, TemplateParams->getTemplateLoc(),
3216 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
3217 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
3218 }
3219 }
3220
3221 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
3222 if (QualifierLoc) {
3223 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
3224 TemplateArgs);
3225 if (!QualifierLoc)
3226 return nullptr;
3227 }
3228
3229 DeclContext *DC = Owner;
3230 if (isFriend) {
3231 if (QualifierLoc) {
3232 CXXScopeSpec SS;
3233 SS.Adopt(QualifierLoc);
3234 DC = SemaRef.computeDeclContext(SS);
3235
3236 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
3237 return nullptr;
3238 } else {
3239 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
3240 D->getDeclContext(),
3241 TemplateArgs);
3242 }
3243 if (!DC) return nullptr;
3244 }
3245
3247 AssociatedConstraint TrailingRequiresClause = D->getTrailingRequiresClause();
3248
3249 DeclarationNameInfo NameInfo
3250 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3251
3252 if (FunctionRewriteKind != RewriteKind::None)
3253 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
3254
3255 // Build the instantiated method declaration.
3256 CXXMethodDecl *Method = nullptr;
3257
3258 SourceLocation StartLoc = D->getInnerLocStart();
3259 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
3261 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
3262 InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
3263 Constructor->isInlineSpecified(), false,
3264 Constructor->getConstexprKind(), InheritedConstructor(),
3265 TrailingRequiresClause);
3266 Method->setRangeEnd(Constructor->getEndLoc());
3267 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
3269 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
3270 Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
3271 Destructor->getConstexprKind(), TrailingRequiresClause);
3272 Method->setIneligibleOrNotSelected(true);
3273 Method->setRangeEnd(Destructor->getEndLoc());
3274 Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
3275
3276 SemaRef.Context.getCanonicalTagType(Record)));
3277 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
3279 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
3280 Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
3281 InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
3282 Conversion->getEndLoc(), TrailingRequiresClause);
3283 } else {
3284 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
3286 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
3288 D->getEndLoc(), TrailingRequiresClause);
3289 }
3290
3291 if (D->isInlined())
3292 Method->setImplicitlyInline();
3293
3294 if (QualifierLoc)
3295 Method->setQualifierInfo(QualifierLoc);
3296
3297 if (TemplateParams) {
3298 // Our resulting instantiation is actually a function template, since we
3299 // are substituting only the outer template parameters. For example, given
3300 //
3301 // template<typename T>
3302 // struct X {
3303 // template<typename U> void f(T, U);
3304 // };
3305 //
3306 // X<int> x;
3307 //
3308 // We are instantiating the member template "f" within X<int>, which means
3309 // substituting int for T, but leaving "f" as a member function template.
3310 // Build the function template itself.
3312 Method->getLocation(),
3313 Method->getDeclName(),
3314 TemplateParams, Method);
3315 if (isFriend) {
3316 FunctionTemplate->setLexicalDeclContext(Owner);
3317 FunctionTemplate->setObjectOfFriendDecl();
3318 } else if (D->isOutOfLine())
3319 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
3320 Method->setDescribedFunctionTemplate(FunctionTemplate);
3321 } else if (FunctionTemplate) {
3322 // Record this function template specialization.
3323 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
3324 Method->setFunctionTemplateSpecialization(FunctionTemplate,
3325 TemplateArgumentList::CreateCopy(SemaRef.Context,
3326 Innermost),
3327 /*InsertPos=*/nullptr);
3328 } else if (!isFriend && FunctionRewriteKind == RewriteKind::None) {
3329 // Record that this is an instantiation of a member function.
3330 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
3331 }
3332
3333 // If we are instantiating a member function defined
3334 // out-of-line, the instantiation will have the same lexical
3335 // context (which will be a namespace scope) as the template.
3336 if (isFriend) {
3337 if (!TempParamLists.empty())
3338 Method->setTemplateParameterListsInfo(SemaRef.Context, TempParamLists);
3339
3340 Method->setLexicalDeclContext(Owner);
3341 Method->setObjectOfFriendDecl();
3342 } else if (D->isOutOfLine())
3343 Method->setLexicalDeclContext(D->getLexicalDeclContext());
3344
3345 // Attach the parameters
3346 for (unsigned P = 0; P < Params.size(); ++P)
3347 Params[P]->setOwningFunction(Method);
3348 Method->setParams(Params);
3349
3351 Method->setInvalidDecl();
3352
3355
3356 bool IsExplicitSpecialization = false;
3357
3358 // If the name of this function was written as a template-id, instantiate
3359 // the explicit template arguments.
3362 // Instantiate the explicit template arguments.
3363 TemplateArgumentListInfo ExplicitArgs;
3364 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
3365 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
3366 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
3367 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
3368 ExplicitArgs))
3369 return nullptr;
3370 }
3371
3372 // Map the candidates for the primary template to their instantiations.
3373 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
3374 if (NamedDecl *ND =
3375 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
3376 Previous.addDecl(ND);
3377 else
3378 return nullptr;
3379 }
3380
3381 if (SemaRef.CheckFunctionTemplateSpecialization(
3382 Method, DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
3383 Previous))
3384 Method->setInvalidDecl();
3385
3386 IsExplicitSpecialization = true;
3387 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
3389 SemaRef.LookupQualifiedName(Previous, DC);
3390
3391 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
3392 ArgsWritten->getRAngleLoc());
3393
3394 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
3395 ExplicitArgs))
3396 return nullptr;
3397
3398 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
3399 &ExplicitArgs,
3400 Previous))
3401 Method->setInvalidDecl();
3402
3403 IsExplicitSpecialization = true;
3404 } else if (!FunctionTemplate || TemplateParams || isFriend) {
3405 SemaRef.LookupQualifiedName(Previous, Record);
3406
3407 // In C++, the previous declaration we find might be a tag type
3408 // (class or enum). In this case, the new declaration will hide the
3409 // tag type. Note that this does not apply if we're declaring a
3410 // typedef (C++ [dcl.typedef]p4).
3411 if (Previous.isSingleTagDecl())
3412 Previous.clear();
3413 }
3414
3415 // Per [temp.inst], default arguments in member functions of local classes
3416 // are instantiated along with the member function declaration. For example:
3417 //
3418 // template<typename T>
3419 // void ft() {
3420 // struct lc {
3421 // int operator()(int p = []{ return T::value; }());
3422 // };
3423 // }
3424 // template void ft<int>(); // error: type 'int' cannot be used prior
3425 // to '::'because it has no members
3426 //
3427 // The error is issued during instantiation of ft<int>()::lc::operator()
3428 // because substitution into the default argument fails; the default argument
3429 // is instantiated even though it is never used.
3431 for (unsigned P = 0; P < Params.size(); ++P) {
3432 if (!Params[P]->hasDefaultArg())
3433 continue;
3434 if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
3435 // If substitution fails, the default argument is set to a
3436 // RecoveryExpr that wraps the uninstantiated default argument so
3437 // that downstream diagnostics are omitted.
3438 Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
3439 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
3440 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
3441 { UninstExpr }, UninstExpr->getType());
3442 if (ErrorResult.isUsable())
3443 Params[P]->setDefaultArg(ErrorResult.get());
3444 }
3445 }
3446 }
3447
3448 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
3449 IsExplicitSpecialization,
3450 Method->isThisDeclarationADefinition());
3451
3452 if (D->isPureVirtual())
3453 SemaRef.CheckPureMethod(Method, SourceRange());
3454
3455 // Propagate access. For a non-friend declaration, the access is
3456 // whatever we're propagating from. For a friend, it should be the
3457 // previous declaration we just found.
3458 if (isFriend && Method->getPreviousDecl())
3459 Method->setAccess(Method->getPreviousDecl()->getAccess());
3460 else
3461 Method->setAccess(D->getAccess());
3462 if (FunctionTemplate)
3463 FunctionTemplate->setAccess(Method->getAccess());
3464
3465 SemaRef.CheckOverrideControl(Method);
3466
3467 // If a function is defined as defaulted or deleted, mark it as such now.
3468 if (D->isExplicitlyDefaulted()) {
3470 return nullptr;
3471 }
3472 if (D->isDeletedAsWritten())
3473 SemaRef.SetDeclDeleted(Method, Method->getLocation(),
3474 D->getDeletedMessage());
3475
3476 // If this is an explicit specialization, mark the implicitly-instantiated
3477 // template specialization as being an explicit specialization too.
3478 // FIXME: Is this necessary?
3479 if (IsExplicitSpecialization && !isFriend)
3480 SemaRef.CompleteMemberSpecialization(Method, Previous);
3481
3482 // If the method is a special member function, we need to mark it as
3483 // ineligible so that Owner->addDecl() won't mark the class as non trivial.
3484 // At the end of the class instantiation, we calculate eligibility again and
3485 // then we adjust trivility if needed.
3486 // We need this check to happen only after the method parameters are set,
3487 // because being e.g. a copy constructor depends on the instantiated
3488 // arguments.
3489 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
3490 if (Constructor->isDefaultConstructor() ||
3491 Constructor->isCopyOrMoveConstructor())
3492 Method->setIneligibleOrNotSelected(true);
3493 } else if (Method->isCopyAssignmentOperator() ||
3494 Method->isMoveAssignmentOperator()) {
3495 Method->setIneligibleOrNotSelected(true);
3496 }
3497
3498 // If there's a function template, let our caller handle it.
3499 if (FunctionTemplate) {
3500 // do nothing
3501
3502 // Don't hide a (potentially) valid declaration with an invalid one.
3503 } else if (Method->isInvalidDecl() && !Previous.empty()) {
3504 // do nothing
3505
3506 // Otherwise, check access to friends and make them visible.
3507 } else if (isFriend) {
3508 // We only need to re-check access for methods which we didn't
3509 // manage to match during parsing.
3510 if (!D->getPreviousDecl())
3511 SemaRef.CheckFriendAccess(Method);
3512
3513 Record->makeDeclVisibleInContext(Method);
3514
3515 // Otherwise, add the declaration. We don't need to do this for
3516 // class-scope specializations because we'll have matched them with
3517 // the appropriate template.
3518 } else {
3519 Owner->addDecl(Method);
3520 }
3521
3522 // PR17480: Honor the used attribute to instantiate member function
3523 // definitions
3524 if (Method->hasAttr<UsedAttr>()) {
3525 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
3526 SourceLocation Loc;
3527 if (const MemberSpecializationInfo *MSInfo =
3528 A->getMemberSpecializationInfo())
3529 Loc = MSInfo->getPointOfInstantiation();
3530 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
3531 Loc = Spec->getPointOfInstantiation();
3532 SemaRef.MarkFunctionReferenced(Loc, Method);
3533 }
3534 }
3535
3536 return Method;
3537}
3538
3539Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3540 return VisitCXXMethodDecl(D);
3541}
3542
3543Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3544 return VisitCXXMethodDecl(D);
3545}
3546
3547Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
3548 return VisitCXXMethodDecl(D);
3549}
3550
3551Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
3552 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
3553 std::nullopt,
3554 /*ExpectParameterPack=*/false);
3555}
3556
3557Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
3559 assert(D->getTypeForDecl()->isTemplateTypeParmType());
3560
3561 UnsignedOrNone NumExpanded = std::nullopt;
3562
3563 if (const TypeConstraint *TC = D->getTypeConstraint()) {
3564 if (D->isPackExpansion() && !D->getNumExpansionParameters()) {
3565 assert(TC->getTemplateArgsAsWritten() &&
3566 "type parameter can only be an expansion when explicit arguments "
3567 "are specified");
3568 // The template type parameter pack's type is a pack expansion of types.
3569 // Determine whether we need to expand this parameter pack into separate
3570 // types.
3571 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3572 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
3573 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
3574
3575 // Determine whether the set of unexpanded parameter packs can and should
3576 // be expanded.
3577 bool Expand = true;
3578 bool RetainExpansion = false;
3579 if (SemaRef.CheckParameterPacksForExpansion(
3580 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3581 ->getEllipsisLoc(),
3582 SourceRange(TC->getConceptNameLoc(),
3583 TC->hasExplicitTemplateArgs()
3584 ? TC->getTemplateArgsAsWritten()->getRAngleLoc()
3585 : TC->getConceptNameInfo().getEndLoc()),
3586 Unexpanded, TemplateArgs, /*FailOnPackProducingTemplates=*/true,
3587 Expand, RetainExpansion, NumExpanded))
3588 return nullptr;
3589 }
3590 }
3591
3592 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
3593 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
3594 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
3596 D->hasTypeConstraint(), NumExpanded);
3597
3598 Inst->setAccess(AS_public);
3599 Inst->setImplicit(D->isImplicit());
3600 if (auto *TC = D->getTypeConstraint()) {
3601 if (!D->isImplicit()) {
3602 // Invented template parameter type constraints will be instantiated
3603 // with the corresponding auto-typed parameter as it might reference
3604 // other parameters.
3605 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
3606 EvaluateConstraints))
3607 return nullptr;
3608 }
3609 }
3611 TemplateArgumentLoc Output;
3612 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3613 Output))
3614 Inst->setDefaultArgument(SemaRef.getASTContext(), Output);
3615 }
3616
3617 // Introduce this template parameter's instantiation into the instantiation
3618 // scope.
3619 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3620
3621 return Inst;
3622}
3623
3624Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
3626 // Substitute into the type of the non-type template parameter.
3627 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
3628 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
3629 SmallVector<QualType, 4> ExpandedParameterPackTypes;
3630 bool IsExpandedParameterPack = false;
3631 TypeSourceInfo *TSI;
3632 QualType T;
3633 bool Invalid = false;
3634
3635 if (D->isExpandedParameterPack()) {
3636 // The non-type template parameter pack is an already-expanded pack
3637 // expansion of types. Substitute into each of the expanded types.
3638 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
3639 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
3640 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
3641 TypeSourceInfo *NewTSI =
3642 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
3643 D->getLocation(), D->getDeclName());
3644 if (!NewTSI)
3645 return nullptr;
3646
3647 QualType NewT =
3648 SemaRef.CheckNonTypeTemplateParameterType(NewTSI, D->getLocation());
3649 if (NewT.isNull())
3650 return nullptr;
3651
3652 ExpandedParameterPackTypesAsWritten.push_back(NewTSI);
3653 ExpandedParameterPackTypes.push_back(NewT);
3654 }
3655
3656 IsExpandedParameterPack = true;
3657 TSI = D->getTypeSourceInfo();
3658 T = TSI->getType();
3659 } else if (D->isPackExpansion()) {
3660 // The non-type template parameter pack's type is a pack expansion of types.
3661 // Determine whether we need to expand this parameter pack into separate
3662 // types.
3663 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
3664 TypeLoc Pattern = Expansion.getPatternLoc();
3665 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3666 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
3667
3668 // Determine whether the set of unexpanded parameter packs can and should
3669 // be expanded.
3670 bool Expand = true;
3671 bool RetainExpansion = false;
3672 UnsignedOrNone OrigNumExpansions =
3673 Expansion.getTypePtr()->getNumExpansions();
3674 UnsignedOrNone NumExpansions = OrigNumExpansions;
3675 if (SemaRef.CheckParameterPacksForExpansion(
3676 Expansion.getEllipsisLoc(), Pattern.getSourceRange(), Unexpanded,
3677 TemplateArgs, /*FailOnPackProducingTemplates=*/true, Expand,
3678 RetainExpansion, NumExpansions))
3679 return nullptr;
3680
3681 if (Expand) {
3682 for (unsigned I = 0; I != *NumExpansions; ++I) {
3683 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
3684 TypeSourceInfo *NewTSI = SemaRef.SubstType(
3685 Pattern, TemplateArgs, D->getLocation(), D->getDeclName());
3686 if (!NewTSI)
3687 return nullptr;
3688
3689 QualType NewT =
3690 SemaRef.CheckNonTypeTemplateParameterType(NewTSI, D->getLocation());
3691 if (NewT.isNull())
3692 return nullptr;
3693
3694 ExpandedParameterPackTypesAsWritten.push_back(NewTSI);
3695 ExpandedParameterPackTypes.push_back(NewT);
3696 }
3697
3698 // Note that we have an expanded parameter pack. The "type" of this
3699 // expanded parameter pack is the original expansion type, but callers
3700 // will end up using the expanded parameter pack types for type-checking.
3701 IsExpandedParameterPack = true;
3702 TSI = D->getTypeSourceInfo();
3703 T = TSI->getType();
3704 } else {
3705 // We cannot fully expand the pack expansion now, so substitute into the
3706 // pattern and create a new pack expansion type.
3707 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, std::nullopt);
3708 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
3709 D->getLocation(),
3710 D->getDeclName());
3711 if (!NewPattern)
3712 return nullptr;
3713
3714 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
3715 TSI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
3716 NumExpansions);
3717 if (!TSI)
3718 return nullptr;
3719
3720 T = TSI->getType();
3721 }
3722 } else {
3723 // Simple case: substitution into a parameter that is not a parameter pack.
3724 TSI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3725 D->getLocation(), D->getDeclName());
3726 if (!TSI)
3727 return nullptr;
3728
3729 // Check that this type is acceptable for a non-type template parameter.
3730 T = SemaRef.CheckNonTypeTemplateParameterType(TSI, D->getLocation());
3731 if (T.isNull()) {
3732 T = SemaRef.Context.IntTy;
3733 Invalid = true;
3734 }
3735 }
3736
3737 NonTypeTemplateParmDecl *Param;
3738 if (IsExpandedParameterPack)
3740 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3741 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3742 D->getPosition(), D->getIdentifier(), T, TSI,
3743 ExpandedParameterPackTypes, ExpandedParameterPackTypesAsWritten);
3744 else
3746 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3747 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3748 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), TSI);
3749
3750 if (AutoTypeLoc AutoLoc = TSI->getTypeLoc().getContainedAutoTypeLoc())
3751 if (AutoLoc.isConstrained()) {
3752 SourceLocation EllipsisLoc;
3753 if (IsExpandedParameterPack)
3754 EllipsisLoc =
3755 TSI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
3756 else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
3758 EllipsisLoc = Constraint->getEllipsisLoc();
3759 // Note: We attach the uninstantiated constriant here, so that it can be
3760 // instantiated relative to the top level, like all our other
3761 // constraints.
3762 if (SemaRef.AttachTypeConstraint(AutoLoc, /*NewConstrainedParm=*/Param,
3763 /*OrigConstrainedParm=*/D, EllipsisLoc))
3764 Invalid = true;
3765 }
3766
3767 Param->setAccess(AS_public);
3768 Param->setImplicit(D->isImplicit());
3769 if (Invalid)
3770 Param->setInvalidDecl();
3771
3773 EnterExpressionEvaluationContext ConstantEvaluated(
3775 TemplateArgumentLoc Result;
3776 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3777 Result))
3778 Param->setDefaultArgument(SemaRef.Context, Result);
3779 }
3780
3781 // Introduce this template parameter's instantiation into the instantiation
3782 // scope.
3783 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3784 return Param;
3785}
3786
3788 Sema &S,
3789 TemplateParameterList *Params,
3791 for (const auto &P : *Params) {
3792 if (P->isTemplateParameterPack())
3793 continue;
3794 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3795 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3796 Unexpanded);
3797 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3798 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3799 Unexpanded);
3800 }
3801}
3802
3803Decl *
3804TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3806 // Instantiate the template parameter list of the template template parameter.
3807 TemplateParameterList *TempParams = D->getTemplateParameters();
3808 TemplateParameterList *InstParams;
3809 SmallVector<TemplateParameterList*, 8> ExpandedParams;
3810
3811 bool IsExpandedParameterPack = false;
3812
3813 if (D->isExpandedParameterPack()) {
3814 // The template template parameter pack is an already-expanded pack
3815 // expansion of template parameters. Substitute into each of the expanded
3816 // parameters.
3817 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3818 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3819 I != N; ++I) {
3820 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
3821 TemplateParameterList *Expansion =
3823 if (!Expansion)
3824 return nullptr;
3825 ExpandedParams.push_back(Expansion);
3826 }
3827
3828 IsExpandedParameterPack = true;
3829 InstParams = TempParams;
3830 } else if (D->isPackExpansion()) {
3831 // The template template parameter pack expands to a pack of template
3832 // template parameters. Determine whether we need to expand this parameter
3833 // pack into separate parameters.
3834 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3836 Unexpanded);
3837
3838 // Determine whether the set of unexpanded parameter packs can and should
3839 // be expanded.
3840 bool Expand = true;
3841 bool RetainExpansion = false;
3842 UnsignedOrNone NumExpansions = std::nullopt;
3843 if (SemaRef.CheckParameterPacksForExpansion(
3844 D->getLocation(), TempParams->getSourceRange(), Unexpanded,
3845 TemplateArgs, /*FailOnPackProducingTemplates=*/true, Expand,
3846 RetainExpansion, NumExpansions))
3847 return nullptr;
3848
3849 if (Expand) {
3850 for (unsigned I = 0; I != *NumExpansions; ++I) {
3851 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
3852 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
3853 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3854 if (!Expansion)
3855 return nullptr;
3856 ExpandedParams.push_back(Expansion);
3857 }
3858
3859 // Note that we have an expanded parameter pack. The "type" of this
3860 // expanded parameter pack is the original expansion type, but callers
3861 // will end up using the expanded parameter pack types for type-checking.
3862 IsExpandedParameterPack = true;
3863 }
3864
3865 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, std::nullopt);
3866
3867 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
3868 InstParams = SubstTemplateParams(TempParams);
3869 if (!InstParams)
3870 return nullptr;
3871 } else {
3872 // Perform the actual substitution of template parameters within a new,
3873 // local instantiation scope.
3874 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
3875 InstParams = SubstTemplateParams(TempParams);
3876 if (!InstParams)
3877 return nullptr;
3878 }
3879
3880 // Build the template template parameter.
3881 TemplateTemplateParmDecl *Param;
3882 if (IsExpandedParameterPack)
3884 SemaRef.Context, Owner, D->getLocation(),
3885 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3887 D->wasDeclaredWithTypename(), InstParams, ExpandedParams);
3888 else
3890 SemaRef.Context, Owner, D->getLocation(),
3891 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3892 D->getPosition(), D->isParameterPack(), D->getIdentifier(),
3893 D->templateParameterKind(), D->wasDeclaredWithTypename(), InstParams);
3895 const TemplateArgumentLoc &A = D->getDefaultArgument();
3896 NestedNameSpecifierLoc QualifierLoc = A.getTemplateQualifierLoc();
3897 // FIXME: Pass in the template keyword location.
3898 TemplateName TName = SemaRef.SubstTemplateName(
3899 A.getTemplateKWLoc(), QualifierLoc, A.getArgument().getAsTemplate(),
3900 A.getTemplateNameLoc(), TemplateArgs);
3901 if (!TName.isNull())
3902 Param->setDefaultArgument(
3903 SemaRef.Context,
3904 TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
3905 A.getTemplateKWLoc(), QualifierLoc,
3906 A.getTemplateNameLoc()));
3907 }
3908 Param->setAccess(AS_public);
3909 Param->setImplicit(D->isImplicit());
3910
3911 // Introduce this template parameter's instantiation into the instantiation
3912 // scope.
3913 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3914
3915 return Param;
3916}
3917
3918Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3919 // Using directives are never dependent (and never contain any types or
3920 // expressions), so they require no explicit instantiation work.
3921
3922 UsingDirectiveDecl *Inst
3923 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3925 D->getQualifierLoc(),
3926 D->getIdentLocation(),
3928 D->getCommonAncestor());
3929
3930 // Add the using directive to its declaration context
3931 // only if this is not a function or method.
3932 if (!Owner->isFunctionOrMethod())
3933 Owner->addDecl(Inst);
3934
3935 return Inst;
3936}
3937
3939 BaseUsingDecl *Inst,
3940 LookupResult *Lookup) {
3941
3942 bool isFunctionScope = Owner->isFunctionOrMethod();
3943
3944 for (auto *Shadow : D->shadows()) {
3945 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3946 // reconstruct it in the case where it matters. Hm, can we extract it from
3947 // the DeclSpec when parsing and save it in the UsingDecl itself?
3948 NamedDecl *OldTarget = Shadow->getTargetDecl();
3949 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3950 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3951 OldTarget = BaseShadow;
3952
3953 NamedDecl *InstTarget = nullptr;
3954 if (auto *EmptyD =
3955 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3957 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3958 } else {
3959 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3960 Shadow->getLocation(), OldTarget, TemplateArgs));
3961 }
3962 if (!InstTarget)
3963 return nullptr;
3964
3965 UsingShadowDecl *PrevDecl = nullptr;
3966 if (Lookup &&
3967 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3968 continue;
3969
3970 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3971 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3972 Shadow->getLocation(), OldPrev, TemplateArgs));
3973
3974 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3975 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3976 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3977
3978 if (isFunctionScope)
3979 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3980 }
3981
3982 return Inst;
3983}
3984
3985Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3986
3987 // The nested name specifier may be dependent, for example
3988 // template <typename T> struct t {
3989 // struct s1 { T f1(); };
3990 // struct s2 : s1 { using s1::f1; };
3991 // };
3992 // template struct t<int>;
3993 // Here, in using s1::f1, s1 refers to t<T>::s1;
3994 // we need to substitute for t<int>::s1.
3995 NestedNameSpecifierLoc QualifierLoc
3997 TemplateArgs);
3998 if (!QualifierLoc)
3999 return nullptr;
4000
4001 // For an inheriting constructor declaration, the name of the using
4002 // declaration is the name of a constructor in this class, not in the
4003 // base class.
4004 DeclarationNameInfo NameInfo = D->getNameInfo();
4006 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
4008 SemaRef.Context.getCanonicalTagType(RD)));
4009
4010 // We only need to do redeclaration lookups if we're in a class scope (in
4011 // fact, it's not really even possible in non-class scopes).
4012 bool CheckRedeclaration = Owner->isRecord();
4013 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
4015
4016 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
4017 D->getUsingLoc(),
4018 QualifierLoc,
4019 NameInfo,
4020 D->hasTypename());
4021
4022 CXXScopeSpec SS;
4023 SS.Adopt(QualifierLoc);
4024 if (CheckRedeclaration) {
4025 Prev.setHideTags(false);
4026 SemaRef.LookupQualifiedName(Prev, Owner);
4027
4028 // Check for invalid redeclarations.
4030 D->hasTypename(), SS,
4031 D->getLocation(), Prev))
4032 NewUD->setInvalidDecl();
4033 }
4034
4035 if (!NewUD->isInvalidDecl() &&
4036 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
4037 NameInfo, D->getLocation(), nullptr, D))
4038 NewUD->setInvalidDecl();
4039
4040 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
4041 NewUD->setAccess(D->getAccess());
4042 Owner->addDecl(NewUD);
4043
4044 // Don't process the shadow decls for an invalid decl.
4045 if (NewUD->isInvalidDecl())
4046 return NewUD;
4047
4048 // If the using scope was dependent, or we had dependent bases, we need to
4049 // recheck the inheritance
4052
4053 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
4054}
4055
4056Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
4057 // Cannot be a dependent type, but still could be an instantiation
4058 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
4059 D->getLocation(), D->getEnumDecl(), TemplateArgs));
4060
4061 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
4062 return nullptr;
4063
4064 TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
4065 D->getLocation(), D->getDeclName());
4066
4067 if (!TSI)
4068 return nullptr;
4069
4070 UsingEnumDecl *NewUD =
4071 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
4072 D->getEnumLoc(), D->getLocation(), TSI);
4073
4074 SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
4075 NewUD->setAccess(D->getAccess());
4076 Owner->addDecl(NewUD);
4077
4078 // Don't process the shadow decls for an invalid decl.
4079 if (NewUD->isInvalidDecl())
4080 return NewUD;
4081
4082 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
4083 // cannot be dependent, and will therefore have been checked during template
4084 // definition.
4085
4086 return VisitBaseUsingDecls(D, NewUD, nullptr);
4087}
4088
4089Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
4090 // Ignore these; we handle them in bulk when processing the UsingDecl.
4091 return nullptr;
4092}
4093
4094Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
4096 // Ignore these; we handle them in bulk when processing the UsingDecl.
4097 return nullptr;
4098}
4099
4100template <typename T>
4101Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
4102 T *D, bool InstantiatingPackElement) {
4103 // If this is a pack expansion, expand it now.
4104 if (D->isPackExpansion() && !InstantiatingPackElement) {
4105 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4106 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
4107 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
4108
4109 // Determine whether the set of unexpanded parameter packs can and should
4110 // be expanded.
4111 bool Expand = true;
4112 bool RetainExpansion = false;
4113 UnsignedOrNone NumExpansions = std::nullopt;
4114 if (SemaRef.CheckParameterPacksForExpansion(
4115 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
4116 /*FailOnPackProducingTemplates=*/true, Expand, RetainExpansion,
4117 NumExpansions))
4118 return nullptr;
4119
4120 // This declaration cannot appear within a function template signature,
4121 // so we can't have a partial argument list for a parameter pack.
4122 assert(!RetainExpansion &&
4123 "should never need to retain an expansion for UsingPackDecl");
4124
4125 if (!Expand) {
4126 // We cannot fully expand the pack expansion now, so substitute into the
4127 // pattern and create a new pack expansion.
4128 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, std::nullopt);
4129 return instantiateUnresolvedUsingDecl(D, true);
4130 }
4131
4132 // Within a function, we don't have any normal way to check for conflicts
4133 // between shadow declarations from different using declarations in the
4134 // same pack expansion, but this is always ill-formed because all expansions
4135 // must produce (conflicting) enumerators.
4136 //
4137 // Sadly we can't just reject this in the template definition because it
4138 // could be valid if the pack is empty or has exactly one expansion.
4139 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
4140 SemaRef.Diag(D->getEllipsisLoc(),
4141 diag::err_using_decl_redeclaration_expansion);
4142 return nullptr;
4143 }
4144
4145 // Instantiate the slices of this pack and build a UsingPackDecl.
4146 SmallVector<NamedDecl*, 8> Expansions;
4147 for (unsigned I = 0; I != *NumExpansions; ++I) {
4148 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
4149 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
4150 if (!Slice)
4151 return nullptr;
4152 // Note that we can still get unresolved using declarations here, if we
4153 // had arguments for all packs but the pattern also contained other
4154 // template arguments (this only happens during partial substitution, eg
4155 // into the body of a generic lambda in a function template).
4156 Expansions.push_back(cast<NamedDecl>(Slice));
4157 }
4158
4159 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
4160 if (isDeclWithinFunction(D))
4161 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
4162 return NewD;
4163 }
4164
4165 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
4166 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
4167
4168 NestedNameSpecifierLoc QualifierLoc
4169 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
4170 TemplateArgs);
4171 if (!QualifierLoc)
4172 return nullptr;
4173
4174 CXXScopeSpec SS;
4175 SS.Adopt(QualifierLoc);
4176
4177 DeclarationNameInfo NameInfo
4178 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
4179
4180 // Produce a pack expansion only if we're not instantiating a particular
4181 // slice of a pack expansion.
4182 bool InstantiatingSlice =
4183 D->getEllipsisLoc().isValid() && SemaRef.ArgPackSubstIndex;
4184 SourceLocation EllipsisLoc =
4185 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
4186
4187 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
4188 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
4189 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
4190 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
4191 ParsedAttributesView(),
4192 /*IsInstantiation*/ true, IsUsingIfExists);
4193 if (UD) {
4194 SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
4195 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
4196 }
4197
4198 return UD;
4199}
4200
4201Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
4203 return instantiateUnresolvedUsingDecl(D);
4204}
4205
4206Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
4208 return instantiateUnresolvedUsingDecl(D);
4209}
4210
4211Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
4213 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
4214}
4215
4216Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
4217 SmallVector<NamedDecl*, 8> Expansions;
4218 for (auto *UD : D->expansions()) {
4219 if (NamedDecl *NewUD =
4220 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
4221 Expansions.push_back(NewUD);
4222 else
4223 return nullptr;
4224 }
4225
4226 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
4227 if (isDeclWithinFunction(D))
4228 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
4229 return NewD;
4230}
4231
4232Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
4234 SmallVector<Expr *, 5> Vars;
4235 for (auto *I : D->varlist()) {
4236 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
4237 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
4238 Vars.push_back(Var);
4239 }
4240
4241 OMPThreadPrivateDecl *TD =
4242 SemaRef.OpenMP().CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
4243
4244 TD->setAccess(AS_public);
4245 Owner->addDecl(TD);
4246
4247 return TD;
4248}
4249
4250Decl *
4251TemplateDeclInstantiator::VisitOMPGroupPrivateDecl(OMPGroupPrivateDecl *D) {
4252 SmallVector<Expr *, 5> Vars;
4253 for (auto *I : D->varlist()) {
4254 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
4255 assert(isa<DeclRefExpr>(Var) && "groupprivate arg is not a DeclRefExpr");
4256 Vars.push_back(Var);
4257 }
4258
4259 OMPGroupPrivateDecl *TD =
4260 SemaRef.OpenMP().CheckOMPGroupPrivateDecl(D->getLocation(), Vars);
4261
4262 TD->setAccess(AS_public);
4263 Owner->addDecl(TD);
4264
4265 return TD;
4266}
4267
4268Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
4269 SmallVector<Expr *, 5> Vars;
4270 for (auto *I : D->varlist()) {
4271 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
4272 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
4273 Vars.push_back(Var);
4274 }
4275 SmallVector<OMPClause *, 4> Clauses;
4276 // Copy map clauses from the original mapper.
4277 for (OMPClause *C : D->clauselists()) {
4278 OMPClause *IC = nullptr;
4279 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
4280 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
4281 if (!NewE.isUsable())
4282 continue;
4283 IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause(
4284 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
4285 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
4286 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
4287 if (!NewE.isUsable())
4288 continue;
4289 IC = SemaRef.OpenMP().ActOnOpenMPAlignClause(
4290 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
4291 // If align clause value ends up being invalid, this can end up null.
4292 if (!IC)
4293 continue;
4294 }
4295 Clauses.push_back(IC);
4296 }
4297
4298 Sema::DeclGroupPtrTy Res = SemaRef.OpenMP().ActOnOpenMPAllocateDirective(
4299 D->getLocation(), Vars, Clauses, Owner);
4300 if (Res.get().isNull())
4301 return nullptr;
4302 return Res.get().getSingleDecl();
4303}
4304
4305Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
4306 llvm_unreachable(
4307 "Requires directive cannot be instantiated within a dependent context");
4308}
4309
4310Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
4312 // Instantiate type and check if it is allowed.
4313 const bool RequiresInstantiation =
4314 D->getType()->isDependentType() ||
4317 QualType SubstReductionType;
4318 if (RequiresInstantiation) {
4319 SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType(
4320 D->getLocation(),
4321 ParsedType::make(SemaRef.SubstType(
4322 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
4323 } else {
4324 SubstReductionType = D->getType();
4325 }
4326 if (SubstReductionType.isNull())
4327 return nullptr;
4328 Expr *Combiner = D->getCombiner();
4329 Expr *Init = D->getInitializer();
4330 bool IsCorrect = true;
4331 // Create instantiated copy.
4332 std::pair<QualType, SourceLocation> ReductionTypes[] = {
4333 std::make_pair(SubstReductionType, D->getLocation())};
4334 auto *PrevDeclInScope = D->getPrevDeclInScope();
4335 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
4336 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
4337 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
4338 PrevDeclInScope)));
4339 }
4340 auto DRD = SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveStart(
4341 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
4342 PrevDeclInScope);
4343 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
4344 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
4345 Expr *SubstCombiner = nullptr;
4346 Expr *SubstInitializer = nullptr;
4347 // Combiners instantiation sequence.
4348 if (Combiner) {
4349 SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerStart(
4350 /*S=*/nullptr, NewDRD);
4351 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4352 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
4353 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
4354 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4355 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
4356 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
4357 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
4358 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
4359 ThisContext);
4360 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
4361 SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerEnd(NewDRD,
4362 SubstCombiner);
4363 }
4364 // Initializers instantiation sequence.
4365 if (Init) {
4366 VarDecl *OmpPrivParm =
4367 SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerStart(
4368 /*S=*/nullptr, NewDRD);
4369 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4370 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
4371 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
4372 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4373 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
4374 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
4376 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
4377 } else {
4378 auto *OldPrivParm =
4380 IsCorrect = IsCorrect && OldPrivParm->hasInit();
4381 if (IsCorrect)
4382 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
4383 TemplateArgs);
4384 }
4385 SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerEnd(
4386 NewDRD, SubstInitializer, OmpPrivParm);
4387 }
4388 IsCorrect = IsCorrect && SubstCombiner &&
4389 (!Init ||
4391 SubstInitializer) ||
4393 !SubstInitializer));
4394
4395 (void)SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveEnd(
4396 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
4397
4398 return NewDRD;
4399}
4400
4401Decl *
4402TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
4403 // Instantiate type and check if it is allowed.
4404 const bool RequiresInstantiation =
4405 D->getType()->isDependentType() ||
4408 QualType SubstMapperTy;
4409 DeclarationName VN = D->getVarName();
4410 if (RequiresInstantiation) {
4411 SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType(
4412 D->getLocation(),
4413 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
4414 D->getLocation(), VN)));
4415 } else {
4416 SubstMapperTy = D->getType();
4417 }
4418 if (SubstMapperTy.isNull())
4419 return nullptr;
4420 // Create an instantiated copy of mapper.
4421 auto *PrevDeclInScope = D->getPrevDeclInScope();
4422 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
4423 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
4424 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
4425 PrevDeclInScope)));
4426 }
4427 bool IsCorrect = true;
4428 SmallVector<OMPClause *, 6> Clauses;
4429 // Instantiate the mapper variable.
4430 DeclarationNameInfo DirName;
4431 SemaRef.OpenMP().StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
4432 /*S=*/nullptr,
4433 (*D->clauselist_begin())->getBeginLoc());
4434 ExprResult MapperVarRef =
4435 SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirectiveVarDecl(
4436 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
4437 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4438 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
4439 cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
4440 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
4441 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
4442 ThisContext);
4443 // Instantiate map clauses.
4444 for (OMPClause *C : D->clauselists()) {
4445 auto *OldC = cast<OMPMapClause>(C);
4446 SmallVector<Expr *, 4> NewVars;
4447 for (Expr *OE : OldC->varlist()) {
4448 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
4449 if (!NE) {
4450 IsCorrect = false;
4451 break;
4452 }
4453 NewVars.push_back(NE);
4454 }
4455 if (!IsCorrect)
4456 break;
4457 NestedNameSpecifierLoc NewQualifierLoc =
4458 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
4459 TemplateArgs);
4460 CXXScopeSpec SS;
4461 SS.Adopt(NewQualifierLoc);
4462 DeclarationNameInfo NewNameInfo =
4463 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
4464 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
4465 OldC->getEndLoc());
4466 OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause(
4467 OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
4468 OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
4469 OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
4470 NewVars, Locs);
4471 Clauses.push_back(NewC);
4472 }
4473 SemaRef.OpenMP().EndOpenMPDSABlock(nullptr);
4474 if (!IsCorrect)
4475 return nullptr;
4476 Sema::DeclGroupPtrTy DG = SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirective(
4477 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
4478 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
4479 Decl *NewDMD = DG.get().getSingleDecl();
4480 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
4481 return NewDMD;
4482}
4483
4484Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
4485 OMPCapturedExprDecl * /*D*/) {
4486 llvm_unreachable("Should not be met in templates");
4487}
4488
4490 return VisitFunctionDecl(D, nullptr);
4491}
4492
4493Decl *
4494TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
4495 Decl *Inst = VisitFunctionDecl(D, nullptr);
4496 if (Inst && !D->getDescribedFunctionTemplate())
4497 Owner->addDecl(Inst);
4498 return Inst;
4499}
4500
4502 return VisitCXXMethodDecl(D, nullptr);
4503}
4504
4505Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
4506 llvm_unreachable("There are only CXXRecordDecls in C++");
4507}
4508
4509Decl *
4510TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
4512 // As a MS extension, we permit class-scope explicit specialization
4513 // of member class templates.
4514 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
4515 assert(ClassTemplate->getDeclContext()->isRecord() &&
4517 "can only instantiate an explicit specialization "
4518 "for a member class template");
4519
4520 // Lookup the already-instantiated declaration in the instantiation
4521 // of the class template.
4522 ClassTemplateDecl *InstClassTemplate =
4523 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
4524 D->getLocation(), ClassTemplate, TemplateArgs));
4525 if (!InstClassTemplate)
4526 return nullptr;
4527
4528 // Substitute into the template arguments of the class template explicit
4529 // specialization.
4530 TemplateArgumentListInfo InstTemplateArgs;
4531 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4533 InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4534 InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4535
4536 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4537 TemplateArgs, InstTemplateArgs))
4538 return nullptr;
4539 }
4540
4541 // Check that the template argument list is well-formed for this
4542 // class template.
4543 Sema::CheckTemplateArgumentInfo CTAI;
4544 if (SemaRef.CheckTemplateArgumentList(
4545 InstClassTemplate, D->getLocation(), InstTemplateArgs,
4546 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4547 /*UpdateArgsWithConversions=*/true))
4548 return nullptr;
4549
4550 // Figure out where to insert this class template explicit specialization
4551 // in the member template's set of class template explicit specializations.
4552 void *InsertPos = nullptr;
4553 ClassTemplateSpecializationDecl *PrevDecl =
4554 InstClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4555
4556 // Check whether we've already seen a conflicting instantiation of this
4557 // declaration (for instance, if there was a prior implicit instantiation).
4558 bool Ignored;
4559 if (PrevDecl &&
4560 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
4562 PrevDecl,
4563 PrevDecl->getSpecializationKind(),
4564 PrevDecl->getPointOfInstantiation(),
4565 Ignored))
4566 return nullptr;
4567
4568 // If PrevDecl was a definition and D is also a definition, diagnose.
4569 // This happens in cases like:
4570 //
4571 // template<typename T, typename U>
4572 // struct Outer {
4573 // template<typename X> struct Inner;
4574 // template<> struct Inner<T> {};
4575 // template<> struct Inner<U> {};
4576 // };
4577 //
4578 // Outer<int, int> outer; // error: the explicit specializations of Inner
4579 // // have the same signature.
4580 if (PrevDecl && PrevDecl->getDefinition() &&
4582 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
4583 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
4584 diag::note_previous_definition);
4585 return nullptr;
4586 }
4587
4588 // Create the class template partial specialization declaration.
4589 ClassTemplateSpecializationDecl *InstD =
4591 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
4592 D->getLocation(), InstClassTemplate, CTAI.CanonicalConverted,
4593 CTAI.StrictPackMatch, PrevDecl);
4594 InstD->setTemplateArgsAsWritten(InstTemplateArgs);
4595
4596 // Add this partial specialization to the set of class template partial
4597 // specializations.
4598 if (!PrevDecl)
4599 InstClassTemplate->AddSpecialization(InstD, InsertPos);
4600
4601 // Substitute the nested name specifier, if any.
4602 if (SubstQualifier(D, InstD))
4603 return nullptr;
4604
4605 InstD->setAccess(D->getAccess());
4610
4611 Owner->addDecl(InstD);
4612
4613 // Instantiate the members of the class-scope explicit specialization eagerly.
4614 // We don't have support for lazy instantiation of an explicit specialization
4615 // yet, and MSVC eagerly instantiates in this case.
4616 // FIXME: This is wrong in standard C++.
4618 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
4620 /*Complain=*/true))
4621 return nullptr;
4622
4623 return InstD;
4624}
4625
4628
4629 TemplateArgumentListInfo VarTemplateArgsInfo;
4631 assert(VarTemplate &&
4632 "A template specialization without specialized template?");
4633
4634 VarTemplateDecl *InstVarTemplate =
4635 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
4636 D->getLocation(), VarTemplate, TemplateArgs));
4637 if (!InstVarTemplate)
4638 return nullptr;
4639
4640 // Substitute the current template arguments.
4641 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4643 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4644 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4645
4646 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4647 TemplateArgs, VarTemplateArgsInfo))
4648 return nullptr;
4649 }
4650
4651 // Check that the template argument list is well-formed for this template.
4653 if (SemaRef.CheckTemplateArgumentList(
4654 InstVarTemplate, D->getLocation(), VarTemplateArgsInfo,
4655 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4656 /*UpdateArgsWithConversions=*/true))
4657 return nullptr;
4658
4659 // Check whether we've already seen a declaration of this specialization.
4660 void *InsertPos = nullptr;
4662 InstVarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4663
4664 // Check whether we've already seen a conflicting instantiation of this
4665 // declaration (for instance, if there was a prior implicit instantiation).
4666 bool Ignored;
4667 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
4668 D->getLocation(), D->getSpecializationKind(), PrevDecl,
4669 PrevDecl->getSpecializationKind(),
4670 PrevDecl->getPointOfInstantiation(), Ignored))
4671 return nullptr;
4672
4674 InstVarTemplate, D, CTAI.CanonicalConverted, PrevDecl)) {
4675 VTSD->setTemplateArgsAsWritten(VarTemplateArgsInfo);
4676 return VTSD;
4677 }
4678 return nullptr;
4679}
4680
4686
4687 // Do substitution on the type of the declaration
4688 TypeSourceInfo *TSI =
4689 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
4690 D->getTypeSpecStartLoc(), D->getDeclName());
4691 if (!TSI)
4692 return nullptr;
4693
4694 if (TSI->getType()->isFunctionType()) {
4695 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
4696 << D->isStaticDataMember() << TSI->getType();
4697 return nullptr;
4698 }
4699
4700 // Build the instantiated declaration
4702 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
4703 VarTemplate, TSI->getType(), TSI, D->getStorageClass(), Converted);
4704 if (!PrevDecl) {
4705 void *InsertPos = nullptr;
4706 VarTemplate->findSpecialization(Converted, InsertPos);
4707 VarTemplate->AddSpecialization(Var, InsertPos);
4708 }
4709
4710 if (SemaRef.getLangOpts().OpenCL)
4711 SemaRef.deduceOpenCLAddressSpace(Var);
4712
4713 // Substitute the nested name specifier, if any.
4714 if (SubstQualifier(D, Var))
4715 return nullptr;
4716
4717 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
4718 StartingScope, false, PrevDecl);
4719
4720 return Var;
4721}
4722
4723Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
4724 llvm_unreachable("@defs is not supported in Objective-C++");
4725}
4726
4727Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
4728 // FIXME: We need to be able to instantiate FriendTemplateDecls.
4729 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
4731 "cannot instantiate %0 yet");
4732 SemaRef.Diag(D->getLocation(), DiagID)
4733 << D->getDeclKindName();
4734
4735 return nullptr;
4736}
4737
4738Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
4739 llvm_unreachable("Concept definitions cannot reside inside a template");
4740}
4741
4742Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4744 llvm_unreachable("Concept specializations cannot reside inside a template");
4745}
4746
4747Decl *
4748TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4749 return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
4750 D->getBeginLoc());
4751}
4752
4754 llvm_unreachable("Unexpected decl");
4755}
4756
4758 const MultiLevelTemplateArgumentList &TemplateArgs) {
4759 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4760 if (D->isInvalidDecl())
4761 return nullptr;
4762
4763 Decl *SubstD;
4765 SubstD = Instantiator.Visit(D);
4766 });
4767 return SubstD;
4768}
4769
4771 FunctionDecl *Orig, QualType &T,
4772 TypeSourceInfo *&TInfo,
4773 DeclarationNameInfo &NameInfo) {
4775
4776 // C++2a [class.compare.default]p3:
4777 // the return type is replaced with bool
4778 auto *FPT = T->castAs<FunctionProtoType>();
4779 T = SemaRef.Context.getFunctionType(
4780 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4781
4782 // Update the return type in the source info too. The most straightforward
4783 // way is to create new TypeSourceInfo for the new type. Use the location of
4784 // the '= default' as the location of the new type.
4785 //
4786 // FIXME: Set the correct return type when we initially transform the type,
4787 // rather than delaying it to now.
4788 TypeSourceInfo *NewTInfo =
4789 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4790 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4791 assert(OldLoc && "type of function is not a function type?");
4792 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4793 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4794 NewLoc.setParam(I, OldLoc.getParam(I));
4795 TInfo = NewTInfo;
4796
4797 // and the declarator-id is replaced with operator==
4798 NameInfo.setName(
4799 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4800}
4801
4803 FunctionDecl *Spaceship) {
4804 if (Spaceship->isInvalidDecl())
4805 return nullptr;
4806
4807 // C++2a [class.compare.default]p3:
4808 // an == operator function is declared implicitly [...] with the same
4809 // access and function-definition and in the same class scope as the
4810 // three-way comparison operator function
4811 MultiLevelTemplateArgumentList NoTemplateArgs;
4813 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4814 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4815 Decl *R;
4816 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4817 R = Instantiator.VisitCXXMethodDecl(
4818 MD, /*TemplateParams=*/nullptr,
4820 } else {
4821 assert(Spaceship->getFriendObjectKind() &&
4822 "defaulted spaceship is neither a member nor a friend");
4823
4824 R = Instantiator.VisitFunctionDecl(
4825 Spaceship, /*TemplateParams=*/nullptr,
4827 if (!R)
4828 return nullptr;
4829
4830 FriendDecl *FD =
4831 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4832 cast<NamedDecl>(R), Spaceship->getBeginLoc());
4833 FD->setAccess(AS_public);
4834 RD->addDecl(FD);
4835 }
4836 return cast_or_null<FunctionDecl>(R);
4837}
4838
4839/// Instantiates a nested template parameter list in the current
4840/// instantiation context.
4841///
4842/// \param L The parameter list to instantiate
4843///
4844/// \returns NULL if there was an error
4847 // Get errors for all the parameters before bailing out.
4848 bool Invalid = false;
4849
4850 unsigned N = L->size();
4851 typedef SmallVector<NamedDecl *, 8> ParamVector;
4852 ParamVector Params;
4853 Params.reserve(N);
4854 for (auto &P : *L) {
4855 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4856 Params.push_back(D);
4857 Invalid = Invalid || !D || D->isInvalidDecl();
4858 }
4859
4860 // Clean up if we had an error.
4861 if (Invalid)
4862 return nullptr;
4863
4864 Expr *InstRequiresClause = L->getRequiresClause();
4865
4867 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
4868 L->getLAngleLoc(), Params,
4869 L->getRAngleLoc(), InstRequiresClause);
4870 return InstL;
4871}
4872
4875 const MultiLevelTemplateArgumentList &TemplateArgs,
4876 bool EvaluateConstraints) {
4877 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4878 Instantiator.setEvaluateConstraints(EvaluateConstraints);
4879 return Instantiator.SubstTemplateParams(Params);
4880}
4881
4882/// Instantiate the declaration of a class template partial
4883/// specialization.
4884///
4885/// \param ClassTemplate the (instantiated) class template that is partially
4886// specialized by the instantiation of \p PartialSpec.
4887///
4888/// \param PartialSpec the (uninstantiated) class template partial
4889/// specialization that we are instantiating.
4890///
4891/// \returns The instantiated partial specialization, if successful; otherwise,
4892/// NULL to indicate an error.
4895 ClassTemplateDecl *ClassTemplate,
4897 // Create a local instantiation scope for this class template partial
4898 // specialization, which will contain the instantiations of the template
4899 // parameters.
4901
4902 // Substitute into the template parameters of the class template partial
4903 // specialization.
4904 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4905 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4906 if (!InstParams)
4907 return nullptr;
4908
4909 // Substitute into the template arguments of the class template partial
4910 // specialization.
4911 const ASTTemplateArgumentListInfo *TemplArgInfo
4912 = PartialSpec->getTemplateArgsAsWritten();
4913 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4914 TemplArgInfo->RAngleLoc);
4915 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4916 InstTemplateArgs))
4917 return nullptr;
4918
4919 // Check that the template argument list is well-formed for this
4920 // class template.
4922 if (SemaRef.CheckTemplateArgumentList(
4923 ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4924 /*DefaultArgs=*/{},
4925 /*PartialTemplateArgs=*/false, CTAI))
4926 return nullptr;
4927
4928 // Check these arguments are valid for a template partial specialization.
4929 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4930 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4931 CTAI.CanonicalConverted))
4932 return nullptr;
4933
4934 // Figure out where to insert this class template partial specialization
4935 // in the member template's set of class template partial specializations.
4936 void *InsertPos = nullptr;
4939 InstParams, InsertPos);
4940
4941 // Create the class template partial specialization declaration.
4944 SemaRef.Context, PartialSpec->getTagKind(), Owner,
4945 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4946 ClassTemplate, CTAI.CanonicalConverted,
4947 /*CanonInjectedTST=*/CanQualType(),
4948 /*PrevDecl=*/nullptr);
4949
4950 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4951
4952 // Substitute the nested name specifier, if any.
4953 if (SubstQualifier(PartialSpec, InstPartialSpec))
4954 return nullptr;
4955
4956 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4957
4958 if (PrevDecl) {
4959 // We've already seen a partial specialization with the same template
4960 // parameters and template arguments. This can happen, for example, when
4961 // substituting the outer template arguments ends up causing two
4962 // class template partial specializations of a member class template
4963 // to have identical forms, e.g.,
4964 //
4965 // template<typename T, typename U>
4966 // struct Outer {
4967 // template<typename X, typename Y> struct Inner;
4968 // template<typename Y> struct Inner<T, Y>;
4969 // template<typename Y> struct Inner<U, Y>;
4970 // };
4971 //
4972 // Outer<int, int> outer; // error: the partial specializations of Inner
4973 // // have the same signature.
4974 SemaRef.Diag(InstPartialSpec->getLocation(),
4975 diag::err_partial_spec_redeclared)
4976 << InstPartialSpec;
4977 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4978 << SemaRef.Context.getCanonicalTagType(PrevDecl);
4979 return nullptr;
4980 }
4981
4982 // Check the completed partial specialization.
4983 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4984
4985 // Add this partial specialization to the set of class template partial
4986 // specializations.
4987 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4988 /*InsertPos=*/nullptr);
4989 return InstPartialSpec;
4990}
4991
4992/// Instantiate the declaration of a variable template partial
4993/// specialization.
4994///
4995/// \param VarTemplate the (instantiated) variable template that is partially
4996/// specialized by the instantiation of \p PartialSpec.
4997///
4998/// \param PartialSpec the (uninstantiated) variable template partial
4999/// specialization that we are instantiating.
5000///
5001/// \returns The instantiated partial specialization, if successful; otherwise,
5002/// NULL to indicate an error.
5007 // Create a local instantiation scope for this variable template partial
5008 // specialization, which will contain the instantiations of the template
5009 // parameters.
5011
5012 // Substitute into the template parameters of the variable template partial
5013 // specialization.
5014 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
5015 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
5016 if (!InstParams)
5017 return nullptr;
5018
5019 // Substitute into the template arguments of the variable template partial
5020 // specialization.
5021 const ASTTemplateArgumentListInfo *TemplArgInfo
5022 = PartialSpec->getTemplateArgsAsWritten();
5023 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
5024 TemplArgInfo->RAngleLoc);
5025 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
5026 InstTemplateArgs))
5027 return nullptr;
5028
5029 // Check that the template argument list is well-formed for this
5030 // class template.
5032 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
5033 InstTemplateArgs, /*DefaultArgs=*/{},
5034 /*PartialTemplateArgs=*/false, CTAI))
5035 return nullptr;
5036
5037 // Check these arguments are valid for a template partial specialization.
5038 if (SemaRef.CheckTemplatePartialSpecializationArgs(
5039 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
5040 CTAI.CanonicalConverted))
5041 return nullptr;
5042
5043 // Figure out where to insert this variable template partial specialization
5044 // in the member template's set of variable template partial specializations.
5045 void *InsertPos = nullptr;
5047 VarTemplate->findPartialSpecialization(CTAI.CanonicalConverted,
5048 InstParams, InsertPos);
5049
5050 // Do substitution on the type of the declaration
5051 TypeSourceInfo *TSI = SemaRef.SubstType(
5052 PartialSpec->getTypeSourceInfo(), TemplateArgs,
5053 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
5054 if (!TSI)
5055 return nullptr;
5056
5057 if (TSI->getType()->isFunctionType()) {
5058 SemaRef.Diag(PartialSpec->getLocation(),
5059 diag::err_variable_instantiates_to_function)
5060 << PartialSpec->isStaticDataMember() << TSI->getType();
5061 return nullptr;
5062 }
5063
5064 // Create the variable template partial specialization declaration.
5065 VarTemplatePartialSpecializationDecl *InstPartialSpec =
5067 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
5068 PartialSpec->getLocation(), InstParams, VarTemplate, TSI->getType(),
5069 TSI, PartialSpec->getStorageClass(), CTAI.CanonicalConverted);
5070
5071 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
5072
5073 // Substitute the nested name specifier, if any.
5074 if (SubstQualifier(PartialSpec, InstPartialSpec))
5075 return nullptr;
5076
5077 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
5078
5079 if (PrevDecl) {
5080 // We've already seen a partial specialization with the same template
5081 // parameters and template arguments. This can happen, for example, when
5082 // substituting the outer template arguments ends up causing two
5083 // variable template partial specializations of a member variable template
5084 // to have identical forms, e.g.,
5085 //
5086 // template<typename T, typename U>
5087 // struct Outer {
5088 // template<typename X, typename Y> pair<X,Y> p;
5089 // template<typename Y> pair<T, Y> p;
5090 // template<typename Y> pair<U, Y> p;
5091 // };
5092 //
5093 // Outer<int, int> outer; // error: the partial specializations of Inner
5094 // // have the same signature.
5095 SemaRef.Diag(PartialSpec->getLocation(),
5096 diag::err_var_partial_spec_redeclared)
5097 << InstPartialSpec;
5098 SemaRef.Diag(PrevDecl->getLocation(),
5099 diag::note_var_prev_partial_spec_here);
5100 return nullptr;
5101 }
5102 // Check the completed partial specialization.
5103 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
5104
5105 // Add this partial specialization to the set of variable template partial
5106 // specializations. The instantiation of the initializer is not necessary.
5107 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
5108
5109 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
5110 LateAttrs, Owner, StartingScope);
5111
5112 return InstPartialSpec;
5113}
5114
5118 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
5119 assert(OldTInfo && "substituting function without type source info");
5120 assert(Params.empty() && "parameter vector is non-empty at start");
5121
5122 CXXRecordDecl *ThisContext = nullptr;
5123 Qualifiers ThisTypeQuals;
5124 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5125 ThisContext = cast<CXXRecordDecl>(Owner);
5126 ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
5127 }
5128
5129 TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
5130 OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
5131 ThisContext, ThisTypeQuals, EvaluateConstraints);
5132 if (!NewTInfo)
5133 return nullptr;
5134
5135 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
5136 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
5137 if (NewTInfo != OldTInfo) {
5138 // Get parameters from the new type info.
5139 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
5140 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
5141 unsigned NewIdx = 0;
5142 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
5143 OldIdx != NumOldParams; ++OldIdx) {
5144 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
5145 if (!OldParam)
5146 return nullptr;
5147
5148 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
5149
5150 UnsignedOrNone NumArgumentsInExpansion = std::nullopt;
5151 if (OldParam->isParameterPack())
5152 NumArgumentsInExpansion =
5153 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
5154 TemplateArgs);
5155 if (!NumArgumentsInExpansion) {
5156 // Simple case: normal parameter, or a parameter pack that's
5157 // instantiated to a (still-dependent) parameter pack.
5158 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
5159 Params.push_back(NewParam);
5160 Scope->InstantiatedLocal(OldParam, NewParam);
5161 } else {
5162 // Parameter pack expansion: make the instantiation an argument pack.
5163 Scope->MakeInstantiatedLocalArgPack(OldParam);
5164 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
5165 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
5166 Params.push_back(NewParam);
5167 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
5168 }
5169 }
5170 }
5171 } else {
5172 // The function type itself was not dependent and therefore no
5173 // substitution occurred. However, we still need to instantiate
5174 // the function parameters themselves.
5175 const FunctionProtoType *OldProto =
5176 cast<FunctionProtoType>(OldProtoLoc.getType());
5177 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
5178 ++i) {
5179 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
5180 if (!OldParam) {
5181 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
5182 D, D->getLocation(), OldProto->getParamType(i)));
5183 continue;
5184 }
5185
5186 ParmVarDecl *Parm =
5187 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
5188 if (!Parm)
5189 return nullptr;
5190 Params.push_back(Parm);
5191 }
5192 }
5193 } else {
5194 // If the type of this function, after ignoring parentheses, is not
5195 // *directly* a function type, then we're instantiating a function that
5196 // was declared via a typedef or with attributes, e.g.,
5197 //
5198 // typedef int functype(int, int);
5199 // functype func;
5200 // int __cdecl meth(int, int);
5201 //
5202 // In this case, we'll just go instantiate the ParmVarDecls that we
5203 // synthesized in the method declaration.
5204 SmallVector<QualType, 4> ParamTypes;
5205 Sema::ExtParameterInfoBuilder ExtParamInfos;
5206 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
5207 TemplateArgs, ParamTypes, &Params,
5208 ExtParamInfos))
5209 return nullptr;
5210 }
5211
5212 return NewTInfo;
5213}
5214
5215void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
5216 const FunctionDecl *PatternDecl,
5219
5220 for (auto *decl : PatternDecl->decls()) {
5222 continue;
5223
5224 VarDecl *VD = cast<VarDecl>(decl);
5225 IdentifierInfo *II = VD->getIdentifier();
5226
5227 auto it = llvm::find_if(Function->decls(), [&](Decl *inst) {
5228 VarDecl *InstVD = dyn_cast<VarDecl>(inst);
5229 return InstVD && InstVD->isLocalVarDecl() &&
5230 InstVD->getIdentifier() == II;
5231 });
5232
5233 if (it == Function->decls().end())
5234 continue;
5235
5236 Scope.InstantiatedLocal(VD, *it);
5237 LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false,
5238 /*isNested=*/false, VD->getLocation(), SourceLocation(),
5239 VD->getType(), /*Invalid=*/false);
5240 }
5241}
5242
5243bool Sema::addInstantiatedParametersToScope(
5244 FunctionDecl *Function, const FunctionDecl *PatternDecl,
5246 const MultiLevelTemplateArgumentList &TemplateArgs) {
5247 unsigned FParamIdx = 0;
5248 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
5249 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
5250 if (!PatternParam->isParameterPack()) {
5251 // Simple case: not a parameter pack.
5252 assert(FParamIdx < Function->getNumParams());
5253 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
5254 FunctionParam->setDeclName(PatternParam->getDeclName());
5255 // If the parameter's type is not dependent, update it to match the type
5256 // in the pattern. They can differ in top-level cv-qualifiers, and we want
5257 // the pattern's type here. If the type is dependent, they can't differ,
5258 // per core issue 1668. Substitute into the type from the pattern, in case
5259 // it's instantiation-dependent.
5260 // FIXME: Updating the type to work around this is at best fragile.
5261 if (!PatternDecl->getType()->isDependentType()) {
5262 QualType T = SubstType(PatternParam->getType(), TemplateArgs,
5263 FunctionParam->getLocation(),
5264 FunctionParam->getDeclName());
5265 if (T.isNull())
5266 return true;
5267 FunctionParam->setType(T);
5268 }
5269
5270 Scope.InstantiatedLocal(PatternParam, FunctionParam);
5271 ++FParamIdx;
5272 continue;
5273 }
5274
5275 // Expand the parameter pack.
5276 Scope.MakeInstantiatedLocalArgPack(PatternParam);
5277 UnsignedOrNone NumArgumentsInExpansion =
5278 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
5279 if (NumArgumentsInExpansion) {
5280 QualType PatternType =
5281 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
5282 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
5283 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
5284 FunctionParam->setDeclName(PatternParam->getDeclName());
5285 if (!PatternDecl->getType()->isDependentType()) {
5286 Sema::ArgPackSubstIndexRAII SubstIndex(*this, Arg);
5287 QualType T =
5288 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
5289 FunctionParam->getDeclName());
5290 if (T.isNull())
5291 return true;
5292 FunctionParam->setType(T);
5293 }
5294
5295 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
5296 ++FParamIdx;
5297 }
5298 }
5299 }
5300
5301 return false;
5302}
5303
5305 ParmVarDecl *Param) {
5306 assert(Param->hasUninstantiatedDefaultArg());
5307
5308 // FIXME: We don't track member specialization info for non-defining
5309 // friend declarations, so we will not be able to later find the function
5310 // pattern. As a workaround, don't instantiate the default argument in this
5311 // case. This is correct per the standard and only an issue for recovery
5312 // purposes. [dcl.fct.default]p4:
5313 // if a friend declaration D specifies a default argument expression,
5314 // that declaration shall be a definition.
5315 if (FD->getFriendObjectKind() != Decl::FOK_None &&
5317 return true;
5318
5319 // Instantiate the expression.
5320 //
5321 // FIXME: Pass in a correct Pattern argument, otherwise
5322 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
5323 //
5324 // template<typename T>
5325 // struct A {
5326 // static int FooImpl();
5327 //
5328 // template<typename Tp>
5329 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
5330 // // template argument list [[T], [Tp]], should be [[Tp]].
5331 // friend A<Tp> Foo(int a);
5332 // };
5333 //
5334 // template<typename T>
5335 // A<T> Foo(int a = A<T>::FooImpl());
5337 FD, FD->getLexicalDeclContext(),
5338 /*Final=*/false, /*Innermost=*/std::nullopt,
5339 /*RelativeToPrimary=*/true, /*Pattern=*/nullptr,
5340 /*ForConstraintInstantiation=*/false, /*SkipForSpecialization=*/false,
5341 /*ForDefaultArgumentSubstitution=*/true);
5342
5343 if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
5344 return true;
5345
5347 L->DefaultArgumentInstantiated(Param);
5348
5349 return false;
5350}
5351
5353 FunctionDecl *Decl) {
5354 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
5356 return;
5357
5358 RecursiveInstGuard AlreadyInstantiating(
5360 if (AlreadyInstantiating) {
5361 // This exception specification indirectly depends on itself. Reject.
5362 // FIXME: Corresponding rule in the standard?
5363 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
5365 return;
5366 }
5367
5368 NonSFINAEContext _(*this);
5369 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
5371 if (Inst.isInvalid()) {
5372 // We hit the instantiation depth limit. Clear the exception specification
5373 // so that our callers don't have to cope with EST_Uninstantiated.
5375 return;
5376 }
5377
5378 // Enter the scope of this instantiation. We don't use
5379 // PushDeclContext because we don't have a scope.
5380 Sema::ContextRAII savedContext(*this, Decl);
5382
5383 MultiLevelTemplateArgumentList TemplateArgs =
5385 /*Final=*/false, /*Innermost=*/std::nullopt,
5386 /*RelativeToPrimary*/ true);
5387
5388 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
5389 // here, because for a non-defining friend declaration in a class template,
5390 // we don't store enough information to map back to the friend declaration in
5391 // the template.
5393 if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
5395 return;
5396 }
5397
5398 // The noexcept specification could reference any lambda captures. Ensure
5399 // those are added to the LocalInstantiationScope.
5401 *this, Decl, TemplateArgs, Scope,
5402 /*ShouldAddDeclsFromParentScope=*/false);
5403
5404 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
5405 TemplateArgs);
5406}
5407
5408/// Initializes the common fields of an instantiation function
5409/// declaration (New) from the corresponding fields of its template (Tmpl).
5410///
5411/// \returns true if there was an error
5412bool
5414 FunctionDecl *Tmpl) {
5415 New->setImplicit(Tmpl->isImplicit());
5416
5417 // Forward the mangling number from the template to the instantiated decl.
5418 SemaRef.Context.setManglingNumber(New,
5419 SemaRef.Context.getManglingNumber(Tmpl));
5420
5421 // If we are performing substituting explicitly-specified template arguments
5422 // or deduced template arguments into a function template and we reach this
5423 // point, we are now past the point where SFINAE applies and have committed
5424 // to keeping the new function template specialization. We therefore
5425 // convert the active template instantiation for the function template
5426 // into a template instantiation for this specific function template
5427 // specialization, which is not a SFINAE context, so that we diagnose any
5428 // further errors in the declaration itself.
5429 //
5430 // FIXME: This is a hack.
5431 typedef Sema::CodeSynthesisContext ActiveInstType;
5432 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
5433 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
5434 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
5435 if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
5436 SemaRef.CurrentSFINAEContext = nullptr;
5437 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
5438 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
5439 ActiveInst.Entity = New;
5440 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
5441 }
5442 }
5443
5444 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
5445 assert(Proto && "Function template without prototype?");
5446
5447 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
5449
5450 // DR1330: In C++11, defer instantiation of a non-trivial
5451 // exception specification.
5452 // DR1484: Local classes and their members are instantiated along with the
5453 // containing function.
5454 if (SemaRef.getLangOpts().CPlusPlus11 &&
5455 EPI.ExceptionSpec.Type != EST_None &&
5459 FunctionDecl *ExceptionSpecTemplate = Tmpl;
5461 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
5464 NewEST = EST_Unevaluated;
5465
5466 // Mark the function has having an uninstantiated exception specification.
5467 const FunctionProtoType *NewProto
5468 = New->getType()->getAs<FunctionProtoType>();
5469 assert(NewProto && "Template instantiation without function prototype?");
5470 EPI = NewProto->getExtProtoInfo();
5471 EPI.ExceptionSpec.Type = NewEST;
5473 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
5474 New->setType(SemaRef.Context.getFunctionType(
5475 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
5476 } else {
5477 Sema::ContextRAII SwitchContext(SemaRef, New);
5478 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
5479 }
5480 }
5481
5482 // Get the definition. Leaves the variable unchanged if undefined.
5483 const FunctionDecl *Definition = Tmpl;
5484 Tmpl->isDefined(Definition);
5485
5486 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
5487 LateAttrs, StartingScope);
5488
5489 SemaRef.inferLifetimeBoundAttribute(New);
5490
5491 return false;
5492}
5493
5494/// Initializes common fields of an instantiated method
5495/// declaration (New) from the corresponding fields of its template
5496/// (Tmpl).
5497///
5498/// \returns true if there was an error
5499bool
5501 CXXMethodDecl *Tmpl) {
5502 if (InitFunctionInstantiation(New, Tmpl))
5503 return true;
5504
5505 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
5506 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
5507
5508 New->setAccess(Tmpl->getAccess());
5509 if (Tmpl->isVirtualAsWritten())
5510 New->setVirtualAsWritten(true);
5511
5512 // FIXME: New needs a pointer to Tmpl
5513 return false;
5514}
5515
5517 FunctionDecl *Tmpl) {
5518 // Transfer across any unqualified lookups.
5519 if (auto *DFI = Tmpl->getDefaultedOrDeletedInfo()) {
5521 Lookups.reserve(DFI->getUnqualifiedLookups().size());
5522 bool AnyChanged = false;
5523 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
5524 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
5525 DA.getDecl(), TemplateArgs);
5526 if (!D)
5527 return true;
5528 AnyChanged |= (D != DA.getDecl());
5529 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
5530 }
5531
5532 // It's unlikely that substitution will change any declarations. Don't
5533 // store an unnecessary copy in that case.
5534 New->setDefaultedOrDeletedInfo(
5536 SemaRef.Context, Lookups)
5537 : DFI);
5538 }
5539
5540 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
5541 return false;
5542}
5543
5547 FunctionDecl *FD = FTD->getTemplatedDecl();
5548
5549 InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC);
5550 if (Inst.isInvalid())
5551 return nullptr;
5552
5553 ContextRAII SavedContext(*this, FD);
5554 MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
5555 /*Final=*/false);
5556
5557 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
5558}
5559
5562 bool Recursive,
5563 bool DefinitionRequired,
5564 bool AtEndOfTU) {
5565 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
5566 return;
5567
5568 // Never instantiate an explicit specialization except if it is a class scope
5569 // explicit specialization.
5571 Function->getTemplateSpecializationKindForInstantiation();
5572 if (TSK == TSK_ExplicitSpecialization)
5573 return;
5574
5575 // Never implicitly instantiate a builtin; we don't actually need a function
5576 // body.
5577 if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
5578 !DefinitionRequired)
5579 return;
5580
5581 // Don't instantiate a definition if we already have one.
5582 const FunctionDecl *ExistingDefn = nullptr;
5583 if (Function->isDefined(ExistingDefn,
5584 /*CheckForPendingFriendDefinition=*/true)) {
5585 if (ExistingDefn->isThisDeclarationADefinition())
5586 return;
5587
5588 // If we're asked to instantiate a function whose body comes from an
5589 // instantiated friend declaration, attach the instantiated body to the
5590 // corresponding declaration of the function.
5592 Function = const_cast<FunctionDecl*>(ExistingDefn);
5593 }
5594
5595#ifndef NDEBUG
5596 RecursiveInstGuard AlreadyInstantiating(*this, Function,
5598 assert(!AlreadyInstantiating && "should have been caught by caller");
5599#endif
5600
5601 // Find the function body that we'll be substituting.
5602 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
5603 assert(PatternDecl && "instantiating a non-template");
5604
5605 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
5606 Stmt *Pattern = nullptr;
5607 if (PatternDef) {
5608 Pattern = PatternDef->getBody(PatternDef);
5609 PatternDecl = PatternDef;
5610 if (PatternDef->willHaveBody())
5611 PatternDef = nullptr;
5612 }
5613
5614 // True is the template definition is unreachable, otherwise false.
5615 bool Unreachable = false;
5616 // FIXME: We need to track the instantiation stack in order to know which
5617 // definitions should be visible within this instantiation.
5619 PointOfInstantiation, Function,
5620 Function->getInstantiatedFromMemberFunction(), PatternDecl,
5621 PatternDef, TSK,
5622 /*Complain*/ DefinitionRequired, &Unreachable)) {
5623 if (DefinitionRequired)
5624 Function->setInvalidDecl();
5625 else if (TSK == TSK_ExplicitInstantiationDefinition ||
5626 (Function->isConstexpr() && !Recursive)) {
5627 // Try again at the end of the translation unit (at which point a
5628 // definition will be required).
5629 assert(!Recursive);
5630 Function->setInstantiationIsPending(true);
5631 PendingInstantiations.emplace_back(Function, PointOfInstantiation);
5632
5633 if (llvm::isTimeTraceVerbose()) {
5634 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
5635 std::string Name;
5636 llvm::raw_string_ostream OS(Name);
5637 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5638 /*Qualified=*/true);
5639 return Name;
5640 });
5641 }
5642 } else if (TSK == TSK_ImplicitInstantiation) {
5643 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5644 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5645 Diag(PointOfInstantiation, diag::warn_func_template_missing)
5646 << Function;
5647 if (Unreachable) {
5648 // FIXME: would be nice to mention which module the function template
5649 // comes from.
5650 Diag(PatternDecl->getLocation(),
5651 diag::note_unreachable_template_decl);
5652 } else {
5653 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5655 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
5656 << Function;
5657 }
5658 }
5659 }
5660
5661 return;
5662 }
5663
5664 // Postpone late parsed template instantiations.
5665 if (PatternDecl->isLateTemplateParsed() &&
5667 Function->setInstantiationIsPending(true);
5668 LateParsedInstantiations.push_back(
5669 std::make_pair(Function, PointOfInstantiation));
5670 return;
5671 }
5672
5673 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
5674 llvm::TimeTraceMetadata M;
5675 llvm::raw_string_ostream OS(M.Detail);
5676 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5677 /*Qualified=*/true);
5678 if (llvm::isTimeTraceVerbose()) {
5679 auto Loc = SourceMgr.getExpansionLoc(Function->getLocation());
5680 M.File = SourceMgr.getFilename(Loc);
5681 M.Line = SourceMgr.getExpansionLineNumber(Loc);
5682 }
5683 return M;
5684 });
5685
5686 // If we're performing recursive template instantiation, create our own
5687 // queue of pending implicit instantiations that we will instantiate later,
5688 // while we're still within our own instantiation context.
5689 // This has to happen before LateTemplateParser below is called, so that
5690 // it marks vtables used in late parsed templates as used.
5691 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5692 /*Enabled=*/Recursive,
5693 /*AtEndOfTU=*/AtEndOfTU);
5694 LocalEagerInstantiationScope LocalInstantiations(*this,
5695 /*AtEndOfTU=*/AtEndOfTU);
5696
5697 // Call the LateTemplateParser callback if there is a need to late parse
5698 // a templated function definition.
5699 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
5701 // FIXME: Optimize to allow individual templates to be deserialized.
5702 if (PatternDecl->isFromASTFile())
5703 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
5704
5705 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
5706 assert(LPTIter != LateParsedTemplateMap.end() &&
5707 "missing LateParsedTemplate");
5708 LateTemplateParser(OpaqueParser, *LPTIter->second);
5709 Pattern = PatternDecl->getBody(PatternDecl);
5711 }
5712
5713 // Note, we should never try to instantiate a deleted function template.
5714 assert((Pattern || PatternDecl->isDefaulted() ||
5715 PatternDecl->hasSkippedBody()) &&
5716 "unexpected kind of function template definition");
5717
5718 // C++1y [temp.explicit]p10:
5719 // Except for inline functions, declarations with types deduced from their
5720 // initializer or return value, and class template specializations, other
5721 // explicit instantiation declarations have the effect of suppressing the
5722 // implicit instantiation of the entity to which they refer.
5724 !PatternDecl->isInlined() &&
5725 !PatternDecl->getReturnType()->getContainedAutoType())
5726 return;
5727
5728 if (PatternDecl->isInlined()) {
5729 // Function, and all later redeclarations of it (from imported modules,
5730 // for instance), are now implicitly inline.
5731 for (auto *D = Function->getMostRecentDecl(); /**/;
5732 D = D->getPreviousDecl()) {
5733 D->setImplicitlyInline();
5734 if (D == Function)
5735 break;
5736 }
5737 }
5738
5739 NonSFINAEContext _(*this);
5740 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
5741 if (Inst.isInvalid())
5742 return;
5744 "instantiating function definition");
5745
5746 // The instantiation is visible here, even if it was first declared in an
5747 // unimported module.
5748 Function->setVisibleDespiteOwningModule();
5749
5750 // Copy the source locations from the pattern.
5751 Function->setLocation(PatternDecl->getLocation());
5752 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
5753 Function->setRangeEnd(PatternDecl->getEndLoc());
5754 // Let the instantiation use the Pattern's DeclarationNameLoc, due to the
5755 // following awkwardness:
5756 //
5757 // 1. There are out-of-tree users of getNameInfo().getSourceRange(), who
5758 // expect the source range of the instantiated declaration to be set to
5759 // point to the definition.
5760 //
5761 // 2. That getNameInfo().getSourceRange() might return the TypeLocInfo's
5762 // location it tracked.
5763 //
5764 // 3. Function might come from an (implicit) declaration, while the pattern
5765 // comes from a definition. In these cases, we need the PatternDecl's source
5766 // location.
5767 //
5768 // To that end, we need to more or less tweak the DeclarationNameLoc. However,
5769 // we can't blindly copy the DeclarationNameLoc from the PatternDecl to the
5770 // function, since it contains associated TypeLocs that should have already
5771 // been transformed. So, we rebuild the TypeLoc for that purpose. Technically,
5772 // we should create a new function declaration and assign everything we need,
5773 // but InstantiateFunctionDefinition updates the declaration in place.
5774 auto NameLocPointsToPattern = [&] {
5775 DeclarationNameInfo PatternName = PatternDecl->getNameInfo();
5776 DeclarationNameLoc PatternNameLoc = PatternName.getInfo();
5777 switch (PatternName.getName().getNameKind()) {
5781 break;
5782 default:
5783 // Cases where DeclarationNameLoc doesn't matter, as it merely contains a
5784 // source range.
5785 return PatternNameLoc;
5786 }
5787
5788 TypeSourceInfo *TSI = Function->getNameInfo().getNamedTypeInfo();
5789 // TSI might be null if the function is named by a constructor template id.
5790 // E.g. S<T>() {} for class template S with a template parameter T.
5791 if (!TSI) {
5792 // We don't care about the DeclarationName of the instantiated function,
5793 // but only the DeclarationNameLoc. So if the TypeLoc is absent, we do
5794 // nothing.
5795 return PatternNameLoc;
5796 }
5797
5798 QualType InstT = TSI->getType();
5799 // We want to use a TypeLoc that reflects the transformed type while
5800 // preserving the source location from the pattern.
5801 TypeLocBuilder TLB;
5802 TypeSourceInfo *PatternTSI = PatternName.getNamedTypeInfo();
5803 assert(PatternTSI && "Pattern is supposed to have an associated TSI");
5804 // FIXME: PatternTSI is not trivial. We should copy the source location
5805 // along the TypeLoc chain. However a trivial TypeLoc is sufficient for
5806 // getNameInfo().getSourceRange().
5807 TLB.pushTrivial(Context, InstT, PatternTSI->getTypeLoc().getBeginLoc());
5809 TLB.getTypeSourceInfo(Context, InstT));
5810 };
5811 Function->setDeclarationNameLoc(NameLocPointsToPattern());
5812
5815
5816 Qualifiers ThisTypeQuals;
5817 CXXRecordDecl *ThisContext = nullptr;
5818 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5819 ThisContext = Method->getParent();
5820 ThisTypeQuals = Method->getMethodQualifiers();
5821 }
5822 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals);
5823
5824 // Introduce a new scope where local variable instantiations will be
5825 // recorded, unless we're actually a member function within a local
5826 // class, in which case we need to merge our results with the parent
5827 // scope (of the enclosing function). The exception is instantiating
5828 // a function template specialization, since the template to be
5829 // instantiated already has references to locals properly substituted.
5830 bool MergeWithParentScope = false;
5831 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
5832 MergeWithParentScope =
5833 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
5834
5835 LocalInstantiationScope Scope(*this, MergeWithParentScope);
5836 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
5837 // Special members might get their TypeSourceInfo set up w.r.t the
5838 // PatternDecl context, in which case parameters could still be pointing
5839 // back to the original class, make sure arguments are bound to the
5840 // instantiated record instead.
5841 assert(PatternDecl->isDefaulted() &&
5842 "Special member needs to be defaulted");
5843 auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
5844 if (!(PatternSM == CXXSpecialMemberKind::CopyConstructor ||
5848 return;
5849
5850 auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
5851 const auto *PatternRec =
5852 dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
5853 if (!NewRec || !PatternRec)
5854 return;
5855 if (!PatternRec->isLambda())
5856 return;
5857
5858 struct SpecialMemberTypeInfoRebuilder
5859 : TreeTransform<SpecialMemberTypeInfoRebuilder> {
5861 const CXXRecordDecl *OldDecl;
5862 CXXRecordDecl *NewDecl;
5863
5864 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5865 CXXRecordDecl *N)
5866 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5867
5868 bool TransformExceptionSpec(SourceLocation Loc,
5870 SmallVectorImpl<QualType> &Exceptions,
5871 bool &Changed) {
5872 return false;
5873 }
5874
5875 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5876 const RecordType *T = TL.getTypePtr();
5877 RecordDecl *Record = cast_or_null<RecordDecl>(
5878 getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5879 if (Record != OldDecl)
5880 return Base::TransformRecordType(TLB, TL);
5881
5882 // FIXME: transform the rest of the record type.
5883 QualType Result = getDerived().RebuildTagType(
5884 ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt, NewDecl);
5885 if (Result.isNull())
5886 return QualType();
5887
5888 TagTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5891 NewTL.setNameLoc(TL.getNameLoc());
5892 return Result;
5893 }
5894 } IR{*this, PatternRec, NewRec};
5895
5896 TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5897 assert(NewSI && "Type Transform failed?");
5898 Function->setType(NewSI->getType());
5899 Function->setTypeSourceInfo(NewSI);
5900
5901 ParmVarDecl *Parm = Function->getParamDecl(0);
5902 TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5903 assert(NewParmSI && "Type transformation failed.");
5904 Parm->setType(NewParmSI->getType());
5905 Parm->setTypeSourceInfo(NewParmSI);
5906 };
5907
5908 if (PatternDecl->isDefaulted()) {
5909 RebuildTypeSourceInfoForDefaultSpecialMembers();
5910 SetDeclDefaulted(Function, PatternDecl->getLocation());
5911 } else {
5912 DeclContext *DC = Function->getLexicalDeclContext();
5913 std::optional<ArrayRef<TemplateArgument>> Innermost;
5914 if (auto *Primary = Function->getPrimaryTemplate();
5915 Primary &&
5917 Function->getTemplateSpecializationKind() !=
5919 auto It = llvm::find_if(Primary->redecls(),
5920 [](const RedeclarableTemplateDecl *RTD) {
5921 return cast<FunctionTemplateDecl>(RTD)
5922 ->isCompatibleWithDefinition();
5923 });
5924 assert(It != Primary->redecls().end() &&
5925 "Should't get here without a definition");
5927 ->getTemplatedDecl()
5928 ->getDefinition())
5929 DC = Def->getLexicalDeclContext();
5930 else
5931 DC = (*It)->getLexicalDeclContext();
5932 Innermost.emplace(Function->getTemplateSpecializationArgs()->asArray());
5933 }
5935 Function, DC, /*Final=*/false, Innermost, false, PatternDecl);
5936
5937 // Substitute into the qualifier; we can get a substitution failure here
5938 // through evil use of alias templates.
5939 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5940 // of the) lexical context of the pattern?
5941 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5942
5944
5945 // Enter the scope of this instantiation. We don't use
5946 // PushDeclContext because we don't have a scope.
5947 Sema::ContextRAII savedContext(*this, Function);
5948
5949 FPFeaturesStateRAII SavedFPFeatures(*this);
5951 FpPragmaStack.CurrentValue = FPOptionsOverride();
5952
5953 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5954 TemplateArgs))
5955 return;
5956
5957 StmtResult Body;
5958 if (PatternDecl->hasSkippedBody()) {
5960 Body = nullptr;
5961 } else {
5962 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5963 // If this is a constructor, instantiate the member initializers.
5965 TemplateArgs);
5966
5967 // If this is an MS ABI dllexport default constructor, instantiate any
5968 // default arguments.
5969 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5970 Ctor->isDefaultConstructor()) {
5972 }
5973 }
5974
5975 // Instantiate the function body.
5976 Body = SubstStmt(Pattern, TemplateArgs);
5977
5978 if (Body.isInvalid())
5979 Function->setInvalidDecl();
5980 }
5981 // FIXME: finishing the function body while in an expression evaluation
5982 // context seems wrong. Investigate more.
5983 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5984
5986
5987 checkReferenceToTULocalFromOtherTU(Function, PointOfInstantiation);
5988
5989 if (PatternDecl->isDependentContext())
5990 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5991
5992 if (auto *Listener = getASTMutationListener())
5993 Listener->FunctionDefinitionInstantiated(Function);
5994
5995 savedContext.pop();
5996 }
5997
5998 // We never need to emit the code for a lambda in unevaluated context.
5999 // We also can't mangle a lambda in the require clause of a function template
6000 // during constraint checking as the MSI ABI would need to mangle the (not yet
6001 // specialized) enclosing declaration
6002 // FIXME: Should we try to skip this for non-lambda functions too?
6003 bool ShouldSkipCG = [&] {
6004 auto *RD = dyn_cast<CXXRecordDecl>(Function->getParent());
6005 if (!RD || !RD->isLambda())
6006 return false;
6007
6008 return llvm::any_of(ExprEvalContexts, [](auto &Context) {
6009 return Context.isUnevaluated() || Context.isImmediateFunctionContext();
6010 });
6011 }();
6012 if (!ShouldSkipCG) {
6014 Consumer.HandleTopLevelDecl(DG);
6015 }
6016
6017 // This class may have local implicit instantiations that need to be
6018 // instantiation within this scope.
6019 LocalInstantiations.perform();
6020 Scope.Exit();
6021 GlobalInstantiations.perform();
6022}
6023
6026 const TemplateArgumentList *PartialSpecArgs,
6028 SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
6029 LocalInstantiationScope *StartingScope) {
6030 if (FromVar->isInvalidDecl())
6031 return nullptr;
6032
6033 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
6034 if (Inst.isInvalid())
6035 return nullptr;
6036
6037 // Instantiate the first declaration of the variable template: for a partial
6038 // specialization of a static data member template, the first declaration may
6039 // or may not be the declaration in the class; if it's in the class, we want
6040 // to instantiate a member in the class (a declaration), and if it's outside,
6041 // we want to instantiate a definition.
6042 //
6043 // If we're instantiating an explicitly-specialized member template or member
6044 // partial specialization, don't do this. The member specialization completely
6045 // replaces the original declaration in this case.
6046 bool IsMemberSpec = false;
6047 MultiLevelTemplateArgumentList MultiLevelList;
6048 if (auto *PartialSpec =
6049 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
6050 assert(PartialSpecArgs);
6051 IsMemberSpec = PartialSpec->isMemberSpecialization();
6052 MultiLevelList.addOuterTemplateArguments(
6053 PartialSpec, PartialSpecArgs->asArray(), /*Final=*/false);
6054 } else {
6055 assert(VarTemplate == FromVar->getDescribedVarTemplate());
6056 IsMemberSpec = VarTemplate->isMemberSpecialization();
6057 MultiLevelList.addOuterTemplateArguments(VarTemplate, Converted,
6058 /*Final=*/false);
6059 }
6060 if (!IsMemberSpec)
6061 FromVar = FromVar->getFirstDecl();
6062
6063 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
6064 MultiLevelList);
6065
6066 // TODO: Set LateAttrs and StartingScope ...
6067
6068 return Instantiator.VisitVarTemplateSpecializationDecl(VarTemplate, FromVar,
6069 Converted);
6070}
6071
6073 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
6074 const MultiLevelTemplateArgumentList &TemplateArgs) {
6075 assert(PatternDecl->isThisDeclarationADefinition() &&
6076 "don't have a definition to instantiate from");
6077
6078 // Do substitution on the type of the declaration
6079 TypeSourceInfo *TSI =
6080 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
6081 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
6082 if (!TSI)
6083 return nullptr;
6084
6085 // Update the type of this variable template specialization.
6086 VarSpec->setType(TSI->getType());
6087
6088 // Convert the declaration into a definition now.
6089 VarSpec->setCompleteDefinition();
6090
6091 // Instantiate the initializer.
6092 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
6093
6094 if (getLangOpts().OpenCL)
6095 deduceOpenCLAddressSpace(VarSpec);
6096
6097 return VarSpec;
6098}
6099
6101 VarDecl *NewVar, VarDecl *OldVar,
6102 const MultiLevelTemplateArgumentList &TemplateArgs,
6103 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
6104 LocalInstantiationScope *StartingScope,
6105 bool InstantiatingVarTemplate,
6106 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
6107 // Instantiating a partial specialization to produce a partial
6108 // specialization.
6109 bool InstantiatingVarTemplatePartialSpec =
6112 // Instantiating from a variable template (or partial specialization) to
6113 // produce a variable template specialization.
6114 bool InstantiatingSpecFromTemplate =
6116 (OldVar->getDescribedVarTemplate() ||
6118
6119 // If we are instantiating a local extern declaration, the
6120 // instantiation belongs lexically to the containing function.
6121 // If we are instantiating a static data member defined
6122 // out-of-line, the instantiation will have the same lexical
6123 // context (which will be a namespace scope) as the template.
6124 if (OldVar->isLocalExternDecl()) {
6125 NewVar->setLocalExternDecl();
6126 NewVar->setLexicalDeclContext(Owner);
6127 } else if (OldVar->isOutOfLine())
6129 NewVar->setTSCSpec(OldVar->getTSCSpec());
6130 NewVar->setInitStyle(OldVar->getInitStyle());
6131 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
6132 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
6133 NewVar->setConstexpr(OldVar->isConstexpr());
6134 NewVar->setInitCapture(OldVar->isInitCapture());
6137 NewVar->setAccess(OldVar->getAccess());
6138
6139 if (!OldVar->isStaticDataMember()) {
6140 if (OldVar->isUsed(false))
6141 NewVar->setIsUsed();
6142 NewVar->setReferenced(OldVar->isReferenced());
6143 }
6144
6145 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
6146
6148 *this, NewVar->getDeclName(), NewVar->getLocation(),
6153
6154 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
6156 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
6157 // We have a previous declaration. Use that one, so we merge with the
6158 // right type.
6159 if (NamedDecl *NewPrev = FindInstantiatedDecl(
6160 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
6161 Previous.addDecl(NewPrev);
6162 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
6163 OldVar->hasLinkage()) {
6164 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
6165 } else if (PrevDeclForVarTemplateSpecialization) {
6166 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
6167 }
6169
6170 if (!InstantiatingVarTemplate) {
6171 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
6172 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
6173 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
6174 }
6175
6176 if (!OldVar->isOutOfLine()) {
6177 if (NewVar->getDeclContext()->isFunctionOrMethod())
6178 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
6179 }
6180
6181 // Link instantiations of static data members back to the template from
6182 // which they were instantiated.
6183 //
6184 // Don't do this when instantiating a template (we link the template itself
6185 // back in that case) nor when instantiating a static data member template
6186 // (that's not a member specialization).
6187 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
6188 !InstantiatingSpecFromTemplate)
6191
6192 // If the pattern is an (in-class) explicit specialization, then the result
6193 // is also an explicit specialization.
6194 if (VarTemplateSpecializationDecl *OldVTSD =
6195 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
6196 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
6198 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
6200 }
6201
6202 // Forward the mangling number from the template to the instantiated decl.
6203 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
6204 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
6205
6206 // Figure out whether to eagerly instantiate the initializer.
6207 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
6208 // We're producing a template. Don't instantiate the initializer yet.
6209 } else if (NewVar->getType()->isUndeducedType()) {
6210 // We need the type to complete the declaration of the variable.
6211 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
6212 } else if (InstantiatingSpecFromTemplate ||
6213 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
6214 !NewVar->isThisDeclarationADefinition())) {
6215 // Delay instantiation of the initializer for variable template
6216 // specializations or inline static data members until a definition of the
6217 // variable is needed.
6218 } else {
6219 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
6220 }
6221
6222 // Diagnose unused local variables with dependent types, where the diagnostic
6223 // will have been deferred.
6224 if (!NewVar->isInvalidDecl() &&
6225 NewVar->getDeclContext()->isFunctionOrMethod() &&
6226 OldVar->getType()->isDependentType())
6227 DiagnoseUnusedDecl(NewVar);
6228}
6229
6231 VarDecl *Var, VarDecl *OldVar,
6232 const MultiLevelTemplateArgumentList &TemplateArgs) {
6234 L->VariableDefinitionInstantiated(Var);
6235
6236 // We propagate the 'inline' flag with the initializer, because it
6237 // would otherwise imply that the variable is a definition for a
6238 // non-static data member.
6239 if (OldVar->isInlineSpecified())
6240 Var->setInlineSpecified();
6241 else if (OldVar->isInline())
6242 Var->setImplicitlyInline();
6243
6244 ContextRAII SwitchContext(*this, Var->getDeclContext());
6245
6253
6254 // Set DeclForInitializer for this variable so DiagIfReachable can properly
6255 // suppress runtime diagnostics for constexpr/static member variables
6257
6258 if (OldVar->getInit()) {
6259 // Instantiate the initializer.
6261 SubstInitializer(OldVar->getInit(), TemplateArgs,
6262 OldVar->getInitStyle() == VarDecl::CallInit);
6263
6264 if (!Init.isInvalid()) {
6265 Expr *InitExpr = Init.get();
6266
6267 if (Var->hasAttr<DLLImportAttr>() &&
6268 (!InitExpr || !InitExpr->isConstantInitializer(getASTContext()))) {
6269 // Do not dynamically initialize dllimport variables.
6270 } else if (InitExpr) {
6271 bool DirectInit = OldVar->isDirectInit();
6272 AddInitializerToDecl(Var, InitExpr, DirectInit);
6273 } else
6275 } else {
6276 // FIXME: Not too happy about invalidating the declaration
6277 // because of a bogus initializer.
6278 Var->setInvalidDecl();
6279 }
6280 } else {
6281 // `inline` variables are a definition and declaration all in one; we won't
6282 // pick up an initializer from anywhere else.
6283 if (Var->isStaticDataMember() && !Var->isInline()) {
6284 if (!Var->isOutOfLine())
6285 return;
6286
6287 // If the declaration inside the class had an initializer, don't add
6288 // another one to the out-of-line definition.
6289 if (OldVar->getFirstDecl()->hasInit())
6290 return;
6291 }
6292
6293 // We'll add an initializer to a for-range declaration later.
6294 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
6295 return;
6296
6298 }
6299
6300 if (getLangOpts().CUDA)
6302}
6303
6305 VarDecl *Var, bool Recursive,
6306 bool DefinitionRequired, bool AtEndOfTU) {
6307 if (Var->isInvalidDecl())
6308 return;
6309
6310 // Never instantiate an explicitly-specialized entity.
6313 if (TSK == TSK_ExplicitSpecialization)
6314 return;
6315
6316 RecursiveInstGuard AlreadyInstantiating(*this, Var,
6318 if (AlreadyInstantiating)
6319 return;
6320
6321 // Find the pattern and the arguments to substitute into it.
6322 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
6323 assert(PatternDecl && "no pattern for templated variable");
6324 MultiLevelTemplateArgumentList TemplateArgs =
6326
6328 dyn_cast<VarTemplateSpecializationDecl>(Var);
6329 if (VarSpec) {
6330 // If this is a static data member template, there might be an
6331 // uninstantiated initializer on the declaration. If so, instantiate
6332 // it now.
6333 //
6334 // FIXME: This largely duplicates what we would do below. The difference
6335 // is that along this path we may instantiate an initializer from an
6336 // in-class declaration of the template and instantiate the definition
6337 // from a separate out-of-class definition.
6338 if (PatternDecl->isStaticDataMember() &&
6339 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
6340 !Var->hasInit()) {
6341 // FIXME: Factor out the duplicated instantiation context setup/tear down
6342 // code here.
6343 NonSFINAEContext _(*this);
6344 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
6345 if (Inst.isInvalid())
6346 return;
6348 "instantiating variable initializer");
6349
6350 // The instantiation is visible here, even if it was first declared in an
6351 // unimported module.
6353
6354 // If we're performing recursive template instantiation, create our own
6355 // queue of pending implicit instantiations that we will instantiate
6356 // later, while we're still within our own instantiation context.
6357 GlobalEagerInstantiationScope GlobalInstantiations(
6358 *this,
6359 /*Enabled=*/Recursive, /*AtEndOfTU=*/AtEndOfTU);
6360 LocalInstantiationScope Local(*this);
6361 LocalEagerInstantiationScope LocalInstantiations(*this,
6362 /*AtEndOfTU=*/AtEndOfTU);
6363
6364 // Enter the scope of this instantiation. We don't use
6365 // PushDeclContext because we don't have a scope.
6366 ContextRAII PreviousContext(*this, Var->getDeclContext());
6367 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
6368 PreviousContext.pop();
6369
6370 // This variable may have local implicit instantiations that need to be
6371 // instantiated within this scope.
6372 LocalInstantiations.perform();
6373 Local.Exit();
6374 GlobalInstantiations.perform();
6375 }
6376 } else {
6377 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
6378 "not a static data member?");
6379 }
6380
6381 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
6382
6383 // If we don't have a definition of the variable template, we won't perform
6384 // any instantiation. Rather, we rely on the user to instantiate this
6385 // definition (or provide a specialization for it) in another translation
6386 // unit.
6387 if (!Def && !DefinitionRequired) {
6389 PendingInstantiations.emplace_back(Var, PointOfInstantiation);
6390 } else if (TSK == TSK_ImplicitInstantiation) {
6391 // Warn about missing definition at the end of translation unit.
6392 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
6393 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
6394 Diag(PointOfInstantiation, diag::warn_var_template_missing)
6395 << Var;
6396 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
6398 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
6399 }
6400 return;
6401 }
6402 }
6403
6404 // FIXME: We need to track the instantiation stack in order to know which
6405 // definitions should be visible within this instantiation.
6406 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
6407 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
6408 /*InstantiatedFromMember*/false,
6409 PatternDecl, Def, TSK,
6410 /*Complain*/DefinitionRequired))
6411 return;
6412
6413 // C++11 [temp.explicit]p10:
6414 // Except for inline functions, const variables of literal types, variables
6415 // of reference types, [...] explicit instantiation declarations
6416 // have the effect of suppressing the implicit instantiation of the entity
6417 // to which they refer.
6418 //
6419 // FIXME: That's not exactly the same as "might be usable in constant
6420 // expressions", which only allows constexpr variables and const integral
6421 // types, not arbitrary const literal types.
6424 return;
6425
6426 // Make sure to pass the instantiated variable to the consumer at the end.
6427 struct PassToConsumerRAII {
6429 VarDecl *Var;
6430
6431 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
6432 : Consumer(Consumer), Var(Var) { }
6433
6434 ~PassToConsumerRAII() {
6435 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
6436 }
6437 } PassToConsumerRAII(Consumer, Var);
6438
6439 // If we already have a definition, we're done.
6440 if (VarDecl *Def = Var->getDefinition()) {
6441 // We may be explicitly instantiating something we've already implicitly
6442 // instantiated.
6444 PointOfInstantiation);
6445 return;
6446 }
6447
6448 NonSFINAEContext _(*this);
6449 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
6450 if (Inst.isInvalid())
6451 return;
6453 "instantiating variable definition");
6454
6455 // If we're performing recursive template instantiation, create our own
6456 // queue of pending implicit instantiations that we will instantiate later,
6457 // while we're still within our own instantiation context.
6458 GlobalEagerInstantiationScope GlobalInstantiations(*this,
6459 /*Enabled=*/Recursive,
6460 /*AtEndOfTU=*/AtEndOfTU);
6461
6462 // Enter the scope of this instantiation. We don't use
6463 // PushDeclContext because we don't have a scope.
6464 ContextRAII PreviousContext(*this, Var->getDeclContext());
6465 LocalInstantiationScope Local(*this);
6466
6467 LocalEagerInstantiationScope LocalInstantiations(*this,
6468 /*AtEndOfTU=*/AtEndOfTU);
6469
6470 VarDecl *OldVar = Var;
6471 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
6472 // We're instantiating an inline static data member whose definition was
6473 // provided inside the class.
6474 InstantiateVariableInitializer(Var, Def, TemplateArgs);
6475 } else if (!VarSpec) {
6476 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
6477 TemplateArgs));
6478 } else if (Var->isStaticDataMember() &&
6479 Var->getLexicalDeclContext()->isRecord()) {
6480 // We need to instantiate the definition of a static data member template,
6481 // and all we have is the in-class declaration of it. Instantiate a separate
6482 // declaration of the definition.
6483 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
6484 TemplateArgs);
6485
6486 TemplateArgumentListInfo TemplateArgInfo;
6487 if (const ASTTemplateArgumentListInfo *ArgInfo =
6488 VarSpec->getTemplateArgsAsWritten()) {
6489 TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
6490 TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
6491 for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
6492 TemplateArgInfo.addArgument(Arg);
6493 }
6494
6497 VarSpec->getSpecializedTemplate(), Def,
6498 VarSpec->getTemplateArgs().asArray(), VarSpec);
6499 Var = VTSD;
6500
6501 if (Var) {
6502 VTSD->setTemplateArgsAsWritten(TemplateArgInfo);
6503
6504 llvm::PointerUnion<VarTemplateDecl *,
6508 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
6509 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
6510 Partial, &VarSpec->getTemplateInstantiationArgs());
6511
6512 // Attach the initializer.
6513 InstantiateVariableInitializer(Var, Def, TemplateArgs);
6514 }
6515 } else
6516 // Complete the existing variable's definition with an appropriately
6517 // substituted type and initializer.
6518 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
6519
6520 PreviousContext.pop();
6521
6522 if (Var) {
6523 PassToConsumerRAII.Var = Var;
6525 OldVar->getPointOfInstantiation());
6526 // Emit any deferred warnings for the variable's initializer
6527 AnalysisWarnings.issueWarningsForRegisteredVarDecl(Var);
6528 }
6529
6530 // This variable may have local implicit instantiations that need to be
6531 // instantiated within this scope.
6532 LocalInstantiations.perform();
6533 Local.Exit();
6534 GlobalInstantiations.perform();
6535}
6536
6537void
6539 const CXXConstructorDecl *Tmpl,
6540 const MultiLevelTemplateArgumentList &TemplateArgs) {
6541
6543 bool AnyErrors = Tmpl->isInvalidDecl();
6544
6545 // Instantiate all the initializers.
6546 for (const auto *Init : Tmpl->inits()) {
6547 // Only instantiate written initializers, let Sema re-construct implicit
6548 // ones.
6549 if (!Init->isWritten())
6550 continue;
6551
6552 SourceLocation EllipsisLoc;
6553
6554 if (Init->isPackExpansion()) {
6555 // This is a pack expansion. We should expand it now.
6556 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
6558 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
6559 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
6560 bool ShouldExpand = false;
6561 bool RetainExpansion = false;
6562 UnsignedOrNone NumExpansions = std::nullopt;
6564 Init->getEllipsisLoc(), BaseTL.getSourceRange(), Unexpanded,
6565 TemplateArgs, /*FailOnPackProducingTemplates=*/true, ShouldExpand,
6566 RetainExpansion, NumExpansions)) {
6567 AnyErrors = true;
6568 New->setInvalidDecl();
6569 continue;
6570 }
6571 assert(ShouldExpand && "Partial instantiation of base initializer?");
6572
6573 // Loop over all of the arguments in the argument pack(s),
6574 for (unsigned I = 0; I != *NumExpansions; ++I) {
6575 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
6576
6577 // Instantiate the initializer.
6578 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
6579 /*CXXDirectInit=*/true);
6580 if (TempInit.isInvalid()) {
6581 AnyErrors = true;
6582 break;
6583 }
6584
6585 // Instantiate the base type.
6586 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
6587 TemplateArgs,
6588 Init->getSourceLocation(),
6589 New->getDeclName());
6590 if (!BaseTInfo) {
6591 AnyErrors = true;
6592 break;
6593 }
6594
6595 // Build the initializer.
6596 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
6597 BaseTInfo, TempInit.get(),
6598 New->getParent(),
6599 SourceLocation());
6600 if (NewInit.isInvalid()) {
6601 AnyErrors = true;
6602 break;
6603 }
6604
6605 NewInits.push_back(NewInit.get());
6606 }
6607
6608 continue;
6609 }
6610
6611 // Instantiate the initializer.
6612 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
6613 /*CXXDirectInit=*/true);
6614 if (TempInit.isInvalid()) {
6615 AnyErrors = true;
6616 continue;
6617 }
6618
6619 MemInitResult NewInit;
6620 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
6621 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
6622 TemplateArgs,
6623 Init->getSourceLocation(),
6624 New->getDeclName());
6625 if (!TInfo) {
6626 AnyErrors = true;
6627 New->setInvalidDecl();
6628 continue;
6629 }
6630
6631 if (Init->isBaseInitializer())
6632 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
6633 New->getParent(), EllipsisLoc);
6634 else
6635 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
6636 cast<CXXRecordDecl>(CurContext->getParent()));
6637 } else if (Init->isMemberInitializer()) {
6638 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
6639 Init->getMemberLocation(),
6640 Init->getMember(),
6641 TemplateArgs));
6642 if (!Member) {
6643 AnyErrors = true;
6644 New->setInvalidDecl();
6645 continue;
6646 }
6647
6648 NewInit = BuildMemberInitializer(Member, TempInit.get(),
6649 Init->getSourceLocation());
6650 } else if (Init->isIndirectMemberInitializer()) {
6651 IndirectFieldDecl *IndirectMember =
6652 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
6653 Init->getMemberLocation(),
6654 Init->getIndirectMember(), TemplateArgs));
6655
6656 if (!IndirectMember) {
6657 AnyErrors = true;
6658 New->setInvalidDecl();
6659 continue;
6660 }
6661
6662 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
6663 Init->getSourceLocation());
6664 }
6665
6666 if (NewInit.isInvalid()) {
6667 AnyErrors = true;
6668 New->setInvalidDecl();
6669 } else {
6670 NewInits.push_back(NewInit.get());
6671 }
6672 }
6673
6674 // Assign all the initializers to the new constructor.
6676 /*FIXME: ColonLoc */
6678 NewInits,
6679 AnyErrors);
6680}
6681
6682// TODO: this could be templated if the various decl types used the
6683// same method name.
6685 ClassTemplateDecl *Instance) {
6686 Pattern = Pattern->getCanonicalDecl();
6687
6688 do {
6689 Instance = Instance->getCanonicalDecl();
6690 if (Pattern == Instance) return true;
6691 Instance = Instance->getInstantiatedFromMemberTemplate();
6692 } while (Instance);
6693
6694 return false;
6695}
6696
6698 FunctionTemplateDecl *Instance) {
6699 Pattern = Pattern->getCanonicalDecl();
6700
6701 do {
6702 Instance = Instance->getCanonicalDecl();
6703 if (Pattern == Instance) return true;
6704 Instance = Instance->getInstantiatedFromMemberTemplate();
6705 } while (Instance);
6706
6707 return false;
6708}
6709
6710static bool
6713 Pattern
6715 do {
6717 Instance->getCanonicalDecl());
6718 if (Pattern == Instance)
6719 return true;
6720 Instance = Instance->getInstantiatedFromMember();
6721 } while (Instance);
6722
6723 return false;
6724}
6725
6727 CXXRecordDecl *Instance) {
6728 Pattern = Pattern->getCanonicalDecl();
6729
6730 do {
6731 Instance = Instance->getCanonicalDecl();
6732 if (Pattern == Instance) return true;
6733 Instance = Instance->getInstantiatedFromMemberClass();
6734 } while (Instance);
6735
6736 return false;
6737}
6738
6739static bool isInstantiationOf(FunctionDecl *Pattern,
6740 FunctionDecl *Instance) {
6741 Pattern = Pattern->getCanonicalDecl();
6742
6743 do {
6744 Instance = Instance->getCanonicalDecl();
6745 if (Pattern == Instance) return true;
6746 Instance = Instance->getInstantiatedFromMemberFunction();
6747 } while (Instance);
6748
6749 return false;
6750}
6751
6752static bool isInstantiationOf(EnumDecl *Pattern,
6753 EnumDecl *Instance) {
6754 Pattern = Pattern->getCanonicalDecl();
6755
6756 do {
6757 Instance = Instance->getCanonicalDecl();
6758 if (Pattern == Instance) return true;
6759 Instance = Instance->getInstantiatedFromMemberEnum();
6760 } while (Instance);
6761
6762 return false;
6763}
6764
6766 UsingShadowDecl *Instance,
6767 ASTContext &C) {
6768 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
6769 Pattern);
6770}
6771
6772static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
6773 ASTContext &C) {
6774 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
6775}
6776
6777template<typename T>
6779 ASTContext &Ctx) {
6780 // An unresolved using declaration can instantiate to an unresolved using
6781 // declaration, or to a using declaration or a using declaration pack.
6782 //
6783 // Multiple declarations can claim to be instantiated from an unresolved
6784 // using declaration if it's a pack expansion. We want the UsingPackDecl
6785 // in that case, not the individual UsingDecls within the pack.
6786 bool OtherIsPackExpansion;
6787 NamedDecl *OtherFrom;
6788 if (auto *OtherUUD = dyn_cast<T>(Other)) {
6789 OtherIsPackExpansion = OtherUUD->isPackExpansion();
6790 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
6791 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
6792 OtherIsPackExpansion = true;
6793 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
6794 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
6795 OtherIsPackExpansion = false;
6796 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
6797 } else {
6798 return false;
6799 }
6800 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
6801 declaresSameEntity(OtherFrom, Pattern);
6802}
6803
6805 VarDecl *Instance) {
6806 assert(Instance->isStaticDataMember());
6807
6808 Pattern = Pattern->getCanonicalDecl();
6809
6810 do {
6811 Instance = Instance->getCanonicalDecl();
6812 if (Pattern == Instance) return true;
6813 Instance = Instance->getInstantiatedFromStaticDataMember();
6814 } while (Instance);
6815
6816 return false;
6817}
6818
6819// Other is the prospective instantiation
6820// D is the prospective pattern
6822 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
6824
6825 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
6827
6828 if (D->getKind() != Other->getKind())
6829 return false;
6830
6831 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
6833
6834 if (auto *Function = dyn_cast<FunctionDecl>(Other))
6835 return isInstantiationOf(cast<FunctionDecl>(D), Function);
6836
6837 if (auto *Enum = dyn_cast<EnumDecl>(Other))
6839
6840 if (auto *Var = dyn_cast<VarDecl>(Other))
6841 if (Var->isStaticDataMember())
6843
6844 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
6846
6847 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
6849
6850 if (auto *PartialSpec =
6851 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
6853 PartialSpec);
6854
6855 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
6856 if (!Field->getDeclName()) {
6857 // This is an unnamed field.
6859 cast<FieldDecl>(D));
6860 }
6861 }
6862
6863 if (auto *Using = dyn_cast<UsingDecl>(Other))
6864 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
6865
6866 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
6867 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
6868
6869 return D->getDeclName() &&
6870 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
6871}
6872
6873template<typename ForwardIterator>
6875 NamedDecl *D,
6876 ForwardIterator first,
6877 ForwardIterator last) {
6878 for (; first != last; ++first)
6879 if (isInstantiationOf(Ctx, D, *first))
6880 return cast<NamedDecl>(*first);
6881
6882 return nullptr;
6883}
6884
6886 const MultiLevelTemplateArgumentList &TemplateArgs) {
6887 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
6888 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
6889 return cast_or_null<DeclContext>(ID);
6890 } else return DC;
6891}
6892
6893/// Determine whether the given context is dependent on template parameters at
6894/// level \p Level or below.
6895///
6896/// Sometimes we only substitute an inner set of template arguments and leave
6897/// the outer templates alone. In such cases, contexts dependent only on the
6898/// outer levels are not effectively dependent.
6899static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
6900 if (!DC->isDependentContext())
6901 return false;
6902 if (!Level)
6903 return true;
6904 return cast<Decl>(DC)->getTemplateDepth() > Level;
6905}
6906
6908 const MultiLevelTemplateArgumentList &TemplateArgs,
6909 bool FindingInstantiatedContext) {
6910 DeclContext *ParentDC = D->getDeclContext();
6911 // Determine whether our parent context depends on any of the template
6912 // arguments we're currently substituting.
6913 bool ParentDependsOnArgs = isDependentContextAtLevel(
6914 ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6915 // FIXME: Parameters of pointer to functions (y below) that are themselves
6916 // parameters (p below) can have their ParentDC set to the translation-unit
6917 // - thus we can not consistently check if the ParentDC of such a parameter
6918 // is Dependent or/and a FunctionOrMethod.
6919 // For e.g. this code, during Template argument deduction tries to
6920 // find an instantiated decl for (T y) when the ParentDC for y is
6921 // the translation unit.
6922 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6923 // float baz(float(*)()) { return 0.0; }
6924 // Foo(baz);
6925 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6926 // it gets here, always has a FunctionOrMethod as its ParentDC??
6927 // For now:
6928 // - as long as we have a ParmVarDecl whose parent is non-dependent and
6929 // whose type is not instantiation dependent, do nothing to the decl
6930 // - otherwise find its instantiated decl.
6931 if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6932 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6933 return D;
6936 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6937 isa<OMPDeclareReductionDecl>(ParentDC) ||
6938 isa<OMPDeclareMapperDecl>(ParentDC))) ||
6939 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6940 cast<CXXRecordDecl>(D)->getTemplateDepth() >
6941 TemplateArgs.getNumRetainedOuterLevels())) {
6942 // D is a local of some kind. Look into the map of local
6943 // declarations to their instantiations.
6945 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
6946 if (Decl *FD = Found->dyn_cast<Decl *>()) {
6947 if (auto *BD = dyn_cast<BindingDecl>(FD);
6948 BD && BD->isParameterPack() && ArgPackSubstIndex) {
6949 return BD->getBindingPackDecls()[*ArgPackSubstIndex];
6950 }
6951 return cast<NamedDecl>(FD);
6952 }
6953
6954 assert(ArgPackSubstIndex &&
6955 "found declaration pack but not pack expanding");
6956 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6957 return cast<NamedDecl>(
6959 }
6960 }
6961
6962 // If we're performing a partial substitution during template argument
6963 // deduction, we may not have values for template parameters yet. They
6964 // just map to themselves.
6967 return D;
6968
6969 if (D->isInvalidDecl())
6970 return nullptr;
6971
6972 // Normally this function only searches for already instantiated declaration
6973 // however we have to make an exclusion for local types used before
6974 // definition as in the code:
6975 //
6976 // template<typename T> void f1() {
6977 // void g1(struct x1);
6978 // struct x1 {};
6979 // }
6980 //
6981 // In this case instantiation of the type of 'g1' requires definition of
6982 // 'x1', which is defined later. Error recovery may produce an enum used
6983 // before definition. In these cases we need to instantiate relevant
6984 // declarations here.
6985 bool NeedInstantiate = false;
6986 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6987 NeedInstantiate = RD->isLocalClass();
6988 else if (isa<TypedefNameDecl>(D) &&
6990 NeedInstantiate = true;
6991 else
6992 NeedInstantiate = isa<EnumDecl>(D);
6993 if (NeedInstantiate) {
6994 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6995 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6996 return cast<TypeDecl>(Inst);
6997 }
6998
6999 // If we didn't find the decl, then we must have a label decl that hasn't
7000 // been found yet. Lazily instantiate it and return it now.
7001 assert(isa<LabelDecl>(D));
7002
7003 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
7004 assert(Inst && "Failed to instantiate label??");
7005
7006 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
7007 return cast<LabelDecl>(Inst);
7008 }
7009
7010 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
7011 if (!Record->isDependentContext())
7012 return D;
7013
7014 // Determine whether this record is the "templated" declaration describing
7015 // a class template or class template specialization.
7016 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
7017 if (ClassTemplate)
7018 ClassTemplate = ClassTemplate->getCanonicalDecl();
7019 else if (ClassTemplateSpecializationDecl *Spec =
7020 dyn_cast<ClassTemplateSpecializationDecl>(Record))
7021 ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl();
7022
7023 // Walk the current context to find either the record or an instantiation of
7024 // it.
7025 DeclContext *DC = CurContext;
7026 while (!DC->isFileContext()) {
7027 // If we're performing substitution while we're inside the template
7028 // definition, we'll find our own context. We're done.
7029 if (DC->Equals(Record))
7030 return Record;
7031
7032 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
7033 // Check whether we're in the process of instantiating a class template
7034 // specialization of the template we're mapping.
7036 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
7037 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
7038 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
7039 return InstRecord;
7040 }
7041
7042 // Check whether we're in the process of instantiating a member class.
7043 if (isInstantiationOf(Record, InstRecord))
7044 return InstRecord;
7045 }
7046
7047 // Move to the outer template scope.
7048 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
7049 if (FD->getFriendObjectKind() &&
7051 DC = FD->getLexicalDeclContext();
7052 continue;
7053 }
7054 // An implicit deduction guide acts as if it's within the class template
7055 // specialization described by its name and first N template params.
7056 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
7057 if (Guide && Guide->isImplicit()) {
7058 TemplateDecl *TD = Guide->getDeducedTemplate();
7059 // Convert the arguments to an "as-written" list.
7060 TemplateArgumentListInfo Args(Loc, Loc);
7061 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
7062 TD->getTemplateParameters()->size())) {
7063 ArrayRef<TemplateArgument> Unpacked(Arg);
7064 if (Arg.getKind() == TemplateArgument::Pack)
7065 Unpacked = Arg.pack_elements();
7066 for (TemplateArgument UnpackedArg : Unpacked)
7067 Args.addArgument(
7068 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
7069 }
7072 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
7073 // We may get a non-null type with errors, in which case
7074 // `getAsCXXRecordDecl` will return `nullptr`. For instance, this
7075 // happens when one of the template arguments is an invalid
7076 // expression. We return early to avoid triggering the assertion
7077 // about the `CodeSynthesisContext`.
7078 if (T.isNull() || T->containsErrors())
7079 return nullptr;
7080 CXXRecordDecl *SubstRecord = T->getAsCXXRecordDecl();
7081
7082 if (!SubstRecord) {
7083 // T can be a dependent TemplateSpecializationType when performing a
7084 // substitution for building a deduction guide or for template
7085 // argument deduction in the process of rebuilding immediate
7086 // expressions. (Because the default argument that involves a lambda
7087 // is untransformed and thus could be dependent at this point.)
7088 assert(SemaRef.RebuildingImmediateInvocation ||
7089 CodeSynthesisContexts.back().Kind ==
7091 // Return a nullptr as a sentinel value, we handle it properly in
7092 // the TemplateInstantiator::TransformInjectedClassNameType
7093 // override, which we transform it to a TemplateSpecializationType.
7094 return nullptr;
7095 }
7096 // Check that this template-id names the primary template and not a
7097 // partial or explicit specialization. (In the latter cases, it's
7098 // meaningless to attempt to find an instantiation of D within the
7099 // specialization.)
7100 // FIXME: The standard doesn't say what should happen here.
7101 if (FindingInstantiatedContext &&
7103 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
7104 Diag(Loc, diag::err_specialization_not_primary_template)
7105 << T << (SubstRecord->getTemplateSpecializationKind() ==
7107 return nullptr;
7108 }
7109 DC = SubstRecord;
7110 continue;
7111 }
7112 }
7113
7114 DC = DC->getParent();
7115 }
7116
7117 // Fall through to deal with other dependent record types (e.g.,
7118 // anonymous unions in class templates).
7119 }
7120
7121 if (!ParentDependsOnArgs)
7122 return D;
7123
7124 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
7125 if (!ParentDC)
7126 return nullptr;
7127
7128 if (ParentDC != D->getDeclContext()) {
7129 // We performed some kind of instantiation in the parent context,
7130 // so now we need to look into the instantiated parent context to
7131 // find the instantiation of the declaration D.
7132
7133 // If our context used to be dependent, we may need to instantiate
7134 // it before performing lookup into that context.
7135 bool IsBeingInstantiated = false;
7136 if (auto *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
7137 if (!Spec->isDependentContext()) {
7138 if (Spec->isEntityBeingDefined())
7139 IsBeingInstantiated = true;
7140 else if (RequireCompleteType(Loc, Context.getCanonicalTagType(Spec),
7141 diag::err_incomplete_type))
7142 return nullptr;
7143
7144 ParentDC = Spec->getDefinitionOrSelf();
7145 }
7146 }
7147
7148 NamedDecl *Result = nullptr;
7149 // FIXME: If the name is a dependent name, this lookup won't necessarily
7150 // find it. Does that ever matter?
7151 if (auto Name = D->getDeclName()) {
7152 DeclarationNameInfo NameInfo(Name, D->getLocation());
7153 DeclarationNameInfo NewNameInfo =
7154 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
7155 Name = NewNameInfo.getName();
7156 if (!Name)
7157 return nullptr;
7158 DeclContext::lookup_result Found = ParentDC->lookup(Name);
7159
7160 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
7161 } else {
7162 // Since we don't have a name for the entity we're looking for,
7163 // our only option is to walk through all of the declarations to
7164 // find that name. This will occur in a few cases:
7165 //
7166 // - anonymous struct/union within a template
7167 // - unnamed class/struct/union/enum within a template
7168 //
7169 // FIXME: Find a better way to find these instantiations!
7171 ParentDC->decls_begin(),
7172 ParentDC->decls_end());
7173 }
7174
7175 if (!Result) {
7176 if (isa<UsingShadowDecl>(D)) {
7177 // UsingShadowDecls can instantiate to nothing because of using hiding.
7178 } else if (hasUncompilableErrorOccurred()) {
7179 // We've already complained about some ill-formed code, so most likely
7180 // this declaration failed to instantiate. There's no point in
7181 // complaining further, since this is normal in invalid code.
7182 // FIXME: Use more fine-grained 'invalid' tracking for this.
7183 } else if (IsBeingInstantiated) {
7184 // The class in which this member exists is currently being
7185 // instantiated, and we haven't gotten around to instantiating this
7186 // member yet. This can happen when the code uses forward declarations
7187 // of member classes, and introduces ordering dependencies via
7188 // template instantiation.
7189 Diag(Loc, diag::err_member_not_yet_instantiated)
7190 << D->getDeclName()
7191 << Context.getCanonicalTagType(cast<CXXRecordDecl>(ParentDC));
7192 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
7193 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
7194 // This enumeration constant was found when the template was defined,
7195 // but can't be found in the instantiation. This can happen if an
7196 // unscoped enumeration member is explicitly specialized.
7197 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
7199 TemplateArgs));
7200 assert(Spec->getTemplateSpecializationKind() ==
7202 Diag(Loc, diag::err_enumerator_does_not_exist)
7203 << D->getDeclName()
7204 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
7205 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
7206 << Context.getCanonicalTagType(Spec);
7207 } else {
7208 // We should have found something, but didn't.
7209 llvm_unreachable("Unable to find instantiation of declaration!");
7210 }
7211 }
7212
7213 D = Result;
7214 }
7215
7216 return D;
7217}
7218
7219void Sema::PerformPendingInstantiations(bool LocalOnly, bool AtEndOfTU) {
7220 std::deque<PendingImplicitInstantiation> DelayedImplicitInstantiations;
7221 while (!PendingLocalImplicitInstantiations.empty() ||
7222 (!LocalOnly && !PendingInstantiations.empty())) {
7224
7225 bool LocalInstantiation = false;
7227 Inst = PendingInstantiations.front();
7228 PendingInstantiations.pop_front();
7229 } else {
7232 LocalInstantiation = true;
7233 }
7234
7235 // Instantiate function definitions
7236 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
7237 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
7239 if (Function->isMultiVersion()) {
7241 Function,
7242 [this, Inst, DefinitionRequired, AtEndOfTU](FunctionDecl *CurFD) {
7243 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
7244 DefinitionRequired, AtEndOfTU);
7245 if (CurFD->isDefined())
7246 CurFD->setInstantiationIsPending(false);
7247 });
7248 } else {
7249 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
7250 DefinitionRequired, AtEndOfTU);
7251 if (Function->isDefined())
7252 Function->setInstantiationIsPending(false);
7253 }
7254 // Definition of a PCH-ed template declaration may be available only in the TU.
7255 if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
7256 TUKind == TU_Prefix && Function->instantiationIsPending())
7257 DelayedImplicitInstantiations.push_back(Inst);
7258 else if (!AtEndOfTU && Function->instantiationIsPending() &&
7259 !LocalInstantiation)
7260 DelayedImplicitInstantiations.push_back(Inst);
7261 continue;
7262 }
7263
7264 // Instantiate variable definitions
7265 VarDecl *Var = cast<VarDecl>(Inst.first);
7266
7267 assert((Var->isStaticDataMember() ||
7269 "Not a static data member, nor a variable template"
7270 " specialization?");
7271
7272 // Don't try to instantiate declarations if the most recent redeclaration
7273 // is invalid.
7274 if (Var->getMostRecentDecl()->isInvalidDecl())
7275 continue;
7276
7277 // Check if the most recent declaration has changed the specialization kind
7278 // and removed the need for implicit instantiation.
7279 switch (Var->getMostRecentDecl()
7281 case TSK_Undeclared:
7282 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
7285 continue; // No longer need to instantiate this type.
7287 // We only need an instantiation if the pending instantiation *is* the
7288 // explicit instantiation.
7289 if (Var != Var->getMostRecentDecl())
7290 continue;
7291 break;
7293 break;
7294 }
7295
7297 "instantiating variable definition");
7298 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
7300
7301 // Instantiate static data member definitions or variable template
7302 // specializations.
7303 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
7304 DefinitionRequired, AtEndOfTU);
7305 }
7306
7307 if (!DelayedImplicitInstantiations.empty())
7308 PendingInstantiations.swap(DelayedImplicitInstantiations);
7309}
7310
7312 const MultiLevelTemplateArgumentList &TemplateArgs) {
7313 for (auto *DD : Pattern->ddiags()) {
7314 switch (DD->getKind()) {
7316 HandleDependentAccessCheck(*DD, TemplateArgs);
7317 break;
7318 }
7319 }
7320}
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
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 bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A)
Determine whether the attribute A might be relevant to the declaration D.
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 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 bool isInstantiationOf(ClassTemplateDecl *Pattern, ClassTemplateDecl *Instance)
static void instantiateDependentAllocAlignAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AllocAlignAttr *Align, Decl *New)
static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, VarDecl *Instance)
static void instantiateOMPDeclareSimdDeclAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const OMPDeclareSimdDeclAttr &Attr, Decl *New)
Instantiation of 'declare simd' attribute and its arguments.
static void instantiateDependentSYCLKernelAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLKernelAttr &Attr, Decl *New)
static void instantiateDependentAlignValueAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AlignValueAttr *Aligned, Decl *New)
static void instantiateDependentAlignedAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion)
static void instantiateOMPDeclareVariantAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const OMPDeclareVariantAttr &Attr, Decl *New)
Instantiation of 'declare variant' attribute and its arguments.
static void instantiateDependentEnableIfAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New)
static void instantiateDependentAnnotationAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AnnotateAttr *Attr, Decl *New)
static Sema::RetainOwnershipKind attrToRetainOwnershipKind(const Attr *A)
static 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:227
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:809
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
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:46
attr::Kind getKind() const
Definition Attr.h:92
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition Attr.h:99
SourceLocation getLoc() const
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3501
shadow_range shadows() const
Definition DeclCXX.h:3567
A binding in a decomposition declaration.
Definition DeclCXX.h:4190
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T)
Definition DeclCXX.cpp:3699
ArrayRef< BindingDecl * > getBindingPackDecls() const
Definition DeclCXX.cpp:3723
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:2620
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3051
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:3020
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2952
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:3275
Represents a C++ deduction guide declaration.
Definition DeclCXX.h:1983
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:2385
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
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:3150
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
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:2506
bool isStatic() const
Definition DeclCXX.cpp:2419
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:132
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1679
unsigned getLambdaDependencyKind() const
Definition DeclCXX.h:1861
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1560
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, unsigned DependencyKind, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
Definition DeclCXX.cpp:141
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2060
TypeSourceInfo * getLambdaTypeInfo() const
Definition DeclCXX.h:1867
void setInstantiationOfMemberClass(CXXRecordDecl *RD, TemplateSpecializationKind TSK)
Specify that this record is an instantiation of the member class RD.
Definition DeclCXX.cpp:2043
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2156
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition DeclCXX.h:1059
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2056
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:75
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Declaration of a class template.
void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D, void *InsertPos)
Insert the specified partial specialization knowing that it is not already in.
ClassTemplateDecl * getMostRecentDecl()
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
llvm::FoldingSetVector< ClassTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
ClassTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, TemplateParameterList *TPL, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
ClassTemplateDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
ClassTemplatePartialSpecializationDecl * findPartialSpecInstantiatedFromMember(ClassTemplatePartialSpecializationDecl *D)
Find a class template partial specialization which was instantiated from the given member partial spe...
void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos)
Insert the specified specialization knowing that it is not already in.
void setCommonPtr(Common *C)
Common * getCommonPtr() const
ClassTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
void setInstantiatedFromMember(ClassTemplatePartialSpecializationDecl *PartialSpec)
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, 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:3682
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:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2251
bool isFileContext() const
Definition DeclBase.h:2193
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2590
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:2202
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:2388
ddiag_range ddiags() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2386
bool isFunctionOrMethod() const
Definition DeclBase.h:2174
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:79
bool isNull() const
Definition DeclGroup.h:75
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:488
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:1074
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1239
T * getAttr() const
Definition DeclBase.h:581
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition DeclBase.h:1164
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:99
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:906
@ FOK_None
Not a friend object.
Definition DeclBase.h:1230
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:601
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:1193
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition DeclBase.h:801
bool isInLocalScopeForInstantiation() const
Determine whether a substitution into this declaration would occur as part of a substitution into a d...
Definition DeclBase.cpp:423
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
bool isInvalidDecl() const
Definition DeclBase.h:596
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1182
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:510
SourceLocation getLocation() const
Definition DeclBase.h:447
const char * getDeclKindName() const
Definition DeclBase.cpp:169
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
void setImplicit(bool I=true)
Definition DeclBase.h:602
void setReferenced(bool R=true)
Definition DeclBase.h:631
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition DeclBase.h:616
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:576
DeclContext * getDeclContext()
Definition DeclBase.h:456
attr_range attrs() const
Definition DeclBase.h:543
AccessSpecifier getAccess() const
Definition DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:931
bool hasAttr() const
Definition DeclBase.h:585
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1248
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:386
Kind getKind() const
Definition DeclBase.h:450
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:878
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:780
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:822
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2003
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
Definition Decl.h:862
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition Decl.h:845
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
A decomposition declaration.
Definition DeclCXX.h:4254
ArrayRef< BindingDecl * > bindings() const
Definition DeclCXX.h:4292
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3734
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:3441
Represents an enum.
Definition Decl.h:4029
enumerator_range enumerators() const
Definition Decl.h:4175
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4247
bool isScopedUsingClassTag() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4250
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5069
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition Decl.h:4218
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4256
EnumDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.h:4119
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4202
EnumDecl * getDefinition() const
Definition Decl.h:4141
TemplateSpecializationKind getTemplateSpecializationKind() const
If this enumeration is a member of a specialization of a templated class, determine what kind of temp...
Definition Decl.cpp:5116
Represents an explicit instantiation of a template entity in source code.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1931
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1939
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition DeclCXX.h:1960
static ExplicitSpecifier Invalid()
Definition DeclCXX.h:1968
const Expr * getExpr() const
Definition DeclCXX.h:1940
static ExplicitSpecifier getFromDecl(const FunctionDecl *Function)
Definition DeclCXX.cpp:2372
This represents one expression.
Definition Expr.h:112
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:177
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:3347
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) 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:277
QualType getType() const
Definition Expr.h:144
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:247
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:3178
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition Decl.h:3278
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3352
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3294
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:54
bool isUnsupportedFriend() const
Determines if this friend kind is unsupported.
Definition DeclFriend.h:183
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
SourceLocation getFriendLoc() const
Retrieves the location of the 'friend' keyword.
Definition DeclFriend.h:144
void setUnsupportedFriend(bool Unsupported)
Definition DeclFriend.h:186
SourceRange getSourceRange() const override LLVM_READONLY
Retrieves the source range for the friend declaration.
Definition DeclFriend.h:152
SourceLocation getEllipsisLoc() const
Retrieves the location of the '...', if present.
Definition DeclFriend.h:149
NamedDecl * getFriendDecl() const
If this friend declaration doesn't name a type, return the inner declaration.
Definition DeclFriend.h:139
TypeSourceInfo * getFriendType() const
If this friend declaration names an (untemplated but possibly dependent) type, return the type; other...
Definition DeclFriend.h:125
bool isPackExpansion() const
Definition DeclFriend.h:190
Declaration of a friend template.
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition Decl.cpp:3135
Represents a function declaration or definition.
Definition Decl.h:2018
void setInstantiationIsPending(bool IC)
State that the instantiation of this function is pending.
Definition Decl.h:2531
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:2207
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3274
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2494
DefaultedOrDeletedFunctionInfo * getDefaultedOrDeletedInfo() const
Definition Decl.cpp:3189
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4188
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2332
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3546
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition Decl.h:2776
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2939
bool UsesFPIntrin() const
Determine whether the function was declared in source context that requires constrained FP intrinsics...
Definition Decl.h:2927
QualType getReturnType() const
Definition Decl.h:2863
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2792
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:4259
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2407
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2466
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3742
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition Decl.cpp:4384
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2558
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2906
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4521
bool FriendConstraintRefersToEnclosingTemplate() const
Definition Decl.h:2725
bool isDeletedAsWritten() const
Definition Decl.h:2562
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2371
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2375
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2697
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2300
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3554
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3218
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2403
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4544
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2362
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3821
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2229
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3194
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:3241
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:2917
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2703
const ASTTemplateArgumentListInfo * getTemplateSpecializationArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
Definition Decl.cpp:4334
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5362
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5669
QualType getParamType(unsigned i) const
Definition TypeBase.h:5642
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5675
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5651
FunctionDecl * getExceptionSpecTemplate() const
If this function type has an uninstantiated exception specification, this is the function whose excep...
Definition TypeBase.h:5748
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5647
Declaration of a template function.
FunctionTemplateDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
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:1722
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1723
ExtInfo getExtInfo() const
Definition TypeBase.h:4914
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4906
QualType getReturnType() const
Definition TypeBase.h:4898
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
Definition Decl.h:5212
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:3485
unsigned getChainingSize() const
Definition Decl.h:3510
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5738
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3506
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2591
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:975
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3672
Represents the declaration of a label.
Definition Decl.h:524
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
Definition Decl.cpp:5550
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:371
SmallVector< ValueDecl *, 4 > DeclArgumentPack
A set of declarations.
Definition Template.h:374
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:4403
An instance of this class represents the declaration of a property member.
Definition DeclCXX.h:4349
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition DeclCXX.cpp:3774
IdentifierInfo * getGetterId() const
Definition DeclCXX.h:4371
IdentifierInfo * getSetterId() const
Definition DeclCXX.h:4373
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:271
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:212
void setKind(TemplateSubstitutionKind K)
Definition Template.h:109
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:266
unsigned getNumRetainedOuterLevels() const
Definition Template.h:139
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1943
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:397
Represents a C++ namespace alias.
Definition DeclCXX.h:3206
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name of the namespace, with source-location inf...
Definition DeclCXX.h:3267
SourceLocation getAliasLoc() const
Returns the location of the alias name, i.e.
Definition DeclCXX.h:3289
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamespaceBaseDecl *Namespace)
Definition DeclCXX.cpp:3406
SourceLocation getNamespaceLoc() const
Returns the location of the namespace keyword.
Definition DeclCXX.h:3292
SourceLocation getTargetNameLoc() const
Returns the location of the identifier in the named namespace.
Definition DeclCXX.h:3295
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition DeclCXX.h:3276
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
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.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
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...
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
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...
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:2030
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:2629
TypeLoc getPatternLoc() const
Definition TypeLoc.h:2645
Represents a parameter to a function.
Definition Decl.h:1808
Represents a #pragma comment line.
Definition Decl.h:167
Represents a #pragma detect_mismatch line.
Definition Decl.h:201
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8514
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
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:8621
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1719
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
Represents a struct/union/class.
Definition Decl.h:4343
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4395
Wrapper for source info for record types.
Definition TypeLoc.h:855
Declaration of a redeclarable 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:5348
Represents the body of a requires-expression.
Definition DeclCXX.h:2101
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition DeclCXX.cpp:2407
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:40
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:758
QualType getInoutParameterType(QualType Ty)
bool inferObjCARCLifetime(ValueDecl *decl)
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
void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, ArrayRef< Expr * > AdjustArgsNothing, ArrayRef< Expr * > AdjustArgsNeedDevicePtr, ArrayRef< Expr * > AdjustArgsNeedDeviceAddr, ArrayRef< OMPInteropInfo > AppendArgs, SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, SourceRange SR)
Called on well-formed '#pragma omp declare variant' after parsing of the associated method/function.
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...
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:13758
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8532
A RAII object to temporarily push a declaration context.
Definition Sema.h:3526
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6465
A helper class for building up ExtParameterInfos.
Definition Sema.h:13119
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition Sema.h:14163
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12595
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
SemaAMDGPU & AMDGPU()
Definition Sema.h:1448
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13697
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13148
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9415
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9442
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9447
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:5122
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition Sema.h:1533
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:1262
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:1473
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7010
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2076
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
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:7022
LateParsedTemplateMapT LateParsedTemplateMap
Definition Sema.h:11463
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:1308
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
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:1518
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:81
void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs)
void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Name, bool InInstantiation=false)
AddModeAttr - Adds a mode attribute to a particular declaration.
void CleanupVarDeclMarking()
ASTContext & getASTContext() const
Definition Sema.h:939
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:14252
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1212
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:12249
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
NamedReturnInfo getNamedReturnInfo(Expr *&E, SimplerImplicitMoveMode Mode=SimplerImplicitMoveMode::Normal)
Determine whether the given expression might be move-eligible or copy-elidable in either a (co_)retur...
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition Sema.h:932
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:238
void * OpaqueParser
Definition Sema.h:1352
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
const LangOptions & LangOpts
Definition Sema.h:1306
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1483
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:14115
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
SemaSwift & Swift()
Definition Sema.h:1563
const VarDecl * getCopyElisionCandidate(NamedReturnInfo &Info, QualType ReturnType)
Updates given NamedReturnInfo's move-eligible and copy-elidable statuses, considering the function re...
void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr)
AddAllocAlignAttr - Adds an alloc_align attribute to a particular declaration.
UnsignedOrNone getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2601
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1446
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:1528
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition Sema.h:14128
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
SourceManager & getSourceManager() const
Definition Sema.h:937
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)
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:13752
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
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:1584
ASTConsumer & Consumer
Definition Sema.h:1309
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1346
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1851
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14111
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:6811
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6821
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6790
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:1351
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:8401
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:1311
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
FPOptions CurFPFeatures
Definition Sema.h:1304
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Attr * CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
Definition Sema.cpp:3022
@ TPC_FriendFunctionTemplate
Definition Sema.h:11681
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11682
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:631
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:14107
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.
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11455
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1299
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:657
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8743
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
Represents a C++11 static_assert declaration.
Definition DeclCXX.h:4141
bool isFailed() const
Definition DeclCXX.h:4170
SourceLocation getRParenLoc() const
Definition DeclCXX.h:4172
Stmt - This represents one statement.
Definition Stmt.h:86
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:3735
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:3831
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3836
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition Decl.h:3989
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3972
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:4896
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:4938
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:3968
TagKind getTagKind() const
Definition Decl.h:3935
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.
void setEvaluateConstraints(bool B)
Definition Template.h:614
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)
TypeSourceInfo * SubstFunctionType(FunctionDecl *D, SmallVectorImpl< ParmVarDecl * > &Params)
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.
bool isNull() const
Determine whether this template name is NULL.
A template parameter object.
Stores a list of template parameters for a TemplateDecl and its derived classes.
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
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.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
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.
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.
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.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
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:105
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:3706
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5812
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition Decl.h:3725
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:3556
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3565
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
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1437
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:884
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2735
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8407
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:8418
The base class of the type hierarchy.
Definition TypeBase.h:1871
bool isRValueReferenceType() const
Definition TypeBase.h:8705
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9333
bool isReferenceType() const
Definition TypeBase.h:8697
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2954
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2845
bool isLValueReferenceType() const
Definition TypeBase.h:8701
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2837
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2458
bool isTemplateTypeParmType() const
Definition TypeBase.h:9004
bool isAtomicType() const
Definition TypeBase.h:8865
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2855
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9182
bool isFunctionType() const
Definition TypeBase.h:8669
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9266
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3685
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5761
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3580
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3630
QualType getUnderlyingType() const
Definition Decl.h:3635
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4460
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition DeclCXX.h:4123
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition DeclCXX.cpp:3651
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4042
SourceLocation getTypenameLoc() const
Returns the source location of the 'typename' keyword.
Definition DeclCXX.h:4072
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3945
Represents a C++ using-declaration.
Definition DeclCXX.h:3596
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition DeclCXX.h:3645
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name, with source-location information.
Definition DeclCXX.h:3630
DeclarationNameInfo getNameInfo() const
Definition DeclCXX.h:3637
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition DeclCXX.cpp:3539
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition DeclCXX.h:3623
Represents C++ using-directive.
Definition DeclCXX.h:3101
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition DeclCXX.cpp:3322
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition DeclCXX.cpp:3349
DeclContext * getCommonAncestor()
Returns the common ancestor context of this using-directive and its nominated namespace.
Definition DeclCXX.h:3168
SourceLocation getNamespaceKeyLocation() const
Returns the location of the namespace keyword.
Definition DeclCXX.h:3176
SourceLocation getIdentLocation() const
Returns the location of this using declaration's identifier.
Definition DeclCXX.h:3179
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name of the namespace, with source-location inf...
Definition DeclCXX.h:3146
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3797
SourceLocation getEnumLoc() const
The source location of the 'enum' keyword.
Definition DeclCXX.h:3821
EnumDecl * getEnumDecl() const
Definition DeclCXX.h:3839
TypeSourceInfo * getEnumType() const
Definition DeclCXX.h:3833
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition DeclCXX.cpp:3560
SourceLocation getUsingLoc() const
The source location of the 'using' keyword.
Definition DeclCXX.h:3817
Represents a pack of using declarations that a single using-declarator pack-expanded into.
Definition DeclCXX.h:3878
ArrayRef< NamedDecl * > expansions() const
Get the set of using declarations that this pack expanded into.
Definition DeclCXX.h:3911
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3404
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5588
Represents a variable declaration or definition.
Definition Decl.h:924
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2789
void setObjCForDecl(bool FRD)
Definition Decl.h:1549
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2130
void setCXXForRangeDecl(bool FRD)
Definition Decl.h:1538
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1582
void setInstantiationOfStaticDataMember(VarDecl *VD, TemplateSpecializationKind TSK)
Specify that this variable is an instantiation of the static data member VD.
Definition Decl.cpp:2914
TLSKind getTLSKind() const
Definition Decl.cpp:2147
bool hasInit() const
Definition Decl.cpp:2377
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1465
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
InitializationStyle getInitStyle() const
The style of initialization for this declaration.
Definition Decl.h:1479
void setInitCapture(bool IC)
Definition Decl.h:1594
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2239
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:2440
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2236
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1591
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:932
bool isObjCForDecl() const
Determine whether this variable is a for-loop declaration for a for-in statement in Objective-C.
Definition Decl.h:1545
void setPreviousDeclInSameBlockScope(bool Same)
Definition Decl.h:1606
bool isInlineSpecified() const
Definition Decl.h:1567
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1296
VarDecl * getTemplateInstantiationPattern() const
Retrieve the variable declaration from which this variable could be instantiated, if it is an instant...
Definition Decl.cpp:2693
bool isCXXForRangeDecl() const
Determine whether this variable is the for-range-declaration in a C++0x for-range statement.
Definition Decl.h:1535
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2345
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:2465
bool isNRVOVariable() const
Determine whether this local variable can be used with the named return value optimization (NRVO).
Definition Decl.h:1525
void setInlineSpecified()
Definition Decl.h:1571
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1206
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:2886
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition Decl.h:1171
void setNRVOVariable(bool NRVO)
Definition Decl.h:1528
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1564
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1175
const Expr * getInit() const
Definition Decl.h:1381
void setConstexpr(bool IC)
Definition Decl.h:1585
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition Decl.cpp:2794
bool isDirectInit() const
Whether the initializer is a direct-initializer (list or call).
Definition Decl.h:1484
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1166
void setImplicitlyInline()
Definition Decl.h:1576
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition Decl.h:1601
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:2779
TemplateSpecializationKind getTemplateSpecializationKindForInstantiation() const
Get the template specialization kind of this variable for the purposes of template instantiation.
Definition Decl.cpp:2769
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:2758
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
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.
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
VarTemplatePartialSpecializationDecl * findPartialSpecInstantiatedFromMember(VarTemplatePartialSpecializationDecl *D)
Find a variable template partial specialization which was instantiated from the given member partial ...
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
void setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec)
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the variable template specialization.
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate the initializer of the vari...
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition ScopeInfo.h:804
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:741
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1442
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)
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
OpenACCDirectiveKind
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus11
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
Definition Template.h:54
QualType getFunctionOrMethodResultType(const Decl *D)
Definition Attr.h:98
@ 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:125
@ AS_none
Definition Specifiers.h:128
StorageClass
Storage classes.
Definition Specifiers.h:249
@ SC_Static
Definition Specifiers.h:253
@ SC_None
Definition Specifiers.h:251
Expr * Cond
};
ExprResult ExprEmpty()
Definition Ownership.h:272
bool isGenericLambdaCallOperatorOrStaticInvokerSpecialization(const DeclContext *DC)
Definition ASTLambda.h:89
@ Property
The type of a property.
Definition TypeBase.h:911
@ Result
The result type of a method or function.
Definition TypeBase.h:905
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:587
@ VarTemplate
The name was classified as a variable template name.
Definition Sema.h:585
@ 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:136
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1301
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5982
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5975
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1763
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
getNamedTypeInfo - Returns the source type info associated to the name.
Holds information about the various types of exception specification.
Definition TypeBase.h:5419
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition TypeBase.h:5431
FunctionDecl * SourceTemplate
The function template whose exception specification this is instantiated from, for EST_Uninstantiated...
Definition TypeBase.h:5435
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5421
Extra information about a function prototype.
Definition TypeBase.h:5447
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12099
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12085
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13199
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:13201
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13306
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13227
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6932
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition Sema.h:6938
VarDecl * DeclForInitializer
Declaration for initializer if one is currently being parsed.
Definition Sema.h:6871
A stack object to be created when performing template instantiation.
Definition Sema.h:13393
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13546