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