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