Thanks to visit codestin.com
Credit goes to clang.llvm.org

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, /*CombineWithOuterScope=*/true);
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, /*CombineWithOuterScope=*/true);
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 }
3789
3790 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, std::nullopt);
3791
3792 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
3793 InstParams = SubstTemplateParams(TempParams);
3794 if (!InstParams)
3795 return nullptr;
3796 } else {
3797 // Perform the actual substitution of template parameters within a new,
3798 // local instantiation scope.
3799 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
3800 InstParams = SubstTemplateParams(TempParams);
3801 if (!InstParams)
3802 return nullptr;
3803 }
3804
3805 // Build the template template parameter.
3806 TemplateTemplateParmDecl *Param;
3807 if (IsExpandedParameterPack)
3809 SemaRef.Context, Owner, D->getLocation(),
3810 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3812 D->wasDeclaredWithTypename(), InstParams, ExpandedParams);
3813 else
3815 SemaRef.Context, Owner, D->getLocation(),
3816 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3817 D->getPosition(), D->isParameterPack(), D->getIdentifier(),
3818 D->templateParameterKind(), D->wasDeclaredWithTypename(), InstParams);
3820 const TemplateArgumentLoc &A = D->getDefaultArgument();
3821 NestedNameSpecifierLoc QualifierLoc = A.getTemplateQualifierLoc();
3822 // FIXME: Pass in the template keyword location.
3823 TemplateName TName = SemaRef.SubstTemplateName(
3824 A.getTemplateKWLoc(), QualifierLoc, A.getArgument().getAsTemplate(),
3825 A.getTemplateNameLoc(), TemplateArgs);
3826 if (!TName.isNull())
3827 Param->setDefaultArgument(
3828 SemaRef.Context,
3829 TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
3830 A.getTemplateKWLoc(), QualifierLoc,
3831 A.getTemplateNameLoc()));
3832 }
3833 Param->setAccess(AS_public);
3834 Param->setImplicit(D->isImplicit());
3835
3836 // Introduce this template parameter's instantiation into the instantiation
3837 // scope.
3838 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3839
3840 return Param;
3841}
3842
3843Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3844 // Using directives are never dependent (and never contain any types or
3845 // expressions), so they require no explicit instantiation work.
3846
3847 UsingDirectiveDecl *Inst
3848 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3850 D->getQualifierLoc(),
3851 D->getIdentLocation(),
3853 D->getCommonAncestor());
3854
3855 // Add the using directive to its declaration context
3856 // only if this is not a function or method.
3857 if (!Owner->isFunctionOrMethod())
3858 Owner->addDecl(Inst);
3859
3860 return Inst;
3861}
3862
3864 BaseUsingDecl *Inst,
3865 LookupResult *Lookup) {
3866
3867 bool isFunctionScope = Owner->isFunctionOrMethod();
3868
3869 for (auto *Shadow : D->shadows()) {
3870 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3871 // reconstruct it in the case where it matters. Hm, can we extract it from
3872 // the DeclSpec when parsing and save it in the UsingDecl itself?
3873 NamedDecl *OldTarget = Shadow->getTargetDecl();
3874 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3875 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3876 OldTarget = BaseShadow;
3877
3878 NamedDecl *InstTarget = nullptr;
3879 if (auto *EmptyD =
3880 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3882 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3883 } else {
3884 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3885 Shadow->getLocation(), OldTarget, TemplateArgs));
3886 }
3887 if (!InstTarget)
3888 return nullptr;
3889
3890 UsingShadowDecl *PrevDecl = nullptr;
3891 if (Lookup &&
3892 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3893 continue;
3894
3895 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3896 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3897 Shadow->getLocation(), OldPrev, TemplateArgs));
3898
3899 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3900 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3901 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3902
3903 if (isFunctionScope)
3904 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3905 }
3906
3907 return Inst;
3908}
3909
3910Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3911
3912 // The nested name specifier may be dependent, for example
3913 // template <typename T> struct t {
3914 // struct s1 { T f1(); };
3915 // struct s2 : s1 { using s1::f1; };
3916 // };
3917 // template struct t<int>;
3918 // Here, in using s1::f1, s1 refers to t<T>::s1;
3919 // we need to substitute for t<int>::s1.
3920 NestedNameSpecifierLoc QualifierLoc
3922 TemplateArgs);
3923 if (!QualifierLoc)
3924 return nullptr;
3925
3926 // For an inheriting constructor declaration, the name of the using
3927 // declaration is the name of a constructor in this class, not in the
3928 // base class.
3929 DeclarationNameInfo NameInfo = D->getNameInfo();
3931 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3933 SemaRef.Context.getCanonicalTagType(RD)));
3934
3935 // We only need to do redeclaration lookups if we're in a class scope (in
3936 // fact, it's not really even possible in non-class scopes).
3937 bool CheckRedeclaration = Owner->isRecord();
3938 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3940
3941 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3942 D->getUsingLoc(),
3943 QualifierLoc,
3944 NameInfo,
3945 D->hasTypename());
3946
3947 CXXScopeSpec SS;
3948 SS.Adopt(QualifierLoc);
3949 if (CheckRedeclaration) {
3950 Prev.setHideTags(false);
3951 SemaRef.LookupQualifiedName(Prev, Owner);
3952
3953 // Check for invalid redeclarations.
3955 D->hasTypename(), SS,
3956 D->getLocation(), Prev))
3957 NewUD->setInvalidDecl();
3958 }
3959
3960 if (!NewUD->isInvalidDecl() &&
3961 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3962 NameInfo, D->getLocation(), nullptr, D))
3963 NewUD->setInvalidDecl();
3964
3965 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3966 NewUD->setAccess(D->getAccess());
3967 Owner->addDecl(NewUD);
3968
3969 // Don't process the shadow decls for an invalid decl.
3970 if (NewUD->isInvalidDecl())
3971 return NewUD;
3972
3973 // If the using scope was dependent, or we had dependent bases, we need to
3974 // recheck the inheritance
3977
3978 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3979}
3980
3981Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3982 // Cannot be a dependent type, but still could be an instantiation
3983 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3984 D->getLocation(), D->getEnumDecl(), TemplateArgs));
3985
3986 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3987 return nullptr;
3988
3989 TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3990 D->getLocation(), D->getDeclName());
3991
3992 if (!TSI)
3993 return nullptr;
3994
3995 UsingEnumDecl *NewUD =
3996 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3997 D->getEnumLoc(), D->getLocation(), TSI);
3998
3999 SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
4000 NewUD->setAccess(D->getAccess());
4001 Owner->addDecl(NewUD);
4002
4003 // Don't process the shadow decls for an invalid decl.
4004 if (NewUD->isInvalidDecl())
4005 return NewUD;
4006
4007 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
4008 // cannot be dependent, and will therefore have been checked during template
4009 // definition.
4010
4011 return VisitBaseUsingDecls(D, NewUD, nullptr);
4012}
4013
4014Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
4015 // Ignore these; we handle them in bulk when processing the UsingDecl.
4016 return nullptr;
4017}
4018
4019Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
4021 // Ignore these; we handle them in bulk when processing the UsingDecl.
4022 return nullptr;
4023}
4024
4025template <typename T>
4026Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
4027 T *D, bool InstantiatingPackElement) {
4028 // If this is a pack expansion, expand it now.
4029 if (D->isPackExpansion() && !InstantiatingPackElement) {
4030 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4031 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
4032 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
4033
4034 // Determine whether the set of unexpanded parameter packs can and should
4035 // be expanded.
4036 bool Expand = true;
4037 bool RetainExpansion = false;
4038 UnsignedOrNone NumExpansions = std::nullopt;
4039 if (SemaRef.CheckParameterPacksForExpansion(
4040 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
4041 /*FailOnPackProducingTemplates=*/true, Expand, RetainExpansion,
4042 NumExpansions))
4043 return nullptr;
4044
4045 // This declaration cannot appear within a function template signature,
4046 // so we can't have a partial argument list for a parameter pack.
4047 assert(!RetainExpansion &&
4048 "should never need to retain an expansion for UsingPackDecl");
4049
4050 if (!Expand) {
4051 // We cannot fully expand the pack expansion now, so substitute into the
4052 // pattern and create a new pack expansion.
4053 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, std::nullopt);
4054 return instantiateUnresolvedUsingDecl(D, true);
4055 }
4056
4057 // Within a function, we don't have any normal way to check for conflicts
4058 // between shadow declarations from different using declarations in the
4059 // same pack expansion, but this is always ill-formed because all expansions
4060 // must produce (conflicting) enumerators.
4061 //
4062 // Sadly we can't just reject this in the template definition because it
4063 // could be valid if the pack is empty or has exactly one expansion.
4064 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
4065 SemaRef.Diag(D->getEllipsisLoc(),
4066 diag::err_using_decl_redeclaration_expansion);
4067 return nullptr;
4068 }
4069
4070 // Instantiate the slices of this pack and build a UsingPackDecl.
4071 SmallVector<NamedDecl*, 8> Expansions;
4072 for (unsigned I = 0; I != *NumExpansions; ++I) {
4073 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
4074 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
4075 if (!Slice)
4076 return nullptr;
4077 // Note that we can still get unresolved using declarations here, if we
4078 // had arguments for all packs but the pattern also contained other
4079 // template arguments (this only happens during partial substitution, eg
4080 // into the body of a generic lambda in a function template).
4081 Expansions.push_back(cast<NamedDecl>(Slice));
4082 }
4083
4084 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
4085 if (isDeclWithinFunction(D))
4086 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
4087 return NewD;
4088 }
4089
4090 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
4091 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
4092
4093 NestedNameSpecifierLoc QualifierLoc
4094 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
4095 TemplateArgs);
4096 if (!QualifierLoc)
4097 return nullptr;
4098
4099 CXXScopeSpec SS;
4100 SS.Adopt(QualifierLoc);
4101
4102 DeclarationNameInfo NameInfo
4103 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
4104
4105 // Produce a pack expansion only if we're not instantiating a particular
4106 // slice of a pack expansion.
4107 bool InstantiatingSlice =
4108 D->getEllipsisLoc().isValid() && SemaRef.ArgPackSubstIndex;
4109 SourceLocation EllipsisLoc =
4110 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
4111
4112 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
4113 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
4114 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
4115 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
4116 ParsedAttributesView(),
4117 /*IsInstantiation*/ true, IsUsingIfExists);
4118 if (UD) {
4119 SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
4120 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
4121 }
4122
4123 return UD;
4124}
4125
4126Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
4128 return instantiateUnresolvedUsingDecl(D);
4129}
4130
4131Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
4133 return instantiateUnresolvedUsingDecl(D);
4134}
4135
4136Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
4138 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
4139}
4140
4141Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
4142 SmallVector<NamedDecl*, 8> Expansions;
4143 for (auto *UD : D->expansions()) {
4144 if (NamedDecl *NewUD =
4145 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
4146 Expansions.push_back(NewUD);
4147 else
4148 return nullptr;
4149 }
4150
4151 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
4152 if (isDeclWithinFunction(D))
4153 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
4154 return NewD;
4155}
4156
4157Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
4159 SmallVector<Expr *, 5> Vars;
4160 for (auto *I : D->varlist()) {
4161 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
4162 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
4163 Vars.push_back(Var);
4164 }
4165
4166 OMPThreadPrivateDecl *TD =
4167 SemaRef.OpenMP().CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
4168
4169 TD->setAccess(AS_public);
4170 Owner->addDecl(TD);
4171
4172 return TD;
4173}
4174
4175Decl *
4176TemplateDeclInstantiator::VisitOMPGroupPrivateDecl(OMPGroupPrivateDecl *D) {
4177 SmallVector<Expr *, 5> Vars;
4178 for (auto *I : D->varlist()) {
4179 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
4180 assert(isa<DeclRefExpr>(Var) && "groupprivate arg is not a DeclRefExpr");
4181 Vars.push_back(Var);
4182 }
4183
4184 OMPGroupPrivateDecl *TD =
4185 SemaRef.OpenMP().CheckOMPGroupPrivateDecl(D->getLocation(), Vars);
4186
4187 TD->setAccess(AS_public);
4188 Owner->addDecl(TD);
4189
4190 return TD;
4191}
4192
4193Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
4194 SmallVector<Expr *, 5> Vars;
4195 for (auto *I : D->varlist()) {
4196 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
4197 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
4198 Vars.push_back(Var);
4199 }
4200 SmallVector<OMPClause *, 4> Clauses;
4201 // Copy map clauses from the original mapper.
4202 for (OMPClause *C : D->clauselists()) {
4203 OMPClause *IC = nullptr;
4204 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
4205 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
4206 if (!NewE.isUsable())
4207 continue;
4208 IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause(
4209 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
4210 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
4211 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
4212 if (!NewE.isUsable())
4213 continue;
4214 IC = SemaRef.OpenMP().ActOnOpenMPAlignClause(
4215 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
4216 // If align clause value ends up being invalid, this can end up null.
4217 if (!IC)
4218 continue;
4219 }
4220 Clauses.push_back(IC);
4221 }
4222
4223 Sema::DeclGroupPtrTy Res = SemaRef.OpenMP().ActOnOpenMPAllocateDirective(
4224 D->getLocation(), Vars, Clauses, Owner);
4225 if (Res.get().isNull())
4226 return nullptr;
4227 return Res.get().getSingleDecl();
4228}
4229
4230Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
4231 llvm_unreachable(
4232 "Requires directive cannot be instantiated within a dependent context");
4233}
4234
4235Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
4237 // Instantiate type and check if it is allowed.
4238 const bool RequiresInstantiation =
4239 D->getType()->isDependentType() ||
4242 QualType SubstReductionType;
4243 if (RequiresInstantiation) {
4244 SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType(
4245 D->getLocation(),
4246 ParsedType::make(SemaRef.SubstType(
4247 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
4248 } else {
4249 SubstReductionType = D->getType();
4250 }
4251 if (SubstReductionType.isNull())
4252 return nullptr;
4253 Expr *Combiner = D->getCombiner();
4254 Expr *Init = D->getInitializer();
4255 bool IsCorrect = true;
4256 // Create instantiated copy.
4257 std::pair<QualType, SourceLocation> ReductionTypes[] = {
4258 std::make_pair(SubstReductionType, D->getLocation())};
4259 auto *PrevDeclInScope = D->getPrevDeclInScope();
4260 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
4261 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
4262 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
4263 PrevDeclInScope)));
4264 }
4265 auto DRD = SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveStart(
4266 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
4267 PrevDeclInScope);
4268 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
4269 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
4270 Expr *SubstCombiner = nullptr;
4271 Expr *SubstInitializer = nullptr;
4272 // Combiners instantiation sequence.
4273 if (Combiner) {
4274 SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerStart(
4275 /*S=*/nullptr, NewDRD);
4276 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4277 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
4278 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
4279 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4280 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
4281 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
4282 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
4283 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
4284 ThisContext);
4285 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
4286 SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerEnd(NewDRD,
4287 SubstCombiner);
4288 }
4289 // Initializers instantiation sequence.
4290 if (Init) {
4291 VarDecl *OmpPrivParm =
4292 SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerStart(
4293 /*S=*/nullptr, NewDRD);
4294 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4295 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
4296 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
4297 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4298 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
4299 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
4301 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
4302 } else {
4303 auto *OldPrivParm =
4305 IsCorrect = IsCorrect && OldPrivParm->hasInit();
4306 if (IsCorrect)
4307 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
4308 TemplateArgs);
4309 }
4310 SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerEnd(
4311 NewDRD, SubstInitializer, OmpPrivParm);
4312 }
4313 IsCorrect = IsCorrect && SubstCombiner &&
4314 (!Init ||
4316 SubstInitializer) ||
4318 !SubstInitializer));
4319
4320 (void)SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveEnd(
4321 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
4322
4323 return NewDRD;
4324}
4325
4326Decl *
4327TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
4328 // Instantiate type and check if it is allowed.
4329 const bool RequiresInstantiation =
4330 D->getType()->isDependentType() ||
4333 QualType SubstMapperTy;
4334 DeclarationName VN = D->getVarName();
4335 if (RequiresInstantiation) {
4336 SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType(
4337 D->getLocation(),
4338 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
4339 D->getLocation(), VN)));
4340 } else {
4341 SubstMapperTy = D->getType();
4342 }
4343 if (SubstMapperTy.isNull())
4344 return nullptr;
4345 // Create an instantiated copy of mapper.
4346 auto *PrevDeclInScope = D->getPrevDeclInScope();
4347 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
4348 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
4349 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
4350 PrevDeclInScope)));
4351 }
4352 bool IsCorrect = true;
4353 SmallVector<OMPClause *, 6> Clauses;
4354 // Instantiate the mapper variable.
4355 DeclarationNameInfo DirName;
4356 SemaRef.OpenMP().StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
4357 /*S=*/nullptr,
4358 (*D->clauselist_begin())->getBeginLoc());
4359 ExprResult MapperVarRef =
4360 SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirectiveVarDecl(
4361 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
4362 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4363 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
4364 cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
4365 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
4366 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
4367 ThisContext);
4368 // Instantiate map clauses.
4369 for (OMPClause *C : D->clauselists()) {
4370 auto *OldC = cast<OMPMapClause>(C);
4371 SmallVector<Expr *, 4> NewVars;
4372 for (Expr *OE : OldC->varlist()) {
4373 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
4374 if (!NE) {
4375 IsCorrect = false;
4376 break;
4377 }
4378 NewVars.push_back(NE);
4379 }
4380 if (!IsCorrect)
4381 break;
4382 NestedNameSpecifierLoc NewQualifierLoc =
4383 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
4384 TemplateArgs);
4385 CXXScopeSpec SS;
4386 SS.Adopt(NewQualifierLoc);
4387 DeclarationNameInfo NewNameInfo =
4388 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
4389 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
4390 OldC->getEndLoc());
4391 OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause(
4392 OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
4393 OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
4394 OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
4395 NewVars, Locs);
4396 Clauses.push_back(NewC);
4397 }
4398 SemaRef.OpenMP().EndOpenMPDSABlock(nullptr);
4399 if (!IsCorrect)
4400 return nullptr;
4401 Sema::DeclGroupPtrTy DG = SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirective(
4402 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
4403 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
4404 Decl *NewDMD = DG.get().getSingleDecl();
4405 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
4406 return NewDMD;
4407}
4408
4409Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
4410 OMPCapturedExprDecl * /*D*/) {
4411 llvm_unreachable("Should not be met in templates");
4412}
4413
4415 return VisitFunctionDecl(D, nullptr);
4416}
4417
4418Decl *
4419TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
4420 Decl *Inst = VisitFunctionDecl(D, nullptr);
4421 if (Inst && !D->getDescribedFunctionTemplate())
4422 Owner->addDecl(Inst);
4423 return Inst;
4424}
4425
4427 return VisitCXXMethodDecl(D, nullptr);
4428}
4429
4430Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
4431 llvm_unreachable("There are only CXXRecordDecls in C++");
4432}
4433
4434Decl *
4435TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
4437 // As a MS extension, we permit class-scope explicit specialization
4438 // of member class templates.
4439 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
4440 assert(ClassTemplate->getDeclContext()->isRecord() &&
4442 "can only instantiate an explicit specialization "
4443 "for a member class template");
4444
4445 // Lookup the already-instantiated declaration in the instantiation
4446 // of the class template.
4447 ClassTemplateDecl *InstClassTemplate =
4448 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
4449 D->getLocation(), ClassTemplate, TemplateArgs));
4450 if (!InstClassTemplate)
4451 return nullptr;
4452
4453 // Substitute into the template arguments of the class template explicit
4454 // specialization.
4455 TemplateArgumentListInfo InstTemplateArgs;
4456 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4458 InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4459 InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4460
4461 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4462 TemplateArgs, InstTemplateArgs))
4463 return nullptr;
4464 }
4465
4466 // Check that the template argument list is well-formed for this
4467 // class template.
4468 Sema::CheckTemplateArgumentInfo CTAI;
4469 if (SemaRef.CheckTemplateArgumentList(
4470 InstClassTemplate, D->getLocation(), InstTemplateArgs,
4471 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4472 /*UpdateArgsWithConversions=*/true))
4473 return nullptr;
4474
4475 // Figure out where to insert this class template explicit specialization
4476 // in the member template's set of class template explicit specializations.
4477 void *InsertPos = nullptr;
4478 ClassTemplateSpecializationDecl *PrevDecl =
4479 InstClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4480
4481 // Check whether we've already seen a conflicting instantiation of this
4482 // declaration (for instance, if there was a prior implicit instantiation).
4483 bool Ignored;
4484 if (PrevDecl &&
4485 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
4487 PrevDecl,
4488 PrevDecl->getSpecializationKind(),
4489 PrevDecl->getPointOfInstantiation(),
4490 Ignored))
4491 return nullptr;
4492
4493 // If PrevDecl was a definition and D is also a definition, diagnose.
4494 // This happens in cases like:
4495 //
4496 // template<typename T, typename U>
4497 // struct Outer {
4498 // template<typename X> struct Inner;
4499 // template<> struct Inner<T> {};
4500 // template<> struct Inner<U> {};
4501 // };
4502 //
4503 // Outer<int, int> outer; // error: the explicit specializations of Inner
4504 // // have the same signature.
4505 if (PrevDecl && PrevDecl->getDefinition() &&
4507 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
4508 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
4509 diag::note_previous_definition);
4510 return nullptr;
4511 }
4512
4513 // Create the class template partial specialization declaration.
4514 ClassTemplateSpecializationDecl *InstD =
4516 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
4517 D->getLocation(), InstClassTemplate, CTAI.CanonicalConverted,
4518 CTAI.StrictPackMatch, PrevDecl);
4519 InstD->setTemplateArgsAsWritten(InstTemplateArgs);
4520
4521 // Add this partial specialization to the set of class template partial
4522 // specializations.
4523 if (!PrevDecl)
4524 InstClassTemplate->AddSpecialization(InstD, InsertPos);
4525
4526 // Substitute the nested name specifier, if any.
4527 if (SubstQualifier(D, InstD))
4528 return nullptr;
4529
4530 InstD->setAccess(D->getAccess());
4535
4536 Owner->addDecl(InstD);
4537
4538 // Instantiate the members of the class-scope explicit specialization eagerly.
4539 // We don't have support for lazy instantiation of an explicit specialization
4540 // yet, and MSVC eagerly instantiates in this case.
4541 // FIXME: This is wrong in standard C++.
4543 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
4545 /*Complain=*/true))
4546 return nullptr;
4547
4548 return InstD;
4549}
4550
4553
4554 TemplateArgumentListInfo VarTemplateArgsInfo;
4556 assert(VarTemplate &&
4557 "A template specialization without specialized template?");
4558
4559 VarTemplateDecl *InstVarTemplate =
4560 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
4561 D->getLocation(), VarTemplate, TemplateArgs));
4562 if (!InstVarTemplate)
4563 return nullptr;
4564
4565 // Substitute the current template arguments.
4566 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4568 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4569 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4570
4571 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4572 TemplateArgs, VarTemplateArgsInfo))
4573 return nullptr;
4574 }
4575
4576 // Check that the template argument list is well-formed for this template.
4578 if (SemaRef.CheckTemplateArgumentList(
4579 InstVarTemplate, D->getLocation(), VarTemplateArgsInfo,
4580 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4581 /*UpdateArgsWithConversions=*/true))
4582 return nullptr;
4583
4584 // Check whether we've already seen a declaration of this specialization.
4585 void *InsertPos = nullptr;
4587 InstVarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4588
4589 // Check whether we've already seen a conflicting instantiation of this
4590 // declaration (for instance, if there was a prior implicit instantiation).
4591 bool Ignored;
4592 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
4593 D->getLocation(), D->getSpecializationKind(), PrevDecl,
4594 PrevDecl->getSpecializationKind(),
4595 PrevDecl->getPointOfInstantiation(), Ignored))
4596 return nullptr;
4597
4599 InstVarTemplate, D, CTAI.CanonicalConverted, PrevDecl)) {
4600 VTSD->setTemplateArgsAsWritten(VarTemplateArgsInfo);
4601 return VTSD;
4602 }
4603 return nullptr;
4604}
4605
4611
4612 // Do substitution on the type of the declaration
4613 TypeSourceInfo *DI =
4614 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
4615 D->getTypeSpecStartLoc(), D->getDeclName());
4616 if (!DI)
4617 return nullptr;
4618
4619 if (DI->getType()->isFunctionType()) {
4620 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
4621 << D->isStaticDataMember() << DI->getType();
4622 return nullptr;
4623 }
4624
4625 // Build the instantiated declaration
4627 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
4628 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
4629 if (!PrevDecl) {
4630 void *InsertPos = nullptr;
4631 VarTemplate->findSpecialization(Converted, InsertPos);
4632 VarTemplate->AddSpecialization(Var, InsertPos);
4633 }
4634
4635 if (SemaRef.getLangOpts().OpenCL)
4636 SemaRef.deduceOpenCLAddressSpace(Var);
4637
4638 // Substitute the nested name specifier, if any.
4639 if (SubstQualifier(D, Var))
4640 return nullptr;
4641
4642 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
4643 StartingScope, false, PrevDecl);
4644
4645 return Var;
4646}
4647
4648Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
4649 llvm_unreachable("@defs is not supported in Objective-C++");
4650}
4651
4652Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
4653 // FIXME: We need to be able to instantiate FriendTemplateDecls.
4654 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
4656 "cannot instantiate %0 yet");
4657 SemaRef.Diag(D->getLocation(), DiagID)
4658 << D->getDeclKindName();
4659
4660 return nullptr;
4661}
4662
4663Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
4664 llvm_unreachable("Concept definitions cannot reside inside a template");
4665}
4666
4667Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4669 llvm_unreachable("Concept specializations cannot reside inside a template");
4670}
4671
4672Decl *
4673TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4674 return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
4675 D->getBeginLoc());
4676}
4677
4679 llvm_unreachable("Unexpected decl");
4680}
4681
4683 const MultiLevelTemplateArgumentList &TemplateArgs) {
4684 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4685 if (D->isInvalidDecl())
4686 return nullptr;
4687
4688 Decl *SubstD;
4690 SubstD = Instantiator.Visit(D);
4691 });
4692 return SubstD;
4693}
4694
4696 FunctionDecl *Orig, QualType &T,
4697 TypeSourceInfo *&TInfo,
4698 DeclarationNameInfo &NameInfo) {
4700
4701 // C++2a [class.compare.default]p3:
4702 // the return type is replaced with bool
4703 auto *FPT = T->castAs<FunctionProtoType>();
4704 T = SemaRef.Context.getFunctionType(
4705 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4706
4707 // Update the return type in the source info too. The most straightforward
4708 // way is to create new TypeSourceInfo for the new type. Use the location of
4709 // the '= default' as the location of the new type.
4710 //
4711 // FIXME: Set the correct return type when we initially transform the type,
4712 // rather than delaying it to now.
4713 TypeSourceInfo *NewTInfo =
4714 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4715 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4716 assert(OldLoc && "type of function is not a function type?");
4717 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4718 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4719 NewLoc.setParam(I, OldLoc.getParam(I));
4720 TInfo = NewTInfo;
4721
4722 // and the declarator-id is replaced with operator==
4723 NameInfo.setName(
4724 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4725}
4726
4728 FunctionDecl *Spaceship) {
4729 if (Spaceship->isInvalidDecl())
4730 return nullptr;
4731
4732 // C++2a [class.compare.default]p3:
4733 // an == operator function is declared implicitly [...] with the same
4734 // access and function-definition and in the same class scope as the
4735 // three-way comparison operator function
4736 MultiLevelTemplateArgumentList NoTemplateArgs;
4738 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4739 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4740 Decl *R;
4741 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4742 R = Instantiator.VisitCXXMethodDecl(
4743 MD, /*TemplateParams=*/nullptr,
4745 } else {
4746 assert(Spaceship->getFriendObjectKind() &&
4747 "defaulted spaceship is neither a member nor a friend");
4748
4749 R = Instantiator.VisitFunctionDecl(
4750 Spaceship, /*TemplateParams=*/nullptr,
4752 if (!R)
4753 return nullptr;
4754
4755 FriendDecl *FD =
4756 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4757 cast<NamedDecl>(R), Spaceship->getBeginLoc());
4758 FD->setAccess(AS_public);
4759 RD->addDecl(FD);
4760 }
4761 return cast_or_null<FunctionDecl>(R);
4762}
4763
4764/// Instantiates a nested template parameter list in the current
4765/// instantiation context.
4766///
4767/// \param L The parameter list to instantiate
4768///
4769/// \returns NULL if there was an error
4772 // Get errors for all the parameters before bailing out.
4773 bool Invalid = false;
4774
4775 unsigned N = L->size();
4776 typedef SmallVector<NamedDecl *, 8> ParamVector;
4777 ParamVector Params;
4778 Params.reserve(N);
4779 for (auto &P : *L) {
4780 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4781 Params.push_back(D);
4782 Invalid = Invalid || !D || D->isInvalidDecl();
4783 }
4784
4785 // Clean up if we had an error.
4786 if (Invalid)
4787 return nullptr;
4788
4789 Expr *InstRequiresClause = L->getRequiresClause();
4790
4792 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
4793 L->getLAngleLoc(), Params,
4794 L->getRAngleLoc(), InstRequiresClause);
4795 return InstL;
4796}
4797
4800 const MultiLevelTemplateArgumentList &TemplateArgs,
4801 bool EvaluateConstraints) {
4802 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4803 Instantiator.setEvaluateConstraints(EvaluateConstraints);
4804 return Instantiator.SubstTemplateParams(Params);
4805}
4806
4807/// Instantiate the declaration of a class template partial
4808/// specialization.
4809///
4810/// \param ClassTemplate the (instantiated) class template that is partially
4811// specialized by the instantiation of \p PartialSpec.
4812///
4813/// \param PartialSpec the (uninstantiated) class template partial
4814/// specialization that we are instantiating.
4815///
4816/// \returns The instantiated partial specialization, if successful; otherwise,
4817/// NULL to indicate an error.
4820 ClassTemplateDecl *ClassTemplate,
4822 // Create a local instantiation scope for this class template partial
4823 // specialization, which will contain the instantiations of the template
4824 // parameters.
4826
4827 // Substitute into the template parameters of the class template partial
4828 // specialization.
4829 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4830 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4831 if (!InstParams)
4832 return nullptr;
4833
4834 // Substitute into the template arguments of the class template partial
4835 // specialization.
4836 const ASTTemplateArgumentListInfo *TemplArgInfo
4837 = PartialSpec->getTemplateArgsAsWritten();
4838 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4839 TemplArgInfo->RAngleLoc);
4840 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4841 InstTemplateArgs))
4842 return nullptr;
4843
4844 // Check that the template argument list is well-formed for this
4845 // class template.
4847 if (SemaRef.CheckTemplateArgumentList(
4848 ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4849 /*DefaultArgs=*/{},
4850 /*PartialTemplateArgs=*/false, CTAI))
4851 return nullptr;
4852
4853 // Check these arguments are valid for a template partial specialization.
4854 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4855 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4856 CTAI.CanonicalConverted))
4857 return nullptr;
4858
4859 // Figure out where to insert this class template partial specialization
4860 // in the member template's set of class template partial specializations.
4861 void *InsertPos = nullptr;
4864 InstParams, InsertPos);
4865
4866 // Create the class template partial specialization declaration.
4869 SemaRef.Context, PartialSpec->getTagKind(), Owner,
4870 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4871 ClassTemplate, CTAI.CanonicalConverted,
4872 /*CanonInjectedTST=*/CanQualType(),
4873 /*PrevDecl=*/nullptr);
4874
4875 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4876
4877 // Substitute the nested name specifier, if any.
4878 if (SubstQualifier(PartialSpec, InstPartialSpec))
4879 return nullptr;
4880
4881 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4882
4883 if (PrevDecl) {
4884 // We've already seen a partial specialization with the same template
4885 // parameters and template arguments. This can happen, for example, when
4886 // substituting the outer template arguments ends up causing two
4887 // class template partial specializations of a member class template
4888 // to have identical forms, e.g.,
4889 //
4890 // template<typename T, typename U>
4891 // struct Outer {
4892 // template<typename X, typename Y> struct Inner;
4893 // template<typename Y> struct Inner<T, Y>;
4894 // template<typename Y> struct Inner<U, Y>;
4895 // };
4896 //
4897 // Outer<int, int> outer; // error: the partial specializations of Inner
4898 // // have the same signature.
4899 SemaRef.Diag(InstPartialSpec->getLocation(),
4900 diag::err_partial_spec_redeclared)
4901 << InstPartialSpec;
4902 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4903 << SemaRef.Context.getCanonicalTagType(PrevDecl);
4904 return nullptr;
4905 }
4906
4907 // Check the completed partial specialization.
4908 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4909
4910 // Add this partial specialization to the set of class template partial
4911 // specializations.
4912 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4913 /*InsertPos=*/nullptr);
4914 return InstPartialSpec;
4915}
4916
4917/// Instantiate the declaration of a variable template partial
4918/// specialization.
4919///
4920/// \param VarTemplate the (instantiated) variable template that is partially
4921/// specialized by the instantiation of \p PartialSpec.
4922///
4923/// \param PartialSpec the (uninstantiated) variable template partial
4924/// specialization that we are instantiating.
4925///
4926/// \returns The instantiated partial specialization, if successful; otherwise,
4927/// NULL to indicate an error.
4932 // Create a local instantiation scope for this variable template partial
4933 // specialization, which will contain the instantiations of the template
4934 // parameters.
4936
4937 // Substitute into the template parameters of the variable template partial
4938 // specialization.
4939 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4940 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4941 if (!InstParams)
4942 return nullptr;
4943
4944 // Substitute into the template arguments of the variable template partial
4945 // specialization.
4946 const ASTTemplateArgumentListInfo *TemplArgInfo
4947 = PartialSpec->getTemplateArgsAsWritten();
4948 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4949 TemplArgInfo->RAngleLoc);
4950 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4951 InstTemplateArgs))
4952 return nullptr;
4953
4954 // Check that the template argument list is well-formed for this
4955 // class template.
4957 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
4958 InstTemplateArgs, /*DefaultArgs=*/{},
4959 /*PartialTemplateArgs=*/false, CTAI))
4960 return nullptr;
4961
4962 // Check these arguments are valid for a template partial specialization.
4963 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4964 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4965 CTAI.CanonicalConverted))
4966 return nullptr;
4967
4968 // Figure out where to insert this variable template partial specialization
4969 // in the member template's set of variable template partial specializations.
4970 void *InsertPos = nullptr;
4972 VarTemplate->findPartialSpecialization(CTAI.CanonicalConverted,
4973 InstParams, InsertPos);
4974
4975 // Do substitution on the type of the declaration
4976 TypeSourceInfo *DI = SemaRef.SubstType(
4977 PartialSpec->getTypeSourceInfo(), TemplateArgs,
4978 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4979 if (!DI)
4980 return nullptr;
4981
4982 if (DI->getType()->isFunctionType()) {
4983 SemaRef.Diag(PartialSpec->getLocation(),
4984 diag::err_variable_instantiates_to_function)
4985 << PartialSpec->isStaticDataMember() << DI->getType();
4986 return nullptr;
4987 }
4988
4989 // Create the variable template partial specialization declaration.
4990 VarTemplatePartialSpecializationDecl *InstPartialSpec =
4992 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4993 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4994 DI, PartialSpec->getStorageClass(), CTAI.CanonicalConverted);
4995
4996 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4997
4998 // Substitute the nested name specifier, if any.
4999 if (SubstQualifier(PartialSpec, InstPartialSpec))
5000 return nullptr;
5001
5002 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
5003
5004 if (PrevDecl) {
5005 // We've already seen a partial specialization with the same template
5006 // parameters and template arguments. This can happen, for example, when
5007 // substituting the outer template arguments ends up causing two
5008 // variable template partial specializations of a member variable template
5009 // to have identical forms, e.g.,
5010 //
5011 // template<typename T, typename U>
5012 // struct Outer {
5013 // template<typename X, typename Y> pair<X,Y> p;
5014 // template<typename Y> pair<T, Y> p;
5015 // template<typename Y> pair<U, Y> p;
5016 // };
5017 //
5018 // Outer<int, int> outer; // error: the partial specializations of Inner
5019 // // have the same signature.
5020 SemaRef.Diag(PartialSpec->getLocation(),
5021 diag::err_var_partial_spec_redeclared)
5022 << InstPartialSpec;
5023 SemaRef.Diag(PrevDecl->getLocation(),
5024 diag::note_var_prev_partial_spec_here);
5025 return nullptr;
5026 }
5027 // Check the completed partial specialization.
5028 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
5029
5030 // Add this partial specialization to the set of variable template partial
5031 // specializations. The instantiation of the initializer is not necessary.
5032 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
5033
5034 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
5035 LateAttrs, Owner, StartingScope);
5036
5037 return InstPartialSpec;
5038}
5039
5043 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
5044 assert(OldTInfo && "substituting function without type source info");
5045 assert(Params.empty() && "parameter vector is non-empty at start");
5046
5047 CXXRecordDecl *ThisContext = nullptr;
5048 Qualifiers ThisTypeQuals;
5049 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5050 ThisContext = cast<CXXRecordDecl>(Owner);
5051 ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
5052 }
5053
5054 TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
5055 OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
5056 ThisContext, ThisTypeQuals, EvaluateConstraints);
5057 if (!NewTInfo)
5058 return nullptr;
5059
5060 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
5061 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
5062 if (NewTInfo != OldTInfo) {
5063 // Get parameters from the new type info.
5064 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
5065 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
5066 unsigned NewIdx = 0;
5067 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
5068 OldIdx != NumOldParams; ++OldIdx) {
5069 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
5070 if (!OldParam)
5071 return nullptr;
5072
5073 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
5074
5075 UnsignedOrNone NumArgumentsInExpansion = std::nullopt;
5076 if (OldParam->isParameterPack())
5077 NumArgumentsInExpansion =
5078 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
5079 TemplateArgs);
5080 if (!NumArgumentsInExpansion) {
5081 // Simple case: normal parameter, or a parameter pack that's
5082 // instantiated to a (still-dependent) parameter pack.
5083 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
5084 Params.push_back(NewParam);
5085 Scope->InstantiatedLocal(OldParam, NewParam);
5086 } else {
5087 // Parameter pack expansion: make the instantiation an argument pack.
5088 Scope->MakeInstantiatedLocalArgPack(OldParam);
5089 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
5090 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
5091 Params.push_back(NewParam);
5092 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
5093 }
5094 }
5095 }
5096 } else {
5097 // The function type itself was not dependent and therefore no
5098 // substitution occurred. However, we still need to instantiate
5099 // the function parameters themselves.
5100 const FunctionProtoType *OldProto =
5101 cast<FunctionProtoType>(OldProtoLoc.getType());
5102 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
5103 ++i) {
5104 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
5105 if (!OldParam) {
5106 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
5107 D, D->getLocation(), OldProto->getParamType(i)));
5108 continue;
5109 }
5110
5111 ParmVarDecl *Parm =
5112 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
5113 if (!Parm)
5114 return nullptr;
5115 Params.push_back(Parm);
5116 }
5117 }
5118 } else {
5119 // If the type of this function, after ignoring parentheses, is not
5120 // *directly* a function type, then we're instantiating a function that
5121 // was declared via a typedef or with attributes, e.g.,
5122 //
5123 // typedef int functype(int, int);
5124 // functype func;
5125 // int __cdecl meth(int, int);
5126 //
5127 // In this case, we'll just go instantiate the ParmVarDecls that we
5128 // synthesized in the method declaration.
5129 SmallVector<QualType, 4> ParamTypes;
5130 Sema::ExtParameterInfoBuilder ExtParamInfos;
5131 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
5132 TemplateArgs, ParamTypes, &Params,
5133 ExtParamInfos))
5134 return nullptr;
5135 }
5136
5137 return NewTInfo;
5138}
5139
5140void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
5141 const FunctionDecl *PatternDecl,
5144
5145 for (auto *decl : PatternDecl->decls()) {
5147 continue;
5148
5149 VarDecl *VD = cast<VarDecl>(decl);
5150 IdentifierInfo *II = VD->getIdentifier();
5151
5152 auto it = llvm::find_if(Function->decls(), [&](Decl *inst) {
5153 VarDecl *InstVD = dyn_cast<VarDecl>(inst);
5154 return InstVD && InstVD->isLocalVarDecl() &&
5155 InstVD->getIdentifier() == II;
5156 });
5157
5158 if (it == Function->decls().end())
5159 continue;
5160
5161 Scope.InstantiatedLocal(VD, *it);
5162 LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false,
5163 /*isNested=*/false, VD->getLocation(), SourceLocation(),
5164 VD->getType(), /*Invalid=*/false);
5165 }
5166}
5167
5168bool Sema::addInstantiatedParametersToScope(
5169 FunctionDecl *Function, const FunctionDecl *PatternDecl,
5171 const MultiLevelTemplateArgumentList &TemplateArgs) {
5172 unsigned FParamIdx = 0;
5173 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
5174 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
5175 if (!PatternParam->isParameterPack()) {
5176 // Simple case: not a parameter pack.
5177 assert(FParamIdx < Function->getNumParams());
5178 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
5179 FunctionParam->setDeclName(PatternParam->getDeclName());
5180 // If the parameter's type is not dependent, update it to match the type
5181 // in the pattern. They can differ in top-level cv-qualifiers, and we want
5182 // the pattern's type here. If the type is dependent, they can't differ,
5183 // per core issue 1668. Substitute into the type from the pattern, in case
5184 // it's instantiation-dependent.
5185 // FIXME: Updating the type to work around this is at best fragile.
5186 if (!PatternDecl->getType()->isDependentType()) {
5187 QualType T = SubstType(PatternParam->getType(), TemplateArgs,
5188 FunctionParam->getLocation(),
5189 FunctionParam->getDeclName());
5190 if (T.isNull())
5191 return true;
5192 FunctionParam->setType(T);
5193 }
5194
5195 Scope.InstantiatedLocal(PatternParam, FunctionParam);
5196 ++FParamIdx;
5197 continue;
5198 }
5199
5200 // Expand the parameter pack.
5201 Scope.MakeInstantiatedLocalArgPack(PatternParam);
5202 UnsignedOrNone NumArgumentsInExpansion =
5203 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
5204 if (NumArgumentsInExpansion) {
5205 QualType PatternType =
5206 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
5207 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
5208 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
5209 FunctionParam->setDeclName(PatternParam->getDeclName());
5210 if (!PatternDecl->getType()->isDependentType()) {
5211 Sema::ArgPackSubstIndexRAII SubstIndex(*this, Arg);
5212 QualType T =
5213 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
5214 FunctionParam->getDeclName());
5215 if (T.isNull())
5216 return true;
5217 FunctionParam->setType(T);
5218 }
5219
5220 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
5221 ++FParamIdx;
5222 }
5223 }
5224 }
5225
5226 return false;
5227}
5228
5230 ParmVarDecl *Param) {
5231 assert(Param->hasUninstantiatedDefaultArg());
5232
5233 // FIXME: We don't track member specialization info for non-defining
5234 // friend declarations, so we will not be able to later find the function
5235 // pattern. As a workaround, don't instantiate the default argument in this
5236 // case. This is correct per the standard and only an issue for recovery
5237 // purposes. [dcl.fct.default]p4:
5238 // if a friend declaration D specifies a default argument expression,
5239 // that declaration shall be a definition.
5240 if (FD->getFriendObjectKind() != Decl::FOK_None &&
5242 return true;
5243
5244 // Instantiate the expression.
5245 //
5246 // FIXME: Pass in a correct Pattern argument, otherwise
5247 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
5248 //
5249 // template<typename T>
5250 // struct A {
5251 // static int FooImpl();
5252 //
5253 // template<typename Tp>
5254 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
5255 // // template argument list [[T], [Tp]], should be [[Tp]].
5256 // friend A<Tp> Foo(int a);
5257 // };
5258 //
5259 // template<typename T>
5260 // A<T> Foo(int a = A<T>::FooImpl());
5262 FD, FD->getLexicalDeclContext(),
5263 /*Final=*/false, /*Innermost=*/std::nullopt,
5264 /*RelativeToPrimary=*/true, /*Pattern=*/nullptr,
5265 /*ForConstraintInstantiation=*/false, /*SkipForSpecialization=*/false,
5266 /*ForDefaultArgumentSubstitution=*/true);
5267
5268 if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
5269 return true;
5270
5272 L->DefaultArgumentInstantiated(Param);
5273
5274 return false;
5275}
5276
5278 FunctionDecl *Decl) {
5279 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
5281 return;
5282
5283 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
5285 if (Inst.isInvalid()) {
5286 // We hit the instantiation depth limit. Clear the exception specification
5287 // so that our callers don't have to cope with EST_Uninstantiated.
5289 return;
5290 }
5291 if (Inst.isAlreadyInstantiating()) {
5292 // This exception specification indirectly depends on itself. Reject.
5293 // FIXME: Corresponding rule in the standard?
5294 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
5296 return;
5297 }
5298
5299 // Enter the scope of this instantiation. We don't use
5300 // PushDeclContext because we don't have a scope.
5301 Sema::ContextRAII savedContext(*this, Decl);
5303
5304 MultiLevelTemplateArgumentList TemplateArgs =
5306 /*Final=*/false, /*Innermost=*/std::nullopt,
5307 /*RelativeToPrimary*/ true);
5308
5309 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
5310 // here, because for a non-defining friend declaration in a class template,
5311 // we don't store enough information to map back to the friend declaration in
5312 // the template.
5314 if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
5316 return;
5317 }
5318
5319 // The noexcept specification could reference any lambda captures. Ensure
5320 // those are added to the LocalInstantiationScope.
5322 *this, Decl, TemplateArgs, Scope,
5323 /*ShouldAddDeclsFromParentScope=*/false);
5324
5325 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
5326 TemplateArgs);
5327}
5328
5329/// Initializes the common fields of an instantiation function
5330/// declaration (New) from the corresponding fields of its template (Tmpl).
5331///
5332/// \returns true if there was an error
5333bool
5335 FunctionDecl *Tmpl) {
5336 New->setImplicit(Tmpl->isImplicit());
5337
5338 // Forward the mangling number from the template to the instantiated decl.
5339 SemaRef.Context.setManglingNumber(New,
5340 SemaRef.Context.getManglingNumber(Tmpl));
5341
5342 // If we are performing substituting explicitly-specified template arguments
5343 // or deduced template arguments into a function template and we reach this
5344 // point, we are now past the point where SFINAE applies and have committed
5345 // to keeping the new function template specialization. We therefore
5346 // convert the active template instantiation for the function template
5347 // into a template instantiation for this specific function template
5348 // specialization, which is not a SFINAE context, so that we diagnose any
5349 // further errors in the declaration itself.
5350 //
5351 // FIXME: This is a hack.
5352 typedef Sema::CodeSynthesisContext ActiveInstType;
5353 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
5354 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
5355 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
5356 if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
5357 SemaRef.InstantiatingSpecializations.erase(
5358 {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
5359 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
5360 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
5361 ActiveInst.Entity = New;
5362 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
5363 }
5364 }
5365
5366 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
5367 assert(Proto && "Function template without prototype?");
5368
5369 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
5371
5372 // DR1330: In C++11, defer instantiation of a non-trivial
5373 // exception specification.
5374 // DR1484: Local classes and their members are instantiated along with the
5375 // containing function.
5376 if (SemaRef.getLangOpts().CPlusPlus11 &&
5377 EPI.ExceptionSpec.Type != EST_None &&
5381 FunctionDecl *ExceptionSpecTemplate = Tmpl;
5383 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
5386 NewEST = EST_Unevaluated;
5387
5388 // Mark the function has having an uninstantiated exception specification.
5389 const FunctionProtoType *NewProto
5390 = New->getType()->getAs<FunctionProtoType>();
5391 assert(NewProto && "Template instantiation without function prototype?");
5392 EPI = NewProto->getExtProtoInfo();
5393 EPI.ExceptionSpec.Type = NewEST;
5395 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
5396 New->setType(SemaRef.Context.getFunctionType(
5397 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
5398 } else {
5399 Sema::ContextRAII SwitchContext(SemaRef, New);
5400 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
5401 }
5402 }
5403
5404 // Get the definition. Leaves the variable unchanged if undefined.
5405 const FunctionDecl *Definition = Tmpl;
5406 Tmpl->isDefined(Definition);
5407
5408 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
5409 LateAttrs, StartingScope);
5410
5411 return false;
5412}
5413
5414/// Initializes common fields of an instantiated method
5415/// declaration (New) from the corresponding fields of its template
5416/// (Tmpl).
5417///
5418/// \returns true if there was an error
5419bool
5421 CXXMethodDecl *Tmpl) {
5422 if (InitFunctionInstantiation(New, Tmpl))
5423 return true;
5424
5425 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
5426 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
5427
5428 New->setAccess(Tmpl->getAccess());
5429 if (Tmpl->isVirtualAsWritten())
5430 New->setVirtualAsWritten(true);
5431
5432 // FIXME: New needs a pointer to Tmpl
5433 return false;
5434}
5435
5437 FunctionDecl *Tmpl) {
5438 // Transfer across any unqualified lookups.
5439 if (auto *DFI = Tmpl->getDefalutedOrDeletedInfo()) {
5441 Lookups.reserve(DFI->getUnqualifiedLookups().size());
5442 bool AnyChanged = false;
5443 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
5444 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
5445 DA.getDecl(), TemplateArgs);
5446 if (!D)
5447 return true;
5448 AnyChanged |= (D != DA.getDecl());
5449 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
5450 }
5451
5452 // It's unlikely that substitution will change any declarations. Don't
5453 // store an unnecessary copy in that case.
5454 New->setDefaultedOrDeletedInfo(
5456 SemaRef.Context, Lookups)
5457 : DFI);
5458 }
5459
5460 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
5461 return false;
5462}
5463
5467 FunctionDecl *FD = FTD->getTemplatedDecl();
5468
5470 InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC, Info);
5471 if (Inst.isInvalid())
5472 return nullptr;
5473
5474 ContextRAII SavedContext(*this, FD);
5475 MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
5476 /*Final=*/false);
5477
5478 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
5479}
5480
5483 bool Recursive,
5484 bool DefinitionRequired,
5485 bool AtEndOfTU) {
5486 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
5487 return;
5488
5489 // Never instantiate an explicit specialization except if it is a class scope
5490 // explicit specialization.
5492 Function->getTemplateSpecializationKindForInstantiation();
5493 if (TSK == TSK_ExplicitSpecialization)
5494 return;
5495
5496 // Never implicitly instantiate a builtin; we don't actually need a function
5497 // body.
5498 if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
5499 !DefinitionRequired)
5500 return;
5501
5502 // Don't instantiate a definition if we already have one.
5503 const FunctionDecl *ExistingDefn = nullptr;
5504 if (Function->isDefined(ExistingDefn,
5505 /*CheckForPendingFriendDefinition=*/true)) {
5506 if (ExistingDefn->isThisDeclarationADefinition())
5507 return;
5508
5509 // If we're asked to instantiate a function whose body comes from an
5510 // instantiated friend declaration, attach the instantiated body to the
5511 // corresponding declaration of the function.
5513 Function = const_cast<FunctionDecl*>(ExistingDefn);
5514 }
5515
5516 // Find the function body that we'll be substituting.
5517 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
5518 assert(PatternDecl && "instantiating a non-template");
5519
5520 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
5521 Stmt *Pattern = nullptr;
5522 if (PatternDef) {
5523 Pattern = PatternDef->getBody(PatternDef);
5524 PatternDecl = PatternDef;
5525 if (PatternDef->willHaveBody())
5526 PatternDef = nullptr;
5527 }
5528
5529 // True is the template definition is unreachable, otherwise false.
5530 bool Unreachable = false;
5531 // FIXME: We need to track the instantiation stack in order to know which
5532 // definitions should be visible within this instantiation.
5534 PointOfInstantiation, Function,
5535 Function->getInstantiatedFromMemberFunction(), PatternDecl,
5536 PatternDef, TSK,
5537 /*Complain*/ DefinitionRequired, &Unreachable)) {
5538 if (DefinitionRequired)
5539 Function->setInvalidDecl();
5540 else if (TSK == TSK_ExplicitInstantiationDefinition ||
5541 (Function->isConstexpr() && !Recursive)) {
5542 // Try again at the end of the translation unit (at which point a
5543 // definition will be required).
5544 assert(!Recursive);
5545 Function->setInstantiationIsPending(true);
5546 PendingInstantiations.emplace_back(Function, PointOfInstantiation);
5547
5548 if (llvm::isTimeTraceVerbose()) {
5549 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
5550 std::string Name;
5551 llvm::raw_string_ostream OS(Name);
5552 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5553 /*Qualified=*/true);
5554 return Name;
5555 });
5556 }
5557 } else if (TSK == TSK_ImplicitInstantiation) {
5558 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5559 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5560 Diag(PointOfInstantiation, diag::warn_func_template_missing)
5561 << Function;
5562 if (Unreachable) {
5563 // FIXME: would be nice to mention which module the function template
5564 // comes from.
5565 Diag(PatternDecl->getLocation(),
5566 diag::note_unreachable_template_decl);
5567 } else {
5568 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5570 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
5571 << Function;
5572 }
5573 }
5574 }
5575
5576 return;
5577 }
5578
5579 // Postpone late parsed template instantiations.
5580 if (PatternDecl->isLateTemplateParsed() &&
5582 Function->setInstantiationIsPending(true);
5583 LateParsedInstantiations.push_back(
5584 std::make_pair(Function, PointOfInstantiation));
5585 return;
5586 }
5587
5588 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
5589 llvm::TimeTraceMetadata M;
5590 llvm::raw_string_ostream OS(M.Detail);
5591 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5592 /*Qualified=*/true);
5593 if (llvm::isTimeTraceVerbose()) {
5594 auto Loc = SourceMgr.getExpansionLoc(Function->getLocation());
5595 M.File = SourceMgr.getFilename(Loc);
5596 M.Line = SourceMgr.getExpansionLineNumber(Loc);
5597 }
5598 return M;
5599 });
5600
5601 // If we're performing recursive template instantiation, create our own
5602 // queue of pending implicit instantiations that we will instantiate later,
5603 // while we're still within our own instantiation context.
5604 // This has to happen before LateTemplateParser below is called, so that
5605 // it marks vtables used in late parsed templates as used.
5606 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5607 /*Enabled=*/Recursive,
5608 /*AtEndOfTU=*/AtEndOfTU);
5609 LocalEagerInstantiationScope LocalInstantiations(*this,
5610 /*AtEndOfTU=*/AtEndOfTU);
5611
5612 // Call the LateTemplateParser callback if there is a need to late parse
5613 // a templated function definition.
5614 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
5616 // FIXME: Optimize to allow individual templates to be deserialized.
5617 if (PatternDecl->isFromASTFile())
5618 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
5619
5620 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
5621 assert(LPTIter != LateParsedTemplateMap.end() &&
5622 "missing LateParsedTemplate");
5623 LateTemplateParser(OpaqueParser, *LPTIter->second);
5624 Pattern = PatternDecl->getBody(PatternDecl);
5626 }
5627
5628 // Note, we should never try to instantiate a deleted function template.
5629 assert((Pattern || PatternDecl->isDefaulted() ||
5630 PatternDecl->hasSkippedBody()) &&
5631 "unexpected kind of function template definition");
5632
5633 // C++1y [temp.explicit]p10:
5634 // Except for inline functions, declarations with types deduced from their
5635 // initializer or return value, and class template specializations, other
5636 // explicit instantiation declarations have the effect of suppressing the
5637 // implicit instantiation of the entity to which they refer.
5639 !PatternDecl->isInlined() &&
5640 !PatternDecl->getReturnType()->getContainedAutoType())
5641 return;
5642
5643 if (PatternDecl->isInlined()) {
5644 // Function, and all later redeclarations of it (from imported modules,
5645 // for instance), are now implicitly inline.
5646 for (auto *D = Function->getMostRecentDecl(); /**/;
5647 D = D->getPreviousDecl()) {
5648 D->setImplicitlyInline();
5649 if (D == Function)
5650 break;
5651 }
5652 }
5653
5654 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
5655 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5656 return;
5658 "instantiating function definition");
5659
5660 // The instantiation is visible here, even if it was first declared in an
5661 // unimported module.
5662 Function->setVisibleDespiteOwningModule();
5663
5664 // Copy the source locations from the pattern.
5665 Function->setLocation(PatternDecl->getLocation());
5666 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
5667 Function->setRangeEnd(PatternDecl->getEndLoc());
5668 // Let the instantiation use the Pattern's DeclarationNameLoc, due to the
5669 // following awkwardness:
5670 //
5671 // 1. There are out-of-tree users of getNameInfo().getSourceRange(), who
5672 // expect the source range of the instantiated declaration to be set to
5673 // point to the definition.
5674 //
5675 // 2. That getNameInfo().getSourceRange() might return the TypeLocInfo's
5676 // location it tracked.
5677 //
5678 // 3. Function might come from an (implicit) declaration, while the pattern
5679 // comes from a definition. In these cases, we need the PatternDecl's source
5680 // location.
5681 //
5682 // To that end, we need to more or less tweak the DeclarationNameLoc. However,
5683 // we can't blindly copy the DeclarationNameLoc from the PatternDecl to the
5684 // function, since it contains associated TypeLocs that should have already
5685 // been transformed. So, we rebuild the TypeLoc for that purpose. Technically,
5686 // we should create a new function declaration and assign everything we need,
5687 // but InstantiateFunctionDefinition updates the declaration in place.
5688 auto NameLocPointsToPattern = [&] {
5689 DeclarationNameInfo PatternName = PatternDecl->getNameInfo();
5690 DeclarationNameLoc PatternNameLoc = PatternName.getInfo();
5691 switch (PatternName.getName().getNameKind()) {
5695 break;
5696 default:
5697 // Cases where DeclarationNameLoc doesn't matter, as it merely contains a
5698 // source range.
5699 return PatternNameLoc;
5700 }
5701
5702 TypeSourceInfo *TSI = Function->getNameInfo().getNamedTypeInfo();
5703 // TSI might be null if the function is named by a constructor template id.
5704 // E.g. S<T>() {} for class template S with a template parameter T.
5705 if (!TSI) {
5706 // We don't care about the DeclarationName of the instantiated function,
5707 // but only the DeclarationNameLoc. So if the TypeLoc is absent, we do
5708 // nothing.
5709 return PatternNameLoc;
5710 }
5711
5712 QualType InstT = TSI->getType();
5713 // We want to use a TypeLoc that reflects the transformed type while
5714 // preserving the source location from the pattern.
5715 TypeLocBuilder TLB;
5716 TypeSourceInfo *PatternTSI = PatternName.getNamedTypeInfo();
5717 assert(PatternTSI && "Pattern is supposed to have an associated TSI");
5718 // FIXME: PatternTSI is not trivial. We should copy the source location
5719 // along the TypeLoc chain. However a trivial TypeLoc is sufficient for
5720 // getNameInfo().getSourceRange().
5721 TLB.pushTrivial(Context, InstT, PatternTSI->getTypeLoc().getBeginLoc());
5723 TLB.getTypeSourceInfo(Context, InstT));
5724 };
5725 Function->setDeclarationNameLoc(NameLocPointsToPattern());
5726
5729
5730 Qualifiers ThisTypeQuals;
5731 CXXRecordDecl *ThisContext = nullptr;
5732 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5733 ThisContext = Method->getParent();
5734 ThisTypeQuals = Method->getMethodQualifiers();
5735 }
5736 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals);
5737
5738 // Introduce a new scope where local variable instantiations will be
5739 // recorded, unless we're actually a member function within a local
5740 // class, in which case we need to merge our results with the parent
5741 // scope (of the enclosing function). The exception is instantiating
5742 // a function template specialization, since the template to be
5743 // instantiated already has references to locals properly substituted.
5744 bool MergeWithParentScope = false;
5745 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
5746 MergeWithParentScope =
5747 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
5748
5749 LocalInstantiationScope Scope(*this, MergeWithParentScope);
5750 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
5751 // Special members might get their TypeSourceInfo set up w.r.t the
5752 // PatternDecl context, in which case parameters could still be pointing
5753 // back to the original class, make sure arguments are bound to the
5754 // instantiated record instead.
5755 assert(PatternDecl->isDefaulted() &&
5756 "Special member needs to be defaulted");
5757 auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
5758 if (!(PatternSM == CXXSpecialMemberKind::CopyConstructor ||
5762 return;
5763
5764 auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
5765 const auto *PatternRec =
5766 dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
5767 if (!NewRec || !PatternRec)
5768 return;
5769 if (!PatternRec->isLambda())
5770 return;
5771
5772 struct SpecialMemberTypeInfoRebuilder
5773 : TreeTransform<SpecialMemberTypeInfoRebuilder> {
5775 const CXXRecordDecl *OldDecl;
5776 CXXRecordDecl *NewDecl;
5777
5778 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5779 CXXRecordDecl *N)
5780 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5781
5782 bool TransformExceptionSpec(SourceLocation Loc,
5784 SmallVectorImpl<QualType> &Exceptions,
5785 bool &Changed) {
5786 return false;
5787 }
5788
5789 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5790 const RecordType *T = TL.getTypePtr();
5791 RecordDecl *Record = cast_or_null<RecordDecl>(
5792 getDerived().TransformDecl(TL.getNameLoc(), T->getOriginalDecl()));
5793 if (Record != OldDecl)
5794 return Base::TransformRecordType(TLB, TL);
5795
5796 // FIXME: transform the rest of the record type.
5797 QualType Result = getDerived().RebuildTagType(
5798 ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt, NewDecl);
5799 if (Result.isNull())
5800 return QualType();
5801
5802 TagTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5805 NewTL.setNameLoc(TL.getNameLoc());
5806 return Result;
5807 }
5808 } IR{*this, PatternRec, NewRec};
5809
5810 TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5811 assert(NewSI && "Type Transform failed?");
5812 Function->setType(NewSI->getType());
5813 Function->setTypeSourceInfo(NewSI);
5814
5815 ParmVarDecl *Parm = Function->getParamDecl(0);
5816 TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5817 assert(NewParmSI && "Type transformation failed.");
5818 Parm->setType(NewParmSI->getType());
5819 Parm->setTypeSourceInfo(NewParmSI);
5820 };
5821
5822 if (PatternDecl->isDefaulted()) {
5823 RebuildTypeSourceInfoForDefaultSpecialMembers();
5824 SetDeclDefaulted(Function, PatternDecl->getLocation());
5825 } else {
5826 DeclContext *DC = Function->getLexicalDeclContext();
5827 std::optional<ArrayRef<TemplateArgument>> Innermost;
5828 if (auto *Primary = Function->getPrimaryTemplate();
5829 Primary &&
5831 Function->getTemplateSpecializationKind() !=
5833 auto It = llvm::find_if(Primary->redecls(),
5834 [](const RedeclarableTemplateDecl *RTD) {
5835 return cast<FunctionTemplateDecl>(RTD)
5836 ->isCompatibleWithDefinition();
5837 });
5838 assert(It != Primary->redecls().end() &&
5839 "Should't get here without a definition");
5841 ->getTemplatedDecl()
5842 ->getDefinition())
5843 DC = Def->getLexicalDeclContext();
5844 else
5845 DC = (*It)->getLexicalDeclContext();
5846 Innermost.emplace(Function->getTemplateSpecializationArgs()->asArray());
5847 }
5849 Function, DC, /*Final=*/false, Innermost, false, PatternDecl);
5850
5851 // Substitute into the qualifier; we can get a substitution failure here
5852 // through evil use of alias templates.
5853 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5854 // of the) lexical context of the pattern?
5855 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5856
5858
5859 // Enter the scope of this instantiation. We don't use
5860 // PushDeclContext because we don't have a scope.
5861 Sema::ContextRAII savedContext(*this, Function);
5862
5863 FPFeaturesStateRAII SavedFPFeatures(*this);
5865 FpPragmaStack.CurrentValue = FPOptionsOverride();
5866
5867 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5868 TemplateArgs))
5869 return;
5870
5871 StmtResult Body;
5872 if (PatternDecl->hasSkippedBody()) {
5874 Body = nullptr;
5875 } else {
5876 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5877 // If this is a constructor, instantiate the member initializers.
5879 TemplateArgs);
5880
5881 // If this is an MS ABI dllexport default constructor, instantiate any
5882 // default arguments.
5883 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5884 Ctor->isDefaultConstructor()) {
5886 }
5887 }
5888
5889 // Instantiate the function body.
5890 Body = SubstStmt(Pattern, TemplateArgs);
5891
5892 if (Body.isInvalid())
5893 Function->setInvalidDecl();
5894 }
5895 // FIXME: finishing the function body while in an expression evaluation
5896 // context seems wrong. Investigate more.
5897 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5898
5899 checkReferenceToTULocalFromOtherTU(Function, PointOfInstantiation);
5900
5901 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5902
5903 if (auto *Listener = getASTMutationListener())
5904 Listener->FunctionDefinitionInstantiated(Function);
5905
5906 savedContext.pop();
5907 }
5908
5909 // We never need to emit the code for a lambda in unevaluated context.
5910 // We also can't mangle a lambda in the require clause of a function template
5911 // during constraint checking as the MSI ABI would need to mangle the (not yet
5912 // specialized) enclosing declaration
5913 // FIXME: Should we try to skip this for non-lambda functions too?
5914 bool ShouldSkipCG = [&] {
5915 auto *RD = dyn_cast<CXXRecordDecl>(Function->getParent());
5916 if (!RD || !RD->isLambda())
5917 return false;
5918
5919 return llvm::any_of(ExprEvalContexts, [](auto &Context) {
5920 return Context.isUnevaluated() || Context.isImmediateFunctionContext();
5921 });
5922 }();
5923 if (!ShouldSkipCG) {
5925 Consumer.HandleTopLevelDecl(DG);
5926 }
5927
5928 // This class may have local implicit instantiations that need to be
5929 // instantiation within this scope.
5930 LocalInstantiations.perform();
5931 Scope.Exit();
5932 GlobalInstantiations.perform();
5933}
5934
5937 const TemplateArgumentList *PartialSpecArgs,
5939 SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
5940 LocalInstantiationScope *StartingScope) {
5941 if (FromVar->isInvalidDecl())
5942 return nullptr;
5943
5944 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5945 if (Inst.isInvalid())
5946 return nullptr;
5947
5948 // Instantiate the first declaration of the variable template: for a partial
5949 // specialization of a static data member template, the first declaration may
5950 // or may not be the declaration in the class; if it's in the class, we want
5951 // to instantiate a member in the class (a declaration), and if it's outside,
5952 // we want to instantiate a definition.
5953 //
5954 // If we're instantiating an explicitly-specialized member template or member
5955 // partial specialization, don't do this. The member specialization completely
5956 // replaces the original declaration in this case.
5957 bool IsMemberSpec = false;
5958 MultiLevelTemplateArgumentList MultiLevelList;
5959 if (auto *PartialSpec =
5960 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
5961 assert(PartialSpecArgs);
5962 IsMemberSpec = PartialSpec->isMemberSpecialization();
5963 MultiLevelList.addOuterTemplateArguments(
5964 PartialSpec, PartialSpecArgs->asArray(), /*Final=*/false);
5965 } else {
5966 assert(VarTemplate == FromVar->getDescribedVarTemplate());
5967 IsMemberSpec = VarTemplate->isMemberSpecialization();
5968 MultiLevelList.addOuterTemplateArguments(VarTemplate, Converted,
5969 /*Final=*/false);
5970 }
5971 if (!IsMemberSpec)
5972 FromVar = FromVar->getFirstDecl();
5973
5974 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
5975 MultiLevelList);
5976
5977 // TODO: Set LateAttrs and StartingScope ...
5978
5979 return Instantiator.VisitVarTemplateSpecializationDecl(VarTemplate, FromVar,
5980 Converted);
5981}
5982
5984 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
5985 const MultiLevelTemplateArgumentList &TemplateArgs) {
5986 assert(PatternDecl->isThisDeclarationADefinition() &&
5987 "don't have a definition to instantiate from");
5988
5989 // Do substitution on the type of the declaration
5990 TypeSourceInfo *DI =
5991 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
5992 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
5993 if (!DI)
5994 return nullptr;
5995
5996 // Update the type of this variable template specialization.
5997 VarSpec->setType(DI->getType());
5998
5999 // Convert the declaration into a definition now.
6000 VarSpec->setCompleteDefinition();
6001
6002 // Instantiate the initializer.
6003 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
6004
6005 if (getLangOpts().OpenCL)
6006 deduceOpenCLAddressSpace(VarSpec);
6007
6008 return VarSpec;
6009}
6010
6012 VarDecl *NewVar, VarDecl *OldVar,
6013 const MultiLevelTemplateArgumentList &TemplateArgs,
6014 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
6015 LocalInstantiationScope *StartingScope,
6016 bool InstantiatingVarTemplate,
6017 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
6018 // Instantiating a partial specialization to produce a partial
6019 // specialization.
6020 bool InstantiatingVarTemplatePartialSpec =
6023 // Instantiating from a variable template (or partial specialization) to
6024 // produce a variable template specialization.
6025 bool InstantiatingSpecFromTemplate =
6027 (OldVar->getDescribedVarTemplate() ||
6029
6030 // If we are instantiating a local extern declaration, the
6031 // instantiation belongs lexically to the containing function.
6032 // If we are instantiating a static data member defined
6033 // out-of-line, the instantiation will have the same lexical
6034 // context (which will be a namespace scope) as the template.
6035 if (OldVar->isLocalExternDecl()) {
6036 NewVar->setLocalExternDecl();
6037 NewVar->setLexicalDeclContext(Owner);
6038 } else if (OldVar->isOutOfLine())
6040 NewVar->setTSCSpec(OldVar->getTSCSpec());
6041 NewVar->setInitStyle(OldVar->getInitStyle());
6042 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
6043 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
6044 NewVar->setConstexpr(OldVar->isConstexpr());
6045 NewVar->setInitCapture(OldVar->isInitCapture());
6048 NewVar->setAccess(OldVar->getAccess());
6049
6050 if (!OldVar->isStaticDataMember()) {
6051 if (OldVar->isUsed(false))
6052 NewVar->setIsUsed();
6053 NewVar->setReferenced(OldVar->isReferenced());
6054 }
6055
6056 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
6057
6059 *this, NewVar->getDeclName(), NewVar->getLocation(),
6064
6065 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
6067 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
6068 // We have a previous declaration. Use that one, so we merge with the
6069 // right type.
6070 if (NamedDecl *NewPrev = FindInstantiatedDecl(
6071 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
6072 Previous.addDecl(NewPrev);
6073 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
6074 OldVar->hasLinkage()) {
6075 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
6076 } else if (PrevDeclForVarTemplateSpecialization) {
6077 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
6078 }
6080
6081 if (!InstantiatingVarTemplate) {
6082 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
6083 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
6084 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
6085 }
6086
6087 if (!OldVar->isOutOfLine()) {
6088 if (NewVar->getDeclContext()->isFunctionOrMethod())
6089 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
6090 }
6091
6092 // Link instantiations of static data members back to the template from
6093 // which they were instantiated.
6094 //
6095 // Don't do this when instantiating a template (we link the template itself
6096 // back in that case) nor when instantiating a static data member template
6097 // (that's not a member specialization).
6098 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
6099 !InstantiatingSpecFromTemplate)
6102
6103 // If the pattern is an (in-class) explicit specialization, then the result
6104 // is also an explicit specialization.
6105 if (VarTemplateSpecializationDecl *OldVTSD =
6106 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
6107 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
6109 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
6111 }
6112
6113 // Forward the mangling number from the template to the instantiated decl.
6114 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
6115 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
6116
6117 // Figure out whether to eagerly instantiate the initializer.
6118 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
6119 // We're producing a template. Don't instantiate the initializer yet.
6120 } else if (NewVar->getType()->isUndeducedType()) {
6121 // We need the type to complete the declaration of the variable.
6122 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
6123 } else if (InstantiatingSpecFromTemplate ||
6124 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
6125 !NewVar->isThisDeclarationADefinition())) {
6126 // Delay instantiation of the initializer for variable template
6127 // specializations or inline static data members until a definition of the
6128 // variable is needed.
6129 } else {
6130 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
6131 }
6132
6133 // Diagnose unused local variables with dependent types, where the diagnostic
6134 // will have been deferred.
6135 if (!NewVar->isInvalidDecl() &&
6136 NewVar->getDeclContext()->isFunctionOrMethod() &&
6137 OldVar->getType()->isDependentType())
6138 DiagnoseUnusedDecl(NewVar);
6139}
6140
6142 VarDecl *Var, VarDecl *OldVar,
6143 const MultiLevelTemplateArgumentList &TemplateArgs) {
6145 L->VariableDefinitionInstantiated(Var);
6146
6147 // We propagate the 'inline' flag with the initializer, because it
6148 // would otherwise imply that the variable is a definition for a
6149 // non-static data member.
6150 if (OldVar->isInlineSpecified())
6151 Var->setInlineSpecified();
6152 else if (OldVar->isInline())
6153 Var->setImplicitlyInline();
6154
6155 ContextRAII SwitchContext(*this, Var->getDeclContext());
6156
6164
6165 if (OldVar->getInit()) {
6166 // Instantiate the initializer.
6168 SubstInitializer(OldVar->getInit(), TemplateArgs,
6169 OldVar->getInitStyle() == VarDecl::CallInit);
6170
6171 if (!Init.isInvalid()) {
6172 Expr *InitExpr = Init.get();
6173
6174 if (Var->hasAttr<DLLImportAttr>() &&
6175 (!InitExpr ||
6176 !InitExpr->isConstantInitializer(getASTContext(), false))) {
6177 // Do not dynamically initialize dllimport variables.
6178 } else if (InitExpr) {
6179 bool DirectInit = OldVar->isDirectInit();
6180 AddInitializerToDecl(Var, InitExpr, DirectInit);
6181 } else
6183 } else {
6184 // FIXME: Not too happy about invalidating the declaration
6185 // because of a bogus initializer.
6186 Var->setInvalidDecl();
6187 }
6188 } else {
6189 // `inline` variables are a definition and declaration all in one; we won't
6190 // pick up an initializer from anywhere else.
6191 if (Var->isStaticDataMember() && !Var->isInline()) {
6192 if (!Var->isOutOfLine())
6193 return;
6194
6195 // If the declaration inside the class had an initializer, don't add
6196 // another one to the out-of-line definition.
6197 if (OldVar->getFirstDecl()->hasInit())
6198 return;
6199 }
6200
6201 // We'll add an initializer to a for-range declaration later.
6202 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
6203 return;
6204
6206 }
6207
6208 if (getLangOpts().CUDA)
6210}
6211
6213 VarDecl *Var, bool Recursive,
6214 bool DefinitionRequired, bool AtEndOfTU) {
6215 if (Var->isInvalidDecl())
6216 return;
6217
6218 // Never instantiate an explicitly-specialized entity.
6221 if (TSK == TSK_ExplicitSpecialization)
6222 return;
6223
6224 // Find the pattern and the arguments to substitute into it.
6225 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
6226 assert(PatternDecl && "no pattern for templated variable");
6227 MultiLevelTemplateArgumentList TemplateArgs =
6229
6231 dyn_cast<VarTemplateSpecializationDecl>(Var);
6232 if (VarSpec) {
6233 // If this is a static data member template, there might be an
6234 // uninstantiated initializer on the declaration. If so, instantiate
6235 // it now.
6236 //
6237 // FIXME: This largely duplicates what we would do below. The difference
6238 // is that along this path we may instantiate an initializer from an
6239 // in-class declaration of the template and instantiate the definition
6240 // from a separate out-of-class definition.
6241 if (PatternDecl->isStaticDataMember() &&
6242 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
6243 !Var->hasInit()) {
6244 // FIXME: Factor out the duplicated instantiation context setup/tear down
6245 // code here.
6246 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
6247 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
6248 return;
6250 "instantiating variable initializer");
6251
6252 // The instantiation is visible here, even if it was first declared in an
6253 // unimported module.
6255
6256 // If we're performing recursive template instantiation, create our own
6257 // queue of pending implicit instantiations that we will instantiate
6258 // later, while we're still within our own instantiation context.
6259 GlobalEagerInstantiationScope GlobalInstantiations(
6260 *this,
6261 /*Enabled=*/Recursive, /*AtEndOfTU=*/AtEndOfTU);
6262 LocalInstantiationScope Local(*this);
6263 LocalEagerInstantiationScope LocalInstantiations(*this,
6264 /*AtEndOfTU=*/AtEndOfTU);
6265
6266 // Enter the scope of this instantiation. We don't use
6267 // PushDeclContext because we don't have a scope.
6268 ContextRAII PreviousContext(*this, Var->getDeclContext());
6269 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
6270 PreviousContext.pop();
6271
6272 // This variable may have local implicit instantiations that need to be
6273 // instantiated within this scope.
6274 LocalInstantiations.perform();
6275 Local.Exit();
6276 GlobalInstantiations.perform();
6277 }
6278 } else {
6279 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
6280 "not a static data member?");
6281 }
6282
6283 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
6284
6285 // If we don't have a definition of the variable template, we won't perform
6286 // any instantiation. Rather, we rely on the user to instantiate this
6287 // definition (or provide a specialization for it) in another translation
6288 // unit.
6289 if (!Def && !DefinitionRequired) {
6291 PendingInstantiations.emplace_back(Var, PointOfInstantiation);
6292 } else if (TSK == TSK_ImplicitInstantiation) {
6293 // Warn about missing definition at the end of translation unit.
6294 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
6295 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
6296 Diag(PointOfInstantiation, diag::warn_var_template_missing)
6297 << Var;
6298 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
6300 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
6301 }
6302 return;
6303 }
6304 }
6305
6306 // FIXME: We need to track the instantiation stack in order to know which
6307 // definitions should be visible within this instantiation.
6308 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
6309 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
6310 /*InstantiatedFromMember*/false,
6311 PatternDecl, Def, TSK,
6312 /*Complain*/DefinitionRequired))
6313 return;
6314
6315 // C++11 [temp.explicit]p10:
6316 // Except for inline functions, const variables of literal types, variables
6317 // of reference types, [...] explicit instantiation declarations
6318 // have the effect of suppressing the implicit instantiation of the entity
6319 // to which they refer.
6320 //
6321 // FIXME: That's not exactly the same as "might be usable in constant
6322 // expressions", which only allows constexpr variables and const integral
6323 // types, not arbitrary const literal types.
6326 return;
6327
6328 // Make sure to pass the instantiated variable to the consumer at the end.
6329 struct PassToConsumerRAII {
6331 VarDecl *Var;
6332
6333 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
6334 : Consumer(Consumer), Var(Var) { }
6335
6336 ~PassToConsumerRAII() {
6337 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
6338 }
6339 } PassToConsumerRAII(Consumer, Var);
6340
6341 // If we already have a definition, we're done.
6342 if (VarDecl *Def = Var->getDefinition()) {
6343 // We may be explicitly instantiating something we've already implicitly
6344 // instantiated.
6346 PointOfInstantiation);
6347 return;
6348 }
6349
6350 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
6351 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
6352 return;
6354 "instantiating variable definition");
6355
6356 // If we're performing recursive template instantiation, create our own
6357 // queue of pending implicit instantiations that we will instantiate later,
6358 // while we're still within our own instantiation context.
6359 GlobalEagerInstantiationScope GlobalInstantiations(*this,
6360 /*Enabled=*/Recursive,
6361 /*AtEndOfTU=*/AtEndOfTU);
6362
6363 // Enter the scope of this instantiation. We don't use
6364 // PushDeclContext because we don't have a scope.
6365 ContextRAII PreviousContext(*this, Var->getDeclContext());
6366 LocalInstantiationScope Local(*this);
6367
6368 LocalEagerInstantiationScope LocalInstantiations(*this,
6369 /*AtEndOfTU=*/AtEndOfTU);
6370
6371 VarDecl *OldVar = Var;
6372 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
6373 // We're instantiating an inline static data member whose definition was
6374 // provided inside the class.
6375 InstantiateVariableInitializer(Var, Def, TemplateArgs);
6376 } else if (!VarSpec) {
6377 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
6378 TemplateArgs));
6379 } else if (Var->isStaticDataMember() &&
6380 Var->getLexicalDeclContext()->isRecord()) {
6381 // We need to instantiate the definition of a static data member template,
6382 // and all we have is the in-class declaration of it. Instantiate a separate
6383 // declaration of the definition.
6384 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
6385 TemplateArgs);
6386
6387 TemplateArgumentListInfo TemplateArgInfo;
6388 if (const ASTTemplateArgumentListInfo *ArgInfo =
6389 VarSpec->getTemplateArgsAsWritten()) {
6390 TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
6391 TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
6392 for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
6393 TemplateArgInfo.addArgument(Arg);
6394 }
6395
6398 VarSpec->getSpecializedTemplate(), Def,
6399 VarSpec->getTemplateArgs().asArray(), VarSpec);
6400 Var = VTSD;
6401
6402 if (Var) {
6403 VTSD->setTemplateArgsAsWritten(TemplateArgInfo);
6404
6405 llvm::PointerUnion<VarTemplateDecl *,
6409 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
6410 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
6411 Partial, &VarSpec->getTemplateInstantiationArgs());
6412
6413 // Attach the initializer.
6414 InstantiateVariableInitializer(Var, Def, TemplateArgs);
6415 }
6416 } else
6417 // Complete the existing variable's definition with an appropriately
6418 // substituted type and initializer.
6419 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
6420
6421 PreviousContext.pop();
6422
6423 if (Var) {
6424 PassToConsumerRAII.Var = Var;
6426 OldVar->getPointOfInstantiation());
6427 }
6428
6429 // This variable may have local implicit instantiations that need to be
6430 // instantiated within this scope.
6431 LocalInstantiations.perform();
6432 Local.Exit();
6433 GlobalInstantiations.perform();
6434}
6435
6436void
6438 const CXXConstructorDecl *Tmpl,
6439 const MultiLevelTemplateArgumentList &TemplateArgs) {
6440
6442 bool AnyErrors = Tmpl->isInvalidDecl();
6443
6444 // Instantiate all the initializers.
6445 for (const auto *Init : Tmpl->inits()) {
6446 // Only instantiate written initializers, let Sema re-construct implicit
6447 // ones.
6448 if (!Init->isWritten())
6449 continue;
6450
6451 SourceLocation EllipsisLoc;
6452
6453 if (Init->isPackExpansion()) {
6454 // This is a pack expansion. We should expand it now.
6455 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
6457 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
6458 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
6459 bool ShouldExpand = false;
6460 bool RetainExpansion = false;
6461 UnsignedOrNone NumExpansions = std::nullopt;
6463 Init->getEllipsisLoc(), BaseTL.getSourceRange(), Unexpanded,
6464 TemplateArgs, /*FailOnPackProducingTemplates=*/true, ShouldExpand,
6465 RetainExpansion, NumExpansions)) {
6466 AnyErrors = true;
6467 New->setInvalidDecl();
6468 continue;
6469 }
6470 assert(ShouldExpand && "Partial instantiation of base initializer?");
6471
6472 // Loop over all of the arguments in the argument pack(s),
6473 for (unsigned I = 0; I != *NumExpansions; ++I) {
6474 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
6475
6476 // Instantiate the initializer.
6477 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
6478 /*CXXDirectInit=*/true);
6479 if (TempInit.isInvalid()) {
6480 AnyErrors = true;
6481 break;
6482 }
6483
6484 // Instantiate the base type.
6485 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
6486 TemplateArgs,
6487 Init->getSourceLocation(),
6488 New->getDeclName());
6489 if (!BaseTInfo) {
6490 AnyErrors = true;
6491 break;
6492 }
6493
6494 // Build the initializer.
6495 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
6496 BaseTInfo, TempInit.get(),
6497 New->getParent(),
6498 SourceLocation());
6499 if (NewInit.isInvalid()) {
6500 AnyErrors = true;
6501 break;
6502 }
6503
6504 NewInits.push_back(NewInit.get());
6505 }
6506
6507 continue;
6508 }
6509
6510 // Instantiate the initializer.
6511 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
6512 /*CXXDirectInit=*/true);
6513 if (TempInit.isInvalid()) {
6514 AnyErrors = true;
6515 continue;
6516 }
6517
6518 MemInitResult NewInit;
6519 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
6520 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
6521 TemplateArgs,
6522 Init->getSourceLocation(),
6523 New->getDeclName());
6524 if (!TInfo) {
6525 AnyErrors = true;
6526 New->setInvalidDecl();
6527 continue;
6528 }
6529
6530 if (Init->isBaseInitializer())
6531 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
6532 New->getParent(), EllipsisLoc);
6533 else
6534 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
6535 cast<CXXRecordDecl>(CurContext->getParent()));
6536 } else if (Init->isMemberInitializer()) {
6537 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
6538 Init->getMemberLocation(),
6539 Init->getMember(),
6540 TemplateArgs));
6541 if (!Member) {
6542 AnyErrors = true;
6543 New->setInvalidDecl();
6544 continue;
6545 }
6546
6547 NewInit = BuildMemberInitializer(Member, TempInit.get(),
6548 Init->getSourceLocation());
6549 } else if (Init->isIndirectMemberInitializer()) {
6550 IndirectFieldDecl *IndirectMember =
6551 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
6552 Init->getMemberLocation(),
6553 Init->getIndirectMember(), TemplateArgs));
6554
6555 if (!IndirectMember) {
6556 AnyErrors = true;
6557 New->setInvalidDecl();
6558 continue;
6559 }
6560
6561 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
6562 Init->getSourceLocation());
6563 }
6564
6565 if (NewInit.isInvalid()) {
6566 AnyErrors = true;
6567 New->setInvalidDecl();
6568 } else {
6569 NewInits.push_back(NewInit.get());
6570 }
6571 }
6572
6573 // Assign all the initializers to the new constructor.
6575 /*FIXME: ColonLoc */
6577 NewInits,
6578 AnyErrors);
6579}
6580
6581// TODO: this could be templated if the various decl types used the
6582// same method name.
6584 ClassTemplateDecl *Instance) {
6585 Pattern = Pattern->getCanonicalDecl();
6586
6587 do {
6588 Instance = Instance->getCanonicalDecl();
6589 if (Pattern == Instance) return true;
6590 Instance = Instance->getInstantiatedFromMemberTemplate();
6591 } while (Instance);
6592
6593 return false;
6594}
6595
6597 FunctionTemplateDecl *Instance) {
6598 Pattern = Pattern->getCanonicalDecl();
6599
6600 do {
6601 Instance = Instance->getCanonicalDecl();
6602 if (Pattern == Instance) return true;
6603 Instance = Instance->getInstantiatedFromMemberTemplate();
6604 } while (Instance);
6605
6606 return false;
6607}
6608
6609static bool
6612 Pattern
6614 do {
6616 Instance->getCanonicalDecl());
6617 if (Pattern == Instance)
6618 return true;
6619 Instance = Instance->getInstantiatedFromMember();
6620 } while (Instance);
6621
6622 return false;
6623}
6624
6626 CXXRecordDecl *Instance) {
6627 Pattern = Pattern->getCanonicalDecl();
6628
6629 do {
6630 Instance = Instance->getCanonicalDecl();
6631 if (Pattern == Instance) return true;
6632 Instance = Instance->getInstantiatedFromMemberClass();
6633 } while (Instance);
6634
6635 return false;
6636}
6637
6638static bool isInstantiationOf(FunctionDecl *Pattern,
6639 FunctionDecl *Instance) {
6640 Pattern = Pattern->getCanonicalDecl();
6641
6642 do {
6643 Instance = Instance->getCanonicalDecl();
6644 if (Pattern == Instance) return true;
6645 Instance = Instance->getInstantiatedFromMemberFunction();
6646 } while (Instance);
6647
6648 return false;
6649}
6650
6651static bool isInstantiationOf(EnumDecl *Pattern,
6652 EnumDecl *Instance) {
6653 Pattern = Pattern->getCanonicalDecl();
6654
6655 do {
6656 Instance = Instance->getCanonicalDecl();
6657 if (Pattern == Instance) return true;
6658 Instance = Instance->getInstantiatedFromMemberEnum();
6659 } while (Instance);
6660
6661 return false;
6662}
6663
6665 UsingShadowDecl *Instance,
6666 ASTContext &C) {
6667 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
6668 Pattern);
6669}
6670
6671static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
6672 ASTContext &C) {
6673 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
6674}
6675
6676template<typename T>
6678 ASTContext &Ctx) {
6679 // An unresolved using declaration can instantiate to an unresolved using
6680 // declaration, or to a using declaration or a using declaration pack.
6681 //
6682 // Multiple declarations can claim to be instantiated from an unresolved
6683 // using declaration if it's a pack expansion. We want the UsingPackDecl
6684 // in that case, not the individual UsingDecls within the pack.
6685 bool OtherIsPackExpansion;
6686 NamedDecl *OtherFrom;
6687 if (auto *OtherUUD = dyn_cast<T>(Other)) {
6688 OtherIsPackExpansion = OtherUUD->isPackExpansion();
6689 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
6690 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
6691 OtherIsPackExpansion = true;
6692 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
6693 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
6694 OtherIsPackExpansion = false;
6695 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
6696 } else {
6697 return false;
6698 }
6699 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
6700 declaresSameEntity(OtherFrom, Pattern);
6701}
6702
6704 VarDecl *Instance) {
6705 assert(Instance->isStaticDataMember());
6706
6707 Pattern = Pattern->getCanonicalDecl();
6708
6709 do {
6710 Instance = Instance->getCanonicalDecl();
6711 if (Pattern == Instance) return true;
6712 Instance = Instance->getInstantiatedFromStaticDataMember();
6713 } while (Instance);
6714
6715 return false;
6716}
6717
6718// Other is the prospective instantiation
6719// D is the prospective pattern
6721 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
6723
6724 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
6726
6727 if (D->getKind() != Other->getKind())
6728 return false;
6729
6730 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
6732
6733 if (auto *Function = dyn_cast<FunctionDecl>(Other))
6734 return isInstantiationOf(cast<FunctionDecl>(D), Function);
6735
6736 if (auto *Enum = dyn_cast<EnumDecl>(Other))
6738
6739 if (auto *Var = dyn_cast<VarDecl>(Other))
6740 if (Var->isStaticDataMember())
6742
6743 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
6745
6746 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
6748
6749 if (auto *PartialSpec =
6750 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
6752 PartialSpec);
6753
6754 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
6755 if (!Field->getDeclName()) {
6756 // This is an unnamed field.
6758 cast<FieldDecl>(D));
6759 }
6760 }
6761
6762 if (auto *Using = dyn_cast<UsingDecl>(Other))
6763 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
6764
6765 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
6766 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
6767
6768 return D->getDeclName() &&
6769 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
6770}
6771
6772template<typename ForwardIterator>
6774 NamedDecl *D,
6775 ForwardIterator first,
6776 ForwardIterator last) {
6777 for (; first != last; ++first)
6778 if (isInstantiationOf(Ctx, D, *first))
6779 return cast<NamedDecl>(*first);
6780
6781 return nullptr;
6782}
6783
6785 const MultiLevelTemplateArgumentList &TemplateArgs) {
6786 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
6787 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
6788 return cast_or_null<DeclContext>(ID);
6789 } else return DC;
6790}
6791
6792/// Determine whether the given context is dependent on template parameters at
6793/// level \p Level or below.
6794///
6795/// Sometimes we only substitute an inner set of template arguments and leave
6796/// the outer templates alone. In such cases, contexts dependent only on the
6797/// outer levels are not effectively dependent.
6798static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
6799 if (!DC->isDependentContext())
6800 return false;
6801 if (!Level)
6802 return true;
6803 return cast<Decl>(DC)->getTemplateDepth() > Level;
6804}
6805
6807 const MultiLevelTemplateArgumentList &TemplateArgs,
6808 bool FindingInstantiatedContext) {
6809 DeclContext *ParentDC = D->getDeclContext();
6810 // Determine whether our parent context depends on any of the template
6811 // arguments we're currently substituting.
6812 bool ParentDependsOnArgs = isDependentContextAtLevel(
6813 ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6814 // FIXME: Parameters of pointer to functions (y below) that are themselves
6815 // parameters (p below) can have their ParentDC set to the translation-unit
6816 // - thus we can not consistently check if the ParentDC of such a parameter
6817 // is Dependent or/and a FunctionOrMethod.
6818 // For e.g. this code, during Template argument deduction tries to
6819 // find an instantiated decl for (T y) when the ParentDC for y is
6820 // the translation unit.
6821 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6822 // float baz(float(*)()) { return 0.0; }
6823 // Foo(baz);
6824 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6825 // it gets here, always has a FunctionOrMethod as its ParentDC??
6826 // For now:
6827 // - as long as we have a ParmVarDecl whose parent is non-dependent and
6828 // whose type is not instantiation dependent, do nothing to the decl
6829 // - otherwise find its instantiated decl.
6830 if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6831 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6832 return D;
6835 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6836 isa<OMPDeclareReductionDecl>(ParentDC) ||
6837 isa<OMPDeclareMapperDecl>(ParentDC))) ||
6838 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6839 cast<CXXRecordDecl>(D)->getTemplateDepth() >
6840 TemplateArgs.getNumRetainedOuterLevels())) {
6841 // D is a local of some kind. Look into the map of local
6842 // declarations to their instantiations.
6844 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
6845 if (Decl *FD = Found->dyn_cast<Decl *>()) {
6846 if (auto *BD = dyn_cast<BindingDecl>(FD);
6847 BD && BD->isParameterPack() && ArgPackSubstIndex) {
6848 return BD->getBindingPackDecls()[*ArgPackSubstIndex];
6849 }
6850 return cast<NamedDecl>(FD);
6851 }
6852
6853 assert(ArgPackSubstIndex &&
6854 "found declaration pack but not pack expanding");
6855 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6856 return cast<NamedDecl>(
6858 }
6859 }
6860
6861 // If we're performing a partial substitution during template argument
6862 // deduction, we may not have values for template parameters yet. They
6863 // just map to themselves.
6866 return D;
6867
6868 if (D->isInvalidDecl())
6869 return nullptr;
6870
6871 // Normally this function only searches for already instantiated declaration
6872 // however we have to make an exclusion for local types used before
6873 // definition as in the code:
6874 //
6875 // template<typename T> void f1() {
6876 // void g1(struct x1);
6877 // struct x1 {};
6878 // }
6879 //
6880 // In this case instantiation of the type of 'g1' requires definition of
6881 // 'x1', which is defined later. Error recovery may produce an enum used
6882 // before definition. In these cases we need to instantiate relevant
6883 // declarations here.
6884 bool NeedInstantiate = false;
6885 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6886 NeedInstantiate = RD->isLocalClass();
6887 else if (isa<TypedefNameDecl>(D) &&
6889 NeedInstantiate = true;
6890 else
6891 NeedInstantiate = isa<EnumDecl>(D);
6892 if (NeedInstantiate) {
6893 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6894 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6895 return cast<TypeDecl>(Inst);
6896 }
6897
6898 // If we didn't find the decl, then we must have a label decl that hasn't
6899 // been found yet. Lazily instantiate it and return it now.
6900 assert(isa<LabelDecl>(D));
6901
6902 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6903 assert(Inst && "Failed to instantiate label??");
6904
6905 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6906 return cast<LabelDecl>(Inst);
6907 }
6908
6909 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
6910 if (!Record->isDependentContext())
6911 return D;
6912
6913 // Determine whether this record is the "templated" declaration describing
6914 // a class template or class template specialization.
6915 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
6916 if (ClassTemplate)
6917 ClassTemplate = ClassTemplate->getCanonicalDecl();
6918 else if (ClassTemplateSpecializationDecl *Spec =
6919 dyn_cast<ClassTemplateSpecializationDecl>(Record))
6920 ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl();
6921
6922 // Walk the current context to find either the record or an instantiation of
6923 // it.
6924 DeclContext *DC = CurContext;
6925 while (!DC->isFileContext()) {
6926 // If we're performing substitution while we're inside the template
6927 // definition, we'll find our own context. We're done.
6928 if (DC->Equals(Record))
6929 return Record;
6930
6931 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
6932 // Check whether we're in the process of instantiating a class template
6933 // specialization of the template we're mapping.
6935 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
6936 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
6937 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
6938 return InstRecord;
6939 }
6940
6941 // Check whether we're in the process of instantiating a member class.
6942 if (isInstantiationOf(Record, InstRecord))
6943 return InstRecord;
6944 }
6945
6946 // Move to the outer template scope.
6947 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
6948 if (FD->getFriendObjectKind() &&
6950 DC = FD->getLexicalDeclContext();
6951 continue;
6952 }
6953 // An implicit deduction guide acts as if it's within the class template
6954 // specialization described by its name and first N template params.
6955 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
6956 if (Guide && Guide->isImplicit()) {
6957 TemplateDecl *TD = Guide->getDeducedTemplate();
6958 // Convert the arguments to an "as-written" list.
6959 TemplateArgumentListInfo Args(Loc, Loc);
6960 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
6961 TD->getTemplateParameters()->size())) {
6962 ArrayRef<TemplateArgument> Unpacked(Arg);
6963 if (Arg.getKind() == TemplateArgument::Pack)
6964 Unpacked = Arg.pack_elements();
6965 for (TemplateArgument UnpackedArg : Unpacked)
6966 Args.addArgument(
6967 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
6968 }
6971 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
6972 // We may get a non-null type with errors, in which case
6973 // `getAsCXXRecordDecl` will return `nullptr`. For instance, this
6974 // happens when one of the template arguments is an invalid
6975 // expression. We return early to avoid triggering the assertion
6976 // about the `CodeSynthesisContext`.
6977 if (T.isNull() || T->containsErrors())
6978 return nullptr;
6979 CXXRecordDecl *SubstRecord = T->getAsCXXRecordDecl();
6980
6981 if (!SubstRecord) {
6982 // T can be a dependent TemplateSpecializationType when performing a
6983 // substitution for building a deduction guide or for template
6984 // argument deduction in the process of rebuilding immediate
6985 // expressions. (Because the default argument that involves a lambda
6986 // is untransformed and thus could be dependent at this point.)
6987 assert(SemaRef.RebuildingImmediateInvocation ||
6988 CodeSynthesisContexts.back().Kind ==
6990 // Return a nullptr as a sentinel value, we handle it properly in
6991 // the TemplateInstantiator::TransformInjectedClassNameType
6992 // override, which we transform it to a TemplateSpecializationType.
6993 return nullptr;
6994 }
6995 // Check that this template-id names the primary template and not a
6996 // partial or explicit specialization. (In the latter cases, it's
6997 // meaningless to attempt to find an instantiation of D within the
6998 // specialization.)
6999 // FIXME: The standard doesn't say what should happen here.
7000 if (FindingInstantiatedContext &&
7002 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
7003 Diag(Loc, diag::err_specialization_not_primary_template)
7004 << T << (SubstRecord->getTemplateSpecializationKind() ==
7006 return nullptr;
7007 }
7008 DC = SubstRecord;
7009 continue;
7010 }
7011 }
7012
7013 DC = DC->getParent();
7014 }
7015
7016 // Fall through to deal with other dependent record types (e.g.,
7017 // anonymous unions in class templates).
7018 }
7019
7020 if (!ParentDependsOnArgs)
7021 return D;
7022
7023 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
7024 if (!ParentDC)
7025 return nullptr;
7026
7027 if (ParentDC != D->getDeclContext()) {
7028 // We performed some kind of instantiation in the parent context,
7029 // so now we need to look into the instantiated parent context to
7030 // find the instantiation of the declaration D.
7031
7032 // If our context used to be dependent, we may need to instantiate
7033 // it before performing lookup into that context.
7034 bool IsBeingInstantiated = false;
7035 if (auto *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
7036 if (!Spec->isDependentContext()) {
7037 if (Spec->isEntityBeingDefined())
7038 IsBeingInstantiated = true;
7039 else if (RequireCompleteType(Loc, Context.getCanonicalTagType(Spec),
7040 diag::err_incomplete_type))
7041 return nullptr;
7042
7043 ParentDC = Spec->getDefinitionOrSelf();
7044 }
7045 }
7046
7047 NamedDecl *Result = nullptr;
7048 // FIXME: If the name is a dependent name, this lookup won't necessarily
7049 // find it. Does that ever matter?
7050 if (auto Name = D->getDeclName()) {
7051 DeclarationNameInfo NameInfo(Name, D->getLocation());
7052 DeclarationNameInfo NewNameInfo =
7053 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
7054 Name = NewNameInfo.getName();
7055 if (!Name)
7056 return nullptr;
7057 DeclContext::lookup_result Found = ParentDC->lookup(Name);
7058
7059 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
7060 } else {
7061 // Since we don't have a name for the entity we're looking for,
7062 // our only option is to walk through all of the declarations to
7063 // find that name. This will occur in a few cases:
7064 //
7065 // - anonymous struct/union within a template
7066 // - unnamed class/struct/union/enum within a template
7067 //
7068 // FIXME: Find a better way to find these instantiations!
7070 ParentDC->decls_begin(),
7071 ParentDC->decls_end());
7072 }
7073
7074 if (!Result) {
7075 if (isa<UsingShadowDecl>(D)) {
7076 // UsingShadowDecls can instantiate to nothing because of using hiding.
7077 } else if (hasUncompilableErrorOccurred()) {
7078 // We've already complained about some ill-formed code, so most likely
7079 // this declaration failed to instantiate. There's no point in
7080 // complaining further, since this is normal in invalid code.
7081 // FIXME: Use more fine-grained 'invalid' tracking for this.
7082 } else if (IsBeingInstantiated) {
7083 // The class in which this member exists is currently being
7084 // instantiated, and we haven't gotten around to instantiating this
7085 // member yet. This can happen when the code uses forward declarations
7086 // of member classes, and introduces ordering dependencies via
7087 // template instantiation.
7088 Diag(Loc, diag::err_member_not_yet_instantiated)
7089 << D->getDeclName()
7090 << Context.getCanonicalTagType(cast<CXXRecordDecl>(ParentDC));
7091 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
7092 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
7093 // This enumeration constant was found when the template was defined,
7094 // but can't be found in the instantiation. This can happen if an
7095 // unscoped enumeration member is explicitly specialized.
7096 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
7098 TemplateArgs));
7099 assert(Spec->getTemplateSpecializationKind() ==
7101 Diag(Loc, diag::err_enumerator_does_not_exist)
7102 << D->getDeclName()
7103 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
7104 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
7105 << Context.getCanonicalTagType(Spec);
7106 } else {
7107 // We should have found something, but didn't.
7108 llvm_unreachable("Unable to find instantiation of declaration!");
7109 }
7110 }
7111
7112 D = Result;
7113 }
7114
7115 return D;
7116}
7117
7118void Sema::PerformPendingInstantiations(bool LocalOnly, bool AtEndOfTU) {
7119 std::deque<PendingImplicitInstantiation> DelayedImplicitInstantiations;
7120 while (!PendingLocalImplicitInstantiations.empty() ||
7121 (!LocalOnly && !PendingInstantiations.empty())) {
7123
7124 bool LocalInstantiation = false;
7126 Inst = PendingInstantiations.front();
7127 PendingInstantiations.pop_front();
7128 } else {
7131 LocalInstantiation = true;
7132 }
7133
7134 // Instantiate function definitions
7135 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
7136 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
7138 if (Function->isMultiVersion()) {
7140 Function,
7141 [this, Inst, DefinitionRequired, AtEndOfTU](FunctionDecl *CurFD) {
7142 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
7143 DefinitionRequired, AtEndOfTU);
7144 if (CurFD->isDefined())
7145 CurFD->setInstantiationIsPending(false);
7146 });
7147 } else {
7148 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
7149 DefinitionRequired, AtEndOfTU);
7150 if (Function->isDefined())
7151 Function->setInstantiationIsPending(false);
7152 }
7153 // Definition of a PCH-ed template declaration may be available only in the TU.
7154 if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
7155 TUKind == TU_Prefix && Function->instantiationIsPending())
7156 DelayedImplicitInstantiations.push_back(Inst);
7157 else if (!AtEndOfTU && Function->instantiationIsPending() &&
7158 !LocalInstantiation)
7159 DelayedImplicitInstantiations.push_back(Inst);
7160 continue;
7161 }
7162
7163 // Instantiate variable definitions
7164 VarDecl *Var = cast<VarDecl>(Inst.first);
7165
7166 assert((Var->isStaticDataMember() ||
7168 "Not a static data member, nor a variable template"
7169 " specialization?");
7170
7171 // Don't try to instantiate declarations if the most recent redeclaration
7172 // is invalid.
7173 if (Var->getMostRecentDecl()->isInvalidDecl())
7174 continue;
7175
7176 // Check if the most recent declaration has changed the specialization kind
7177 // and removed the need for implicit instantiation.
7178 switch (Var->getMostRecentDecl()
7180 case TSK_Undeclared:
7181 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
7184 continue; // No longer need to instantiate this type.
7186 // We only need an instantiation if the pending instantiation *is* the
7187 // explicit instantiation.
7188 if (Var != Var->getMostRecentDecl())
7189 continue;
7190 break;
7192 break;
7193 }
7194
7196 "instantiating variable definition");
7197 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
7199
7200 // Instantiate static data member definitions or variable template
7201 // specializations.
7202 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
7203 DefinitionRequired, AtEndOfTU);
7204 }
7205
7206 if (!DelayedImplicitInstantiations.empty())
7207 PendingInstantiations.swap(DelayedImplicitInstantiations);
7208}
7209
7211 const MultiLevelTemplateArgumentList &TemplateArgs) {
7212 for (auto *DD : Pattern->ddiags()) {
7213 switch (DD->getKind()) {
7215 HandleDependentAccessCheck(*DD, TemplateArgs);
7216 break;
7217 }
7218 }
7219}
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:220
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:776
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:3342
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
QualType getType() const
Definition Expr.h:144
Declaration context for names declared as extern "C" in C++.
Definition Decl.h: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:5266
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5573
QualType getParamType(unsigned i) const
Definition TypeBase.h:5546
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5579
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5555
FunctionDecl * getExceptionSpecTemplate() const
If this function type has an uninstantiated exception specification, this is the function whose excep...
Definition TypeBase.h:5652
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5551
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:4818
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4810
QualType getReturnType() const
Definition TypeBase.h:4802
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
Definition Decl.h:5173
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:5610
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:5427
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:8472
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:5309
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:13520
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8400
A RAII object to temporarily push a declaration context.
Definition Sema.h:3475
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6349
A helper class for building up ExtParameterInfos.
Definition Sema.h:12931
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition Sema.h:13905
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12425
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:853
SemaAMDGPU & AMDGPU()
Definition Sema.h:1419
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13454
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12960
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:9290
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9317
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9322
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:5012
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition Sema.h:1504
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:1240
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:1444
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:6889
void deduceOpenCLAddressSpace(ValueDecl *decl)
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2047
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:6901
LateParsedTemplateMapT LateParsedTemplateMap
Definition Sema.h:11319
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:1282
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:921
SemaObjC & ObjC()
Definition Sema.h:1489
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:924
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:13987
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1190
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:12097
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:917
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:1326
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:1280
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1454
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:13861
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
SemaSwift & Swift()
Definition Sema.h:1534
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:1417
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:1499
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition Sema.h:13874
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
SourceManager & getSourceManager() const
Definition Sema.h:922
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:13514
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:1555
ASTConsumer & Consumer
Definition Sema.h:1283
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:13857
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:6695
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6705
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6674
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
LateTemplateParserCB * LateTemplateParser
Definition Sema.h:1324
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8269
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:1285
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:1278
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:11537
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11538
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:13853
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:11311
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1273
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:8608
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:5684
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:8258
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:8269
bool isRValueReferenceType() const
Definition TypeBase.h:8556
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9167
bool isReferenceType() const
Definition TypeBase.h:8548
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:8552
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:8845
bool isAtomicType() const
Definition TypeBase.h:8706
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:9016
bool isFunctionType() const
Definition TypeBase.h:8520
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9100
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:5633
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:5465
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:584
@ VarTemplate
The name was classified as a variable template name.
Definition Sema.h:582
@ 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:5886
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5879
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:5323
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition TypeBase.h:5335
FunctionDecl * SourceTemplate
The function template whose exception specification this is instantiated from, for EST_Uninstantiated...
Definition TypeBase.h:5339
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5325
Extra information about a function prototype.
Definition TypeBase.h:5351
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:11954
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:11940
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:12977
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:12979
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13084
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13005
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6811
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition Sema.h:6817
A stack object to be created when performing template instantiation.
Definition Sema.h:13168
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13328
bool isAlreadyInstantiating() const
Determine whether we are already instantiating this specialization in some surrounding active instant...
Definition Sema.h:13332