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