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