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