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