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