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