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