clang 19.0.0git
SemaTemplateInstantiate.cpp
Go to the documentation of this file.
1//===------- SemaTemplateInstantiate.cpp - C++ Template 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.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/DeclBase.h"
20#include "clang/AST/Expr.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/Stack.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Sema.h"
36#include "clang/Sema/Template.h"
39#include "llvm/ADT/StringExtras.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/TimeProfiler.h"
42#include <optional>
43
44using namespace clang;
45using namespace sema;
46
47//===----------------------------------------------------------------------===/
48// Template Instantiation Support
49//===----------------------------------------------------------------------===/
50
51namespace {
53struct Response {
54 const Decl *NextDecl = nullptr;
55 bool IsDone = false;
56 bool ClearRelativeToPrimary = true;
57 static Response Done() {
58 Response R;
59 R.IsDone = true;
60 return R;
61 }
62 static Response ChangeDecl(const Decl *ND) {
63 Response R;
64 R.NextDecl = ND;
65 return R;
66 }
67 static Response ChangeDecl(const DeclContext *Ctx) {
68 Response R;
69 R.NextDecl = Decl::castFromDeclContext(Ctx);
70 return R;
71 }
72
73 static Response UseNextDecl(const Decl *CurDecl) {
74 return ChangeDecl(CurDecl->getDeclContext());
75 }
76
77 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
78 Response R = Response::UseNextDecl(CurDecl);
79 R.ClearRelativeToPrimary = false;
80 return R;
81 }
82};
83// Add template arguments from a variable template instantiation.
84Response
85HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
87 bool SkipForSpecialization) {
88 // For a class-scope explicit specialization, there are no template arguments
89 // at this level, but there may be enclosing template arguments.
90 if (VarTemplSpec->isClassScopeExplicitSpecialization())
91 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
92
93 // We're done when we hit an explicit specialization.
95 !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec))
96 return Response::Done();
97
98 // If this variable template specialization was instantiated from a
99 // specialized member that is a variable template, we're done.
100 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
101 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
102 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
104 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
105 if (!SkipForSpecialization)
106 Result.addOuterTemplateArguments(
107 Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
108 /*Final=*/false);
109 if (Partial->isMemberSpecialization())
110 return Response::Done();
111 } else {
112 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
113 if (!SkipForSpecialization)
114 Result.addOuterTemplateArguments(
115 Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
116 /*Final=*/false);
117 if (Tmpl->isMemberSpecialization())
118 return Response::Done();
119 }
120 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
121}
122
123// If we have a template template parameter with translation unit context,
124// then we're performing substitution into a default template argument of
125// this template template parameter before we've constructed the template
126// that will own this template template parameter. In this case, we
127// use empty template parameter lists for all of the outer templates
128// to avoid performing any substitutions.
129Response
130HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
132 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
133 Result.addOuterTemplateArguments(std::nullopt);
134 return Response::Done();
135}
136
137Response HandlePartialClassTemplateSpec(
138 const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,
139 MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {
140 if (!SkipForSpecialization)
141 Result.addOuterRetainedLevels(PartialClassTemplSpec->getTemplateDepth());
142 return Response::Done();
143}
144
145// Add template arguments from a class template instantiation.
146Response
147HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
149 bool SkipForSpecialization) {
150 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
151 // We're done when we hit an explicit specialization.
152 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
153 !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec))
154 return Response::Done();
155
156 if (!SkipForSpecialization)
157 Result.addOuterTemplateArguments(
158 const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
159 ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
160 /*Final=*/false);
161
162 // If this class template specialization was instantiated from a
163 // specialized member that is a class template, we're done.
164 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
165 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
166 return Response::Done();
167
168 // If this was instantiated from a partial template specialization, we need
169 // to get the next level of declaration context from the partial
170 // specialization, as the ClassTemplateSpecializationDecl's
171 // DeclContext/LexicalDeclContext will be for the primary template.
172 if (auto *InstFromPartialTempl = ClassTemplSpec->getSpecializedTemplateOrPartial()
174 return Response::ChangeDecl(InstFromPartialTempl->getLexicalDeclContext());
175 }
176 return Response::UseNextDecl(ClassTemplSpec);
177}
178
179Response HandleFunction(const FunctionDecl *Function,
181 const FunctionDecl *Pattern, bool RelativeToPrimary,
182 bool ForConstraintInstantiation) {
183 // Add template arguments from a function template specialization.
184 if (!RelativeToPrimary &&
185 Function->getTemplateSpecializationKindForInstantiation() ==
187 return Response::Done();
188
189 if (!RelativeToPrimary &&
190 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
191 // This is an implicit instantiation of an explicit specialization. We
192 // don't get any template arguments from this function but might get
193 // some from an enclosing template.
194 return Response::UseNextDecl(Function);
195 } else if (const TemplateArgumentList *TemplateArgs =
196 Function->getTemplateSpecializationArgs()) {
197 // Add the template arguments for this specialization.
198 Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
199 TemplateArgs->asArray(),
200 /*Final=*/false);
201
202 // If this function was instantiated from a specialized member that is
203 // a function template, we're done.
204 assert(Function->getPrimaryTemplate() && "No function template?");
205 if (Function->getPrimaryTemplate()->isMemberSpecialization())
206 return Response::Done();
207
208 // If this function is a generic lambda specialization, we are done.
209 if (!ForConstraintInstantiation &&
211 return Response::Done();
212
213 } else if (Function->getDescribedFunctionTemplate()) {
214 assert(
215 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
216 "Outer template not instantiated?");
217 }
218 // If this is a friend or local declaration and it declares an entity at
219 // namespace scope, take arguments from its lexical parent
220 // instead of its semantic parent, unless of course the pattern we're
221 // instantiating actually comes from the file's context!
222 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
223 Function->getNonTransparentDeclContext()->isFileContext() &&
224 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
225 return Response::ChangeDecl(Function->getLexicalDeclContext());
226 }
227
228 if (ForConstraintInstantiation && Function->getFriendObjectKind())
229 return Response::ChangeDecl(Function->getLexicalDeclContext());
230 return Response::UseNextDecl(Function);
231}
232
233Response HandleFunctionTemplateDecl(const FunctionTemplateDecl *FTD,
235 if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) {
236 Result.addOuterTemplateArguments(
237 const_cast<FunctionTemplateDecl *>(FTD),
238 const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(),
239 /*Final=*/false);
240
242
243 while (const Type *Ty = NNS ? NNS->getAsType() : nullptr) {
244 if (NNS->isInstantiationDependent()) {
245 if (const auto *TSTy = Ty->getAs<TemplateSpecializationType>()) {
246 ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();
247 // Prefer template arguments from the injected-class-type if possible.
248 // For example,
249 // ```cpp
250 // template <class... Pack> struct S {
251 // template <class T> void foo();
252 // };
253 // template <class... Pack> template <class T>
254 // ^^^^^^^^^^^^^ InjectedTemplateArgs
255 // They're of kind TemplateArgument::Pack, not of
256 // TemplateArgument::Type.
257 // void S<Pack...>::foo() {}
258 // ^^^^^^^
259 // TSTy->template_arguments() (which are of PackExpansionType)
260 // ```
261 // This meets the contract in
262 // TreeTransform::TryExpandParameterPacks that the template arguments
263 // for unexpanded parameters should be of a Pack kind.
264 if (TSTy->isCurrentInstantiation()) {
265 auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
266 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
267 Arguments = CTD->getInjectedTemplateArgs();
268 else if (auto *Specialization =
269 dyn_cast<ClassTemplateSpecializationDecl>(RD))
270 Arguments =
271 Specialization->getTemplateInstantiationArgs().asArray();
272 }
273 Result.addOuterTemplateArguments(
274 const_cast<FunctionTemplateDecl *>(FTD), Arguments,
275 /*Final=*/false);
276 }
277 }
278
279 NNS = NNS->getPrefix();
280 }
281 }
282
283 return Response::ChangeDecl(FTD->getLexicalDeclContext());
284}
285
286Response HandleRecordDecl(const CXXRecordDecl *Rec,
288 ASTContext &Context,
289 bool ForConstraintInstantiation) {
290 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
291 assert(
292 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
293 "Outer template not instantiated?");
294 if (ClassTemplate->isMemberSpecialization())
295 return Response::Done();
296 if (ForConstraintInstantiation)
297 Result.addOuterTemplateArguments(const_cast<CXXRecordDecl *>(Rec),
298 ClassTemplate->getInjectedTemplateArgs(),
299 /*Final=*/false);
300 }
301
302 if (const MemberSpecializationInfo *MSInfo =
304 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
305 return Response::Done();
306
307 bool IsFriend = Rec->getFriendObjectKind() ||
310 if (ForConstraintInstantiation && IsFriend &&
312 return Response::ChangeDecl(Rec->getLexicalDeclContext());
313 }
314
315 // This is to make sure we pick up the VarTemplateSpecializationDecl that this
316 // lambda is defined inside of.
317 if (Rec->isLambda())
318 if (const Decl *LCD = Rec->getLambdaContextDecl())
319 return Response::ChangeDecl(LCD);
320
321 return Response::UseNextDecl(Rec);
322}
323
324Response HandleImplicitConceptSpecializationDecl(
327 Result.addOuterTemplateArguments(
328 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
330 /*Final=*/false);
331 return Response::UseNextDecl(CSD);
332}
333
334Response HandleGenericDeclContext(const Decl *CurDecl) {
335 return Response::UseNextDecl(CurDecl);
336}
337} // namespace TemplateInstArgsHelpers
338} // namespace
339
340/// Retrieve the template argument list(s) that should be used to
341/// instantiate the definition of the given declaration.
342///
343/// \param ND the declaration for which we are computing template instantiation
344/// arguments.
345///
346/// \param DC In the event we don't HAVE a declaration yet, we instead provide
347/// the decl context where it will be created. In this case, the `Innermost`
348/// should likely be provided. If ND is non-null, this is ignored.
349///
350/// \param Innermost if non-NULL, specifies a template argument list for the
351/// template declaration passed as ND.
352///
353/// \param RelativeToPrimary true if we should get the template
354/// arguments relative to the primary template, even when we're
355/// dealing with a specialization. This is only relevant for function
356/// template specializations.
357///
358/// \param Pattern If non-NULL, indicates the pattern from which we will be
359/// instantiating the definition of the given declaration, \p ND. This is
360/// used to determine the proper set of template instantiation arguments for
361/// friend function template specializations.
362///
363/// \param ForConstraintInstantiation when collecting arguments,
364/// ForConstraintInstantiation indicates we should continue looking when
365/// encountering a lambda generic call operator, and continue looking for
366/// arguments on an enclosing class template.
367
369 const NamedDecl *ND, const DeclContext *DC, bool Final,
370 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
371 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
372 bool SkipForSpecialization) {
373 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
374 // Accumulate the set of template argument lists in this structure.
376
377 using namespace TemplateInstArgsHelpers;
378 const Decl *CurDecl = ND;
379
380 if (!CurDecl)
381 CurDecl = Decl::castFromDeclContext(DC);
382
383 if (Innermost) {
384 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,
385 Final);
386 // Populate placeholder template arguments for TemplateTemplateParmDecls.
387 // This is essential for the case e.g.
388 //
389 // template <class> concept Concept = false;
390 // template <template <Concept C> class T> void foo(T<int>)
391 //
392 // where parameter C has a depth of 1 but the substituting argument `int`
393 // has a depth of 0.
394 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))
395 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
396 CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
397 }
398
399 while (!CurDecl->isFileContextDecl()) {
400 Response R;
401 if (const auto *VarTemplSpec =
402 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
403 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
404 } else if (const auto *PartialClassTemplSpec =
405 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
406 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
407 SkipForSpecialization);
408 } else if (const auto *ClassTemplSpec =
409 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
410 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
411 SkipForSpecialization);
412 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
413 R = HandleFunction(Function, Result, Pattern, RelativeToPrimary,
414 ForConstraintInstantiation);
415 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
416 R = HandleRecordDecl(Rec, Result, Context, ForConstraintInstantiation);
417 } else if (const auto *CSD =
418 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
419 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
420 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
421 R = HandleFunctionTemplateDecl(FTD, Result);
422 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) {
423 R = Response::ChangeDecl(CTD->getLexicalDeclContext());
424 } else if (!isa<DeclContext>(CurDecl)) {
425 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
426 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
427 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
428 }
429 } else {
430 R = HandleGenericDeclContext(CurDecl);
431 }
432
433 if (R.IsDone)
434 return Result;
435 if (R.ClearRelativeToPrimary)
436 RelativeToPrimary = false;
437 assert(R.NextDecl);
438 CurDecl = R.NextDecl;
439 }
440
441 return Result;
442}
443
445 switch (Kind) {
453 case ConstraintsCheck:
455 return true;
456
473 return false;
474
475 // This function should never be called when Kind's value is Memoization.
476 case Memoization:
477 break;
478 }
479
480 llvm_unreachable("Invalid SynthesisKind!");
481}
482
485 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
486 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
487 sema::TemplateDeductionInfo *DeductionInfo)
488 : SemaRef(SemaRef) {
489 // Don't allow further instantiation if a fatal error and an uncompilable
490 // error have occurred. Any diagnostics we might have raised will not be
491 // visible, and we do not need to construct a correct AST.
492 if (SemaRef.Diags.hasFatalErrorOccurred() &&
494 Invalid = true;
495 return;
496 }
497 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
498 if (!Invalid) {
500 Inst.Kind = Kind;
501 Inst.PointOfInstantiation = PointOfInstantiation;
502 Inst.Entity = Entity;
503 Inst.Template = Template;
504 Inst.TemplateArgs = TemplateArgs.data();
505 Inst.NumTemplateArgs = TemplateArgs.size();
506 Inst.DeductionInfo = DeductionInfo;
507 Inst.InstantiationRange = InstantiationRange;
508 SemaRef.pushCodeSynthesisContext(Inst);
509
510 AlreadyInstantiating = !Inst.Entity ? false :
512 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
513 .second;
514 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
515 }
516}
517
519 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
520 SourceRange InstantiationRange)
521 : InstantiatingTemplate(SemaRef,
522 CodeSynthesisContext::TemplateInstantiation,
523 PointOfInstantiation, InstantiationRange, Entity) {}
524
526 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
527 ExceptionSpecification, SourceRange InstantiationRange)
529 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
530 PointOfInstantiation, InstantiationRange, Entity) {}
531
533 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
534 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
535 SourceRange InstantiationRange)
537 SemaRef,
538 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
539 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
540 Template, TemplateArgs) {}
541
543 Sema &SemaRef, SourceLocation PointOfInstantiation,
545 ArrayRef<TemplateArgument> TemplateArgs,
547 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
548 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
549 InstantiationRange, FunctionTemplate, nullptr,
550 TemplateArgs, &DeductionInfo) {
554}
555
557 Sema &SemaRef, SourceLocation PointOfInstantiation,
558 TemplateDecl *Template,
559 ArrayRef<TemplateArgument> TemplateArgs,
560 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
562 SemaRef,
563 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
564 PointOfInstantiation, InstantiationRange, Template, nullptr,
565 TemplateArgs, &DeductionInfo) {}
566
568 Sema &SemaRef, SourceLocation PointOfInstantiation,
570 ArrayRef<TemplateArgument> TemplateArgs,
571 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
573 SemaRef,
574 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
575 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
576 TemplateArgs, &DeductionInfo) {}
577
579 Sema &SemaRef, SourceLocation PointOfInstantiation,
581 ArrayRef<TemplateArgument> TemplateArgs,
582 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
584 SemaRef,
585 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
586 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
587 TemplateArgs, &DeductionInfo) {}
588
590 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
591 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
593 SemaRef,
594 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
595 PointOfInstantiation, InstantiationRange, Param, nullptr,
596 TemplateArgs) {}
597
599 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
601 SourceRange InstantiationRange)
603 SemaRef,
604 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
605 PointOfInstantiation, InstantiationRange, Param, Template,
606 TemplateArgs) {}
607
609 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
611 SourceRange InstantiationRange)
613 SemaRef,
614 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
615 PointOfInstantiation, InstantiationRange, Param, Template,
616 TemplateArgs) {}
617
619 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
620 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
621 SourceRange InstantiationRange)
623 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
624 PointOfInstantiation, InstantiationRange, Param, Template,
625 TemplateArgs) {}
626
628 Sema &SemaRef, SourceLocation PointOfInstantiation,
630 SourceRange InstantiationRange)
632 SemaRef, CodeSynthesisContext::RequirementInstantiation,
633 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
634 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
635}
636
638 Sema &SemaRef, SourceLocation PointOfInstantiation,
640 SourceRange InstantiationRange)
642 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
643 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
644 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt) {}
645
647 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
648 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
650 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
651 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
652 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
653}
654
656 Sema &SemaRef, SourceLocation PointOfInstantiation,
657 ConstraintsCheck, NamedDecl *Template,
658 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
661 PointOfInstantiation, InstantiationRange, Template, nullptr,
662 TemplateArgs) {}
663
665 Sema &SemaRef, SourceLocation PointOfInstantiation,
667 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
670 PointOfInstantiation, InstantiationRange, Template, nullptr,
671 {}, &DeductionInfo) {}
672
674 Sema &SemaRef, SourceLocation PointOfInstantiation,
676 SourceRange InstantiationRange)
679 PointOfInstantiation, InstantiationRange, Template) {}
680
682 Sema &SemaRef, SourceLocation PointOfInstantiation,
684 SourceRange InstantiationRange)
687 PointOfInstantiation, InstantiationRange, Template) {}
688
690 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
691 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
693 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
694 PointOfInstantiation, InstantiationRange, Entity) {}
695
696
700
701 CodeSynthesisContexts.push_back(Ctx);
702
703 if (!Ctx.isInstantiationRecord())
705
706 // Check to see if we're low on stack space. We can't do anything about this
707 // from here, but we can at least warn the user.
710}
711
713 auto &Active = CodeSynthesisContexts.back();
714 if (!Active.isInstantiationRecord()) {
715 assert(NonInstantiationEntries > 0);
717 }
718
719 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
720
721 // Name lookup no longer looks in this template's defining module.
722 assert(CodeSynthesisContexts.size() >=
724 "forgot to remove a lookup module for a template instantiation");
725 if (CodeSynthesisContexts.size() ==
728 LookupModulesCache.erase(M);
730 }
731
732 // If we've left the code synthesis context for the current context stack,
733 // stop remembering that we've emitted that stack.
734 if (CodeSynthesisContexts.size() ==
737
738 CodeSynthesisContexts.pop_back();
739}
740
742 if (!Invalid) {
743 if (!AlreadyInstantiating) {
744 auto &Active = SemaRef.CodeSynthesisContexts.back();
745 if (Active.Entity)
746 SemaRef.InstantiatingSpecializations.erase(
747 {Active.Entity->getCanonicalDecl(), Active.Kind});
748 }
749
750 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
751 SemaRef.CodeSynthesisContexts.back());
752
753 SemaRef.popCodeSynthesisContext();
754 Invalid = true;
755 }
756}
757
758static std::string convertCallArgsToString(Sema &S,
760 std::string Result;
761 llvm::raw_string_ostream OS(Result);
762 llvm::ListSeparator Comma;
763 for (const Expr *Arg : Args) {
764 OS << Comma;
765 Arg->IgnoreParens()->printPretty(OS, nullptr,
767 }
768 return Result;
769}
770
771bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
772 SourceLocation PointOfInstantiation,
773 SourceRange InstantiationRange) {
774 assert(SemaRef.NonInstantiationEntries <=
775 SemaRef.CodeSynthesisContexts.size());
776 if ((SemaRef.CodeSynthesisContexts.size() -
778 <= SemaRef.getLangOpts().InstantiationDepth)
779 return false;
780
781 SemaRef.Diag(PointOfInstantiation,
782 diag::err_template_recursion_depth_exceeded)
783 << SemaRef.getLangOpts().InstantiationDepth
784 << InstantiationRange;
785 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
786 << SemaRef.getLangOpts().InstantiationDepth;
787 return true;
788}
789
790/// Prints the current instantiation stack through a series of
791/// notes.
793 // Determine which template instantiations to skip, if any.
794 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
795 unsigned Limit = Diags.getTemplateBacktraceLimit();
796 if (Limit && Limit < CodeSynthesisContexts.size()) {
797 SkipStart = Limit / 2 + Limit % 2;
798 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
799 }
800
801 // FIXME: In all of these cases, we need to show the template arguments
802 unsigned InstantiationIdx = 0;
804 Active = CodeSynthesisContexts.rbegin(),
805 ActiveEnd = CodeSynthesisContexts.rend();
806 Active != ActiveEnd;
807 ++Active, ++InstantiationIdx) {
808 // Skip this instantiation?
809 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
810 if (InstantiationIdx == SkipStart) {
811 // Note that we're skipping instantiations.
812 Diags.Report(Active->PointOfInstantiation,
813 diag::note_instantiation_contexts_suppressed)
814 << unsigned(CodeSynthesisContexts.size() - Limit);
815 }
816 continue;
817 }
818
819 switch (Active->Kind) {
821 Decl *D = Active->Entity;
822 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
823 unsigned DiagID = diag::note_template_member_class_here;
824 if (isa<ClassTemplateSpecializationDecl>(Record))
825 DiagID = diag::note_template_class_instantiation_here;
826 Diags.Report(Active->PointOfInstantiation, DiagID)
827 << Record << Active->InstantiationRange;
828 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
829 unsigned DiagID;
830 if (Function->getPrimaryTemplate())
831 DiagID = diag::note_function_template_spec_here;
832 else
833 DiagID = diag::note_template_member_function_here;
834 Diags.Report(Active->PointOfInstantiation, DiagID)
835 << Function
836 << Active->InstantiationRange;
837 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
838 Diags.Report(Active->PointOfInstantiation,
839 VD->isStaticDataMember()?
840 diag::note_template_static_data_member_def_here
841 : diag::note_template_variable_def_here)
842 << VD
843 << Active->InstantiationRange;
844 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
845 Diags.Report(Active->PointOfInstantiation,
846 diag::note_template_enum_def_here)
847 << ED
848 << Active->InstantiationRange;
849 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
850 Diags.Report(Active->PointOfInstantiation,
851 diag::note_template_nsdmi_here)
852 << FD << Active->InstantiationRange;
853 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
854 Diags.Report(Active->PointOfInstantiation,
855 diag::note_template_class_instantiation_here)
856 << CTD << Active->InstantiationRange;
857 } else {
858 Diags.Report(Active->PointOfInstantiation,
859 diag::note_template_type_alias_instantiation_here)
860 << cast<TypeAliasTemplateDecl>(D)
861 << Active->InstantiationRange;
862 }
863 break;
864 }
865
867 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
868 SmallString<128> TemplateArgsStr;
869 llvm::raw_svector_ostream OS(TemplateArgsStr);
870 Template->printName(OS, getPrintingPolicy());
871 printTemplateArgumentList(OS, Active->template_arguments(),
873 Diags.Report(Active->PointOfInstantiation,
874 diag::note_default_arg_instantiation_here)
875 << OS.str()
876 << Active->InstantiationRange;
877 break;
878 }
879
881 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
882 Diags.Report(Active->PointOfInstantiation,
883 diag::note_explicit_template_arg_substitution_here)
884 << FnTmpl
886 Active->TemplateArgs,
887 Active->NumTemplateArgs)
888 << Active->InstantiationRange;
889 break;
890 }
891
893 if (FunctionTemplateDecl *FnTmpl =
894 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
895 Diags.Report(Active->PointOfInstantiation,
896 diag::note_function_template_deduction_instantiation_here)
897 << FnTmpl
898 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
899 Active->TemplateArgs,
900 Active->NumTemplateArgs)
901 << Active->InstantiationRange;
902 } else {
903 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
904 isa<VarTemplateSpecializationDecl>(Active->Entity);
905 bool IsTemplate = false;
906 TemplateParameterList *Params;
907 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
908 IsTemplate = true;
909 Params = D->getTemplateParameters();
910 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
911 Active->Entity)) {
912 Params = D->getTemplateParameters();
913 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
914 Active->Entity)) {
915 Params = D->getTemplateParameters();
916 } else {
917 llvm_unreachable("unexpected template kind");
918 }
919
920 Diags.Report(Active->PointOfInstantiation,
921 diag::note_deduced_template_arg_substitution_here)
922 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
923 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
924 Active->NumTemplateArgs)
925 << Active->InstantiationRange;
926 }
927 break;
928 }
929
931 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
932 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
933
934 SmallString<128> TemplateArgsStr;
935 llvm::raw_svector_ostream OS(TemplateArgsStr);
937 printTemplateArgumentList(OS, Active->template_arguments(),
939 Diags.Report(Active->PointOfInstantiation,
940 diag::note_default_function_arg_instantiation_here)
941 << OS.str()
942 << Active->InstantiationRange;
943 break;
944 }
945
947 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
948 std::string Name;
949 if (!Parm->getName().empty())
950 Name = std::string(" '") + Parm->getName().str() + "'";
951
952 TemplateParameterList *TemplateParams = nullptr;
953 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
954 TemplateParams = Template->getTemplateParameters();
955 else
956 TemplateParams =
957 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
958 ->getTemplateParameters();
959 Diags.Report(Active->PointOfInstantiation,
960 diag::note_prior_template_arg_substitution)
961 << isa<TemplateTemplateParmDecl>(Parm)
962 << Name
963 << getTemplateArgumentBindingsText(TemplateParams,
964 Active->TemplateArgs,
965 Active->NumTemplateArgs)
966 << Active->InstantiationRange;
967 break;
968 }
969
971 TemplateParameterList *TemplateParams = nullptr;
972 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
973 TemplateParams = Template->getTemplateParameters();
974 else
975 TemplateParams =
976 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
977 ->getTemplateParameters();
978
979 Diags.Report(Active->PointOfInstantiation,
980 diag::note_template_default_arg_checking)
981 << getTemplateArgumentBindingsText(TemplateParams,
982 Active->TemplateArgs,
983 Active->NumTemplateArgs)
984 << Active->InstantiationRange;
985 break;
986 }
987
989 Diags.Report(Active->PointOfInstantiation,
990 diag::note_evaluating_exception_spec_here)
991 << cast<FunctionDecl>(Active->Entity);
992 break;
993
995 Diags.Report(Active->PointOfInstantiation,
996 diag::note_template_exception_spec_instantiation_here)
997 << cast<FunctionDecl>(Active->Entity)
998 << Active->InstantiationRange;
999 break;
1000
1002 Diags.Report(Active->PointOfInstantiation,
1003 diag::note_template_requirement_instantiation_here)
1004 << Active->InstantiationRange;
1005 break;
1007 Diags.Report(Active->PointOfInstantiation,
1008 diag::note_template_requirement_params_instantiation_here)
1009 << Active->InstantiationRange;
1010 break;
1011
1013 Diags.Report(Active->PointOfInstantiation,
1014 diag::note_nested_requirement_here)
1015 << Active->InstantiationRange;
1016 break;
1017
1019 Diags.Report(Active->PointOfInstantiation,
1020 diag::note_in_declaration_of_implicit_special_member)
1021 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
1022 break;
1023
1025 Diags.Report(Active->Entity->getLocation(),
1026 diag::note_in_declaration_of_implicit_equality_comparison);
1027 break;
1028
1030 // FIXME: For synthesized functions that are not defaulted,
1031 // produce a note.
1032 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1035 if (DFK.isSpecialMember()) {
1036 auto *MD = cast<CXXMethodDecl>(FD);
1037 Diags.Report(Active->PointOfInstantiation,
1038 diag::note_member_synthesized_at)
1039 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
1040 << Context.getTagDeclType(MD->getParent());
1041 } else if (DFK.isComparison()) {
1042 QualType RecordType = FD->getParamDecl(0)
1043 ->getType()
1044 .getNonReferenceType()
1045 .getUnqualifiedType();
1046 Diags.Report(Active->PointOfInstantiation,
1047 diag::note_comparison_synthesized_at)
1048 << (int)DFK.asComparison() << RecordType;
1049 }
1050 break;
1051 }
1052
1054 Diags.Report(Active->Entity->getLocation(),
1055 diag::note_rewriting_operator_as_spaceship);
1056 break;
1057
1059 Diags.Report(Active->PointOfInstantiation,
1060 diag::note_in_binding_decl_init)
1061 << cast<BindingDecl>(Active->Entity);
1062 break;
1063
1065 Diags.Report(Active->PointOfInstantiation,
1066 diag::note_due_to_dllexported_class)
1067 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
1068 break;
1069
1071 Diags.Report(Active->PointOfInstantiation,
1072 diag::note_building_builtin_dump_struct_call)
1074 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
1075 break;
1076
1078 break;
1079
1081 Diags.Report(Active->PointOfInstantiation,
1082 diag::note_lambda_substitution_here);
1083 break;
1085 unsigned DiagID = 0;
1086 if (!Active->Entity) {
1087 Diags.Report(Active->PointOfInstantiation,
1088 diag::note_nested_requirement_here)
1089 << Active->InstantiationRange;
1090 break;
1091 }
1092 if (isa<ConceptDecl>(Active->Entity))
1093 DiagID = diag::note_concept_specialization_here;
1094 else if (isa<TemplateDecl>(Active->Entity))
1095 DiagID = diag::note_checking_constraints_for_template_id_here;
1096 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1097 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1098 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1099 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1100 else {
1101 assert(isa<FunctionDecl>(Active->Entity));
1102 DiagID = diag::note_checking_constraints_for_function_here;
1103 }
1104 SmallString<128> TemplateArgsStr;
1105 llvm::raw_svector_ostream OS(TemplateArgsStr);
1106 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1107 if (!isa<FunctionDecl>(Active->Entity)) {
1108 printTemplateArgumentList(OS, Active->template_arguments(),
1110 }
1111 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
1112 << Active->InstantiationRange;
1113 break;
1114 }
1116 Diags.Report(Active->PointOfInstantiation,
1117 diag::note_constraint_substitution_here)
1118 << Active->InstantiationRange;
1119 break;
1121 Diags.Report(Active->PointOfInstantiation,
1122 diag::note_constraint_normalization_here)
1123 << cast<NamedDecl>(Active->Entity)->getName()
1124 << Active->InstantiationRange;
1125 break;
1127 Diags.Report(Active->PointOfInstantiation,
1128 diag::note_parameter_mapping_substitution_here)
1129 << Active->InstantiationRange;
1130 break;
1132 Diags.Report(Active->PointOfInstantiation,
1133 diag::note_building_deduction_guide_here);
1134 break;
1135 }
1136 }
1137}
1138
1139std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1141 return std::optional<TemplateDeductionInfo *>(nullptr);
1142
1144 Active = CodeSynthesisContexts.rbegin(),
1145 ActiveEnd = CodeSynthesisContexts.rend();
1146 Active != ActiveEnd;
1147 ++Active)
1148 {
1149 switch (Active->Kind) {
1151 // An instantiation of an alias template may or may not be a SFINAE
1152 // context, depending on what else is on the stack.
1153 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1154 break;
1155 [[fallthrough]];
1162 // This is a template instantiation, so there is no SFINAE.
1163 return std::nullopt;
1165 // [temp.deduct]p9
1166 // A lambda-expression appearing in a function type or a template
1167 // parameter is not considered part of the immediate context for the
1168 // purposes of template argument deduction.
1169 // CWG2672: A lambda-expression body is never in the immediate context.
1170 return std::nullopt;
1171
1176 // A default template argument instantiation and substitution into
1177 // template parameters with arguments for prior parameters may or may
1178 // not be a SFINAE context; look further up the stack.
1179 break;
1180
1183 // We're either substituting explicitly-specified template arguments,
1184 // deduced template arguments. SFINAE applies unless we are in a lambda
1185 // body, see [temp.deduct]p9.
1189 // SFINAE always applies in a constraint expression or a requirement
1190 // in a requires expression.
1191 assert(Active->DeductionInfo && "Missing deduction info pointer");
1192 return Active->DeductionInfo;
1193
1201 // This happens in a context unrelated to template instantiation, so
1202 // there is no SFINAE.
1203 return std::nullopt;
1204
1206 // FIXME: This should not be treated as a SFINAE context, because
1207 // we will cache an incorrect exception specification. However, clang
1208 // bootstrap relies this! See PR31692.
1209 break;
1210
1212 break;
1213 }
1214
1215 // The inner context was transparent for SFINAE. If it occurred within a
1216 // non-instantiation SFINAE context, then SFINAE applies.
1217 if (Active->SavedInNonInstantiationSFINAEContext)
1218 return std::optional<TemplateDeductionInfo *>(nullptr);
1219 }
1220
1221 return std::nullopt;
1222}
1223
1224//===----------------------------------------------------------------------===/
1225// Template Instantiation for Types
1226//===----------------------------------------------------------------------===/
1227namespace {
1228 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1229 const MultiLevelTemplateArgumentList &TemplateArgs;
1230 SourceLocation Loc;
1231 DeclarationName Entity;
1232 // Whether to evaluate the C++20 constraints or simply substitute into them.
1233 bool EvaluateConstraints = true;
1234
1235 public:
1236 typedef TreeTransform<TemplateInstantiator> inherited;
1237
1238 TemplateInstantiator(Sema &SemaRef,
1239 const MultiLevelTemplateArgumentList &TemplateArgs,
1240 SourceLocation Loc, DeclarationName Entity)
1241 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1242 Entity(Entity) {}
1243
1244 void setEvaluateConstraints(bool B) {
1245 EvaluateConstraints = B;
1246 }
1247 bool getEvaluateConstraints() {
1248 return EvaluateConstraints;
1249 }
1250
1251 /// Determine whether the given type \p T has already been
1252 /// transformed.
1253 ///
1254 /// For the purposes of template instantiation, a type has already been
1255 /// transformed if it is NULL or if it is not dependent.
1256 bool AlreadyTransformed(QualType T);
1257
1258 /// Returns the location of the entity being instantiated, if known.
1259 SourceLocation getBaseLocation() { return Loc; }
1260
1261 /// Returns the name of the entity being instantiated, if any.
1262 DeclarationName getBaseEntity() { return Entity; }
1263
1264 /// Sets the "base" location and entity when that
1265 /// information is known based on another transformation.
1266 void setBase(SourceLocation Loc, DeclarationName Entity) {
1267 this->Loc = Loc;
1268 this->Entity = Entity;
1269 }
1270
1271 unsigned TransformTemplateDepth(unsigned Depth) {
1272 return TemplateArgs.getNewDepth(Depth);
1273 }
1274
1275 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1276 int Index = getSema().ArgumentPackSubstitutionIndex;
1277 if (Index == -1)
1278 return std::nullopt;
1279 return Pack.pack_size() - 1 - Index;
1280 }
1281
1282 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1283 SourceRange PatternRange,
1285 bool &ShouldExpand, bool &RetainExpansion,
1286 std::optional<unsigned> &NumExpansions) {
1287 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1288 PatternRange, Unexpanded,
1289 TemplateArgs,
1290 ShouldExpand,
1291 RetainExpansion,
1292 NumExpansions);
1293 }
1294
1295 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1297 }
1298
1299 TemplateArgument ForgetPartiallySubstitutedPack() {
1300 TemplateArgument Result;
1301 if (NamedDecl *PartialPack
1303 MultiLevelTemplateArgumentList &TemplateArgs
1304 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1305 unsigned Depth, Index;
1306 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1307 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1308 Result = TemplateArgs(Depth, Index);
1309 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1310 }
1311 }
1312
1313 return Result;
1314 }
1315
1316 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1317 if (Arg.isNull())
1318 return;
1319
1320 if (NamedDecl *PartialPack
1322 MultiLevelTemplateArgumentList &TemplateArgs
1323 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1324 unsigned Depth, Index;
1325 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1326 TemplateArgs.setArgument(Depth, Index, Arg);
1327 }
1328 }
1329
1330 /// Transform the given declaration by instantiating a reference to
1331 /// this declaration.
1332 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1333
1334 void transformAttrs(Decl *Old, Decl *New) {
1335 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1336 }
1337
1338 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1339 if (Old->isParameterPack()) {
1341 for (auto *New : NewDecls)
1343 Old, cast<VarDecl>(New));
1344 return;
1345 }
1346
1347 assert(NewDecls.size() == 1 &&
1348 "should only have multiple expansions for a pack");
1349 Decl *New = NewDecls.front();
1350
1351 // If we've instantiated the call operator of a lambda or the call
1352 // operator template of a generic lambda, update the "instantiation of"
1353 // information.
1354 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1355 if (NewMD && isLambdaCallOperator(NewMD)) {
1356 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1357 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1358 NewTD->setInstantiatedFromMemberTemplate(
1359 OldMD->getDescribedFunctionTemplate());
1360 else
1361 NewMD->setInstantiationOfMemberFunction(OldMD,
1363 }
1364
1366
1367 // We recreated a local declaration, but not by instantiating it. There
1368 // may be pending dependent diagnostics to produce.
1369 if (auto *DC = dyn_cast<DeclContext>(Old);
1370 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1371 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1372 }
1373
1374 /// Transform the definition of the given declaration by
1375 /// instantiating it.
1376 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1377
1378 /// Transform the first qualifier within a scope by instantiating the
1379 /// declaration.
1380 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1381
1382 bool TransformExceptionSpec(SourceLocation Loc,
1384 SmallVectorImpl<QualType> &Exceptions,
1385 bool &Changed);
1386
1387 /// Rebuild the exception declaration and register the declaration
1388 /// as an instantiated local.
1389 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1391 SourceLocation StartLoc,
1392 SourceLocation NameLoc,
1393 IdentifierInfo *Name);
1394
1395 /// Rebuild the Objective-C exception declaration and register the
1396 /// declaration as an instantiated local.
1397 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1398 TypeSourceInfo *TSInfo, QualType T);
1399
1400 /// Check for tag mismatches when instantiating an
1401 /// elaborated type.
1402 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1403 ElaboratedTypeKeyword Keyword,
1404 NestedNameSpecifierLoc QualifierLoc,
1405 QualType T);
1406
1408 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1409 SourceLocation NameLoc,
1410 QualType ObjectType = QualType(),
1411 NamedDecl *FirstQualifierInScope = nullptr,
1412 bool AllowInjectedClassName = false);
1413
1414 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1415 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1416 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1417 const Stmt *InstS,
1418 const NoInlineAttr *A);
1419 const AlwaysInlineAttr *
1420 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1421 const AlwaysInlineAttr *A);
1422 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1423 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1424 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1425 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1426
1427 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1429 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1431 ExprResult TransformSubstNonTypeTemplateParmExpr(
1433
1434 /// Rebuild a DeclRefExpr for a VarDecl reference.
1435 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1436
1437 /// Transform a reference to a function or init-capture parameter pack.
1438 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1439
1440 /// Transform a FunctionParmPackExpr which was built when we couldn't
1441 /// expand a function parameter pack reference which refers to an expanded
1442 /// pack.
1443 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1444
1445 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1447 // Call the base version; it will forward to our overridden version below.
1448 return inherited::TransformFunctionProtoType(TLB, TL);
1449 }
1450
1451 QualType TransformInjectedClassNameType(TypeLocBuilder &TLB,
1453 auto Type = inherited::TransformInjectedClassNameType(TLB, TL);
1454 // Special case for transforming a deduction guide, we return a
1455 // transformed TemplateSpecializationType.
1456 if (Type.isNull() &&
1457 SemaRef.CodeSynthesisContexts.back().Kind ==
1459 // Return a TemplateSpecializationType for transforming a deduction
1460 // guide.
1461 if (auto *ICT = TL.getType()->getAs<InjectedClassNameType>()) {
1462 auto Type =
1463 inherited::TransformType(ICT->getInjectedSpecializationType());
1464 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1465 return Type;
1466 }
1467 }
1468 return Type;
1469 }
1470 // Override the default version to handle a rewrite-template-arg-pack case
1471 // for building a deduction guide.
1472 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1473 TemplateArgumentLoc &Output,
1474 bool Uneval = false) {
1475 const TemplateArgument &Arg = Input.getArgument();
1476 std::vector<TemplateArgument> TArgs;
1477 switch (Arg.getKind()) {
1479 // Literally rewrite the template argument pack, instead of unpacking
1480 // it.
1481 assert(
1482 SemaRef.CodeSynthesisContexts.back().Kind ==
1484 "Transforming a template argument pack is only allowed in building "
1485 "deduction guide");
1486 for (auto &pack : Arg.getPackAsArray()) {
1488 pack, QualType(), SourceLocation{});
1489 TemplateArgumentLoc Output;
1490 if (SemaRef.SubstTemplateArgument(Input, TemplateArgs, Output))
1491 return true; // fails
1492 TArgs.push_back(Output.getArgument());
1493 }
1494 Output = SemaRef.getTrivialTemplateArgumentLoc(
1495 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1497 return false;
1498 default:
1499 break;
1500 }
1501 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1502 }
1503
1504 template<typename Fn>
1505 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1507 CXXRecordDecl *ThisContext,
1508 Qualifiers ThisTypeQuals,
1509 Fn TransformExceptionSpec);
1510
1511 ParmVarDecl *
1512 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1513 std::optional<unsigned> NumExpansions,
1514 bool ExpectParameterPack);
1515
1516 using inherited::TransformTemplateTypeParmType;
1517 /// Transforms a template type parameter type by performing
1518 /// substitution of the corresponding template type argument.
1519 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1521 bool SuppressObjCLifetime);
1522
1523 QualType BuildSubstTemplateTypeParmType(
1524 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1525 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1526 TemplateArgument Arg, SourceLocation NameLoc);
1527
1528 /// Transforms an already-substituted template type parameter pack
1529 /// into either itself (if we aren't substituting into its pack expansion)
1530 /// or the appropriate substituted argument.
1531 using inherited::TransformSubstTemplateTypeParmPackType;
1532 QualType
1533 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1535 bool SuppressObjCLifetime);
1536
1537 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1538 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1540
1541 ExprResult Result = inherited::TransformLambdaExpr(E);
1542 if (Result.isInvalid())
1543 return Result;
1544
1545 CXXMethodDecl *MD = Result.getAs<LambdaExpr>()->getCallOperator();
1546 for (ParmVarDecl *PVD : MD->parameters()) {
1547 assert(PVD && "null in a parameter list");
1548 if (!PVD->hasDefaultArg())
1549 continue;
1550 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1551 // FIXME: Obtain the source location for the '=' token.
1552 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1553 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1554 // If substitution fails, the default argument is set to a
1555 // RecoveryExpr that wraps the uninstantiated default argument so
1556 // that downstream diagnostics are omitted.
1557 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1558 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
1559 { UninstExpr }, UninstExpr->getType());
1560 if (ErrorResult.isUsable())
1561 PVD->setDefaultArg(ErrorResult.get());
1562 }
1563 }
1564
1565 return Result;
1566 }
1567
1568 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1569 // Currently, we instantiate the body when instantiating the lambda
1570 // expression. However, `EvaluateConstraints` is disabled during the
1571 // instantiation of the lambda expression, causing the instantiation
1572 // failure of the return type requirement in the body. If p0588r1 is fully
1573 // implemented, the body will be lazily instantiated, and this problem
1574 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1575 // `true` to temporarily fix this issue.
1576 // FIXME: This temporary fix can be removed after fully implementing
1577 // p0588r1.
1578 bool Prev = EvaluateConstraints;
1579 EvaluateConstraints = true;
1580 StmtResult Stmt = inherited::TransformLambdaBody(E, Body);
1581 EvaluateConstraints = Prev;
1582 return Stmt;
1583 }
1584
1585 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1586 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1587 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1588 if (TransReq.isInvalid())
1589 return TransReq;
1590 assert(TransReq.get() != E &&
1591 "Do not change value of isSatisfied for the existing expression. "
1592 "Create a new expression instead.");
1593 if (E->getBody()->isDependentContext()) {
1594 Sema::SFINAETrap Trap(SemaRef);
1595 // We recreate the RequiresExpr body, but not by instantiating it.
1596 // Produce pending diagnostics for dependent access check.
1597 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1598 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1599 if (Trap.hasErrorOccurred())
1600 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1601 }
1602 return TransReq;
1603 }
1604
1605 bool TransformRequiresExprRequirements(
1608 bool SatisfactionDetermined = false;
1609 for (concepts::Requirement *Req : Reqs) {
1610 concepts::Requirement *TransReq = nullptr;
1611 if (!SatisfactionDetermined) {
1612 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1613 TransReq = TransformTypeRequirement(TypeReq);
1614 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1615 TransReq = TransformExprRequirement(ExprReq);
1616 else
1617 TransReq = TransformNestedRequirement(
1618 cast<concepts::NestedRequirement>(Req));
1619 if (!TransReq)
1620 return true;
1621 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1622 // [expr.prim.req]p6
1623 // [...] The substitution and semantic constraint checking
1624 // proceeds in lexical order and stops when a condition that
1625 // determines the result of the requires-expression is
1626 // encountered. [..]
1627 SatisfactionDetermined = true;
1628 } else
1629 TransReq = Req;
1630 Transformed.push_back(TransReq);
1631 }
1632 return false;
1633 }
1634
1635 TemplateParameterList *TransformTemplateParameterList(
1636 TemplateParameterList *OrigTPL) {
1637 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1638
1639 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1640 TemplateDeclInstantiator DeclInstantiator(getSema(),
1641 /* DeclContext *Owner */ Owner, TemplateArgs);
1642 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1643 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1644 }
1645
1647 TransformTypeRequirement(concepts::TypeRequirement *Req);
1649 TransformExprRequirement(concepts::ExprRequirement *Req);
1651 TransformNestedRequirement(concepts::NestedRequirement *Req);
1652 ExprResult TransformRequiresTypeParams(
1653 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1656 SmallVectorImpl<ParmVarDecl *> &TransParams,
1658
1659 private:
1661 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1662 const NonTypeTemplateParmDecl *parm,
1664 std::optional<unsigned> PackIndex);
1665 };
1666}
1667
1668bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1669 if (T.isNull())
1670 return true;
1671
1673 return false;
1674
1675 getSema().MarkDeclarationsReferencedInType(Loc, T);
1676 return true;
1677}
1678
1679static TemplateArgument
1681 assert(S.ArgumentPackSubstitutionIndex >= 0);
1682 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1684 if (Arg.isPackExpansion())
1685 Arg = Arg.getPackExpansionPattern();
1686 return Arg;
1687}
1688
1689Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1690 if (!D)
1691 return nullptr;
1692
1693 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1694 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1695 // If the corresponding template argument is NULL or non-existent, it's
1696 // because we are performing instantiation from explicitly-specified
1697 // template arguments in a function template, but there were some
1698 // arguments left unspecified.
1699 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1700 TTP->getPosition()))
1701 return D;
1702
1703 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1704
1705 if (TTP->isParameterPack()) {
1706 assert(Arg.getKind() == TemplateArgument::Pack &&
1707 "Missing argument pack");
1708 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1709 }
1710
1712 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1713 "Wrong kind of template template argument");
1714 return Template.getAsTemplateDecl();
1715 }
1716
1717 // Fall through to find the instantiated declaration for this template
1718 // template parameter.
1719 }
1720
1721 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1722}
1723
1724Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1725 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1726 if (!Inst)
1727 return nullptr;
1728
1729 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1730 return Inst;
1731}
1732
1733bool TemplateInstantiator::TransformExceptionSpec(
1735 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1736 if (ESI.Type == EST_Uninstantiated) {
1737 ESI.instantiate();
1738 Changed = true;
1739 }
1740 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1741}
1742
1743NamedDecl *
1744TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1745 SourceLocation Loc) {
1746 // If the first part of the nested-name-specifier was a template type
1747 // parameter, instantiate that type parameter down to a tag type.
1748 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1749 const TemplateTypeParmType *TTP
1750 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1751
1752 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1753 // FIXME: This needs testing w/ member access expressions.
1754 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1755
1756 if (TTP->isParameterPack()) {
1757 assert(Arg.getKind() == TemplateArgument::Pack &&
1758 "Missing argument pack");
1759
1760 if (getSema().ArgumentPackSubstitutionIndex == -1)
1761 return nullptr;
1762
1763 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1764 }
1765
1766 QualType T = Arg.getAsType();
1767 if (T.isNull())
1768 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1769
1770 if (const TagType *Tag = T->getAs<TagType>())
1771 return Tag->getDecl();
1772
1773 // The resulting type is not a tag; complain.
1774 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1775 return nullptr;
1776 }
1777 }
1778
1779 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1780}
1781
1782VarDecl *
1783TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1785 SourceLocation StartLoc,
1786 SourceLocation NameLoc,
1787 IdentifierInfo *Name) {
1788 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1789 StartLoc, NameLoc, Name);
1790 if (Var)
1791 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1792 return Var;
1793}
1794
1795VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1796 TypeSourceInfo *TSInfo,
1797 QualType T) {
1798 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1799 if (Var)
1800 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1801 return Var;
1802}
1803
1805TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1806 ElaboratedTypeKeyword Keyword,
1807 NestedNameSpecifierLoc QualifierLoc,
1808 QualType T) {
1809 if (const TagType *TT = T->getAs<TagType>()) {
1810 TagDecl* TD = TT->getDecl();
1811
1812 SourceLocation TagLocation = KeywordLoc;
1813
1815
1816 // TODO: should we even warn on struct/class mismatches for this? Seems
1817 // like it's likely to produce a lot of spurious errors.
1818 if (Id && Keyword != ElaboratedTypeKeyword::None &&
1821 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1822 TagLocation, Id)) {
1823 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1824 << Id
1826 TD->getKindName());
1827 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1828 }
1829 }
1830 }
1831
1832 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
1833}
1834
1835TemplateName TemplateInstantiator::TransformTemplateName(
1836 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1837 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1838 bool AllowInjectedClassName) {
1840 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1841 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1842 // If the corresponding template argument is NULL or non-existent, it's
1843 // because we are performing instantiation from explicitly-specified
1844 // template arguments in a function template, but there were some
1845 // arguments left unspecified.
1846 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1847 TTP->getPosition()))
1848 return Name;
1849
1850 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1851
1852 if (TemplateArgs.isRewrite()) {
1853 // We're rewriting the template parameter as a reference to another
1854 // template parameter.
1855 if (Arg.getKind() == TemplateArgument::Pack) {
1856 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1857 "unexpected pack arguments in template rewrite");
1858 Arg = Arg.pack_begin()->getPackExpansionPattern();
1859 }
1860 assert(Arg.getKind() == TemplateArgument::Template &&
1861 "unexpected nontype template argument kind in template rewrite");
1862 return Arg.getAsTemplate();
1863 }
1864
1865 auto [AssociatedDecl, Final] =
1866 TemplateArgs.getAssociatedDecl(TTP->getDepth());
1867 std::optional<unsigned> PackIndex;
1868 if (TTP->isParameterPack()) {
1869 assert(Arg.getKind() == TemplateArgument::Pack &&
1870 "Missing argument pack");
1871
1872 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1873 // We have the template argument pack to substitute, but we're not
1874 // actually expanding the enclosing pack expansion yet. So, just
1875 // keep the entire argument pack.
1876 return getSema().Context.getSubstTemplateTemplateParmPack(
1877 Arg, AssociatedDecl, TTP->getIndex(), Final);
1878 }
1879
1880 PackIndex = getPackIndex(Arg);
1881 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1882 }
1883
1885 assert(!Template.isNull() && "Null template template argument");
1886 assert(!Template.getAsQualifiedTemplateName() &&
1887 "template decl to substitute is qualified?");
1888
1889 if (Final)
1890 return Template;
1891 return getSema().Context.getSubstTemplateTemplateParm(
1892 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
1893 }
1894 }
1895
1897 = Name.getAsSubstTemplateTemplateParmPack()) {
1898 if (getSema().ArgumentPackSubstitutionIndex == -1)
1899 return Name;
1900
1901 TemplateArgument Pack = SubstPack->getArgumentPack();
1902 TemplateName Template =
1904 if (SubstPack->getFinal())
1905 return Template;
1906 return getSema().Context.getSubstTemplateTemplateParm(
1907 Template.getNameToSubstitute(), SubstPack->getAssociatedDecl(),
1908 SubstPack->getIndex(), getPackIndex(Pack));
1909 }
1910
1911 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1912 FirstQualifierInScope,
1913 AllowInjectedClassName);
1914}
1915
1917TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1918 if (!E->isTypeDependent())
1919 return E;
1920
1921 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1922}
1923
1925TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1927 // If the corresponding template argument is NULL or non-existent, it's
1928 // because we are performing instantiation from explicitly-specified
1929 // template arguments in a function template, but there were some
1930 // arguments left unspecified.
1931 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1932 NTTP->getPosition()))
1933 return E;
1934
1935 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1936
1937 if (TemplateArgs.isRewrite()) {
1938 // We're rewriting the template parameter as a reference to another
1939 // template parameter.
1940 if (Arg.getKind() == TemplateArgument::Pack) {
1941 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1942 "unexpected pack arguments in template rewrite");
1943 Arg = Arg.pack_begin()->getPackExpansionPattern();
1944 }
1945 assert(Arg.getKind() == TemplateArgument::Expression &&
1946 "unexpected nontype template argument kind in template rewrite");
1947 // FIXME: This can lead to the same subexpression appearing multiple times
1948 // in a complete expression.
1949 return Arg.getAsExpr();
1950 }
1951
1952 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
1953 std::optional<unsigned> PackIndex;
1954 if (NTTP->isParameterPack()) {
1955 assert(Arg.getKind() == TemplateArgument::Pack &&
1956 "Missing argument pack");
1957
1958 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1959 // We have an argument pack, but we can't select a particular argument
1960 // out of it yet. Therefore, we'll build an expression to hold on to that
1961 // argument pack.
1962 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1963 E->getLocation(),
1964 NTTP->getDeclName());
1965 if (TargetType.isNull())
1966 return ExprError();
1967
1968 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
1969 if (TargetType->isRecordType())
1970 ExprType.addConst();
1971 // FIXME: Pass in Final.
1972 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1973 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
1974 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
1975 }
1976 PackIndex = getPackIndex(Arg);
1977 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1978 }
1979 // FIXME: Don't put subst node on Final replacement.
1980 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
1981 Arg, PackIndex);
1982}
1983
1984const CXXAssumeAttr *
1985TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
1986 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
1987 if (!Res.isUsable())
1988 return AA;
1989
1990 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
1991 AA->getRange());
1992 if (!Res.isUsable())
1993 return AA;
1994
1995 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
1996 AA->getRange());
1997}
1998
1999const LoopHintAttr *
2000TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2001 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2002
2003 if (TransformedExpr == LH->getValue())
2004 return LH;
2005
2006 // Generate error if there is a problem with the value.
2007 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
2008 return LH;
2009
2010 // Create new LoopHintValueAttr with integral expression in place of the
2011 // non-type template parameter.
2012 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
2013 LH->getState(), TransformedExpr, *LH);
2014}
2015const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2016 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2017 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2018 return nullptr;
2019
2020 return A;
2021}
2022const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2023 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2024 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2025 return nullptr;
2026
2027 return A;
2028}
2029
2030const CodeAlignAttr *
2031TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2032 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2033 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2034}
2035
2036ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
2037 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
2039 std::optional<unsigned> PackIndex) {
2040 ExprResult result;
2041
2042 // Determine the substituted parameter type. We can usually infer this from
2043 // the template argument, but not always.
2044 auto SubstParamType = [&] {
2045 QualType T;
2046 if (parm->isExpandedParameterPack())
2048 else
2049 T = parm->getType();
2050 if (parm->isParameterPack() && isa<PackExpansionType>(T))
2051 T = cast<PackExpansionType>(T)->getPattern();
2052 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
2053 };
2054
2055 bool refParam = false;
2056
2057 // The template argument itself might be an expression, in which case we just
2058 // return that expression. This happens when substituting into an alias
2059 // template.
2060 if (arg.getKind() == TemplateArgument::Expression) {
2061 Expr *argExpr = arg.getAsExpr();
2062 result = argExpr;
2063 if (argExpr->isLValue()) {
2064 if (argExpr->getType()->isRecordType()) {
2065 // Check whether the parameter was actually a reference.
2066 QualType paramType = SubstParamType();
2067 if (paramType.isNull())
2068 return ExprError();
2069 refParam = paramType->isReferenceType();
2070 } else {
2071 refParam = true;
2072 }
2073 }
2074 } else if (arg.getKind() == TemplateArgument::Declaration ||
2075 arg.getKind() == TemplateArgument::NullPtr) {
2076 if (arg.getKind() == TemplateArgument::Declaration) {
2077 ValueDecl *VD = arg.getAsDecl();
2078
2079 // Find the instantiation of the template argument. This is
2080 // required for nested templates.
2081 VD = cast_or_null<ValueDecl>(
2082 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
2083 if (!VD)
2084 return ExprError();
2085 }
2086
2087 QualType paramType = arg.getNonTypeTemplateArgumentType();
2088 assert(!paramType.isNull() && "type substitution failed for param type");
2089 assert(!paramType->isDependentType() && "param type still dependent");
2090 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
2091 refParam = paramType->isReferenceType();
2092 } else {
2093 QualType paramType = arg.getNonTypeTemplateArgumentType();
2094 result = SemaRef.BuildExpressionFromNonTypeTemplateArgument(arg, loc);
2095 refParam = paramType->isReferenceType();
2096 assert(result.isInvalid() ||
2097 SemaRef.Context.hasSameType(result.get()->getType(),
2098 paramType.getNonReferenceType()));
2099 }
2100
2101 if (result.isInvalid())
2102 return ExprError();
2103
2104 Expr *resultExpr = result.get();
2105 // FIXME: Don't put subst node on final replacement.
2106 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
2107 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
2108 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
2109}
2110
2112TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
2114 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2115 // We aren't expanding the parameter pack, so just return ourselves.
2116 return E;
2117 }
2118
2121 // FIXME: Don't put subst node on final replacement.
2122 return transformNonTypeTemplateParmRef(
2124 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
2125}
2126
2128TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
2130 ExprResult SubstReplacement = E->getReplacement();
2131 if (!isa<ConstantExpr>(SubstReplacement.get()))
2132 SubstReplacement = TransformExpr(E->getReplacement());
2133 if (SubstReplacement.isInvalid())
2134 return true;
2135 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
2136 if (SubstType.isNull())
2137 return true;
2138 // The type may have been previously dependent and not now, which means we
2139 // might have to implicit cast the argument to the new type, for example:
2140 // template<auto T, decltype(T) U>
2141 // concept C = sizeof(U) == 4;
2142 // void foo() requires C<2, 'a'> { }
2143 // When normalizing foo(), we first form the normalized constraints of C:
2144 // AtomicExpr(sizeof(U) == 4,
2145 // U=SubstNonTypeTemplateParmExpr(Param=U,
2146 // Expr=DeclRef(U),
2147 // Type=decltype(T)))
2148 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
2149 // produce:
2150 // AtomicExpr(sizeof(U) == 4,
2151 // U=SubstNonTypeTemplateParmExpr(Param=U,
2152 // Expr=ImpCast(
2153 // decltype(2),
2154 // SubstNTTPE(Param=U, Expr='a',
2155 // Type=char)),
2156 // Type=decltype(2)))
2157 // The call to CheckTemplateArgument here produces the ImpCast.
2158 TemplateArgument SugaredConverted, CanonicalConverted;
2159 if (SemaRef
2161 SubstReplacement.get(), SugaredConverted,
2162 CanonicalConverted, Sema::CTAK_Specified)
2163 .isInvalid())
2164 return true;
2165 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
2166 E->getParameter(), E->getExprLoc(),
2167 SugaredConverted, E->getPackIndex());
2168}
2169
2170ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
2171 SourceLocation Loc) {
2172 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2173 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2174}
2175
2177TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2178 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2179 // We can expand this parameter pack now.
2181 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
2182 if (!VD)
2183 return ExprError();
2184 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2185 }
2186
2187 QualType T = TransformType(E->getType());
2188 if (T.isNull())
2189 return ExprError();
2190
2191 // Transform each of the parameter expansions into the corresponding
2192 // parameters in the instantiation of the function decl.
2194 Vars.reserve(E->getNumExpansions());
2195 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2196 I != End; ++I) {
2197 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2198 if (!D)
2199 return ExprError();
2200 Vars.push_back(D);
2201 }
2202
2203 auto *PackExpr =
2205 E->getParameterPackLocation(), Vars);
2206 getSema().MarkFunctionParmPackReferenced(PackExpr);
2207 return PackExpr;
2208}
2209
2211TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2212 VarDecl *PD) {
2213 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2214 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2215 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2216 assert(Found && "no instantiation for parameter pack");
2217
2218 Decl *TransformedDecl;
2219 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2220 // If this is a reference to a function parameter pack which we can
2221 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2222 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2223 QualType T = TransformType(E->getType());
2224 if (T.isNull())
2225 return ExprError();
2226 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2227 E->getExprLoc(), *Pack);
2228 getSema().MarkFunctionParmPackReferenced(PackExpr);
2229 return PackExpr;
2230 }
2231
2232 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2233 } else {
2234 TransformedDecl = Found->get<Decl*>();
2235 }
2236
2237 // We have either an unexpanded pack or a specific expansion.
2238 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2239}
2240
2242TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2243 NamedDecl *D = E->getDecl();
2244
2245 // Handle references to non-type template parameters and non-type template
2246 // parameter packs.
2247 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2248 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2249 return TransformTemplateParmRefExpr(E, NTTP);
2250
2251 // We have a non-type template parameter that isn't fully substituted;
2252 // FindInstantiatedDecl will find it in the local instantiation scope.
2253 }
2254
2255 // Handle references to function parameter packs.
2256 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2257 if (PD->isParameterPack())
2258 return TransformFunctionParmPackRefExpr(E, PD);
2259
2260 return inherited::TransformDeclRefExpr(E);
2261}
2262
2263ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2264 CXXDefaultArgExpr *E) {
2265 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2266 getDescribedFunctionTemplate() &&
2267 "Default arg expressions are never formed in dependent cases.");
2268 return SemaRef.BuildCXXDefaultArgExpr(
2269 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2270 E->getParam());
2271}
2272
2273template<typename Fn>
2274QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2276 CXXRecordDecl *ThisContext,
2277 Qualifiers ThisTypeQuals,
2278 Fn TransformExceptionSpec) {
2279 // We need a local instantiation scope for this function prototype.
2280 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
2281 return inherited::TransformFunctionProtoType(
2282 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2283}
2284
2285ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2286 ParmVarDecl *OldParm, int indexAdjustment,
2287 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2288 auto NewParm = SemaRef.SubstParmVarDecl(
2289 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2290 ExpectParameterPack, EvaluateConstraints);
2291 if (NewParm && SemaRef.getLangOpts().OpenCL)
2292 SemaRef.deduceOpenCLAddressSpace(NewParm);
2293 return NewParm;
2294}
2295
2296QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2297 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2298 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2299 TemplateArgument Arg, SourceLocation NameLoc) {
2300 QualType Replacement = Arg.getAsType();
2301
2302 // If the template parameter had ObjC lifetime qualifiers,
2303 // then any such qualifiers on the replacement type are ignored.
2304 if (SuppressObjCLifetime) {
2305 Qualifiers RQs;
2306 RQs = Replacement.getQualifiers();
2307 RQs.removeObjCLifetime();
2308 Replacement =
2309 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2310 }
2311
2312 if (Final) {
2313 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2314 return Replacement;
2315 }
2316 // TODO: only do this uniquing once, at the start of instantiation.
2317 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2318 Replacement, AssociatedDecl, Index, PackIndex);
2321 NewTL.setNameLoc(NameLoc);
2322 return Result;
2323}
2324
2326TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2328 bool SuppressObjCLifetime) {
2329 const TemplateTypeParmType *T = TL.getTypePtr();
2330 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2331 // Replace the template type parameter with its corresponding
2332 // template argument.
2333
2334 // If the corresponding template argument is NULL or doesn't exist, it's
2335 // because we are performing instantiation from explicitly-specified
2336 // template arguments in a function template class, but there were some
2337 // arguments left unspecified.
2338 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2341 NewTL.setNameLoc(TL.getNameLoc());
2342 return TL.getType();
2343 }
2344
2345 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2346
2347 if (TemplateArgs.isRewrite()) {
2348 // We're rewriting the template parameter as a reference to another
2349 // template parameter.
2350 if (Arg.getKind() == TemplateArgument::Pack) {
2351 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2352 "unexpected pack arguments in template rewrite");
2353 Arg = Arg.pack_begin()->getPackExpansionPattern();
2354 }
2355 assert(Arg.getKind() == TemplateArgument::Type &&
2356 "unexpected nontype template argument kind in template rewrite");
2357 QualType NewT = Arg.getAsType();
2358 assert(isa<TemplateTypeParmType>(NewT) &&
2359 "type parm not rewritten to type parm");
2360 auto NewTL = TLB.push<TemplateTypeParmTypeLoc>(NewT);
2361 NewTL.setNameLoc(TL.getNameLoc());
2362 return NewT;
2363 }
2364
2365 auto [AssociatedDecl, Final] =
2366 TemplateArgs.getAssociatedDecl(T->getDepth());
2367 std::optional<unsigned> PackIndex;
2368 if (T->isParameterPack()) {
2369 assert(Arg.getKind() == TemplateArgument::Pack &&
2370 "Missing argument pack");
2371
2372 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2373 // We have the template argument pack, but we're not expanding the
2374 // enclosing pack expansion yet. Just save the template argument
2375 // pack for later substitution.
2376 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2377 AssociatedDecl, T->getIndex(), Final, Arg);
2380 NewTL.setNameLoc(TL.getNameLoc());
2381 return Result;
2382 }
2383
2384 // PackIndex starts from last element.
2385 PackIndex = getPackIndex(Arg);
2386 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2387 }
2388
2389 assert(Arg.getKind() == TemplateArgument::Type &&
2390 "Template argument kind mismatch");
2391
2392 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2393 AssociatedDecl, T->getIndex(),
2394 PackIndex, Arg, TL.getNameLoc());
2395 }
2396
2397 // The template type parameter comes from an inner template (e.g.,
2398 // the template parameter list of a member template inside the
2399 // template we are instantiating). Create a new template type
2400 // parameter with the template "level" reduced by one.
2401 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2402 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2403 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2404 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2405 QualType Result = getSema().Context.getTemplateTypeParmType(
2406 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2407 T->isParameterPack(), NewTTPDecl);
2409 NewTL.setNameLoc(TL.getNameLoc());
2410 return Result;
2411}
2412
2413QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2415 bool SuppressObjCLifetime) {
2417
2418 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2419
2420 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2421 // We aren't expanding the parameter pack, so just return ourselves.
2422 QualType Result = TL.getType();
2423 if (NewReplaced != T->getAssociatedDecl())
2424 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2425 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2428 NewTL.setNameLoc(TL.getNameLoc());
2429 return Result;
2430 }
2431
2434 return BuildSubstTemplateTypeParmType(
2435 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2436 getPackIndex(Pack), Arg, TL.getNameLoc());
2437}
2438
2441 concepts::EntityPrinter Printer) {
2442 SmallString<128> Message;
2443 SourceLocation ErrorLoc;
2444 if (Info.hasSFINAEDiagnostic()) {
2447 Info.takeSFINAEDiagnostic(PDA);
2448 PDA.second.EmitToString(S.getDiagnostics(), Message);
2449 ErrorLoc = PDA.first;
2450 } else {
2451 ErrorLoc = Info.getLocation();
2452 }
2453 char *MessageBuf = new (S.Context) char[Message.size()];
2454 std::copy(Message.begin(), Message.end(), MessageBuf);
2455 SmallString<128> Entity;
2456 llvm::raw_svector_ostream OS(Entity);
2457 Printer(OS);
2458 char *EntityBuf = new (S.Context) char[Entity.size()];
2459 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2461 StringRef(EntityBuf, Entity.size()), ErrorLoc,
2462 StringRef(MessageBuf, Message.size())};
2463}
2464
2467 EntityPrinter Printer) {
2468 SmallString<128> Entity;
2469 llvm::raw_svector_ostream OS(Entity);
2470 Printer(OS);
2471 char *EntityBuf = new (S.Context) char[Entity.size()];
2472 llvm::copy(Entity, EntityBuf);
2474 /*SubstitutedEntity=*/StringRef(EntityBuf, Entity.size()),
2475 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2476}
2477
2478ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2479 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2482 SmallVectorImpl<ParmVarDecl *> &TransParams,
2484
2485 TemplateDeductionInfo Info(KWLoc);
2486 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2487 RE, Info,
2488 SourceRange{KWLoc, RBraceLoc});
2489 Sema::SFINAETrap Trap(SemaRef);
2490
2491 unsigned ErrorIdx;
2492 if (getDerived().TransformFunctionTypeParams(
2493 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2494 &TransParams, PInfos, &ErrorIdx) ||
2495 Trap.hasErrorOccurred()) {
2497 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2498 // Add a 'failed' Requirement to contain the error that caused the failure
2499 // here.
2500 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2501 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2502 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2503 TransParams, RE->getRParenLoc(),
2504 TransReqs, RBraceLoc);
2505 }
2506
2507 return ExprResult{};
2508}
2509
2511TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2512 if (!Req->isDependent() && !AlwaysRebuild())
2513 return Req;
2514 if (Req->isSubstitutionFailure()) {
2515 if (AlwaysRebuild())
2516 return RebuildTypeRequirement(
2518 return Req;
2519 }
2520
2521 Sema::SFINAETrap Trap(SemaRef);
2523 Sema::InstantiatingTemplate TypeInst(SemaRef,
2524 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2525 Req->getType()->getTypeLoc().getSourceRange());
2526 if (TypeInst.isInvalid())
2527 return nullptr;
2528 TypeSourceInfo *TransType = TransformType(Req->getType());
2529 if (!TransType || Trap.hasErrorOccurred())
2530 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2531 [&] (llvm::raw_ostream& OS) {
2532 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2533 }));
2534 return RebuildTypeRequirement(TransType);
2535}
2536
2538TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2539 if (!Req->isDependent() && !AlwaysRebuild())
2540 return Req;
2541
2542 Sema::SFINAETrap Trap(SemaRef);
2543
2544 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2545 TransExpr;
2546 if (Req->isExprSubstitutionFailure())
2547 TransExpr = Req->getExprSubstitutionDiagnostic();
2548 else {
2549 Expr *E = Req->getExpr();
2551 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2552 E->getSourceRange());
2553 if (ExprInst.isInvalid())
2554 return nullptr;
2555 ExprResult TransExprRes = TransformExpr(E);
2556 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2557 TransExprRes.get()->hasPlaceholderType())
2558 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2559 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2560 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2561 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2562 });
2563 else
2564 TransExpr = TransExprRes.get();
2565 }
2566
2567 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2568 const auto &RetReq = Req->getReturnTypeRequirement();
2569 if (RetReq.isEmpty())
2570 TransRetReq.emplace();
2571 else if (RetReq.isSubstitutionFailure())
2572 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2573 else if (RetReq.isTypeConstraint()) {
2574 TemplateParameterList *OrigTPL =
2575 RetReq.getTypeConstraintTemplateParameterList();
2576 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2577 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
2578 Req, Info, OrigTPL->getSourceRange());
2579 if (TPLInst.isInvalid())
2580 return nullptr;
2581 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2582 if (!TPL)
2583 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2584 [&] (llvm::raw_ostream& OS) {
2585 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2586 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2587 }));
2588 else {
2589 TPLInst.Clear();
2590 TransRetReq.emplace(TPL);
2591 }
2592 }
2593 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2594 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2595 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2596 std::move(*TransRetReq));
2597 return RebuildExprRequirement(
2599 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2600}
2601
2603TemplateInstantiator::TransformNestedRequirement(
2605 if (!Req->isDependent() && !AlwaysRebuild())
2606 return Req;
2607 if (Req->hasInvalidConstraint()) {
2608 if (AlwaysRebuild())
2609 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2611 return Req;
2612 }
2613 Sema::InstantiatingTemplate ReqInst(SemaRef,
2614 Req->getConstraintExpr()->getBeginLoc(), Req,
2617 if (!getEvaluateConstraints()) {
2618 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2619 if (TransConstraint.isInvalid() || !TransConstraint.get())
2620 return nullptr;
2621 if (TransConstraint.get()->isInstantiationDependent())
2622 return new (SemaRef.Context)
2623 concepts::NestedRequirement(TransConstraint.get());
2624 ConstraintSatisfaction Satisfaction;
2625 return new (SemaRef.Context) concepts::NestedRequirement(
2626 SemaRef.Context, TransConstraint.get(), Satisfaction);
2627 }
2628
2629 ExprResult TransConstraint;
2630 ConstraintSatisfaction Satisfaction;
2632 {
2635 Sema::SFINAETrap Trap(SemaRef);
2636 Sema::InstantiatingTemplate ConstrInst(SemaRef,
2637 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2639 if (ConstrInst.isInvalid())
2640 return nullptr;
2642 if (!SemaRef.CheckConstraintSatisfaction(
2643 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2644 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2645 !Result.empty())
2646 TransConstraint = Result[0];
2647 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2648 "by CheckConstraintSatisfaction.");
2649 }
2650 if (TransConstraint.isUsable() &&
2651 TransConstraint.get()->isInstantiationDependent())
2652 return new (SemaRef.Context)
2653 concepts::NestedRequirement(TransConstraint.get());
2654 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2655 Satisfaction.HasSubstitutionFailure()) {
2656 SmallString<128> Entity;
2657 llvm::raw_svector_ostream OS(Entity);
2658 Req->getConstraintExpr()->printPretty(OS, nullptr,
2659 SemaRef.getPrintingPolicy());
2660 char *EntityBuf = new (SemaRef.Context) char[Entity.size()];
2661 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2662 return new (SemaRef.Context) concepts::NestedRequirement(
2663 SemaRef.Context, StringRef(EntityBuf, Entity.size()), Satisfaction);
2664 }
2665 return new (SemaRef.Context) concepts::NestedRequirement(
2666 SemaRef.Context, TransConstraint.get(), Satisfaction);
2667}
2668
2669
2670/// Perform substitution on the type T with a given set of template
2671/// arguments.
2672///
2673/// This routine substitutes the given template arguments into the
2674/// type T and produces the instantiated type.
2675///
2676/// \param T the type into which the template arguments will be
2677/// substituted. If this type is not dependent, it will be returned
2678/// immediately.
2679///
2680/// \param Args the template arguments that will be
2681/// substituted for the top-level template parameters within T.
2682///
2683/// \param Loc the location in the source code where this substitution
2684/// is being performed. It will typically be the location of the
2685/// declarator (if we're instantiating the type of some declaration)
2686/// or the location of the type in the source code (if, e.g., we're
2687/// instantiating the type of a cast expression).
2688///
2689/// \param Entity the name of the entity associated with a declaration
2690/// being instantiated (if any). May be empty to indicate that there
2691/// is no such entity (if, e.g., this is a type that occurs as part of
2692/// a cast expression) or that the entity has no name (e.g., an
2693/// unnamed function parameter).
2694///
2695/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
2696/// acceptable as the top level type of the result.
2697///
2698/// \returns If the instantiation succeeds, the instantiated
2699/// type. Otherwise, produces diagnostics and returns a NULL type.
2702 SourceLocation Loc,
2703 DeclarationName Entity,
2704 bool AllowDeducedTST) {
2705 assert(!CodeSynthesisContexts.empty() &&
2706 "Cannot perform an instantiation without some context on the "
2707 "instantiation stack");
2708
2711 return T;
2712
2713 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2714 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2715 : Instantiator.TransformType(T);
2716}
2717
2720 SourceLocation Loc,
2721 DeclarationName Entity) {
2722 assert(!CodeSynthesisContexts.empty() &&
2723 "Cannot perform an instantiation without some context on the "
2724 "instantiation stack");
2725
2726 if (TL.getType().isNull())
2727 return nullptr;
2728
2731 // FIXME: Make a copy of the TypeLoc data here, so that we can
2732 // return a new TypeSourceInfo. Inefficient!
2733 TypeLocBuilder TLB;
2734 TLB.pushFullCopy(TL);
2735 return TLB.getTypeSourceInfo(Context, TL.getType());
2736 }
2737
2738 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2739 TypeLocBuilder TLB;
2740 TLB.reserve(TL.getFullDataSize());
2741 QualType Result = Instantiator.TransformType(TLB, TL);
2742 if (Result.isNull())
2743 return nullptr;
2744
2745 return TLB.getTypeSourceInfo(Context, Result);
2746}
2747
2748/// Deprecated form of the above.
2750 const MultiLevelTemplateArgumentList &TemplateArgs,
2751 SourceLocation Loc, DeclarationName Entity) {
2752 assert(!CodeSynthesisContexts.empty() &&
2753 "Cannot perform an instantiation without some context on the "
2754 "instantiation stack");
2755
2756 // If T is not a dependent type or a variably-modified type, there
2757 // is nothing to do.
2759 return T;
2760
2761 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2762 return Instantiator.TransformType(T);
2763}
2764
2768 return true;
2769
2770 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2771 if (!TL.getAs<FunctionProtoTypeLoc>())
2772 return false;
2773
2775 for (ParmVarDecl *P : FP.getParams()) {
2776 // This must be synthesized from a typedef.
2777 if (!P) continue;
2778
2779 // If there are any parameters, a new TypeSourceInfo that refers to the
2780 // instantiated parameters must be built.
2781 return true;
2782 }
2783
2784 return false;
2785}
2786
2787/// A form of SubstType intended specifically for instantiating the
2788/// type of a FunctionDecl. Its purpose is solely to force the
2789/// instantiation of default-argument expressions and to avoid
2790/// instantiating an exception-specification.
2793 SourceLocation Loc,
2794 DeclarationName Entity,
2795 CXXRecordDecl *ThisContext,
2796 Qualifiers ThisTypeQuals,
2797 bool EvaluateConstraints) {
2798 assert(!CodeSynthesisContexts.empty() &&
2799 "Cannot perform an instantiation without some context on the "
2800 "instantiation stack");
2801
2803 return T;
2804
2805 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2806 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2807
2808 TypeLocBuilder TLB;
2809
2810 TypeLoc TL = T->getTypeLoc();
2811 TLB.reserve(TL.getFullDataSize());
2812
2814
2815 if (FunctionProtoTypeLoc Proto =
2817 // Instantiate the type, other than its exception specification. The
2818 // exception specification is instantiated in InitFunctionInstantiation
2819 // once we've built the FunctionDecl.
2820 // FIXME: Set the exception specification to EST_Uninstantiated here,
2821 // instead of rebuilding the function type again later.
2822 Result = Instantiator.TransformFunctionProtoType(
2823 TLB, Proto, ThisContext, ThisTypeQuals,
2825 bool &Changed) { return false; });
2826 } else {
2827 Result = Instantiator.TransformType(TLB, TL);
2828 }
2829 // When there are errors resolving types, clang may use IntTy as a fallback,
2830 // breaking our assumption that function declarations have function types.
2831 if (Result.isNull() || !Result->isFunctionType())
2832 return nullptr;
2833
2834 return TLB.getTypeSourceInfo(Context, Result);
2835}
2836
2839 SmallVectorImpl<QualType> &ExceptionStorage,
2840 const MultiLevelTemplateArgumentList &Args) {
2841 bool Changed = false;
2842 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2843 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2844 Changed);
2845}
2846
2848 const MultiLevelTemplateArgumentList &Args) {
2851
2852 SmallVector<QualType, 4> ExceptionStorage;
2854 ESI, ExceptionStorage, Args))
2855 // On error, recover by dropping the exception specification.
2856 ESI.Type = EST_None;
2857
2858 UpdateExceptionSpec(New, ESI);
2859}
2860
2861namespace {
2862
2863 struct GetContainedInventedTypeParmVisitor :
2864 public TypeVisitor<GetContainedInventedTypeParmVisitor,
2865 TemplateTypeParmDecl *> {
2866 using TypeVisitor<GetContainedInventedTypeParmVisitor,
2867 TemplateTypeParmDecl *>::Visit;
2868
2869 TemplateTypeParmDecl *Visit(QualType T) {
2870 if (T.isNull())
2871 return nullptr;
2872 return Visit(T.getTypePtr());
2873 }
2874 // The deduced type itself.
2875 TemplateTypeParmDecl *VisitTemplateTypeParmType(
2876 const TemplateTypeParmType *T) {
2877 if (!T->getDecl() || !T->getDecl()->isImplicit())
2878 return nullptr;
2879 return T->getDecl();
2880 }
2881
2882 // Only these types can contain 'auto' types, and subsequently be replaced
2883 // by references to invented parameters.
2884
2885 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
2886 return Visit(T->getNamedType());
2887 }
2888
2889 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2890 return Visit(T->getPointeeType());
2891 }
2892
2893 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2894 return Visit(T->getPointeeType());
2895 }
2896
2897 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2898 return Visit(T->getPointeeTypeAsWritten());
2899 }
2900
2901 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2902 return Visit(T->getPointeeType());
2903 }
2904
2905 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
2906 return Visit(T->getElementType());
2907 }
2908
2909 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
2910 const DependentSizedExtVectorType *T) {
2911 return Visit(T->getElementType());
2912 }
2913
2914 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
2915 return Visit(T->getElementType());
2916 }
2917
2918 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
2919 return VisitFunctionType(T);
2920 }
2921
2922 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
2923 return Visit(T->getReturnType());
2924 }
2925
2926 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
2927 return Visit(T->getInnerType());
2928 }
2929
2930 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
2931 return Visit(T->getModifiedType());
2932 }
2933
2934 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2935 return Visit(T->getUnderlyingType());
2936 }
2937
2938 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
2939 return Visit(T->getOriginalType());
2940 }
2941
2942 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
2943 return Visit(T->getPattern());
2944 }
2945 };
2946
2947} // namespace
2948
2950 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
2951 const MultiLevelTemplateArgumentList &TemplateArgs,
2952 bool EvaluateConstraints) {
2953 const ASTTemplateArgumentListInfo *TemplArgInfo =
2955
2956 if (!EvaluateConstraints) {
2959 return false;
2960 }
2961
2962 TemplateArgumentListInfo InstArgs;
2963
2964 if (TemplArgInfo) {
2965 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
2966 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
2967 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
2968 InstArgs))
2969 return true;
2970 }
2971 return AttachTypeConstraint(
2973 TC->getNamedConcept(),
2974 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
2975 Inst->isParameterPack()
2976 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2977 ->getEllipsisLoc()
2978 : SourceLocation());
2979}
2980
2982 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
2983 int indexAdjustment, std::optional<unsigned> NumExpansions,
2984 bool ExpectParameterPack, bool EvaluateConstraint) {
2985 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
2986 TypeSourceInfo *NewDI = nullptr;
2987
2988 TypeLoc OldTL = OldDI->getTypeLoc();
2989 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
2990
2991 // We have a function parameter pack. Substitute into the pattern of the
2992 // expansion.
2993 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
2994 OldParm->getLocation(), OldParm->getDeclName());
2995 if (!NewDI)
2996 return nullptr;
2997
2998 if (NewDI->getType()->containsUnexpandedParameterPack()) {
2999 // We still have unexpanded parameter packs, which means that
3000 // our function parameter is still a function parameter pack.
3001 // Therefore, make its type a pack expansion type.
3002 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3003 NumExpansions);
3004 } else if (ExpectParameterPack) {
3005 // We expected to get a parameter pack but didn't (because the type
3006 // itself is not a pack expansion type), so complain. This can occur when
3007 // the substitution goes through an alias template that "loses" the
3008 // pack expansion.
3009 Diag(OldParm->getLocation(),
3010 diag::err_function_parameter_pack_without_parameter_packs)
3011 << NewDI->getType();
3012 return nullptr;
3013 }
3014 } else {
3015 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3016 OldParm->getDeclName());
3017 }
3018
3019 if (!NewDI)
3020 return nullptr;
3021
3022 if (NewDI->getType()->isVoidType()) {
3023 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3024 return nullptr;
3025 }
3026
3027 // In abbreviated templates, TemplateTypeParmDecls with possible
3028 // TypeConstraints are created when the parameter list is originally parsed.
3029 // The TypeConstraints can therefore reference other functions parameters in
3030 // the abbreviated function template, which is why we must instantiate them
3031 // here, when the instantiated versions of those referenced parameters are in
3032 // scope.
3033 if (TemplateTypeParmDecl *TTP =
3034 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3035 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3036 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3037 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3038 // We will first get here when instantiating the abbreviated function
3039 // template's described function, but we might also get here later.
3040 // Make sure we do not instantiate the TypeConstraint more than once.
3041 if (Inst && !Inst->getTypeConstraint()) {
3042 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3043 return nullptr;
3044 }
3045 }
3046 }
3047
3049 OldParm->getInnerLocStart(),
3050 OldParm->getLocation(),
3051 OldParm->getIdentifier(),
3052 NewDI->getType(), NewDI,
3053 OldParm->getStorageClass());
3054 if (!NewParm)
3055 return nullptr;
3056
3057 // Mark the (new) default argument as uninstantiated (if any).
3058 if (OldParm->hasUninstantiatedDefaultArg()) {
3059 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3060 NewParm->setUninstantiatedDefaultArg(Arg);
3061 } else if (OldParm->hasUnparsedDefaultArg()) {
3062 NewParm->setUnparsedDefaultArg();
3063 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3064 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3065 // Default arguments cannot be substituted until the declaration context
3066 // for the associated function or lambda capture class is available.
3067 // This is necessary for cases like the following where construction of
3068 // the lambda capture class for the outer lambda is dependent on the
3069 // parameter types but where the default argument is dependent on the
3070 // outer lambda's declaration context.
3071 // template <typename T>
3072 // auto f() {
3073 // return [](T = []{ return T{}; }()) { return 0; };
3074 // }
3075 NewParm->setUninstantiatedDefaultArg(Arg);
3076 }
3077
3081
3082 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3083 // Add the new parameter to the instantiated parameter pack.
3085 } else {
3086 // Introduce an Old -> New mapping
3088 }
3089
3090 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3091 // can be anything, is this right ?
3092 NewParm->setDeclContext(CurContext);
3093
3094 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3095 OldParm->getFunctionScopeIndex() + indexAdjustment);
3096
3097 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3098
3099 return NewParm;
3100}
3101
3102/// Substitute the given template arguments into the given set of
3103/// parameters, producing the set of parameter types that would be generated
3104/// from such a substitution.
3107 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3108 const MultiLevelTemplateArgumentList &TemplateArgs,
3109 SmallVectorImpl<QualType> &ParamTypes,
3111 ExtParameterInfoBuilder &ParamInfos) {
3112 assert(!CodeSynthesisContexts.empty() &&
3113 "Cannot perform an instantiation without some context on the "
3114 "instantiation stack");
3115
3116 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3117 DeclarationName());
3118 return Instantiator.TransformFunctionTypeParams(
3119 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3120}
3121
3122/// Substitute the given template arguments into the default argument.
3124 SourceLocation Loc,
3125 ParmVarDecl *Param,
3126 const MultiLevelTemplateArgumentList &TemplateArgs,
3127 bool ForCallExpr) {
3128 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3129 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3130
3133
3134 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3135 if (Inst.isInvalid())
3136 return true;
3137 if (Inst.isAlreadyInstantiating()) {
3138 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3139 Param->setInvalidDecl();
3140 return true;
3141 }
3142
3144 {
3145 // C++ [dcl.fct.default]p5:
3146 // The names in the [default argument] expression are bound, and
3147 // the semantic constraints are checked, at the point where the
3148 // default argument expression appears.
3149 ContextRAII SavedContext(*this, FD);
3150 std::unique_ptr<LocalInstantiationScope> LIS;
3151 MultiLevelTemplateArgumentList NewTemplateArgs = TemplateArgs;
3152
3153 if (ForCallExpr) {
3154 // When instantiating a default argument due to use in a call expression,
3155 // an instantiation scope that includes the parameters of the callee is
3156 // required to satisfy references from the default argument. For example:
3157 // template<typename T> void f(T a, int = decltype(a)());
3158 // void g() { f(0); }
3159 LIS = std::make_unique<LocalInstantiationScope>(*this);
3161 /*ForDefinition*/ false);
3162 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3163 return true;
3164 const FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
3165 if (PrimaryTemplate && PrimaryTemplate->isOutOfLine()) {
3166 TemplateArgumentList *CurrentTemplateArgumentList =
3168 TemplateArgs.getInnermost());
3169 NewTemplateArgs = getTemplateInstantiationArgs(
3170 FD, FD->getDeclContext(), /*Final=*/false,
3171 CurrentTemplateArgumentList->asArray(), /*RelativeToPrimary=*/true);
3172 }
3173 }
3174
3176 Result = SubstInitializer(PatternExpr, NewTemplateArgs,
3177 /*DirectInit*/ false);
3178 });
3179 }
3180 if (Result.isInvalid())
3181 return true;
3182
3183 if (ForCallExpr) {
3184 // Check the expression as an initializer for the parameter.
3185 InitializedEntity Entity
3188 Param->getLocation(),
3189 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3190 Expr *ResultE = Result.getAs<Expr>();
3191
3192 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3193 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3194 if (Result.isInvalid())
3195 return true;
3196
3197 Result =
3199 /*DiscardedValue*/ false);
3200 } else {
3201 // FIXME: Obtain the source location for the '=' token.
3202 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3203 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3204 }
3205 if (Result.isInvalid())
3206 return true;
3207
3208 // Remember the instantiated default argument.
3209 Param->setDefaultArg(Result.getAs<Expr>());
3210
3211 return false;
3212}
3213
3214/// Perform substitution on the base class specifiers of the
3215/// given class template specialization.
3216///
3217/// Produces a diagnostic and returns true on error, returns false and
3218/// attaches the instantiated base classes to the class template
3219/// specialization if successful.
3220bool
3222 CXXRecordDecl *Pattern,
3223 const MultiLevelTemplateArgumentList &TemplateArgs) {
3224 bool Invalid = false;
3225 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3226 for (const auto &Base : Pattern->bases()) {
3227 if (!Base.getType()->isDependentType()) {
3228 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3229 if (RD->isInvalidDecl())
3230 Instantiation->setInvalidDecl();
3231 }
3232 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3233 continue;
3234 }
3235
3236 SourceLocation EllipsisLoc;
3237 TypeSourceInfo *BaseTypeLoc;
3238 if (Base.isPackExpansion()) {
3239 // This is a pack expansion. See whether we should expand it now, or
3240 // wait until later.
3242 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3243 Unexpanded);
3244 bool ShouldExpand = false;
3245 bool RetainExpansion = false;
3246 std::optional<unsigned> NumExpansions;
3247 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3248 Base.getSourceRange(),
3249 Unexpanded,
3250 TemplateArgs, ShouldExpand,
3251 RetainExpansion,
3252 NumExpansions)) {
3253 Invalid = true;
3254 continue;
3255 }
3256
3257 // If we should expand this pack expansion now, do so.
3258 if (ShouldExpand) {
3259 for (unsigned I = 0; I != *NumExpansions; ++I) {
3260 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3261
3262 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3263 TemplateArgs,
3264 Base.getSourceRange().getBegin(),
3265 DeclarationName());
3266 if (!BaseTypeLoc) {
3267 Invalid = true;
3268 continue;
3269 }
3270
3271 if (CXXBaseSpecifier *InstantiatedBase
3272 = CheckBaseSpecifier(Instantiation,
3273 Base.getSourceRange(),
3274 Base.isVirtual(),
3275 Base.getAccessSpecifierAsWritten(),
3276 BaseTypeLoc,
3277 SourceLocation()))
3278 InstantiatedBases.push_back(InstantiatedBase);
3279 else
3280 Invalid = true;
3281 }
3282
3283 continue;
3284 }
3285
3286 // The resulting base specifier will (still) be a pack expansion.
3287 EllipsisLoc = Base.getEllipsisLoc();
3288 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3289 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3290 TemplateArgs,
3291 Base.getSourceRange().getBegin(),
3292 DeclarationName());
3293 } else {
3294 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3295 TemplateArgs,
3296 Base.getSourceRange().getBegin(),
3297 DeclarationName());
3298 }
3299
3300 if (!BaseTypeLoc) {
3301 Invalid = true;
3302 continue;
3303 }
3304
3305 if (CXXBaseSpecifier *InstantiatedBase
3306 = CheckBaseSpecifier(Instantiation,
3307 Base.getSourceRange(),
3308 Base.isVirtual(),
3309 Base.getAccessSpecifierAsWritten(),
3310 BaseTypeLoc,
3311 EllipsisLoc))
3312 InstantiatedBases.push_back(InstantiatedBase);
3313 else
3314 Invalid = true;
3315 }
3316
3317 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3318 Invalid = true;
3319
3320 return Invalid;
3321}
3322
3323// Defined via #include from SemaTemplateInstantiateDecl.cpp
3324namespace clang {
3325 namespace sema {
3327 const MultiLevelTemplateArgumentList &TemplateArgs);
3329 const Attr *At, ASTContext &C, Sema &S,
3330 const MultiLevelTemplateArgumentList &TemplateArgs);
3331 }
3332}
3333
3334/// Instantiate the definition of a class from a given pattern.
3335///
3336/// \param PointOfInstantiation The point of instantiation within the
3337/// source code.
3338///
3339/// \param Instantiation is the declaration whose definition is being
3340/// instantiated. This will be either a class template specialization
3341/// or a member class of a class template specialization.
3342///
3343/// \param Pattern is the pattern from which the instantiation
3344/// occurs. This will be either the declaration of a class template or
3345/// the declaration of a member class of a class template.
3346///
3347/// \param TemplateArgs The template arguments to be substituted into
3348/// the pattern.
3349///
3350/// \param TSK the kind of implicit or explicit instantiation to perform.
3351///
3352/// \param Complain whether to complain if the class cannot be instantiated due
3353/// to the lack of a definition.
3354///
3355/// \returns true if an error occurred, false otherwise.
3356bool
3358 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3359 const MultiLevelTemplateArgumentList &TemplateArgs,
3361 bool Complain) {
3362 CXXRecordDecl *PatternDef
3363 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3364 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3365 Instantiation->getInstantiatedFromMemberClass(),
3366 Pattern, PatternDef, TSK, Complain))
3367 return true;
3368
3369 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3370 std::string Name;
3371 llvm::raw_string_ostream OS(Name);
3372 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3373 /*Qualified=*/true);
3374 return Name;
3375 });
3376
3377 Pattern = PatternDef;
3378
3379 // Record the point of instantiation.
3380 if (MemberSpecializationInfo *MSInfo
3381 = Instantiation->getMemberSpecializationInfo()) {
3382 MSInfo->setTemplateSpecializationKind(TSK);
3383 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3384 } else if (ClassTemplateSpecializationDecl *Spec
3385 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3386 Spec->setTemplateSpecializationKind(TSK);
3387 Spec->setPointOfInstantiation(PointOfInstantiation);
3388 }
3389
3390 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3391 if (Inst.isInvalid())
3392 return true;
3393 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3394 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3395 "instantiating class definition");
3396
3397 // Enter the scope of this instantiation. We don't use
3398 // PushDeclContext because we don't have a scope.
3399 ContextRAII SavedContext(*this, Instantiation);
3402
3403 // If this is an instantiation of a local class, merge this local
3404 // instantiation scope with the enclosing scope. Otherwise, every
3405 // instantiation of a class has its own local instantiation scope.
3406 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3407 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3408
3409 // Some class state isn't processed immediately but delayed till class
3410 // instantiation completes. We may not be ready to handle any delayed state
3411 // already on the stack as it might correspond to a different class, so save
3412 // it now and put it back later.
3413 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3414
3415 // Pull attributes from the pattern onto the instantiation.
3416 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3417
3418 // Start the definition of this instantiation.
3419 Instantiation->startDefinition();
3420
3421 // The instantiation is visible here, even if it was first declared in an
3422 // unimported module.
3423 Instantiation->setVisibleDespiteOwningModule();
3424
3425 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3426 Instantiation->setTagKind(Pattern->getTagKind());
3427
3428 // Do substitution on the base class specifiers.
3429 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3430 Instantiation->setInvalidDecl();
3431
3432 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3433 Instantiator.setEvaluateConstraints(false);
3434 SmallVector<Decl*, 4> Fields;
3435 // Delay instantiation of late parsed attributes.
3436 LateInstantiatedAttrVec LateAttrs;
3437 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3438
3439 bool MightHaveConstexprVirtualFunctions = false;
3440 for (auto *Member : Pattern->decls()) {
3441 // Don't instantiate members not belonging in this semantic context.
3442 // e.g. for:
3443 // @code
3444 // template <int i> class A {
3445 // class B *g;
3446 // };
3447 // @endcode
3448 // 'class B' has the template as lexical context but semantically it is
3449 // introduced in namespace scope.
3450 if (Member->getDeclContext() != Pattern)
3451 continue;
3452
3453 // BlockDecls can appear in a default-member-initializer. They must be the
3454 // child of a BlockExpr, so we only know how to instantiate them from there.
3455 // Similarly, lambda closure types are recreated when instantiating the
3456 // corresponding LambdaExpr.
3457 if (isa<BlockDecl>(Member) ||
3458 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3459 continue;
3460
3461 if (Member->isInvalidDecl()) {
3462 Instantiation->setInvalidDecl();
3463 continue;
3464 }
3465
3466 Decl *NewMember = Instantiator.Visit(Member);
3467 if (NewMember) {
3468 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3469 Fields.push_back(Field);
3470 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3471 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3472 // specialization causes the implicit instantiation of the definitions
3473 // of unscoped member enumerations.
3474 // Record a point of instantiation for this implicit instantiation.
3475 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3476 Enum->isCompleteDefinition()) {
3477 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3478 assert(MSInfo && "no spec info for member enum specialization");
3480 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3481 }
3482 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3483 if (SA->isFailed()) {
3484 // A static_assert failed. Bail out; instantiating this
3485 // class is probably not meaningful.
3486 Instantiation->setInvalidDecl();
3487 break;
3488 }
3489 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3490 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3491 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3492 MightHaveConstexprVirtualFunctions = true;
3493 }
3494
3495 if (NewMember->isInvalidDecl())
3496 Instantiation->setInvalidDecl();
3497 } else {
3498 // FIXME: Eventually, a NULL return will mean that one of the
3499 // instantiations was a semantic disaster, and we'll want to mark the
3500 // declaration invalid.
3501 // For now, we expect to skip some members that we can't yet handle.
3502 }
3503 }
3504
3505 // Finish checking fields.
3506 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3508 CheckCompletedCXXClass(nullptr, Instantiation);
3509
3510 // Default arguments are parsed, if not instantiated. We can go instantiate
3511 // default arg exprs for default constructors if necessary now. Unless we're
3512 // parsing a class, in which case wait until that's finished.
3513 if (ParsingClassDepth == 0)
3515
3516 // Instantiate late parsed attributes, and attach them to their decls.
3517 // See Sema::InstantiateAttrs
3518 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3519 E = LateAttrs.end(); I != E; ++I) {
3520 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3521 CurrentInstantiationScope = I->Scope;
3522
3523 // Allow 'this' within late-parsed attributes.
3524 auto *ND = cast<NamedDecl>(I->NewDecl);
3525 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3526 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3527 ND->isCXXInstanceMember());
3528
3529 Attr *NewAttr =
3530 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3531 if (NewAttr)
3532 I->NewDecl->addAttr(NewAttr);
3534 Instantiator.getStartingScope());
3535 }
3536 Instantiator.disableLateAttributeInstantiation();
3537 LateAttrs.clear();
3538
3540
3541 // FIXME: We should do something similar for explicit instantiations so they
3542 // end up in the right module.
3543 if (TSK == TSK_ImplicitInstantiation) {
3544 Instantiation->setLocation(Pattern->getLocation());
3545 Instantiation->setLocStart(Pattern->getInnerLocStart());
3546 Instantiation->setBraceRange(Pattern->getBraceRange());
3547 }
3548
3549 if (!Instantiation->isInvalidDecl()) {
3550 // Perform any dependent diagnostics from the pattern.
3551 if (Pattern->isDependentContext())
3552 PerformDependentDiagnostics(Pattern, TemplateArgs);
3553
3554 // Instantiate any out-of-line class template partial
3555 // specializations now.
3557 P = Instantiator.delayed_partial_spec_begin(),
3558 PEnd = Instantiator.delayed_partial_spec_end();
3559 P != PEnd; ++P) {
3561 P->first, P->second)) {
3562 Instantiation->setInvalidDecl();
3563 break;
3564 }
3565 }
3566
3567 // Instantiate any out-of-line variable template partial
3568 // specializations now.
3570 P = Instantiator.delayed_var_partial_spec_begin(),
3571 PEnd = Instantiator.delayed_var_partial_spec_end();
3572 P != PEnd; ++P) {
3574 P->first, P->second)) {
3575 Instantiation->setInvalidDecl();
3576 break;
3577 }
3578 }
3579 }
3580
3581 // Exit the scope of this instantiation.
3582 SavedContext.pop();
3583
3584 if (!Instantiation->isInvalidDecl()) {
3585 // Always emit the vtable for an explicit instantiation definition
3586 // of a polymorphic class template specialization. Otherwise, eagerly
3587 // instantiate only constexpr virtual functions in preparation for their use
3588 // in constant evaluation.
3590 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3591 else if (MightHaveConstexprVirtualFunctions)
3592 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3593 /*ConstexprOnly*/ true);
3594 }
3595
3596 Consumer.HandleTagDeclDefinition(Instantiation);
3597
3598 return Instantiation->isInvalidDecl();
3599}
3600
3601/// Instantiate the definition of an enum from a given pattern.
3602///
3603/// \param PointOfInstantiation The point of instantiation within the
3604/// source code.
3605/// \param Instantiation is the declaration whose definition is being
3606/// instantiated. This will be a member enumeration of a class
3607/// temploid specialization, or a local enumeration within a
3608/// function temploid specialization.
3609/// \param Pattern The templated declaration from which the instantiation
3610/// occurs.
3611/// \param TemplateArgs The template arguments to be substituted into
3612/// the pattern.
3613/// \param TSK The kind of implicit or explicit instantiation to perform.
3614///
3615/// \return \c true if an error occurred, \c false otherwise.
3616bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3617 EnumDecl *Instantiation, EnumDecl *Pattern,
3618 const MultiLevelTemplateArgumentList &TemplateArgs,
3620 EnumDecl *PatternDef = Pattern->getDefinition();
3621 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3622 Instantiation->getInstantiatedFromMemberEnum(),
3623 Pattern, PatternDef, TSK,/*Complain*/true))
3624 return true;
3625 Pattern = PatternDef;
3626
3627 // Record the point of instantiation.
3628 if (MemberSpecializationInfo *MSInfo
3629 = Instantiation->getMemberSpecializationInfo()) {
3630 MSInfo->setTemplateSpecializationKind(TSK);
3631 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3632 }
3633
3634 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3635 if (Inst.isInvalid())
3636 return true;
3637 if (Inst.isAlreadyInstantiating())
3638 return false;
3639 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3640 "instantiating enum definition");
3641
3642 // The instantiation is visible here, even if it was first declared in an
3643 // unimported module.
3644 Instantiation->setVisibleDespiteOwningModule();
3645
3646 // Enter the scope of this instantiation. We don't use
3647 // PushDeclContext because we don't have a scope.
3648 ContextRAII SavedContext(*this, Instantiation);
3651
3652 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3653
3654 // Pull attributes from the pattern onto the instantiation.
3655 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3656
3657 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3658 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3659
3660 // Exit the scope of this instantiation.
3661 SavedContext.pop();
3662
3663 return Instantiation->isInvalidDecl();
3664}
3665
3666
3667/// Instantiate the definition of a field from the given pattern.
3668///
3669/// \param PointOfInstantiation The point of instantiation within the
3670/// source code.
3671/// \param Instantiation is the declaration whose definition is being
3672/// instantiated. This will be a class of a class temploid
3673/// specialization, or a local enumeration within a function temploid
3674/// specialization.
3675/// \param Pattern The templated declaration from which the instantiation
3676/// occurs.
3677/// \param TemplateArgs The template arguments to be substituted into
3678/// the pattern.
3679///
3680/// \return \c true if an error occurred, \c false otherwise.
3682 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3683 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3684 // If there is no initializer, we don't need to do anything.
3685 if (!Pattern->hasInClassInitializer())
3686 return false;
3687
3688 assert(Instantiation->getInClassInitStyle() ==
3689 Pattern->getInClassInitStyle() &&
3690 "pattern and instantiation disagree about init style");
3691
3692 // Error out if we haven't parsed the initializer of the pattern yet because
3693 // we are waiting for the closing brace of the outer class.
3694 Expr *OldInit = Pattern->getInClassInitializer();
3695 if (!OldInit) {
3696 RecordDecl *PatternRD = Pattern->getParent();
3697 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3698 Diag(PointOfInstantiation,
3699 diag::err_default_member_initializer_not_yet_parsed)
3700 << OutermostClass << Pattern;
3701 Diag(Pattern->getEndLoc(),
3702 diag::note_default_member_initializer_not_yet_parsed);
3703 Instantiation->setInvalidDecl();
3704 return true;
3705 }
3706
3707 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3708 if (Inst.isInvalid())
3709 return true;
3710 if (Inst.isAlreadyInstantiating()) {
3711 // Error out if we hit an instantiation cycle for this initializer.
3712 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3713 << Instantiation;
3714 return true;
3715 }
3716 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3717 "instantiating default member init");
3718
3719 // Enter the scope of this instantiation. We don't use PushDeclContext because
3720 // we don't have a scope.
3721 ContextRAII SavedContext(*this, Instantiation->getParent());
3724 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3725 PointOfInstantiation, Instantiation, CurContext};
3726
3727 LocalInstantiationScope Scope(*this, true);
3728
3729 // Instantiate the initializer.
3731 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3732
3733 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3734 /*CXXDirectInit=*/false);
3735 Expr *Init = NewInit.get();
3736 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3738 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3739
3740 if (auto *L = getASTMutationListener())
3741 L->DefaultMemberInitializerInstantiated(Instantiation);
3742
3743 // Return true if the in-class initializer is still missing.
3744 return !Instantiation->getInClassInitializer();
3745}
3746
3747namespace {
3748 /// A partial specialization whose template arguments have matched
3749 /// a given template-id.
3750 struct PartialSpecMatchResult {
3753 };
3754}
3755
3757 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3758 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3760 return true;
3761
3763 ClassTemplateSpec->getSpecializedTemplate()
3764 ->getPartialSpecializations(PartialSpecs);
3765 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3766 TemplateDeductionInfo Info(Loc);
3767 if (DeduceTemplateArguments(PartialSpecs[I],
3768 ClassTemplateSpec->getTemplateArgs().asArray(),
3770 return true;
3771 }
3772
3773 return false;
3774}
3775
3776/// Get the instantiation pattern to use to instantiate the definition of a
3777/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3778/// template or of a partial specialization).
3781 Sema &S, SourceLocation PointOfInstantiation,
3782 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3784 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3785 if (Inst.isInvalid())
3786 return {/*Invalid=*/true};
3787 if (Inst.isAlreadyInstantiating())
3788 return {/*Invalid=*/false};
3789
3790 llvm::PointerUnion<ClassTemplateDecl *,
3792 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3793 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
3794 // Find best matching specialization.
3795 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3796
3797 // C++ [temp.class.spec.match]p1:
3798 // When a class template is used in a context that requires an
3799 // instantiation of the class, it is necessary to determine
3800 // whether the instantiation is to be generated using the primary
3801 // template or one of the partial specializations. This is done by
3802 // matching the template arguments of the class template
3803 // specialization with the template argument lists of the partial
3804 // specializations.
3805 typedef PartialSpecMatchResult MatchResult;
3808 Template->getPartialSpecializations(PartialSpecs);
3809 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3810 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3811 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3812 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3814 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
3816 // Store the failed-deduction information for use in diagnostics, later.
3817 // TODO: Actually use the failed-deduction info?
3818 FailedCandidates.addCandidate().set(
3819 DeclAccessPair::make(Template, AS_public), Partial,
3821 (void)Result;
3822 } else {
3823 Matched.push_back(PartialSpecMatchResult());
3824 Matched.back().Partial = Partial;
3825 Matched.back().Args = Info.takeCanonical();
3826 }
3827 }
3828
3829 // If we're dealing with a member template where the template parameters
3830 // have been instantiated, this provides the original template parameters
3831 // from which the member template's parameters were instantiated.
3832
3833 if (Matched.size() >= 1) {
3834 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3835 if (Matched.size() == 1) {
3836 // -- If exactly one matching specialization is found, the
3837 // instantiation is generated from that specialization.
3838 // We don't need to do anything for this.
3839 } else {
3840 // -- If more than one matching specialization is found, the
3841 // partial order rules (14.5.4.2) are used to determine
3842 // whether one of the specializations is more specialized
3843 // than the others. If none of the specializations is more
3844 // specialized than all of the other matching
3845 // specializations, then the use of the class template is
3846 // ambiguous and the program is ill-formed.
3848 PEnd = Matched.end();
3849 P != PEnd; ++P) {
3851 P->Partial, Best->Partial, PointOfInstantiation) ==
3852 P->Partial)
3853 Best = P;
3854 }
3855
3856 // Determine if the best partial specialization is more specialized than
3857 // the others.
3858 bool Ambiguous = false;
3859 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3860 PEnd = Matched.end();
3861 P != PEnd; ++P) {
3863 P->Partial, Best->Partial,
3864 PointOfInstantiation) != Best->Partial) {
3865 Ambiguous = true;
3866 break;
3867 }
3868 }
3869
3870 if (Ambiguous) {
3871 // Partial ordering did not produce a clear winner. Complain.
3872 Inst.Clear();
3873 ClassTemplateSpec->setInvalidDecl();
3874 S.Diag(PointOfInstantiation,
3875 diag::err_partial_spec_ordering_ambiguous)
3876 << ClassTemplateSpec;
3877
3878 // Print the matching partial specializations.
3879 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3880 PEnd = Matched.end();
3881 P != PEnd; ++P)
3882 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
3884 P->Partial->getTemplateParameters(), *P->Args);
3885
3886 return {/*Invalid=*/true};
3887 }
3888 }
3889
3890 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
3891 } else {
3892 // -- If no matches are found, the instantiation is generated
3893 // from the primary template.
3894 }
3895 }
3896
3897 CXXRecordDecl *Pattern = nullptr;
3898 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3899 if (auto *PartialSpec =
3900 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
3901 // Instantiate using the best class template partial specialization.
3902 while (PartialSpec->getInstantiatedFromMember()) {
3903 // If we've found an explicit specialization of this class template,
3904 // stop here and use that as the pattern.
3905 if (PartialSpec->isMemberSpecialization())
3906 break;
3907
3908 PartialSpec = PartialSpec->getInstantiatedFromMember();
3909 }
3910 Pattern = PartialSpec;
3911 } else {
3912 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3913 while (Template->getInstantiatedFromMemberTemplate()) {
3914 // If we've found an explicit specialization of this class template,
3915 // stop here and use that as the pattern.
3916 if (Template->isMemberSpecialization())
3917 break;
3918
3919 Template = Template->getInstantiatedFromMemberTemplate();
3920 }
3921 Pattern = Template->getTemplatedDecl();
3922 }
3923
3924 return Pattern;
3925}
3926
3928 SourceLocation PointOfInstantiation,
3929 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3930 TemplateSpecializationKind TSK, bool Complain) {
3931 // Perform the actual instantiation on the canonical declaration.
3932 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
3933 ClassTemplateSpec->getCanonicalDecl());
3934 if (ClassTemplateSpec->isInvalidDecl())
3935 return true;
3936
3938 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
3939 ClassTemplateSpec, TSK);
3940 if (!Pattern.isUsable())
3941 return Pattern.isInvalid();
3942
3943 return InstantiateClass(
3944 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
3945 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
3946}
3947
3948/// Instantiates the definitions of all of the member
3949/// of the given class, which is an instantiation of a class template
3950/// or a member class of a template.
3951void
3953 CXXRecordDecl *Instantiation,
3954 const MultiLevelTemplateArgumentList &TemplateArgs,
3956 // FIXME: We need to notify the ASTMutationListener that we did all of these
3957 // things, in case we have an explicit instantiation definition in a PCM, a
3958 // module, or preamble, and the declaration is in an imported AST.
3959 assert(
3962 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
3963 "Unexpected template specialization kind!");
3964 for (auto *D : Instantiation->decls()) {
3965 bool SuppressNew = false;
3966 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
3967 if (FunctionDecl *Pattern =
3968 Function->getInstantiatedFromMemberFunction()) {
3969
3970 if (Function->isIneligibleOrNotSelected())
3971 continue;
3972
3973 if (Function->getTrailingRequiresClause()) {
3974 ConstraintSatisfaction Satisfaction;
3975 if (CheckFunctionConstraints(Function, Satisfaction) ||
3976 !Satisfaction.IsSatisfied) {
3977 continue;
3978 }
3979 }
3980
3981 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3982 continue;
3983
3984 MemberSpecializationInfo *MSInfo =
3985 Function->getMemberSpecializationInfo();
3986 assert(MSInfo && "No member specialization information?");
3987 if (MSInfo->getTemplateSpecializationKind()
3989 continue;
3990
3991 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3992 Function,
3994 MSInfo->getPointOfInstantiation(),
3995 SuppressNew) ||
3996 SuppressNew)
3997 continue;
3998
3999 // C++11 [temp.explicit]p8:
4000 // An explicit instantiation definition that names a class template
4001 // specialization explicitly instantiates the class template
4002 // specialization and is only an explicit instantiation definition
4003 // of members whose definition is visible at the point of
4004 // instantiation.
4005 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4006 continue;
4007
4008 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4009
4010 if (Function->isDefined()) {
4011 // Let the ASTConsumer know that this function has been explicitly
4012 // instantiated now, and its linkage might have changed.
4014 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4015 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4016 } else if (TSK == TSK_ImplicitInstantiation) {
4018 std::make_pair(Function, PointOfInstantiation));
4019 }
4020 }
4021 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4022 if (isa<VarTemplateSpecializationDecl>(Var))
4023 continue;
4024
4025 if (Var->isStaticDataMember()) {
4026 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4027 continue;
4028
4030 assert(MSInfo && "No member specialization information?");
4031 if (MSInfo->getTemplateSpecializationKind()
4033 continue;
4034
4035 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4036 Var,
4038 MSInfo->getPointOfInstantiation(),
4039 SuppressNew) ||
4040 SuppressNew)
4041 continue;
4042
4044 // C++0x [temp.explicit]p8:
4045 // An explicit instantiation definition that names a class template
4046 // specialization explicitly instantiates the class template
4047 // specialization and is only an explicit instantiation definition
4048 // of members whose definition is visible at the point of
4049 // instantiation.
4051 continue;
4052
4053 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4054 InstantiateVariableDefinition(PointOfInstantiation, Var);
4055 } else {
4056 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4057 }
4058 }
4059 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4060 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4061 continue;
4062
4063 // Always skip the injected-class-name, along with any
4064 // redeclarations of nested classes, since both would cause us
4065 // to try to instantiate the members of a class twice.
4066 // Skip closure types; they'll get instantiated when we instantiate
4067 // the corresponding lambda-expression.
4068 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4069 Record->isLambda())
4070 continue;
4071
4072 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4073 assert(MSInfo && "No member specialization information?");
4074
4075 if (MSInfo->getTemplateSpecializationKind()
4077 continue;
4078
4079 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4081 // On Windows, explicit instantiation decl of the outer class doesn't
4082 // affect the inner class. Typically extern template declarations are
4083 // used in combination with dll import/export annotations, but those
4084 // are not propagated from the outer class templates to inner classes.
4085 // Therefore, do not instantiate inner classes on this platform, so
4086 // that users don't end up with undefined symbols during linking.
4087 continue;
4088 }
4089
4090 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4091 Record,
4093 MSInfo->getPointOfInstantiation(),
4094 SuppressNew) ||
4095 SuppressNew)
4096 continue;
4097
4099 assert(Pattern && "Missing instantiated-from-template information");
4100
4101 if (!Record->getDefinition()) {
4102 if (!Pattern->getDefinition()) {
4103 // C++0x [temp.explicit]p8:
4104 // An explicit instantiation definition that names a class template
4105 // specialization explicitly instantiates the class template
4106 // specialization and is only an explicit instantiation definition
4107 // of members whose definition is visible at the point of
4108 // instantiation.
4110 MSInfo->setTemplateSpecializationKind(TSK);
4111 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4112 }
4113
4114 continue;
4115 }
4116
4117 InstantiateClass(PointOfInstantiation, Record, Pattern,
4118 TemplateArgs,
4119 TSK);
4120 } else {
4122 Record->getTemplateSpecializationKind() ==
4124 Record->setTemplateSpecializationKind(TSK);
4125 MarkVTableUsed(PointOfInstantiation, Record, true);
4126 }
4127 }
4128
4129 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4130 if (Pattern)
4131 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4132 TSK);
4133 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4134 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4135 assert(MSInfo && "No member specialization information?");
4136
4137 if (MSInfo->getTemplateSpecializationKind()
4139 continue;
4140
4142 PointOfInstantiation, TSK, Enum,
4144 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4145 SuppressNew)
4146 continue;
4147
4148 if (Enum->getDefinition())
4149 continue;
4150
4151 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4152 assert(Pattern && "Missing instantiated-from-template information");
4153
4155 if (!Pattern->getDefinition())
4156 continue;
4157
4158 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4159 } else {
4160 MSInfo->setTemplateSpecializationKind(TSK);
4161 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4162 }
4163 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4164 // No need to instantiate in-class initializers during explicit
4165 // instantiation.
4166 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4167 CXXRecordDecl *ClassPattern =
4168 Instantiation->getTemplateInstantiationPattern();
4170 ClassPattern->lookup(Field->getDeclName());
4171 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4172 assert(Pattern);
4173 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4174 TemplateArgs);
4175 }
4176 }
4177 }
4178}
4179
4180/// Instantiate the definitions of all of the members of the
4181/// given class template specialization, which was named as part of an
4182/// explicit instantiation.
4183void
4185 SourceLocation PointOfInstantiation,
4186 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4188 // C++0x [temp.explicit]p7:
4189 // An explicit instantiation that names a class template
4190 // specialization is an explicit instantion of the same kind
4191 // (declaration or definition) of each of its members (not
4192 // including members inherited from base classes) that has not
4193 // been previously explicitly specialized in the translation unit
4194 // containing the explicit instantiation, except as described
4195 // below.
4196 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4197 getTemplateInstantiationArgs(ClassTemplateSpec),
4198 TSK);
4199}
4200
4203 if (!S)
4204 return S;
4205
4206 TemplateInstantiator Instantiator(*this, TemplateArgs,
4208 DeclarationName());
4209 return Instantiator.TransformStmt(S);
4210}
4211
4213 const TemplateArgumentLoc &Input,
4214 const MultiLevelTemplateArgumentList &TemplateArgs,
4215 TemplateArgumentLoc &Output) {
4216 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4217 DeclarationName());
4218 return Instantiator.TransformTemplateArgument(Input, Output);
4219}
4220
4223 const MultiLevelTemplateArgumentList &TemplateArgs,
4225 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4226 DeclarationName());
4227 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4228}
4229
4232 if (!E)
4233 return E;
4234
4235 TemplateInstantiator Instantiator(*this, TemplateArgs,
4237 DeclarationName());
4238 return Instantiator.TransformExpr(E);
4239}
4240
4243 const MultiLevelTemplateArgumentList &TemplateArgs) {
4244 // FIXME: should call SubstExpr directly if this function is equivalent or
4245 // should it be different?
4246 return SubstExpr(E, TemplateArgs);
4247}
4248
4250 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4251 if (!E)
4252 return E;
4253
4254 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4255 DeclarationName());
4256 Instantiator.setEvaluateConstraints(false);
4257 return Instantiator.TransformExpr(E);
4258}
4259
4261 const MultiLevelTemplateArgumentList &TemplateArgs,
4262 bool CXXDirectInit) {
4263 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4264 DeclarationName());
4265 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4266}
4267
4268bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4269 const MultiLevelTemplateArgumentList &TemplateArgs,
4270 SmallVectorImpl<Expr *> &Outputs) {
4271 if (Exprs.empty())
4272 return false;
4273
4274 TemplateInstantiator Instantiator(*this, TemplateArgs,
4276 DeclarationName());
4277 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4278 IsCall, Outputs);
4279}
4280
4283 const MultiLevelTemplateArgumentList &TemplateArgs) {
4284 if (!NNS)
4285 return NestedNameSpecifierLoc();
4286
4287 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4288 DeclarationName());
4289 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4290}
4291
4292/// Do template substitution on declaration name info.
4295 const MultiLevelTemplateArgumentList &TemplateArgs) {
4296 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4297 NameInfo.getName());
4298 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4299}
4300
4303 TemplateName Name, SourceLocation Loc,
4304 const MultiLevelTemplateArgumentList &TemplateArgs) {
4305 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4306 DeclarationName());
4307 CXXScopeSpec SS;
4308 SS.Adopt(QualifierLoc);
4309 return Instantiator.TransformTemplateName(SS, Name, Loc);
4310}
4311
4312static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4313 // When storing ParmVarDecls in the local instantiation scope, we always
4314 // want to use the ParmVarDecl from the canonical function declaration,
4315 // since the map is then valid for any redeclaration or definition of that
4316 // function.
4317 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4318 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4319 unsigned i = PV->getFunctionScopeIndex();
4320 // This parameter might be from a freestanding function type within the
4321 // function and isn't necessarily referring to one of FD's parameters.
4322 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4323 return FD->getCanonicalDecl()->getParamDecl(i);
4324 }
4325 }
4326 return D;
4327}
4328
4329
4330llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4333 for (LocalInstantiationScope *Current = this; Current;
4334 Current = Current->Outer) {
4335
4336 // Check if we found something within this scope.
4337 const Decl *CheckD = D;
4338 do {
4339 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4340 if (Found != Current->LocalDecls.end())
4341 return &Found->second;
4342
4343 // If this is a tag declaration, it's possible that we need to look for
4344 // a previous declaration.
4345 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4346 CheckD = Tag->getPreviousDecl();
4347 else
4348 CheckD = nullptr;
4349 } while (CheckD);
4350
4351 // If we aren't combined with our outer scope, we're done.
4352 if (!Current->CombineWithOuterScope)
4353 break;
4354 }
4355
4356 // If we're performing a partial substitution during template argument
4357 // deduction, we may not have values for template parameters yet.
4358 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4359 isa<TemplateTemplateParmDecl>(D))
4360 return nullptr;
4361
4362 // Local types referenced prior to definition may require instantiation.
4363 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4364 if (RD->isLocalClass())
4365 return nullptr;
4366
4367 // Enumeration types referenced prior to definition may appear as a result of
4368 // error recovery.
4369 if (isa<EnumDecl>(D))
4370 return nullptr;
4371
4372 // Materialized typedefs/type alias for implicit deduction guides may require
4373 // instantiation.
4374 if (isa<TypedefNameDecl>(D) &&
4375 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4376 return nullptr;
4377
4378 // If we didn't find the decl, then we either have a sema bug, or we have a
4379 // forward reference to a label declaration. Return null to indicate that
4380 // we have an uninstantiated label.
4381 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4382 return nullptr;
4383}
4384
4387 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4388 if (Stored.isNull()) {
4389#ifndef NDEBUG
4390 // It should not be present in any surrounding scope either.
4391 LocalInstantiationScope *Current = this;
4392 while (Current->CombineWithOuterScope && Current->Outer) {
4393 Current = Current->Outer;
4394 assert(!Current->LocalDecls.contains(D) &&
4395 "Instantiated local in inner and outer scopes");
4396 }
4397#endif
4398 Stored = Inst;
4399 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
4400 Pack->push_back(cast<VarDecl>(Inst));
4401 } else {
4402 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
4403 }
4404}
4405
4407 VarDecl *Inst) {
4409 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
4410 Pack->push_back(Inst);
4411}
4412
4414#ifndef NDEBUG
4415 // This should be the first time we've been told about this decl.
4416 for (LocalInstantiationScope *Current = this;
4417 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4418 assert(!Current->LocalDecls.contains(D) &&
4419 "Creating local pack after instantiation of local");
4420#endif
4421
4423 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4425 Stored = Pack;
4426 ArgumentPacks.push_back(Pack);
4427}
4428
4430 for (DeclArgumentPack *Pack : ArgumentPacks)
4431 if (llvm::is_contained(*Pack, D))
4432 return true;
4433 return false;
4434}
4435
4437 const TemplateArgument *ExplicitArgs,
4438 unsigned NumExplicitArgs) {
4439 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4440 "Already have a partially-substituted pack");
4441 assert((!PartiallySubstitutedPack
4442 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4443 "Wrong number of arguments in partially-substituted pack");
4444 PartiallySubstitutedPack = Pack;
4445 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4446 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4447}
4448
4450 const TemplateArgument **ExplicitArgs,
4451 unsigned *NumExplicitArgs) const {
4452 if (ExplicitArgs)
4453 *ExplicitArgs = nullptr;
4454 if (NumExplicitArgs)
4455 *NumExplicitArgs = 0;
4456
4457 for (const LocalInstantiationScope *Current = this; Current;
4458 Current = Current->Outer) {
4459 if (Current->PartiallySubstitutedPack) {
4460 if (ExplicitArgs)
4461 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4462 if (NumExplicitArgs)
4463 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4464
4465 return Current->PartiallySubstitutedPack;
4466 }
4467
4468 if (!Current->CombineWithOuterScope)
4469 break;
4470 }
4471
4472 return nullptr;
4473}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
int Id
Definition: ASTDiff.cpp:190
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines the C++ template declaration subclasses.
Defines Expressions and AST nodes for C++2a concepts.
static void print(llvm::raw_ostream &OS, const T &V, ASTContext &, QualType)
Definition: InterpFrame.cpp:96
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition: MachO.h:28
MatchFinder::MatchResult MatchResult
static const Decl * getCanonicalParmVarDecl(const Decl *D)
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T)
static concepts::Requirement::SubstitutionDiagnostic * createSubstDiag(Sema &S, TemplateDeductionInfo &Info, concepts::EntityPrinter Printer)
static ActionResult< CXXRecordDecl * > getPatternForClassTemplateSpecialization(Sema &S, SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Get the instantiation pattern to use to instantiate the definition of a given ClassTemplateSpecializa...
static std::string convertCallArgsToString(Sema &S, llvm::ArrayRef< const Expr * > Args)
static TemplateArgument getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg)
Defines utilities for dealing with stack allocation and stack space.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__device__ int
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:72
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1070
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2572
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1582
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2148
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:694
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:754
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3087
QualType getOriginalType() const
Definition: Type.h:3100
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3307
QualType getElementType() const
Definition: Type.h:3319
Attr - This represents one attribute.
Definition: Attr.h:42
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:5364
QualType getModifiedType() const
Definition: Type.h:5386
Pointer to a block type.
Definition: Type.h:3138
QualType getPointeeType() const
Definition: Type.h:3150
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1254
SourceLocation getUsedLocation() const
Retrieve the location where this default argument was actually used.
Definition: ExprCXX.h:1328
const ParmVarDecl * getParam() const
Definition: ExprCXX.h:1296
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2053
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
Decl * getLambdaContextDecl() const
Retrieve the declaration that provides additional context for a lambda, when the normal declaration c...
Definition: DeclCXX.cpp:1684
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1547
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1875
base_class_range bases()
Definition: DeclCXX.h:618
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1021
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:612
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1929
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1904
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1896
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1882
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1915
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:132
Declaration of a class template.
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.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
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.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
bool isClassScopeExplicitSpecialization() const
Is this an explicit specialization at class scope (within the class that owns the primary template)?...
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate members of the class templa...
void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec, const TemplateArgumentList *TemplateArgs)
Note that this class template specialization is actually an instantiation of the given class template...
NamedDecl * getFoundDecl() const
Definition: ASTConcept.h:199
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1379
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1446
bool isFileContext() const
Definition: DeclBase.h:2147
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1265
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1785
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1947
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2332
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
ValueDecl * getDecl()
Definition: Expr.h:1328
SourceLocation getLocation() const
Definition: Expr.h:1336
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1061
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1226
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:598
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:220
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
bool isFileContextDecl() const
Definition: DeclBase.cpp:408
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1003
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:274
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1148
bool isInvalidDecl() const
Definition: DeclBase.h:593
SourceLocation getLocation() const
Definition: DeclBase.h:444
void setLocation(SourceLocation L)
Definition: DeclBase.h:445
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:949
DeclContext * getDeclContext()
Definition: DeclBase.h:453
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:336
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:918
bool hasAttr() const
Definition: DeclBase.h:582
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:978
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:870
The name of a declaration.
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:828
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:813
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2047
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1899
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3659
QualType getElementType() const
Definition: Type.h:3674
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:850
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic.
Definition: Diagnostic.h:631
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6131
QualType getNamedType() const
Retrieve the type named by the qualified-id.
Definition: Type.h:6169
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3832
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4091
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For an enumeration member that was instantiated from a member enumeration of a templated class,...
Definition: Decl.cpp:4879
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4905
EnumDecl * getDefinition() const
Definition: Decl.h:3935
This represents one expression.
Definition: Expr.h:110
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
Represents a member of a struct/union/class.
Definition: Decl.h:3025
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4537
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3186
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3180
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3238
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
Represents a function declaration or definition.
Definition: Decl.h:1959
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2651
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:4078
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4127
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2407
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2288
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4599
VarDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition: ExprCXX.h:4626
iterator end() const
Definition: ExprCXX.h:4635
VarDecl * getExpansion(unsigned I) const
Get an expansion of the parameter pack by index.
Definition: ExprCXX.h:4641
VarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:4633
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition: ExprCXX.h:4638
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition: ExprCXX.h:4629
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, VarDecl *ParamPack, SourceLocation NameLoc, ArrayRef< VarDecl * > Params)
Definition: ExprCXX.cpp:1748
iterator begin() const
Definition: ExprCXX.h:4634
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4416
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4660
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1491
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4042
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4016
QualType getReturnType() const
Definition: Type.h:4333
One of these records is kept for each identifier that is lexed.
ArrayRef< TemplateArgument > getTemplateArguments() const
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
Describes the sequence of initializations required to initialize a given object or reference with a s...
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:705
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:5981
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1938
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
void SetPartiallySubstitutedPack(NamedDecl *Pack, const TemplateArgument *ExplicitArgs, unsigned NumExplicitArgs)
Note that the given parameter pack has been partially substituted via explicit specification of templ...
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
bool isLocalPackExpansion(const Decl *D)
Determine whether D is a pack expansion created in this scope.
static void deleteScopes(LocalInstantiationScope *Scope, LocalInstantiationScope *Outermost)
deletes the given scope, and all outer scopes, down to the given outermost scope.
Definition: Template.h:498
void InstantiatedLocal(const Decl *D, Decl *Inst)
void InstantiatedLocalPackArg(const Decl *D, VarDecl *Inst)
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationOf(const Decl *D)
Find the instantiation of the declaration D within the current instantiation scope.
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:5002
QualType getUnderlyingType() const
Definition: Type.h:5018
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3249
QualType getPointeeType() const
Definition: Type.h:3265
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:616
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:647
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:638
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:656
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:661
Describes a module or submodule.
Definition: Module.h:105
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
bool hasTemplateArgument(unsigned Depth, unsigned Index) const
Determine whether there is a non-NULL template argument at the given depth and index.
Definition: Template.h:175
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:265
std::pair< Decl *, bool > getAssociatedDecl(unsigned Depth) const
A template-like entity which owns the whole pattern being substituted.
Definition: Template.h:164
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition: Template.h:123
unsigned getNumSubstitutedLevels() const
Determine the number of substituted levels in this template argument list.
Definition: Template.h:129
unsigned getNewDepth(unsigned OldDepth) const
Determine how many of the OldDepth outermost template parameter lists would be removed by substitutin...
Definition: Template.h:145
void setArgument(unsigned Depth, unsigned Index, TemplateArgument Arg)
Clear out a specific template argument.
Definition: Template.h:197
bool isRewrite() const
Determine whether we are rewriting template parameters rather than substituting for them.
Definition: Template.h:117
This represents a decl that may have a name.
Definition: Decl.h:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition: Decl.cpp:1826
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Definition: Decl.cpp:1675
A C++ nested-name-specifier augmented with source location information.
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isInstantiationDependent() const
Whether this nested name specifier involves a template parameter.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
QualType getExpansionType(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Represents a pack expansion of types.
Definition: Type.h:6329
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:6350
Sugar for parentheses used when specifying types.
Definition: Type.h:2902
QualType getInnerType() const
Definition: Type.h:2911
Represents a parameter to a function.
Definition: Decl.h:1749
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1809
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2980
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1845
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1890
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1878
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:3005
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1782
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1882
bool hasInheritedDefaultArg() const
Definition: Decl.h:1894
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition: Decl.h:1841
Expr * getDefaultArg()
Definition: Decl.cpp:2968
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3010
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1799
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1898
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2928
QualType getPointeeType() const
Definition: Type.h:2938
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1986
PredefinedIdentKind getIdentKind() const
Definition: Expr.h:2021
SourceLocation getLocation() const
Definition: Expr.h:2027
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition: Type.h:738
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3446
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:949
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:805
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7119
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7319
The collection of all-type qualifiers we support.
Definition: Type.h:148
void removeObjCLifetime()
Definition: Type.h:359
Represents a struct/union/class.
Definition: Decl.h:4133
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5309
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:861
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3169
QualType getPointeeTypeAsWritten() const
Definition: Type.h:3185
Represents the body of a requires-expression.
Definition: DeclCXX.h:2023
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:510
SourceLocation getLParenLoc() const
Definition: ExprConcepts.h:578
SourceLocation getRParenLoc() const
Definition: ExprConcepts.h:579
RequiresExprBodyDecl * getBody() const
Definition: ExprConcepts.h:554
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:10548
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6791
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2671
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:4849
DefaultedComparisonKind asComparison() const
Definition: Sema.h:4876
CXXSpecialMember asSpecialMember() const
Definition: Sema.h:4873
A helper class for building up ExtParameterInfos.
Definition: Sema.h:10010
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9760
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:426
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:10498
bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraint)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:10482
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:10039
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, std::optional< unsigned > &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, std::optional< unsigned > NumExpansions, bool ExpectParameterPack, bool EvaluateConstraints=true)
void ActOnFinishCXXNonNestedClass()
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1912
void ActOnFinishDelayedMemberInitializers(Decl *Record)
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:10485
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:7002
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:9430
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:1030
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition: Sema.h:10509
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:498
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
ExprResult SubstConstraintExprWithoutSatisfaction(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTContext & getASTContext() const
Definition: Sema.h:501
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.
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:947
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
Definition: SemaDecl.cpp:17150
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain=true)
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition: Sema.h:494
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:11489
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:15417
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition: Sema.h:10534
void PrintInstantiationStack()
Prints the current instantiation stack through a series of notes.
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:10051
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
int ArgumentPackSubstitutionIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition: Sema.h:10542
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1163
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:10773
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21754
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition: Sema.h:10518
bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:6280
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc)
Definition: SemaExpr.cpp:3920
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
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 SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param, const MultiLevelTemplateArgumentList &TemplateArgs, bool ForCallExpr=false)
Substitute the given template arguments into the default argument.
ExprResult SubstConstraintExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTConsumer & Consumer
Definition: Sema.h:1031
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1618
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced.
Definition: Sema.h:10526
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19331
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6674
DiagnosticsEngine & Diags
Definition: Sema.h:1032
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition: Sema.h:10493
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
Perform template argument deduction to determine whether the given template arguments match the given...
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:512
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21980
bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiate the definition of an enum from a given pattern.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output)
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
void warnStackExhausted(SourceLocation Loc)
Warn that the stack is nearly exhausted.
Definition: Sema.cpp:504
bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Perform substitution on the base class specifiers of the given class template specialization.
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
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)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:542
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6972
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals, bool EvaluateConstraints=true)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
Encodes a location in the source.
A trivial tuple used to represent a source range.
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:4051
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4435
std::optional< unsigned > getPackIndex() const
Definition: ExprCXX.h:4483
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
Definition: ExprCXX.h:4477
QualType getParameterType(const ASTContext &Ctx) const
Determine the substituted type of the template parameter.
Definition: ExprCXX.cpp:1704
NonTypeTemplateParmDecl * getParameter() const
Definition: ExprCXX.cpp:1663
Represents a reference to a non-type template parameter pack that has been substituted with a non-tem...
Definition: ExprCXX.h:4520
TemplateArgument getArgumentPack() const
Retrieve the template argument pack containing the substituted template arguments.
Definition: ExprCXX.cpp:1730
SourceLocation getParameterPackLocation() const
Retrieve the location of the parameter pack name.
Definition: ExprCXX.h:4560
NonTypeTemplateParmDecl * getParameterPack() const
Retrieve the non-type template parameter pack being substituted.
Definition: ExprCXX.cpp:1725
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
Definition: ExprCXX.h:4550
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:141
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:864
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:5649
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
Definition: Type.cpp:4132
TemplateArgument getArgumentPack() const
Definition: Type.cpp:4149
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: Type.h:5675
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:857
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3549
void setTagKind(TagKind TK)
Definition: Decl.h:3748
SourceRange getBraceRange() const
Definition: Decl.h:3628
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3633
StringRef getKindName() const
Definition: Decl.h:3740
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4704
TagKind getTagKind() const
Definition: Decl.h:3744
void setBraceRange(SourceRange R)
Definition: Decl.h:3629
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1220
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
A template argument list.
Definition: DeclTemplate.h:244
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.
Definition: DeclTemplate.h:274
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
Represents a template argument.
Definition: TemplateBase.h:61
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
Definition: TemplateBase.h:444
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:418
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
Definition: TemplateBase.h:298
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
void enableLateAttributeInstantiation(Sema::LateInstantiatedAttrVec *LA)
Definition: Template.h:648
delayed_var_partial_spec_iterator delayed_var_partial_spec_end()
Definition: Template.h:687
delayed_partial_spec_iterator delayed_partial_spec_begin()
Return an iterator to the beginning of the set of "delayed" partial specializations,...
Definition: Template.h:671
void setEvaluateConstraints(bool B)
Definition: Template.h:592
SmallVectorImpl< std::pair< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > >::iterator delayed_var_partial_spec_iterator
Definition: Template.h:665
LocalInstantiationScope * getStartingScope() const
Definition: Template.h:659
VarTemplatePartialSpecializationDecl * InstantiateVarTemplatePartialSpecialization(VarTemplateDecl *VarTemplate, VarTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a variable template partial specialization.
SmallVectorImpl< std::pair< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > >::iterator delayed_partial_spec_iterator
Definition: Template.h:662
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
delayed_partial_spec_iterator delayed_partial_spec_end()
Return an iterator to the end of the set of "delayed" partial specializations, which must be passed t...
Definition: Template.h:683
delayed_var_partial_spec_iterator delayed_var_partial_spec_begin()
Definition: Template.h:675
ClassTemplatePartialSpecializationDecl * InstantiateClassTemplatePartialSpecialization(ClassTemplateDecl *ClassTemplate, ClassTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a class template partial specialization.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
bool isNull() const
Determine whether this template name is NULL.
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
TemplateName getNameToSubstitute() const
Get the template name to substitute when this template name is used as a template template argument.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:5849
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Declaration of a template type parameter.
bool isParameterPack() const
Returns whether this is a parameter pack.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint)
Wrapper for template type parameters.
Definition: TypeLoc.h:758
TemplateTypeParmDecl * getDecl() const
Definition: Type.h:5542
bool isParameterPack() const
Definition: Type.h:5540
unsigned getIndex() const
Definition: Type.h:5539
unsigned getDepth() const
Definition: Type.h:5538
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:231
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ASTConcept.h:264
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:254
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:246
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition: ASTConcept.h:274
const DeclarationNameInfo & getConceptNameInfo() const
Definition: ASTConcept.h:278
ConceptReference * getConceptReference() const
Definition: ASTConcept.h:250
void setLocStart(SourceLocation L)
Definition: Decl.h:3385
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
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
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:133
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:1225
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:153
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:164
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7090
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7101
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
An operation on a type.
Definition: TypeVisitor.h:64
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition: Type.cpp:3148
The base class of the type hierarchy.
Definition: Type.h:1607
bool isVoidType() const
Definition: Type.h:7660
bool isReferenceType() const
Definition: Type.h:7383
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2450
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2442
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2114
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2460
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7878
bool isRecordType() const
Definition: Type.h:7461
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1267
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2363
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2749
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:2876
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1152
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2663
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2867
Declaration of a variable template.
Represents a variable template specialization, which refers to a variable template with a given set o...
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate the initializer of the vari...
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.
Represents a GCC generic vector type.
Definition: Type.h:3729
QualType getElementType() const
Definition: Type.h:3743
A requires-expression requirement which queries the validity and properties of an expression ('simple...
Definition: ExprConcepts.h:280
SubstitutionDiagnostic * getExprSubstitutionDiagnostic() const
Definition: ExprConcepts.h:408
const ReturnTypeRequirement & getReturnTypeRequirement() const
Definition: ExprConcepts.h:398
SourceLocation getNoexceptLoc() const
Definition: ExprConcepts.h:390
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
Definition: ExprConcepts.h:429
const ASTConstraintSatisfaction & getConstraintSatisfaction() const
Definition: ExprConcepts.h:484
A static requirement that can be used in a requires-expression to check properties of types and expre...
Definition: ExprConcepts.h:168
A requires-expression requirement which queries the existence of a type name or type template special...
Definition: ExprConcepts.h:225
SubstitutionDiagnostic * getSubstitutionDiagnostic() const
Definition: ExprConcepts.h:260
TypeSourceInfo * getType() const
Definition: ExprConcepts.h:267
RetTy Visit(PTR(Decl) D)
Definition: DeclVisitor.h:37
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeCanonical()
SourceLocation getLocation() const
Returns the location at which template argument is occurring.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
Requirement::SubstitutionDiagnostic * createSubstDiagAt(Sema &S, SourceLocation Location, EntityPrinter Printer)
create a Requirement::SubstitutionDiagnostic with only a SubstitutedEntity and DiagLoc using Sema's a...
llvm::function_ref< void(llvm::raw_ostream &)> EntityPrinter
Definition: ExprConcepts.h:493
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.
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
NamedDecl * getAsNamedDecl(TemplateParameter P)
bool isStackNearlyExhausted()
Determine whether the stack is nearly exhausted.
Definition: Stack.cpp:45
bool isGenericLambdaCallOperatorOrStaticInvokerSpecialization(const DeclContext *DC)
Definition: ASTLambda.h:82
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
TagTypeKind
The kind of a tag type.
Definition: Type.h:6059
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition: Ownership.h:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:65
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:367
@ Success
Template argument deduction was successful.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:203
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6034
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
@ AS_public
Definition: Specifiers.h:121
Definition: Format.h:5378
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:40
#define false
Definition: stdbool.h:22
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
Definition: TemplateBase.h:691
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
Definition: TemplateBase.h:688
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:705
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
Holds information about the various types of exception specification.
Definition: Type.h:4467
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4469
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4502
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:10056
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition: Sema.h:10214
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool SavedInNonInstantiationSFINAEContext
Was the enclosing context a non-instantiation SFINAE context?
Definition: Sema.h:10167
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition: Sema.h:10183
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition: Sema.h:10209
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation,...
Definition: Sema.h:10178
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:10170
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:10058
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:10150
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition: Sema.h:10068
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:10077
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition: Sema.h:10096
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:10147
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition: Sema.h:10104
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition: Sema.h:10111
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:10154
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition: Sema.h:10122
@ Memoization
Added for Template instantiation observation.
Definition: Sema.h:10160
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition: Sema.h:10087
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:10163
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:10084
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition: Sema.h:10092
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:10100
@ TemplateInstantiation
We are instantiating a template declaration.
Definition: Sema.h:10061
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:10114
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:10118
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:10073
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:10144
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition: Sema.h:10107
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:10173
bool isInstantiationRecord() const
Determines whether this template is an actual instantiation that should be counted toward the maximum...
A stack object to be created when performing template instantiation.
Definition: Sema.h:10238
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:10386
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange=SourceRange())
Note that we are instantiating a class template, function template, variable template,...
void Clear()
Note that we have finished instantiating this template.
bool isAlreadyInstantiating() const
Determine whether we are already instantiating this specialization in some surrounding active instant...
Definition: Sema.h:10390
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)