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