clang 18.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"
26#include "clang/Basic/Stack.h"
28#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Sema.h"
35#include "clang/Sema/Template.h"
38#include "llvm/ADT/ScopeExit.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 return Response::UseNextDecl(Function);
228}
229
230Response HandleFunctionTemplateDecl(const FunctionTemplateDecl *FTD,
232 if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) {
233 Result.addOuterTemplateArguments(
234 const_cast<FunctionTemplateDecl *>(FTD),
235 const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(),
236 /*Final=*/false);
237
239
240 while (const Type *Ty = NNS ? NNS->getAsType() : nullptr) {
241 if (NNS->isInstantiationDependent()) {
242 if (const auto *TSTy = Ty->getAs<TemplateSpecializationType>())
243 Result.addOuterTemplateArguments(
244 const_cast<FunctionTemplateDecl *>(FTD), TSTy->template_arguments(),
245 /*Final=*/false);
246 }
247
248 NNS = NNS->getPrefix();
249 }
250 }
251
252 return Response::ChangeDecl(FTD->getLexicalDeclContext());
253}
254
255Response HandleRecordDecl(const CXXRecordDecl *Rec,
257 ASTContext &Context,
258 bool ForConstraintInstantiation) {
259 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
260 assert(
261 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
262 "Outer template not instantiated?");
263 if (ClassTemplate->isMemberSpecialization())
264 return Response::Done();
265 if (ForConstraintInstantiation)
266 Result.addOuterTemplateArguments(const_cast<CXXRecordDecl *>(Rec),
267 ClassTemplate->getInjectedTemplateArgs(),
268 /*Final=*/false);
269 }
270
271 if (const MemberSpecializationInfo *MSInfo =
273 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
274 return Response::Done();
275
276 bool IsFriend = Rec->getFriendObjectKind() ||
279 if (ForConstraintInstantiation && IsFriend &&
281 return Response::ChangeDecl(Rec->getLexicalDeclContext());
282 }
283
284 // This is to make sure we pick up the VarTemplateSpecializationDecl that this
285 // lambda is defined inside of.
286 if (Rec->isLambda())
287 if (const Decl *LCD = Rec->getLambdaContextDecl())
288 return Response::ChangeDecl(LCD);
289
290 return Response::UseNextDecl(Rec);
291}
292
293Response HandleImplicitConceptSpecializationDecl(
296 Result.addOuterTemplateArguments(
297 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
299 /*Final=*/false);
300 return Response::UseNextDecl(CSD);
301}
302
303Response HandleGenericDeclContext(const Decl *CurDecl) {
304 return Response::UseNextDecl(CurDecl);
305}
306} // namespace TemplateInstArgsHelpers
307} // namespace
308
309/// Retrieve the template argument list(s) that should be used to
310/// instantiate the definition of the given declaration.
311///
312/// \param ND the declaration for which we are computing template instantiation
313/// arguments.
314///
315/// \param Innermost if non-NULL, specifies a template argument list for the
316/// template declaration passed as ND.
317///
318/// \param RelativeToPrimary true if we should get the template
319/// arguments relative to the primary template, even when we're
320/// dealing with a specialization. This is only relevant for function
321/// template specializations.
322///
323/// \param Pattern If non-NULL, indicates the pattern from which we will be
324/// instantiating the definition of the given declaration, \p ND. This is
325/// used to determine the proper set of template instantiation arguments for
326/// friend function template specializations.
327///
328/// \param ForConstraintInstantiation when collecting arguments,
329/// ForConstraintInstantiation indicates we should continue looking when
330/// encountering a lambda generic call operator, and continue looking for
331/// arguments on an enclosing class template.
332
334 const NamedDecl *ND, bool Final, const TemplateArgumentList *Innermost,
335 bool RelativeToPrimary, const FunctionDecl *Pattern,
336 bool ForConstraintInstantiation, bool SkipForSpecialization) {
337 assert(ND && "Can't find arguments for a decl if one isn't provided");
338 // Accumulate the set of template argument lists in this structure.
340
341 using namespace TemplateInstArgsHelpers;
342 const Decl *CurDecl = ND;
343 if (Innermost) {
344 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND),
345 Innermost->asArray(), Final);
346 CurDecl = Response::UseNextDecl(ND).NextDecl;
347 }
348
349 while (!CurDecl->isFileContextDecl()) {
350 Response R;
351 if (const auto *VarTemplSpec =
352 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
353 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
354 } else if (const auto *PartialClassTemplSpec =
355 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
356 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
357 SkipForSpecialization);
358 } else if (const auto *ClassTemplSpec =
359 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
360 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
361 SkipForSpecialization);
362 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
363 R = HandleFunction(Function, Result, Pattern, RelativeToPrimary,
364 ForConstraintInstantiation);
365 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
366 R = HandleRecordDecl(Rec, Result, Context, ForConstraintInstantiation);
367 } else if (const auto *CSD =
368 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
369 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
370 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
371 R = HandleFunctionTemplateDecl(FTD, Result);
372 } else if (!isa<DeclContext>(CurDecl)) {
373 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
374 if (CurDecl->getDeclContext()->isTranslationUnit()) {
375 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
376 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
377 }
378 }
379 } else {
380 R = HandleGenericDeclContext(CurDecl);
381 }
382
383 if (R.IsDone)
384 return Result;
385 if (R.ClearRelativeToPrimary)
386 RelativeToPrimary = false;
387 assert(R.NextDecl);
388 CurDecl = R.NextDecl;
389 }
390
391 return Result;
392}
393
395 switch (Kind) {
403 case ConstraintsCheck:
405 return true;
406
423 return false;
424
425 // This function should never be called when Kind's value is Memoization.
426 case Memoization:
427 break;
428 }
429
430 llvm_unreachable("Invalid SynthesisKind!");
431}
432
435 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
436 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
437 sema::TemplateDeductionInfo *DeductionInfo)
438 : SemaRef(SemaRef) {
439 // Don't allow further instantiation if a fatal error and an uncompilable
440 // error have occurred. Any diagnostics we might have raised will not be
441 // visible, and we do not need to construct a correct AST.
442 if (SemaRef.Diags.hasFatalErrorOccurred() &&
444 Invalid = true;
445 return;
446 }
447 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
448 if (!Invalid) {
450 Inst.Kind = Kind;
451 Inst.PointOfInstantiation = PointOfInstantiation;
452 Inst.Entity = Entity;
453 Inst.Template = Template;
454 Inst.TemplateArgs = TemplateArgs.data();
455 Inst.NumTemplateArgs = TemplateArgs.size();
456 Inst.DeductionInfo = DeductionInfo;
457 Inst.InstantiationRange = InstantiationRange;
458 SemaRef.pushCodeSynthesisContext(Inst);
459
460 AlreadyInstantiating = !Inst.Entity ? false :
462 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
463 .second;
464 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
465 }
466}
467
469 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
470 SourceRange InstantiationRange)
471 : InstantiatingTemplate(SemaRef,
472 CodeSynthesisContext::TemplateInstantiation,
473 PointOfInstantiation, InstantiationRange, Entity) {}
474
476 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
477 ExceptionSpecification, SourceRange InstantiationRange)
479 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
480 PointOfInstantiation, InstantiationRange, Entity) {}
481
483 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
484 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
485 SourceRange InstantiationRange)
487 SemaRef,
488 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
489 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
490 Template, TemplateArgs) {}
491
493 Sema &SemaRef, SourceLocation PointOfInstantiation,
495 ArrayRef<TemplateArgument> TemplateArgs,
497 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
498 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
499 InstantiationRange, FunctionTemplate, nullptr,
500 TemplateArgs, &DeductionInfo) {
501 assert(
504}
505
507 Sema &SemaRef, SourceLocation PointOfInstantiation,
508 TemplateDecl *Template,
509 ArrayRef<TemplateArgument> TemplateArgs,
510 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
512 SemaRef,
513 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
514 PointOfInstantiation, InstantiationRange, Template, nullptr,
515 TemplateArgs, &DeductionInfo) {}
516
518 Sema &SemaRef, SourceLocation PointOfInstantiation,
520 ArrayRef<TemplateArgument> TemplateArgs,
521 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
523 SemaRef,
524 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
525 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
526 TemplateArgs, &DeductionInfo) {}
527
529 Sema &SemaRef, SourceLocation PointOfInstantiation,
531 ArrayRef<TemplateArgument> TemplateArgs,
532 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
534 SemaRef,
535 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
536 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
537 TemplateArgs, &DeductionInfo) {}
538
540 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
541 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
543 SemaRef,
544 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
545 PointOfInstantiation, InstantiationRange, Param, nullptr,
546 TemplateArgs) {}
547
549 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
551 SourceRange InstantiationRange)
553 SemaRef,
554 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
555 PointOfInstantiation, InstantiationRange, Param, Template,
556 TemplateArgs) {}
557
559 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
561 SourceRange InstantiationRange)
563 SemaRef,
564 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
565 PointOfInstantiation, InstantiationRange, Param, Template,
566 TemplateArgs) {}
567
569 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
570 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
571 SourceRange InstantiationRange)
573 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
574 PointOfInstantiation, InstantiationRange, Param, Template,
575 TemplateArgs) {}
576
578 Sema &SemaRef, SourceLocation PointOfInstantiation,
580 SourceRange InstantiationRange)
582 SemaRef, CodeSynthesisContext::RequirementInstantiation,
583 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
584 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
585}
586
588 Sema &SemaRef, SourceLocation PointOfInstantiation,
590 SourceRange InstantiationRange)
592 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
593 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
594 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt) {}
595
597 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
598 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
600 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
601 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
602 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
603}
604
606 Sema &SemaRef, SourceLocation PointOfInstantiation,
607 ConstraintsCheck, NamedDecl *Template,
608 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
611 PointOfInstantiation, InstantiationRange, Template, nullptr,
612 TemplateArgs) {}
613
615 Sema &SemaRef, SourceLocation PointOfInstantiation,
617 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
620 PointOfInstantiation, InstantiationRange, Template, nullptr,
621 {}, &DeductionInfo) {}
622
624 Sema &SemaRef, SourceLocation PointOfInstantiation,
626 SourceRange InstantiationRange)
629 PointOfInstantiation, InstantiationRange, Template) {}
630
632 Sema &SemaRef, SourceLocation PointOfInstantiation,
634 SourceRange InstantiationRange)
637 PointOfInstantiation, InstantiationRange, Template) {}
638
640 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
641 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
643 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
644 PointOfInstantiation, InstantiationRange, Entity) {}
645
646
650
651 CodeSynthesisContexts.push_back(Ctx);
652
653 if (!Ctx.isInstantiationRecord())
655
656 // Check to see if we're low on stack space. We can't do anything about this
657 // from here, but we can at least warn the user.
660}
661
663 auto &Active = CodeSynthesisContexts.back();
664 if (!Active.isInstantiationRecord()) {
665 assert(NonInstantiationEntries > 0);
667 }
668
669 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
670
671 // Name lookup no longer looks in this template's defining module.
672 assert(CodeSynthesisContexts.size() >=
674 "forgot to remove a lookup module for a template instantiation");
675 if (CodeSynthesisContexts.size() ==
678 LookupModulesCache.erase(M);
680 }
681
682 // If we've left the code synthesis context for the current context stack,
683 // stop remembering that we've emitted that stack.
684 if (CodeSynthesisContexts.size() ==
687
688 CodeSynthesisContexts.pop_back();
689}
690
692 if (!Invalid) {
693 if (!AlreadyInstantiating) {
694 auto &Active = SemaRef.CodeSynthesisContexts.back();
695 if (Active.Entity)
696 SemaRef.InstantiatingSpecializations.erase(
697 {Active.Entity->getCanonicalDecl(), Active.Kind});
698 }
699
700 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
701 SemaRef.CodeSynthesisContexts.back());
702
703 SemaRef.popCodeSynthesisContext();
704 Invalid = true;
705 }
706}
707
708static std::string convertCallArgsToString(Sema &S,
710 std::string Result;
711 llvm::raw_string_ostream OS(Result);
712 llvm::ListSeparator Comma;
713 for (const Expr *Arg : Args) {
714 OS << Comma;
715 Arg->IgnoreParens()->printPretty(OS, nullptr,
717 }
718 return Result;
719}
720
721bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
722 SourceLocation PointOfInstantiation,
723 SourceRange InstantiationRange) {
724 assert(SemaRef.NonInstantiationEntries <=
725 SemaRef.CodeSynthesisContexts.size());
726 if ((SemaRef.CodeSynthesisContexts.size() -
728 <= SemaRef.getLangOpts().InstantiationDepth)
729 return false;
730
731 SemaRef.Diag(PointOfInstantiation,
732 diag::err_template_recursion_depth_exceeded)
733 << SemaRef.getLangOpts().InstantiationDepth
734 << InstantiationRange;
735 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
736 << SemaRef.getLangOpts().InstantiationDepth;
737 return true;
738}
739
740/// Prints the current instantiation stack through a series of
741/// notes.
743 // Determine which template instantiations to skip, if any.
744 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
745 unsigned Limit = Diags.getTemplateBacktraceLimit();
746 if (Limit && Limit < CodeSynthesisContexts.size()) {
747 SkipStart = Limit / 2 + Limit % 2;
748 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
749 }
750
751 // FIXME: In all of these cases, we need to show the template arguments
752 unsigned InstantiationIdx = 0;
754 Active = CodeSynthesisContexts.rbegin(),
755 ActiveEnd = CodeSynthesisContexts.rend();
756 Active != ActiveEnd;
757 ++Active, ++InstantiationIdx) {
758 // Skip this instantiation?
759 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
760 if (InstantiationIdx == SkipStart) {
761 // Note that we're skipping instantiations.
762 Diags.Report(Active->PointOfInstantiation,
763 diag::note_instantiation_contexts_suppressed)
764 << unsigned(CodeSynthesisContexts.size() - Limit);
765 }
766 continue;
767 }
768
769 switch (Active->Kind) {
771 Decl *D = Active->Entity;
772 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
773 unsigned DiagID = diag::note_template_member_class_here;
774 if (isa<ClassTemplateSpecializationDecl>(Record))
775 DiagID = diag::note_template_class_instantiation_here;
776 Diags.Report(Active->PointOfInstantiation, DiagID)
777 << Record << Active->InstantiationRange;
778 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
779 unsigned DiagID;
780 if (Function->getPrimaryTemplate())
781 DiagID = diag::note_function_template_spec_here;
782 else
783 DiagID = diag::note_template_member_function_here;
784 Diags.Report(Active->PointOfInstantiation, DiagID)
785 << Function
786 << Active->InstantiationRange;
787 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
788 Diags.Report(Active->PointOfInstantiation,
789 VD->isStaticDataMember()?
790 diag::note_template_static_data_member_def_here
791 : diag::note_template_variable_def_here)
792 << VD
793 << Active->InstantiationRange;
794 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
795 Diags.Report(Active->PointOfInstantiation,
796 diag::note_template_enum_def_here)
797 << ED
798 << Active->InstantiationRange;
799 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
800 Diags.Report(Active->PointOfInstantiation,
801 diag::note_template_nsdmi_here)
802 << FD << Active->InstantiationRange;
803 } else {
804 Diags.Report(Active->PointOfInstantiation,
805 diag::note_template_type_alias_instantiation_here)
806 << cast<TypeAliasTemplateDecl>(D)
807 << Active->InstantiationRange;
808 }
809 break;
810 }
811
813 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
814 SmallString<128> TemplateArgsStr;
815 llvm::raw_svector_ostream OS(TemplateArgsStr);
816 Template->printName(OS, getPrintingPolicy());
817 printTemplateArgumentList(OS, Active->template_arguments(),
819 Diags.Report(Active->PointOfInstantiation,
820 diag::note_default_arg_instantiation_here)
821 << OS.str()
822 << Active->InstantiationRange;
823 break;
824 }
825
827 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
828 Diags.Report(Active->PointOfInstantiation,
829 diag::note_explicit_template_arg_substitution_here)
830 << FnTmpl
832 Active->TemplateArgs,
833 Active->NumTemplateArgs)
834 << Active->InstantiationRange;
835 break;
836 }
837
839 if (FunctionTemplateDecl *FnTmpl =
840 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
841 Diags.Report(Active->PointOfInstantiation,
842 diag::note_function_template_deduction_instantiation_here)
843 << FnTmpl
844 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
845 Active->TemplateArgs,
846 Active->NumTemplateArgs)
847 << Active->InstantiationRange;
848 } else {
849 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
850 isa<VarTemplateSpecializationDecl>(Active->Entity);
851 bool IsTemplate = false;
852 TemplateParameterList *Params;
853 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
854 IsTemplate = true;
855 Params = D->getTemplateParameters();
856 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
857 Active->Entity)) {
858 Params = D->getTemplateParameters();
859 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
860 Active->Entity)) {
861 Params = D->getTemplateParameters();
862 } else {
863 llvm_unreachable("unexpected template kind");
864 }
865
866 Diags.Report(Active->PointOfInstantiation,
867 diag::note_deduced_template_arg_substitution_here)
868 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
869 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
870 Active->NumTemplateArgs)
871 << Active->InstantiationRange;
872 }
873 break;
874 }
875
877 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
878 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
879
880 SmallString<128> TemplateArgsStr;
881 llvm::raw_svector_ostream OS(TemplateArgsStr);
883 printTemplateArgumentList(OS, Active->template_arguments(),
885 Diags.Report(Active->PointOfInstantiation,
886 diag::note_default_function_arg_instantiation_here)
887 << OS.str()
888 << Active->InstantiationRange;
889 break;
890 }
891
893 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
894 std::string Name;
895 if (!Parm->getName().empty())
896 Name = std::string(" '") + Parm->getName().str() + "'";
897
898 TemplateParameterList *TemplateParams = nullptr;
899 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
900 TemplateParams = Template->getTemplateParameters();
901 else
902 TemplateParams =
903 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
904 ->getTemplateParameters();
905 Diags.Report(Active->PointOfInstantiation,
906 diag::note_prior_template_arg_substitution)
907 << isa<TemplateTemplateParmDecl>(Parm)
908 << Name
909 << getTemplateArgumentBindingsText(TemplateParams,
910 Active->TemplateArgs,
911 Active->NumTemplateArgs)
912 << Active->InstantiationRange;
913 break;
914 }
915
917 TemplateParameterList *TemplateParams = nullptr;
918 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
919 TemplateParams = Template->getTemplateParameters();
920 else
921 TemplateParams =
922 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
923 ->getTemplateParameters();
924
925 Diags.Report(Active->PointOfInstantiation,
926 diag::note_template_default_arg_checking)
927 << getTemplateArgumentBindingsText(TemplateParams,
928 Active->TemplateArgs,
929 Active->NumTemplateArgs)
930 << Active->InstantiationRange;
931 break;
932 }
933
935 Diags.Report(Active->PointOfInstantiation,
936 diag::note_evaluating_exception_spec_here)
937 << cast<FunctionDecl>(Active->Entity);
938 break;
939
941 Diags.Report(Active->PointOfInstantiation,
942 diag::note_template_exception_spec_instantiation_here)
943 << cast<FunctionDecl>(Active->Entity)
944 << Active->InstantiationRange;
945 break;
946
948 Diags.Report(Active->PointOfInstantiation,
949 diag::note_template_requirement_instantiation_here)
950 << Active->InstantiationRange;
951 break;
953 Diags.Report(Active->PointOfInstantiation,
954 diag::note_template_requirement_params_instantiation_here)
955 << Active->InstantiationRange;
956 break;
957
959 Diags.Report(Active->PointOfInstantiation,
960 diag::note_nested_requirement_here)
961 << Active->InstantiationRange;
962 break;
963
965 Diags.Report(Active->PointOfInstantiation,
966 diag::note_in_declaration_of_implicit_special_member)
967 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
968 break;
969
971 Diags.Report(Active->Entity->getLocation(),
972 diag::note_in_declaration_of_implicit_equality_comparison);
973 break;
974
976 // FIXME: For synthesized functions that are not defaulted,
977 // produce a note.
978 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
981 if (DFK.isSpecialMember()) {
982 auto *MD = cast<CXXMethodDecl>(FD);
983 Diags.Report(Active->PointOfInstantiation,
984 diag::note_member_synthesized_at)
985 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
986 << Context.getTagDeclType(MD->getParent());
987 } else if (DFK.isComparison()) {
988 QualType RecordType = FD->getParamDecl(0)
989 ->getType()
990 .getNonReferenceType()
991 .getUnqualifiedType();
992 Diags.Report(Active->PointOfInstantiation,
993 diag::note_comparison_synthesized_at)
994 << (int)DFK.asComparison() << RecordType;
995 }
996 break;
997 }
998
1000 Diags.Report(Active->Entity->getLocation(),
1001 diag::note_rewriting_operator_as_spaceship);
1002 break;
1003
1005 Diags.Report(Active->PointOfInstantiation,
1006 diag::note_in_binding_decl_init)
1007 << cast<BindingDecl>(Active->Entity);
1008 break;
1009
1011 Diags.Report(Active->PointOfInstantiation,
1012 diag::note_due_to_dllexported_class)
1013 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
1014 break;
1015
1017 Diags.Report(Active->PointOfInstantiation,
1018 diag::note_building_builtin_dump_struct_call)
1020 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
1021 break;
1022
1024 break;
1025
1027 Diags.Report(Active->PointOfInstantiation,
1028 diag::note_lambda_substitution_here);
1029 break;
1031 unsigned DiagID = 0;
1032 if (!Active->Entity) {
1033 Diags.Report(Active->PointOfInstantiation,
1034 diag::note_nested_requirement_here)
1035 << Active->InstantiationRange;
1036 break;
1037 }
1038 if (isa<ConceptDecl>(Active->Entity))
1039 DiagID = diag::note_concept_specialization_here;
1040 else if (isa<TemplateDecl>(Active->Entity))
1041 DiagID = diag::note_checking_constraints_for_template_id_here;
1042 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1043 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1044 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1045 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1046 else {
1047 assert(isa<FunctionDecl>(Active->Entity));
1048 DiagID = diag::note_checking_constraints_for_function_here;
1049 }
1050 SmallString<128> TemplateArgsStr;
1051 llvm::raw_svector_ostream OS(TemplateArgsStr);
1052 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1053 if (!isa<FunctionDecl>(Active->Entity)) {
1054 printTemplateArgumentList(OS, Active->template_arguments(),
1056 }
1057 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
1058 << Active->InstantiationRange;
1059 break;
1060 }
1062 Diags.Report(Active->PointOfInstantiation,
1063 diag::note_constraint_substitution_here)
1064 << Active->InstantiationRange;
1065 break;
1067 Diags.Report(Active->PointOfInstantiation,
1068 diag::note_constraint_normalization_here)
1069 << cast<NamedDecl>(Active->Entity)->getName()
1070 << Active->InstantiationRange;
1071 break;
1073 Diags.Report(Active->PointOfInstantiation,
1074 diag::note_parameter_mapping_substitution_here)
1075 << Active->InstantiationRange;
1076 break;
1078 llvm_unreachable("unexpected deduction guide in instantiation stack");
1079 }
1080 }
1081}
1082
1083std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1085 return std::optional<TemplateDeductionInfo *>(nullptr);
1086
1088 Active = CodeSynthesisContexts.rbegin(),
1089 ActiveEnd = CodeSynthesisContexts.rend();
1090 Active != ActiveEnd;
1091 ++Active)
1092 {
1093 switch (Active->Kind) {
1095 // An instantiation of an alias template may or may not be a SFINAE
1096 // context, depending on what else is on the stack.
1097 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1098 break;
1099 [[fallthrough]];
1106 // This is a template instantiation, so there is no SFINAE.
1107 return std::nullopt;
1109 // [temp.deduct]p9
1110 // A lambda-expression appearing in a function type or a template
1111 // parameter is not considered part of the immediate context for the
1112 // purposes of template argument deduction.
1113 // CWG2672: A lambda-expression body is never in the immediate context.
1114 return std::nullopt;
1115
1120 // A default template argument instantiation and substitution into
1121 // template parameters with arguments for prior parameters may or may
1122 // not be a SFINAE context; look further up the stack.
1123 break;
1124
1127 // We're either substituting explicitly-specified template arguments,
1128 // deduced template arguments. SFINAE applies unless we are in a lambda
1129 // expression, see [temp.deduct]p9.
1130 [[fallthrough]];
1134 // SFINAE always applies in a constraint expression or a requirement
1135 // in a requires expression.
1136 assert(Active->DeductionInfo && "Missing deduction info pointer");
1137 return Active->DeductionInfo;
1138
1146 // This happens in a context unrelated to template instantiation, so
1147 // there is no SFINAE.
1148 return std::nullopt;
1149
1151 // FIXME: This should not be treated as a SFINAE context, because
1152 // we will cache an incorrect exception specification. However, clang
1153 // bootstrap relies this! See PR31692.
1154 break;
1155
1157 break;
1158 }
1159
1160 // The inner context was transparent for SFINAE. If it occurred within a
1161 // non-instantiation SFINAE context, then SFINAE applies.
1162 if (Active->SavedInNonInstantiationSFINAEContext)
1163 return std::optional<TemplateDeductionInfo *>(nullptr);
1164 }
1165
1166 return std::nullopt;
1167}
1168
1169//===----------------------------------------------------------------------===/
1170// Template Instantiation for Types
1171//===----------------------------------------------------------------------===/
1172namespace {
1173 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1174 const MultiLevelTemplateArgumentList &TemplateArgs;
1175 SourceLocation Loc;
1176 DeclarationName Entity;
1177 bool EvaluateConstraints = true;
1178
1179 public:
1180 typedef TreeTransform<TemplateInstantiator> inherited;
1181
1182 TemplateInstantiator(Sema &SemaRef,
1183 const MultiLevelTemplateArgumentList &TemplateArgs,
1184 SourceLocation Loc, DeclarationName Entity)
1185 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1186 Entity(Entity) {}
1187
1188 void setEvaluateConstraints(bool B) {
1189 EvaluateConstraints = B;
1190 }
1191 bool getEvaluateConstraints() {
1192 return EvaluateConstraints;
1193 }
1194
1195 /// Determine whether the given type \p T has already been
1196 /// transformed.
1197 ///
1198 /// For the purposes of template instantiation, a type has already been
1199 /// transformed if it is NULL or if it is not dependent.
1200 bool AlreadyTransformed(QualType T);
1201
1202 /// Returns the location of the entity being instantiated, if known.
1203 SourceLocation getBaseLocation() { return Loc; }
1204
1205 /// Returns the name of the entity being instantiated, if any.
1206 DeclarationName getBaseEntity() { return Entity; }
1207
1208 /// Sets the "base" location and entity when that
1209 /// information is known based on another transformation.
1210 void setBase(SourceLocation Loc, DeclarationName Entity) {
1211 this->Loc = Loc;
1212 this->Entity = Entity;
1213 }
1214
1215 unsigned TransformTemplateDepth(unsigned Depth) {
1216 return TemplateArgs.getNewDepth(Depth);
1217 }
1218
1219 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1220 int Index = getSema().ArgumentPackSubstitutionIndex;
1221 if (Index == -1)
1222 return std::nullopt;
1223 return Pack.pack_size() - 1 - Index;
1224 }
1225
1226 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1227 SourceRange PatternRange,
1229 bool &ShouldExpand, bool &RetainExpansion,
1230 std::optional<unsigned> &NumExpansions) {
1231 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1232 PatternRange, Unexpanded,
1233 TemplateArgs,
1234 ShouldExpand,
1235 RetainExpansion,
1236 NumExpansions);
1237 }
1238
1239 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1241 }
1242
1243 TemplateArgument ForgetPartiallySubstitutedPack() {
1244 TemplateArgument Result;
1245 if (NamedDecl *PartialPack
1247 MultiLevelTemplateArgumentList &TemplateArgs
1248 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1249 unsigned Depth, Index;
1250 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1251 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1252 Result = TemplateArgs(Depth, Index);
1253 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1254 }
1255 }
1256
1257 return Result;
1258 }
1259
1260 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1261 if (Arg.isNull())
1262 return;
1263
1264 if (NamedDecl *PartialPack
1266 MultiLevelTemplateArgumentList &TemplateArgs
1267 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1268 unsigned Depth, Index;
1269 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1270 TemplateArgs.setArgument(Depth, Index, Arg);
1271 }
1272 }
1273
1274 /// Transform the given declaration by instantiating a reference to
1275 /// this declaration.
1276 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1277
1278 void transformAttrs(Decl *Old, Decl *New) {
1279 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1280 }
1281
1282 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1283 if (Old->isParameterPack()) {
1285 for (auto *New : NewDecls)
1287 Old, cast<VarDecl>(New));
1288 return;
1289 }
1290
1291 assert(NewDecls.size() == 1 &&
1292 "should only have multiple expansions for a pack");
1293 Decl *New = NewDecls.front();
1294
1295 // If we've instantiated the call operator of a lambda or the call
1296 // operator template of a generic lambda, update the "instantiation of"
1297 // information.
1298 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1299 if (NewMD && isLambdaCallOperator(NewMD)) {
1300 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1301 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1302 NewTD->setInstantiatedFromMemberTemplate(
1303 OldMD->getDescribedFunctionTemplate());
1304 else
1305 NewMD->setInstantiationOfMemberFunction(OldMD,
1307 }
1308
1310
1311 // We recreated a local declaration, but not by instantiating it. There
1312 // may be pending dependent diagnostics to produce.
1313 if (auto *DC = dyn_cast<DeclContext>(Old);
1314 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1315 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1316 }
1317
1318 /// Transform the definition of the given declaration by
1319 /// instantiating it.
1320 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1321
1322 /// Transform the first qualifier within a scope by instantiating the
1323 /// declaration.
1324 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1325
1326 /// Rebuild the exception declaration and register the declaration
1327 /// as an instantiated local.
1328 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1330 SourceLocation StartLoc,
1331 SourceLocation NameLoc,
1332 IdentifierInfo *Name);
1333
1334 /// Rebuild the Objective-C exception declaration and register the
1335 /// declaration as an instantiated local.
1336 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1337 TypeSourceInfo *TSInfo, QualType T);
1338
1339 /// Check for tag mismatches when instantiating an
1340 /// elaborated type.
1341 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1342 ElaboratedTypeKeyword Keyword,
1343 NestedNameSpecifierLoc QualifierLoc,
1344 QualType T);
1345
1347 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1348 SourceLocation NameLoc,
1349 QualType ObjectType = QualType(),
1350 NamedDecl *FirstQualifierInScope = nullptr,
1351 bool AllowInjectedClassName = false);
1352
1353 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1354 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1355 const Stmt *InstS,
1356 const NoInlineAttr *A);
1357 const AlwaysInlineAttr *
1358 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1359 const AlwaysInlineAttr *A);
1360
1361 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1362 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1363 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1364
1365 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1367 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1369 ExprResult TransformSubstNonTypeTemplateParmExpr(
1371
1372 /// Rebuild a DeclRefExpr for a VarDecl reference.
1373 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1374
1375 /// Transform a reference to a function or init-capture parameter pack.
1376 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1377
1378 /// Transform a FunctionParmPackExpr which was built when we couldn't
1379 /// expand a function parameter pack reference which refers to an expanded
1380 /// pack.
1381 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1382
1383 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1385 // Call the base version; it will forward to our overridden version below.
1386 return inherited::TransformFunctionProtoType(TLB, TL);
1387 }
1388
1389 template<typename Fn>
1390 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1392 CXXRecordDecl *ThisContext,
1393 Qualifiers ThisTypeQuals,
1394 Fn TransformExceptionSpec);
1395
1396 ParmVarDecl *
1397 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1398 std::optional<unsigned> NumExpansions,
1399 bool ExpectParameterPack);
1400
1401 using inherited::TransformTemplateTypeParmType;
1402 /// Transforms a template type parameter type by performing
1403 /// substitution of the corresponding template type argument.
1404 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1406 bool SuppressObjCLifetime);
1407
1408 QualType BuildSubstTemplateTypeParmType(
1409 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1410 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1411 TemplateArgument Arg, SourceLocation NameLoc);
1412
1413 /// Transforms an already-substituted template type parameter pack
1414 /// into either itself (if we aren't substituting into its pack expansion)
1415 /// or the appropriate substituted argument.
1416 using inherited::TransformSubstTemplateTypeParmPackType;
1417 QualType
1418 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1420 bool SuppressObjCLifetime);
1421
1422 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1423 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1425
1428 C.PointOfInstantiation = E->getBeginLoc();
1429 SemaRef.pushCodeSynthesisContext(C);
1430 auto PopCtx =
1431 llvm::make_scope_exit([this] { SemaRef.popCodeSynthesisContext(); });
1432
1433 ExprResult Result = inherited::TransformLambdaExpr(E);
1434 if (Result.isInvalid())
1435 return Result;
1436
1437 CXXMethodDecl *MD = Result.getAs<LambdaExpr>()->getCallOperator();
1438 for (ParmVarDecl *PVD : MD->parameters()) {
1439 assert(PVD && "null in a parameter list");
1440 if (!PVD->hasDefaultArg())
1441 continue;
1442 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1443 // FIXME: Obtain the source location for the '=' token.
1444 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1445 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1446 // If substitution fails, the default argument is set to a
1447 // RecoveryExpr that wraps the uninstantiated default argument so
1448 // that downstream diagnostics are omitted.
1449 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1450 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
1451 { UninstExpr }, UninstExpr->getType());
1452 if (ErrorResult.isUsable())
1453 PVD->setDefaultArg(ErrorResult.get());
1454 }
1455 }
1456
1457 return Result;
1458 }
1459
1460 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1461 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1462 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1463 if (TransReq.isInvalid())
1464 return TransReq;
1465 assert(TransReq.get() != E &&
1466 "Do not change value of isSatisfied for the existing expression. "
1467 "Create a new expression instead.");
1468 if (E->getBody()->isDependentContext()) {
1469 Sema::SFINAETrap Trap(SemaRef);
1470 // We recreate the RequiresExpr body, but not by instantiating it.
1471 // Produce pending diagnostics for dependent access check.
1472 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1473 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1474 if (Trap.hasErrorOccurred())
1475 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1476 }
1477 return TransReq;
1478 }
1479
1480 bool TransformRequiresExprRequirements(
1483 bool SatisfactionDetermined = false;
1484 for (concepts::Requirement *Req : Reqs) {
1485 concepts::Requirement *TransReq = nullptr;
1486 if (!SatisfactionDetermined) {
1487 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1488 TransReq = TransformTypeRequirement(TypeReq);
1489 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1490 TransReq = TransformExprRequirement(ExprReq);
1491 else
1492 TransReq = TransformNestedRequirement(
1493 cast<concepts::NestedRequirement>(Req));
1494 if (!TransReq)
1495 return true;
1496 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1497 // [expr.prim.req]p6
1498 // [...] The substitution and semantic constraint checking
1499 // proceeds in lexical order and stops when a condition that
1500 // determines the result of the requires-expression is
1501 // encountered. [..]
1502 SatisfactionDetermined = true;
1503 } else
1504 TransReq = Req;
1505 Transformed.push_back(TransReq);
1506 }
1507 return false;
1508 }
1509
1510 TemplateParameterList *TransformTemplateParameterList(
1511 TemplateParameterList *OrigTPL) {
1512 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1513
1514 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1515 TemplateDeclInstantiator DeclInstantiator(getSema(),
1516 /* DeclContext *Owner */ Owner, TemplateArgs);
1517 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1518 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1519 }
1520
1522 TransformTypeRequirement(concepts::TypeRequirement *Req);
1524 TransformExprRequirement(concepts::ExprRequirement *Req);
1526 TransformNestedRequirement(concepts::NestedRequirement *Req);
1527 ExprResult TransformRequiresTypeParams(
1528 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1531 SmallVectorImpl<ParmVarDecl *> &TransParams,
1533
1534 private:
1536 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1537 const NonTypeTemplateParmDecl *parm,
1539 std::optional<unsigned> PackIndex);
1540 };
1541}
1542
1543bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1544 if (T.isNull())
1545 return true;
1546
1548 return false;
1549
1550 getSema().MarkDeclarationsReferencedInType(Loc, T);
1551 return true;
1552}
1553
1554static TemplateArgument
1556 assert(S.ArgumentPackSubstitutionIndex >= 0);
1557 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1559 if (Arg.isPackExpansion())
1560 Arg = Arg.getPackExpansionPattern();
1561 return Arg;
1562}
1563
1564Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1565 if (!D)
1566 return nullptr;
1567
1568 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1569 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1570 // If the corresponding template argument is NULL or non-existent, it's
1571 // because we are performing instantiation from explicitly-specified
1572 // template arguments in a function template, but there were some
1573 // arguments left unspecified.
1574 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1575 TTP->getPosition()))
1576 return D;
1577
1578 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1579
1580 if (TTP->isParameterPack()) {
1581 assert(Arg.getKind() == TemplateArgument::Pack &&
1582 "Missing argument pack");
1583 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1584 }
1585
1587 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1588 "Wrong kind of template template argument");
1589 return Template.getAsTemplateDecl();
1590 }
1591
1592 // Fall through to find the instantiated declaration for this template
1593 // template parameter.
1594 }
1595
1596 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1597}
1598
1599Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1600 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1601 if (!Inst)
1602 return nullptr;
1603
1604 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1605 return Inst;
1606}
1607
1608NamedDecl *
1609TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1610 SourceLocation Loc) {
1611 // If the first part of the nested-name-specifier was a template type
1612 // parameter, instantiate that type parameter down to a tag type.
1613 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1614 const TemplateTypeParmType *TTP
1615 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1616
1617 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1618 // FIXME: This needs testing w/ member access expressions.
1619 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1620
1621 if (TTP->isParameterPack()) {
1622 assert(Arg.getKind() == TemplateArgument::Pack &&
1623 "Missing argument pack");
1624
1625 if (getSema().ArgumentPackSubstitutionIndex == -1)
1626 return nullptr;
1627
1628 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1629 }
1630
1631 QualType T = Arg.getAsType();
1632 if (T.isNull())
1633 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1634
1635 if (const TagType *Tag = T->getAs<TagType>())
1636 return Tag->getDecl();
1637
1638 // The resulting type is not a tag; complain.
1639 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1640 return nullptr;
1641 }
1642 }
1643
1644 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1645}
1646
1647VarDecl *
1648TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1650 SourceLocation StartLoc,
1651 SourceLocation NameLoc,
1652 IdentifierInfo *Name) {
1653 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1654 StartLoc, NameLoc, Name);
1655 if (Var)
1656 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1657 return Var;
1658}
1659
1660VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1661 TypeSourceInfo *TSInfo,
1662 QualType T) {
1663 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1664 if (Var)
1665 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1666 return Var;
1667}
1668
1670TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1671 ElaboratedTypeKeyword Keyword,
1672 NestedNameSpecifierLoc QualifierLoc,
1673 QualType T) {
1674 if (const TagType *TT = T->getAs<TagType>()) {
1675 TagDecl* TD = TT->getDecl();
1676
1677 SourceLocation TagLocation = KeywordLoc;
1678
1680
1681 // TODO: should we even warn on struct/class mismatches for this? Seems
1682 // like it's likely to produce a lot of spurious errors.
1683 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1685 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1686 TagLocation, Id)) {
1687 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1688 << Id
1690 TD->getKindName());
1691 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1692 }
1693 }
1694 }
1695
1696 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
1697}
1698
1699TemplateName TemplateInstantiator::TransformTemplateName(
1700 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1701 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1702 bool AllowInjectedClassName) {
1704 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1705 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1706 // If the corresponding template argument is NULL or non-existent, it's
1707 // because we are performing instantiation from explicitly-specified
1708 // template arguments in a function template, but there were some
1709 // arguments left unspecified.
1710 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1711 TTP->getPosition()))
1712 return Name;
1713
1714 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1715
1716 if (TemplateArgs.isRewrite()) {
1717 // We're rewriting the template parameter as a reference to another
1718 // template parameter.
1719 if (Arg.getKind() == TemplateArgument::Pack) {
1720 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1721 "unexpected pack arguments in template rewrite");
1722 Arg = Arg.pack_begin()->getPackExpansionPattern();
1723 }
1724 assert(Arg.getKind() == TemplateArgument::Template &&
1725 "unexpected nontype template argument kind in template rewrite");
1726 return Arg.getAsTemplate();
1727 }
1728
1729 auto [AssociatedDecl, Final] =
1730 TemplateArgs.getAssociatedDecl(TTP->getDepth());
1731 std::optional<unsigned> PackIndex;
1732 if (TTP->isParameterPack()) {
1733 assert(Arg.getKind() == TemplateArgument::Pack &&
1734 "Missing argument pack");
1735
1736 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1737 // We have the template argument pack to substitute, but we're not
1738 // actually expanding the enclosing pack expansion yet. So, just
1739 // keep the entire argument pack.
1740 return getSema().Context.getSubstTemplateTemplateParmPack(
1741 Arg, AssociatedDecl, TTP->getIndex(), Final);
1742 }
1743
1744 PackIndex = getPackIndex(Arg);
1745 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1746 }
1747
1749 assert(!Template.isNull() && "Null template template argument");
1750 assert(!Template.getAsQualifiedTemplateName() &&
1751 "template decl to substitute is qualified?");
1752
1753 if (Final)
1754 return Template;
1755 return getSema().Context.getSubstTemplateTemplateParm(
1756 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
1757 }
1758 }
1759
1761 = Name.getAsSubstTemplateTemplateParmPack()) {
1762 if (getSema().ArgumentPackSubstitutionIndex == -1)
1763 return Name;
1764
1765 TemplateArgument Pack = SubstPack->getArgumentPack();
1766 TemplateName Template =
1768 if (SubstPack->getFinal())
1769 return Template;
1770 return getSema().Context.getSubstTemplateTemplateParm(
1771 Template.getNameToSubstitute(), SubstPack->getAssociatedDecl(),
1772 SubstPack->getIndex(), getPackIndex(Pack));
1773 }
1774
1775 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1776 FirstQualifierInScope,
1777 AllowInjectedClassName);
1778}
1779
1781TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1782 if (!E->isTypeDependent())
1783 return E;
1784
1785 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1786}
1787
1789TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1791 // If the corresponding template argument is NULL or non-existent, it's
1792 // because we are performing instantiation from explicitly-specified
1793 // template arguments in a function template, but there were some
1794 // arguments left unspecified.
1795 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1796 NTTP->getPosition()))
1797 return E;
1798
1799 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1800
1801 if (TemplateArgs.isRewrite()) {
1802 // We're rewriting the template parameter as a reference to another
1803 // template parameter.
1804 if (Arg.getKind() == TemplateArgument::Pack) {
1805 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1806 "unexpected pack arguments in template rewrite");
1807 Arg = Arg.pack_begin()->getPackExpansionPattern();
1808 }
1809 assert(Arg.getKind() == TemplateArgument::Expression &&
1810 "unexpected nontype template argument kind in template rewrite");
1811 // FIXME: This can lead to the same subexpression appearing multiple times
1812 // in a complete expression.
1813 return Arg.getAsExpr();
1814 }
1815
1816 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
1817 std::optional<unsigned> PackIndex;
1818 if (NTTP->isParameterPack()) {
1819 assert(Arg.getKind() == TemplateArgument::Pack &&
1820 "Missing argument pack");
1821
1822 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1823 // We have an argument pack, but we can't select a particular argument
1824 // out of it yet. Therefore, we'll build an expression to hold on to that
1825 // argument pack.
1826 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1827 E->getLocation(),
1828 NTTP->getDeclName());
1829 if (TargetType.isNull())
1830 return ExprError();
1831
1832 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
1833 if (TargetType->isRecordType())
1834 ExprType.addConst();
1835 // FIXME: Pass in Final.
1836 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1837 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
1838 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
1839 }
1840 PackIndex = getPackIndex(Arg);
1841 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1842 }
1843 // FIXME: Don't put subst node on Final replacement.
1844 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
1845 Arg, PackIndex);
1846}
1847
1848const LoopHintAttr *
1849TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1850 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1851
1852 if (TransformedExpr == LH->getValue())
1853 return LH;
1854
1855 // Generate error if there is a problem with the value.
1856 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1857 return LH;
1858
1859 // Create new LoopHintValueAttr with integral expression in place of the
1860 // non-type template parameter.
1861 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1862 LH->getState(), TransformedExpr, *LH);
1863}
1864const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
1865 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
1866 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
1867 return nullptr;
1868
1869 return A;
1870}
1871const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
1872 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
1873 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
1874 return nullptr;
1875
1876 return A;
1877}
1878
1879ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1880 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
1882 std::optional<unsigned> PackIndex) {
1883 ExprResult result;
1884
1885 // Determine the substituted parameter type. We can usually infer this from
1886 // the template argument, but not always.
1887 auto SubstParamType = [&] {
1888 QualType T;
1889 if (parm->isExpandedParameterPack())
1891 else
1892 T = parm->getType();
1893 if (parm->isParameterPack() && isa<PackExpansionType>(T))
1894 T = cast<PackExpansionType>(T)->getPattern();
1895 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
1896 };
1897
1898 bool refParam = false;
1899
1900 // The template argument itself might be an expression, in which case we just
1901 // return that expression. This happens when substituting into an alias
1902 // template.
1903 if (arg.getKind() == TemplateArgument::Expression) {
1904 Expr *argExpr = arg.getAsExpr();
1905 result = argExpr;
1906 if (argExpr->isLValue()) {
1907 if (argExpr->getType()->isRecordType()) {
1908 // Check whether the parameter was actually a reference.
1909 QualType paramType = SubstParamType();
1910 if (paramType.isNull())
1911 return ExprError();
1912 refParam = paramType->isReferenceType();
1913 } else {
1914 refParam = true;
1915 }
1916 }
1917 } else if (arg.getKind() == TemplateArgument::Declaration ||
1918 arg.getKind() == TemplateArgument::NullPtr) {
1919 ValueDecl *VD;
1920 if (arg.getKind() == TemplateArgument::Declaration) {
1921 VD = arg.getAsDecl();
1922
1923 // Find the instantiation of the template argument. This is
1924 // required for nested templates.
1925 VD = cast_or_null<ValueDecl>(
1926 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1927 if (!VD)
1928 return ExprError();
1929 } else {
1930 // Propagate NULL template argument.
1931 VD = nullptr;
1932 }
1933
1934 QualType paramType = VD ? arg.getParamTypeForDecl() : arg.getNullPtrType();
1935 assert(!paramType.isNull() && "type substitution failed for param type");
1936 assert(!paramType->isDependentType() && "param type still dependent");
1937 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
1938 refParam = paramType->isReferenceType();
1939 } else {
1940 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1941 assert(result.isInvalid() ||
1942 SemaRef.Context.hasSameType(result.get()->getType(),
1943 arg.getIntegralType()));
1944 }
1945
1946 if (result.isInvalid())
1947 return ExprError();
1948
1949 Expr *resultExpr = result.get();
1950 // FIXME: Don't put subst node on final replacement.
1951 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1952 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
1953 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
1954}
1955
1957TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1959 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1960 // We aren't expanding the parameter pack, so just return ourselves.
1961 return E;
1962 }
1963
1966 // FIXME: Don't put subst node on final replacement.
1967 return transformNonTypeTemplateParmRef(
1969 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
1970}
1971
1973TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
1975 ExprResult SubstReplacement = E->getReplacement();
1976 if (!isa<ConstantExpr>(SubstReplacement.get()))
1977 SubstReplacement = TransformExpr(E->getReplacement());
1978 if (SubstReplacement.isInvalid())
1979 return true;
1980 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
1981 if (SubstType.isNull())
1982 return true;
1983 // The type may have been previously dependent and not now, which means we
1984 // might have to implicit cast the argument to the new type, for example:
1985 // template<auto T, decltype(T) U>
1986 // concept C = sizeof(U) == 4;
1987 // void foo() requires C<2, 'a'> { }
1988 // When normalizing foo(), we first form the normalized constraints of C:
1989 // AtomicExpr(sizeof(U) == 4,
1990 // U=SubstNonTypeTemplateParmExpr(Param=U,
1991 // Expr=DeclRef(U),
1992 // Type=decltype(T)))
1993 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
1994 // produce:
1995 // AtomicExpr(sizeof(U) == 4,
1996 // U=SubstNonTypeTemplateParmExpr(Param=U,
1997 // Expr=ImpCast(
1998 // decltype(2),
1999 // SubstNTTPE(Param=U, Expr='a',
2000 // Type=char)),
2001 // Type=decltype(2)))
2002 // The call to CheckTemplateArgument here produces the ImpCast.
2003 TemplateArgument SugaredConverted, CanonicalConverted;
2004 if (SemaRef
2006 SubstReplacement.get(), SugaredConverted,
2007 CanonicalConverted, Sema::CTAK_Specified)
2008 .isInvalid())
2009 return true;
2010 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
2011 E->getParameter(), E->getExprLoc(),
2012 SugaredConverted, E->getPackIndex());
2013}
2014
2015ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
2016 SourceLocation Loc) {
2017 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2018 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2019}
2020
2022TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2023 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2024 // We can expand this parameter pack now.
2026 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
2027 if (!VD)
2028 return ExprError();
2029 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2030 }
2031
2032 QualType T = TransformType(E->getType());
2033 if (T.isNull())
2034 return ExprError();
2035
2036 // Transform each of the parameter expansions into the corresponding
2037 // parameters in the instantiation of the function decl.
2039 Vars.reserve(E->getNumExpansions());
2040 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2041 I != End; ++I) {
2042 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2043 if (!D)
2044 return ExprError();
2045 Vars.push_back(D);
2046 }
2047
2048 auto *PackExpr =
2050 E->getParameterPackLocation(), Vars);
2051 getSema().MarkFunctionParmPackReferenced(PackExpr);
2052 return PackExpr;
2053}
2054
2056TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2057 VarDecl *PD) {
2058 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2059 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2060 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2061 assert(Found && "no instantiation for parameter pack");
2062
2063 Decl *TransformedDecl;
2064 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2065 // If this is a reference to a function parameter pack which we can
2066 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2067 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2068 QualType T = TransformType(E->getType());
2069 if (T.isNull())
2070 return ExprError();
2071 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2072 E->getExprLoc(), *Pack);
2073 getSema().MarkFunctionParmPackReferenced(PackExpr);
2074 return PackExpr;
2075 }
2076
2077 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2078 } else {
2079 TransformedDecl = Found->get<Decl*>();
2080 }
2081
2082 // We have either an unexpanded pack or a specific expansion.
2083 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2084}
2085
2087TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2088 NamedDecl *D = E->getDecl();
2089
2090 // Handle references to non-type template parameters and non-type template
2091 // parameter packs.
2092 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2093 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2094 return TransformTemplateParmRefExpr(E, NTTP);
2095
2096 // We have a non-type template parameter that isn't fully substituted;
2097 // FindInstantiatedDecl will find it in the local instantiation scope.
2098 }
2099
2100 // Handle references to function parameter packs.
2101 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2102 if (PD->isParameterPack())
2103 return TransformFunctionParmPackRefExpr(E, PD);
2104
2105 return inherited::TransformDeclRefExpr(E);
2106}
2107
2108ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2109 CXXDefaultArgExpr *E) {
2110 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2111 getDescribedFunctionTemplate() &&
2112 "Default arg expressions are never formed in dependent cases.");
2113 return SemaRef.BuildCXXDefaultArgExpr(
2114 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2115 E->getParam());
2116}
2117
2118template<typename Fn>
2119QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2121 CXXRecordDecl *ThisContext,
2122 Qualifiers ThisTypeQuals,
2123 Fn TransformExceptionSpec) {
2124 // We need a local instantiation scope for this function prototype.
2125 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
2126 return inherited::TransformFunctionProtoType(
2127 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2128}
2129
2130ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2131 ParmVarDecl *OldParm, int indexAdjustment,
2132 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2133 auto NewParm = SemaRef.SubstParmVarDecl(
2134 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2135 ExpectParameterPack, EvaluateConstraints);
2136 if (NewParm && SemaRef.getLangOpts().OpenCL)
2137 SemaRef.deduceOpenCLAddressSpace(NewParm);
2138 return NewParm;
2139}
2140
2141QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2142 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2143 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2144 TemplateArgument Arg, SourceLocation NameLoc) {
2145 QualType Replacement = Arg.getAsType();
2146
2147 // If the template parameter had ObjC lifetime qualifiers,
2148 // then any such qualifiers on the replacement type are ignored.
2149 if (SuppressObjCLifetime) {
2150 Qualifiers RQs;
2151 RQs = Replacement.getQualifiers();
2152 RQs.removeObjCLifetime();
2153 Replacement =
2154 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2155 }
2156
2157 if (Final) {
2158 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2159 return Replacement;
2160 }
2161 // TODO: only do this uniquing once, at the start of instantiation.
2162 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2163 Replacement, AssociatedDecl, Index, PackIndex);
2166 NewTL.setNameLoc(NameLoc);
2167 return Result;
2168}
2169
2171TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2173 bool SuppressObjCLifetime) {
2174 const TemplateTypeParmType *T = TL.getTypePtr();
2175 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2176 // Replace the template type parameter with its corresponding
2177 // template argument.
2178
2179 // If the corresponding template argument is NULL or doesn't exist, it's
2180 // because we are performing instantiation from explicitly-specified
2181 // template arguments in a function template class, but there were some
2182 // arguments left unspecified.
2183 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2186 NewTL.setNameLoc(TL.getNameLoc());
2187 return TL.getType();
2188 }
2189
2190 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2191
2192 if (TemplateArgs.isRewrite()) {
2193 // We're rewriting the template parameter as a reference to another
2194 // template parameter.
2195 if (Arg.getKind() == TemplateArgument::Pack) {
2196 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2197 "unexpected pack arguments in template rewrite");
2198 Arg = Arg.pack_begin()->getPackExpansionPattern();
2199 }
2200 assert(Arg.getKind() == TemplateArgument::Type &&
2201 "unexpected nontype template argument kind in template rewrite");
2202 QualType NewT = Arg.getAsType();
2203 assert(isa<TemplateTypeParmType>(NewT) &&
2204 "type parm not rewritten to type parm");
2205 auto NewTL = TLB.push<TemplateTypeParmTypeLoc>(NewT);
2206 NewTL.setNameLoc(TL.getNameLoc());
2207 return NewT;
2208 }
2209
2210 auto [AssociatedDecl, Final] =
2211 TemplateArgs.getAssociatedDecl(T->getDepth());
2212 std::optional<unsigned> PackIndex;
2213 if (T->isParameterPack()) {
2214 assert(Arg.getKind() == TemplateArgument::Pack &&
2215 "Missing argument pack");
2216
2217 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2218 // We have the template argument pack, but we're not expanding the
2219 // enclosing pack expansion yet. Just save the template argument
2220 // pack for later substitution.
2221 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2222 AssociatedDecl, T->getIndex(), Final, Arg);
2225 NewTL.setNameLoc(TL.getNameLoc());
2226 return Result;
2227 }
2228
2229 // PackIndex starts from last element.
2230 PackIndex = getPackIndex(Arg);
2231 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2232 }
2233
2234 assert(Arg.getKind() == TemplateArgument::Type &&
2235 "Template argument kind mismatch");
2236
2237 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2238 AssociatedDecl, T->getIndex(),
2239 PackIndex, Arg, TL.getNameLoc());
2240 }
2241
2242 // The template type parameter comes from an inner template (e.g.,
2243 // the template parameter list of a member template inside the
2244 // template we are instantiating). Create a new template type
2245 // parameter with the template "level" reduced by one.
2246 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2247 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2248 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2249 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2250 QualType Result = getSema().Context.getTemplateTypeParmType(
2251 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2252 T->isParameterPack(), NewTTPDecl);
2254 NewTL.setNameLoc(TL.getNameLoc());
2255 return Result;
2256}
2257
2258QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2260 bool SuppressObjCLifetime) {
2262
2263 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2264
2265 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2266 // We aren't expanding the parameter pack, so just return ourselves.
2267 QualType Result = TL.getType();
2268 if (NewReplaced != T->getAssociatedDecl())
2269 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2270 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2273 NewTL.setNameLoc(TL.getNameLoc());
2274 return Result;
2275 }
2276
2279 return BuildSubstTemplateTypeParmType(
2280 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2281 getPackIndex(Pack), Arg, TL.getNameLoc());
2282}
2283
2286 concepts::EntityPrinter Printer) {
2287 SmallString<128> Message;
2288 SourceLocation ErrorLoc;
2289 if (Info.hasSFINAEDiagnostic()) {
2292 Info.takeSFINAEDiagnostic(PDA);
2293 PDA.second.EmitToString(S.getDiagnostics(), Message);
2294 ErrorLoc = PDA.first;
2295 } else {
2296 ErrorLoc = Info.getLocation();
2297 }
2298 char *MessageBuf = new (S.Context) char[Message.size()];
2299 std::copy(Message.begin(), Message.end(), MessageBuf);
2300 SmallString<128> Entity;
2301 llvm::raw_svector_ostream OS(Entity);
2302 Printer(OS);
2303 char *EntityBuf = new (S.Context) char[Entity.size()];
2304 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2306 StringRef(EntityBuf, Entity.size()), ErrorLoc,
2307 StringRef(MessageBuf, Message.size())};
2308}
2309
2312 EntityPrinter Printer) {
2313 SmallString<128> Entity;
2314 llvm::raw_svector_ostream OS(Entity);
2315 Printer(OS);
2316 char *EntityBuf = new (S.Context) char[Entity.size()];
2317 llvm::copy(Entity, EntityBuf);
2319 /*SubstitutedEntity=*/StringRef(EntityBuf, Entity.size()),
2320 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2321}
2322
2323ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2324 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2327 SmallVectorImpl<ParmVarDecl *> &TransParams,
2329
2330 TemplateDeductionInfo Info(KWLoc);
2331 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2332 RE, Info,
2333 SourceRange{KWLoc, RBraceLoc});
2334 Sema::SFINAETrap Trap(SemaRef);
2335
2336 unsigned ErrorIdx;
2337 if (getDerived().TransformFunctionTypeParams(
2338 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2339 &TransParams, PInfos, &ErrorIdx) ||
2340 Trap.hasErrorOccurred()) {
2342 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2343 // Add a 'failed' Requirement to contain the error that caused the failure
2344 // here.
2345 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2346 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2347 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2348 TransParams, RE->getRParenLoc(),
2349 TransReqs, RBraceLoc);
2350 }
2351
2352 return ExprResult{};
2353}
2354
2356TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2357 if (!Req->isDependent() && !AlwaysRebuild())
2358 return Req;
2359 if (Req->isSubstitutionFailure()) {
2360 if (AlwaysRebuild())
2361 return RebuildTypeRequirement(
2363 return Req;
2364 }
2365
2366 Sema::SFINAETrap Trap(SemaRef);
2368 Sema::InstantiatingTemplate TypeInst(SemaRef,
2369 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2370 Req->getType()->getTypeLoc().getSourceRange());
2371 if (TypeInst.isInvalid())
2372 return nullptr;
2373 TypeSourceInfo *TransType = TransformType(Req->getType());
2374 if (!TransType || Trap.hasErrorOccurred())
2375 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2376 [&] (llvm::raw_ostream& OS) {
2377 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2378 }));
2379 return RebuildTypeRequirement(TransType);
2380}
2381
2383TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2384 if (!Req->isDependent() && !AlwaysRebuild())
2385 return Req;
2386
2387 Sema::SFINAETrap Trap(SemaRef);
2388
2389 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2390 TransExpr;
2391 if (Req->isExprSubstitutionFailure())
2392 TransExpr = Req->getExprSubstitutionDiagnostic();
2393 else {
2394 Expr *E = Req->getExpr();
2396 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2397 E->getSourceRange());
2398 if (ExprInst.isInvalid())
2399 return nullptr;
2400 ExprResult TransExprRes = TransformExpr(E);
2401 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2402 TransExprRes.get()->hasPlaceholderType())
2403 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2404 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2405 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2406 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2407 });
2408 else
2409 TransExpr = TransExprRes.get();
2410 }
2411
2412 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2413 const auto &RetReq = Req->getReturnTypeRequirement();
2414 if (RetReq.isEmpty())
2415 TransRetReq.emplace();
2416 else if (RetReq.isSubstitutionFailure())
2417 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2418 else if (RetReq.isTypeConstraint()) {
2419 TemplateParameterList *OrigTPL =
2420 RetReq.getTypeConstraintTemplateParameterList();
2421 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2422 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
2423 Req, Info, OrigTPL->getSourceRange());
2424 if (TPLInst.isInvalid())
2425 return nullptr;
2426 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2427 if (!TPL)
2428 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2429 [&] (llvm::raw_ostream& OS) {
2430 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2431 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2432 }));
2433 else {
2434 TPLInst.Clear();
2435 TransRetReq.emplace(TPL);
2436 }
2437 }
2438 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2439 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2440 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2441 std::move(*TransRetReq));
2442 return RebuildExprRequirement(
2444 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2445}
2446
2448TemplateInstantiator::TransformNestedRequirement(
2450 if (!Req->isDependent() && !AlwaysRebuild())
2451 return Req;
2452 if (Req->hasInvalidConstraint()) {
2453 if (AlwaysRebuild())
2454 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2456 return Req;
2457 }
2458 Sema::InstantiatingTemplate ReqInst(SemaRef,
2459 Req->getConstraintExpr()->getBeginLoc(), Req,
2462
2463 ExprResult TransConstraint;
2464 ConstraintSatisfaction Satisfaction;
2466 {
2469 Sema::SFINAETrap Trap(SemaRef);
2470 Sema::InstantiatingTemplate ConstrInst(SemaRef,
2471 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2473 if (ConstrInst.isInvalid())
2474 return nullptr;
2476 if (!SemaRef.CheckConstraintSatisfaction(
2477 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2478 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2479 !Result.empty())
2480 TransConstraint = Result[0];
2481 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2482 "by CheckConstraintSatisfaction.");
2483 }
2484 if (TransConstraint.isUsable() &&
2485 TransConstraint.get()->isInstantiationDependent())
2486 return new (SemaRef.Context)
2487 concepts::NestedRequirement(TransConstraint.get());
2488 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2489 Satisfaction.HasSubstitutionFailure()) {
2490 SmallString<128> Entity;
2491 llvm::raw_svector_ostream OS(Entity);
2492 Req->getConstraintExpr()->printPretty(OS, nullptr,
2493 SemaRef.getPrintingPolicy());
2494 char *EntityBuf = new (SemaRef.Context) char[Entity.size()];
2495 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2496 return new (SemaRef.Context) concepts::NestedRequirement(
2497 SemaRef.Context, StringRef(EntityBuf, Entity.size()), Satisfaction);
2498 }
2499 return new (SemaRef.Context) concepts::NestedRequirement(
2500 SemaRef.Context, TransConstraint.get(), Satisfaction);
2501}
2502
2503
2504/// Perform substitution on the type T with a given set of template
2505/// arguments.
2506///
2507/// This routine substitutes the given template arguments into the
2508/// type T and produces the instantiated type.
2509///
2510/// \param T the type into which the template arguments will be
2511/// substituted. If this type is not dependent, it will be returned
2512/// immediately.
2513///
2514/// \param Args the template arguments that will be
2515/// substituted for the top-level template parameters within T.
2516///
2517/// \param Loc the location in the source code where this substitution
2518/// is being performed. It will typically be the location of the
2519/// declarator (if we're instantiating the type of some declaration)
2520/// or the location of the type in the source code (if, e.g., we're
2521/// instantiating the type of a cast expression).
2522///
2523/// \param Entity the name of the entity associated with a declaration
2524/// being instantiated (if any). May be empty to indicate that there
2525/// is no such entity (if, e.g., this is a type that occurs as part of
2526/// a cast expression) or that the entity has no name (e.g., an
2527/// unnamed function parameter).
2528///
2529/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
2530/// acceptable as the top level type of the result.
2531///
2532/// \returns If the instantiation succeeds, the instantiated
2533/// type. Otherwise, produces diagnostics and returns a NULL type.
2536 SourceLocation Loc,
2537 DeclarationName Entity,
2538 bool AllowDeducedTST) {
2539 assert(!CodeSynthesisContexts.empty() &&
2540 "Cannot perform an instantiation without some context on the "
2541 "instantiation stack");
2542
2545 return T;
2546
2547 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2548 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2549 : Instantiator.TransformType(T);
2550}
2551
2554 SourceLocation Loc,
2555 DeclarationName Entity) {
2556 assert(!CodeSynthesisContexts.empty() &&
2557 "Cannot perform an instantiation without some context on the "
2558 "instantiation stack");
2559
2560 if (TL.getType().isNull())
2561 return nullptr;
2562
2565 // FIXME: Make a copy of the TypeLoc data here, so that we can
2566 // return a new TypeSourceInfo. Inefficient!
2567 TypeLocBuilder TLB;
2568 TLB.pushFullCopy(TL);
2569 return TLB.getTypeSourceInfo(Context, TL.getType());
2570 }
2571
2572 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2573 TypeLocBuilder TLB;
2574 TLB.reserve(TL.getFullDataSize());
2575 QualType Result = Instantiator.TransformType(TLB, TL);
2576 if (Result.isNull())
2577 return nullptr;
2578
2579 return TLB.getTypeSourceInfo(Context, Result);
2580}
2581
2582/// Deprecated form of the above.
2584 const MultiLevelTemplateArgumentList &TemplateArgs,
2585 SourceLocation Loc, DeclarationName Entity) {
2586 assert(!CodeSynthesisContexts.empty() &&
2587 "Cannot perform an instantiation without some context on the "
2588 "instantiation stack");
2589
2590 // If T is not a dependent type or a variably-modified type, there
2591 // is nothing to do.
2593 return T;
2594
2595 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2596 return Instantiator.TransformType(T);
2597}
2598
2602 return true;
2603
2604 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2605 if (!TL.getAs<FunctionProtoTypeLoc>())
2606 return false;
2607
2609 for (ParmVarDecl *P : FP.getParams()) {
2610 // This must be synthesized from a typedef.
2611 if (!P) continue;
2612
2613 // If there are any parameters, a new TypeSourceInfo that refers to the
2614 // instantiated parameters must be built.
2615 return true;
2616 }
2617
2618 return false;
2619}
2620
2621/// A form of SubstType intended specifically for instantiating the
2622/// type of a FunctionDecl. Its purpose is solely to force the
2623/// instantiation of default-argument expressions and to avoid
2624/// instantiating an exception-specification.
2627 SourceLocation Loc,
2628 DeclarationName Entity,
2629 CXXRecordDecl *ThisContext,
2630 Qualifiers ThisTypeQuals,
2631 bool EvaluateConstraints) {
2632 assert(!CodeSynthesisContexts.empty() &&
2633 "Cannot perform an instantiation without some context on the "
2634 "instantiation stack");
2635
2637 return T;
2638
2639 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2640 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2641
2642 TypeLocBuilder TLB;
2643
2644 TypeLoc TL = T->getTypeLoc();
2645 TLB.reserve(TL.getFullDataSize());
2646
2648
2649 if (FunctionProtoTypeLoc Proto =
2651 // Instantiate the type, other than its exception specification. The
2652 // exception specification is instantiated in InitFunctionInstantiation
2653 // once we've built the FunctionDecl.
2654 // FIXME: Set the exception specification to EST_Uninstantiated here,
2655 // instead of rebuilding the function type again later.
2656 Result = Instantiator.TransformFunctionProtoType(
2657 TLB, Proto, ThisContext, ThisTypeQuals,
2659 bool &Changed) { return false; });
2660 } else {
2661 Result = Instantiator.TransformType(TLB, TL);
2662 }
2663 if (Result.isNull())
2664 return nullptr;
2665
2666 return TLB.getTypeSourceInfo(Context, Result);
2667}
2668
2671 SmallVectorImpl<QualType> &ExceptionStorage,
2672 const MultiLevelTemplateArgumentList &Args) {
2673 assert(ESI.Type != EST_Uninstantiated);
2674
2675 bool Changed = false;
2676 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2677 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2678 Changed);
2679}
2680
2682 const MultiLevelTemplateArgumentList &Args) {
2685
2686 SmallVector<QualType, 4> ExceptionStorage;
2688 ESI, ExceptionStorage, Args))
2689 // On error, recover by dropping the exception specification.
2690 ESI.Type = EST_None;
2691
2692 UpdateExceptionSpec(New, ESI);
2693}
2694
2695namespace {
2696
2697 struct GetContainedInventedTypeParmVisitor :
2698 public TypeVisitor<GetContainedInventedTypeParmVisitor,
2699 TemplateTypeParmDecl *> {
2700 using TypeVisitor<GetContainedInventedTypeParmVisitor,
2701 TemplateTypeParmDecl *>::Visit;
2702
2703 TemplateTypeParmDecl *Visit(QualType T) {
2704 if (T.isNull())
2705 return nullptr;
2706 return Visit(T.getTypePtr());
2707 }
2708 // The deduced type itself.
2709 TemplateTypeParmDecl *VisitTemplateTypeParmType(
2710 const TemplateTypeParmType *T) {
2711 if (!T->getDecl() || !T->getDecl()->isImplicit())
2712 return nullptr;
2713 return T->getDecl();
2714 }
2715
2716 // Only these types can contain 'auto' types, and subsequently be replaced
2717 // by references to invented parameters.
2718
2719 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
2720 return Visit(T->getNamedType());
2721 }
2722
2723 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2724 return Visit(T->getPointeeType());
2725 }
2726
2727 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2728 return Visit(T->getPointeeType());
2729 }
2730
2731 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2732 return Visit(T->getPointeeTypeAsWritten());
2733 }
2734
2735 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2736 return Visit(T->getPointeeType());
2737 }
2738
2739 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
2740 return Visit(T->getElementType());
2741 }
2742
2743 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
2744 const DependentSizedExtVectorType *T) {
2745 return Visit(T->getElementType());
2746 }
2747
2748 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
2749 return Visit(T->getElementType());
2750 }
2751
2752 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
2753 return VisitFunctionType(T);
2754 }
2755
2756 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
2757 return Visit(T->getReturnType());
2758 }
2759
2760 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
2761 return Visit(T->getInnerType());
2762 }
2763
2764 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
2765 return Visit(T->getModifiedType());
2766 }
2767
2768 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2769 return Visit(T->getUnderlyingType());
2770 }
2771
2772 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
2773 return Visit(T->getOriginalType());
2774 }
2775
2776 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
2777 return Visit(T->getPattern());
2778 }
2779 };
2780
2781} // namespace
2782
2784 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
2785 const MultiLevelTemplateArgumentList &TemplateArgs,
2786 bool EvaluateConstraints) {
2787 const ASTTemplateArgumentListInfo *TemplArgInfo =
2789
2790 if (!EvaluateConstraints) {
2793 return false;
2794 }
2795
2796 TemplateArgumentListInfo InstArgs;
2797
2798 if (TemplArgInfo) {
2799 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
2800 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
2801 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
2802 InstArgs))
2803 return true;
2804 }
2805 return AttachTypeConstraint(
2807 TC->getNamedConcept(), &InstArgs, Inst,
2808 Inst->isParameterPack()
2809 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2810 ->getEllipsisLoc()
2811 : SourceLocation());
2812}
2813
2815 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
2816 int indexAdjustment, std::optional<unsigned> NumExpansions,
2817 bool ExpectParameterPack, bool EvaluateConstraint) {
2818 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
2819 TypeSourceInfo *NewDI = nullptr;
2820
2821 TypeLoc OldTL = OldDI->getTypeLoc();
2822 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
2823
2824 // We have a function parameter pack. Substitute into the pattern of the
2825 // expansion.
2826 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
2827 OldParm->getLocation(), OldParm->getDeclName());
2828 if (!NewDI)
2829 return nullptr;
2830
2831 if (NewDI->getType()->containsUnexpandedParameterPack()) {
2832 // We still have unexpanded parameter packs, which means that
2833 // our function parameter is still a function parameter pack.
2834 // Therefore, make its type a pack expansion type.
2835 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
2836 NumExpansions);
2837 } else if (ExpectParameterPack) {
2838 // We expected to get a parameter pack but didn't (because the type
2839 // itself is not a pack expansion type), so complain. This can occur when
2840 // the substitution goes through an alias template that "loses" the
2841 // pack expansion.
2842 Diag(OldParm->getLocation(),
2843 diag::err_function_parameter_pack_without_parameter_packs)
2844 << NewDI->getType();
2845 return nullptr;
2846 }
2847 } else {
2848 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
2849 OldParm->getDeclName());
2850 }
2851
2852 if (!NewDI)
2853 return nullptr;
2854
2855 if (NewDI->getType()->isVoidType()) {
2856 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
2857 return nullptr;
2858 }
2859
2860 // In abbreviated templates, TemplateTypeParmDecls with possible
2861 // TypeConstraints are created when the parameter list is originally parsed.
2862 // The TypeConstraints can therefore reference other functions parameters in
2863 // the abbreviated function template, which is why we must instantiate them
2864 // here, when the instantiated versions of those referenced parameters are in
2865 // scope.
2866 if (TemplateTypeParmDecl *TTP =
2867 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
2868 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
2869 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
2870 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
2871 // We will first get here when instantiating the abbreviated function
2872 // template's described function, but we might also get here later.
2873 // Make sure we do not instantiate the TypeConstraint more than once.
2874 if (Inst && !Inst->getTypeConstraint()) {
2875 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
2876 return nullptr;
2877 }
2878 }
2879 }
2880
2882 OldParm->getInnerLocStart(),
2883 OldParm->getLocation(),
2884 OldParm->getIdentifier(),
2885 NewDI->getType(), NewDI,
2886 OldParm->getStorageClass());
2887 if (!NewParm)
2888 return nullptr;
2889
2890 // Mark the (new) default argument as uninstantiated (if any).
2891 if (OldParm->hasUninstantiatedDefaultArg()) {
2892 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
2893 NewParm->setUninstantiatedDefaultArg(Arg);
2894 } else if (OldParm->hasUnparsedDefaultArg()) {
2895 NewParm->setUnparsedDefaultArg();
2896 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
2897 } else if (Expr *Arg = OldParm->getDefaultArg()) {
2898 // Default arguments cannot be substituted until the declaration context
2899 // for the associated function or lambda capture class is available.
2900 // This is necessary for cases like the following where construction of
2901 // the lambda capture class for the outer lambda is dependent on the
2902 // parameter types but where the default argument is dependent on the
2903 // outer lambda's declaration context.
2904 // template <typename T>
2905 // auto f() {
2906 // return [](T = []{ return T{}; }()) { return 0; };
2907 // }
2908 NewParm->setUninstantiatedDefaultArg(Arg);
2909 }
2910
2912
2913 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
2914 // Add the new parameter to the instantiated parameter pack.
2916 } else {
2917 // Introduce an Old -> New mapping
2919 }
2920
2921 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
2922 // can be anything, is this right ?
2923 NewParm->setDeclContext(CurContext);
2924
2925 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
2926 OldParm->getFunctionScopeIndex() + indexAdjustment);
2927
2928 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
2929
2930 return NewParm;
2931}
2932
2933/// Substitute the given template arguments into the given set of
2934/// parameters, producing the set of parameter types that would be generated
2935/// from such a substitution.
2938 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
2939 const MultiLevelTemplateArgumentList &TemplateArgs,
2940 SmallVectorImpl<QualType> &ParamTypes,
2942 ExtParameterInfoBuilder &ParamInfos) {
2943 assert(!CodeSynthesisContexts.empty() &&
2944 "Cannot perform an instantiation without some context on the "
2945 "instantiation stack");
2946
2947 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2948 DeclarationName());
2949 return Instantiator.TransformFunctionTypeParams(
2950 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
2951}
2952
2953/// Substitute the given template arguments into the default argument.
2955 SourceLocation Loc,
2956 ParmVarDecl *Param,
2957 const MultiLevelTemplateArgumentList &TemplateArgs,
2958 bool ForCallExpr) {
2959 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
2960 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
2961
2964
2965 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
2966 if (Inst.isInvalid())
2967 return true;
2968 if (Inst.isAlreadyInstantiating()) {
2969 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
2970 Param->setInvalidDecl();
2971 return true;
2972 }
2973
2975 {
2976 // C++ [dcl.fct.default]p5:
2977 // The names in the [default argument] expression are bound, and
2978 // the semantic constraints are checked, at the point where the
2979 // default argument expression appears.
2980 ContextRAII SavedContext(*this, FD);
2981 std::unique_ptr<LocalInstantiationScope> LIS;
2982
2983 if (ForCallExpr) {
2984 // When instantiating a default argument due to use in a call expression,
2985 // an instantiation scope that includes the parameters of the callee is
2986 // required to satisfy references from the default argument. For example:
2987 // template<typename T> void f(T a, int = decltype(a)());
2988 // void g() { f(0); }
2989 LIS = std::make_unique<LocalInstantiationScope>(*this);
2991 /*ForDefinition*/ false);
2992 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
2993 return true;
2994 }
2995
2997 Result = SubstInitializer(PatternExpr, TemplateArgs,
2998 /*DirectInit*/false);
2999 });
3000 }
3001 if (Result.isInvalid())
3002 return true;
3003
3004 if (ForCallExpr) {
3005 // Check the expression as an initializer for the parameter.
3006 InitializedEntity Entity
3009 Param->getLocation(),
3010 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3011 Expr *ResultE = Result.getAs<Expr>();
3012
3013 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3014 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3015 if (Result.isInvalid())
3016 return true;
3017
3018 Result =
3020 /*DiscardedValue*/ false);
3021 } else {
3022 // FIXME: Obtain the source location for the '=' token.
3023 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3024 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3025 }
3026 if (Result.isInvalid())
3027 return true;
3028
3029 // Remember the instantiated default argument.
3030 Param->setDefaultArg(Result.getAs<Expr>());
3031
3032 return false;
3033}
3034
3035/// Perform substitution on the base class specifiers of the
3036/// given class template specialization.
3037///
3038/// Produces a diagnostic and returns true on error, returns false and
3039/// attaches the instantiated base classes to the class template
3040/// specialization if successful.
3041bool
3043 CXXRecordDecl *Pattern,
3044 const MultiLevelTemplateArgumentList &TemplateArgs) {
3045 bool Invalid = false;
3046 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3047 for (const auto &Base : Pattern->bases()) {
3048 if (!Base.getType()->isDependentType()) {
3049 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3050 if (RD->isInvalidDecl())
3051 Instantiation->setInvalidDecl();
3052 }
3053 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3054 continue;
3055 }
3056
3057 SourceLocation EllipsisLoc;
3058 TypeSourceInfo *BaseTypeLoc;
3059 if (Base.isPackExpansion()) {
3060 // This is a pack expansion. See whether we should expand it now, or
3061 // wait until later.
3063 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3064 Unexpanded);
3065 bool ShouldExpand = false;
3066 bool RetainExpansion = false;
3067 std::optional<unsigned> NumExpansions;
3068 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3069 Base.getSourceRange(),
3070 Unexpanded,
3071 TemplateArgs, ShouldExpand,
3072 RetainExpansion,
3073 NumExpansions)) {
3074 Invalid = true;
3075 continue;
3076 }
3077
3078 // If we should expand this pack expansion now, do so.
3079 if (ShouldExpand) {
3080 for (unsigned I = 0; I != *NumExpansions; ++I) {
3081 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3082
3083 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3084 TemplateArgs,
3085 Base.getSourceRange().getBegin(),
3086 DeclarationName());
3087 if (!BaseTypeLoc) {
3088 Invalid = true;
3089 continue;
3090 }
3091
3092 if (CXXBaseSpecifier *InstantiatedBase
3093 = CheckBaseSpecifier(Instantiation,
3094 Base.getSourceRange(),
3095 Base.isVirtual(),
3096 Base.getAccessSpecifierAsWritten(),
3097 BaseTypeLoc,
3098 SourceLocation()))
3099 InstantiatedBases.push_back(InstantiatedBase);
3100 else
3101 Invalid = true;
3102 }
3103
3104 continue;
3105 }
3106
3107 // The resulting base specifier will (still) be a pack expansion.
3108 EllipsisLoc = Base.getEllipsisLoc();
3109 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3110 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3111 TemplateArgs,
3112 Base.getSourceRange().getBegin(),
3113 DeclarationName());
3114 } else {
3115 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3116 TemplateArgs,
3117 Base.getSourceRange().getBegin(),
3118 DeclarationName());
3119 }
3120
3121 if (!BaseTypeLoc) {
3122 Invalid = true;
3123 continue;
3124 }
3125
3126 if (CXXBaseSpecifier *InstantiatedBase
3127 = CheckBaseSpecifier(Instantiation,
3128 Base.getSourceRange(),
3129 Base.isVirtual(),
3130 Base.getAccessSpecifierAsWritten(),
3131 BaseTypeLoc,
3132 EllipsisLoc))
3133 InstantiatedBases.push_back(InstantiatedBase);
3134 else
3135 Invalid = true;
3136 }
3137
3138 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3139 Invalid = true;
3140
3141 return Invalid;
3142}
3143
3144// Defined via #include from SemaTemplateInstantiateDecl.cpp
3145namespace clang {
3146 namespace sema {
3148 const MultiLevelTemplateArgumentList &TemplateArgs);
3150 const Attr *At, ASTContext &C, Sema &S,
3151 const MultiLevelTemplateArgumentList &TemplateArgs);
3152 }
3153}
3154
3155/// Instantiate the definition of a class from a given pattern.
3156///
3157/// \param PointOfInstantiation The point of instantiation within the
3158/// source code.
3159///
3160/// \param Instantiation is the declaration whose definition is being
3161/// instantiated. This will be either a class template specialization
3162/// or a member class of a class template specialization.
3163///
3164/// \param Pattern is the pattern from which the instantiation
3165/// occurs. This will be either the declaration of a class template or
3166/// the declaration of a member class of a class template.
3167///
3168/// \param TemplateArgs The template arguments to be substituted into
3169/// the pattern.
3170///
3171/// \param TSK the kind of implicit or explicit instantiation to perform.
3172///
3173/// \param Complain whether to complain if the class cannot be instantiated due
3174/// to the lack of a definition.
3175///
3176/// \returns true if an error occurred, false otherwise.
3177bool
3179 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3180 const MultiLevelTemplateArgumentList &TemplateArgs,
3182 bool Complain) {
3183 CXXRecordDecl *PatternDef
3184 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3185 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3186 Instantiation->getInstantiatedFromMemberClass(),
3187 Pattern, PatternDef, TSK, Complain))
3188 return true;
3189
3190 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3191 std::string Name;
3192 llvm::raw_string_ostream OS(Name);
3193 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3194 /*Qualified=*/true);
3195 return Name;
3196 });
3197
3198 Pattern = PatternDef;
3199
3200 // Record the point of instantiation.
3201 if (MemberSpecializationInfo *MSInfo
3202 = Instantiation->getMemberSpecializationInfo()) {
3203 MSInfo->setTemplateSpecializationKind(TSK);
3204 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3205 } else if (ClassTemplateSpecializationDecl *Spec
3206 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3207 Spec->setTemplateSpecializationKind(TSK);
3208 Spec->setPointOfInstantiation(PointOfInstantiation);
3209 }
3210
3211 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3212 if (Inst.isInvalid())
3213 return true;
3214 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3215 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3216 "instantiating class definition");
3217
3218 // Enter the scope of this instantiation. We don't use
3219 // PushDeclContext because we don't have a scope.
3220 ContextRAII SavedContext(*this, Instantiation);
3223
3224 // If this is an instantiation of a local class, merge this local
3225 // instantiation scope with the enclosing scope. Otherwise, every
3226 // instantiation of a class has its own local instantiation scope.
3227 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3228 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3229
3230 // Some class state isn't processed immediately but delayed till class
3231 // instantiation completes. We may not be ready to handle any delayed state
3232 // already on the stack as it might correspond to a different class, so save
3233 // it now and put it back later.
3234 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3235
3236 // Pull attributes from the pattern onto the instantiation.
3237 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3238
3239 // Start the definition of this instantiation.
3240 Instantiation->startDefinition();
3241
3242 // The instantiation is visible here, even if it was first declared in an
3243 // unimported module.
3244 Instantiation->setVisibleDespiteOwningModule();
3245
3246 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3247 Instantiation->setTagKind(Pattern->getTagKind());
3248
3249 // Do substitution on the base class specifiers.
3250 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3251 Instantiation->setInvalidDecl();
3252
3253 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3254 Instantiator.setEvaluateConstraints(false);
3255 SmallVector<Decl*, 4> Fields;
3256 // Delay instantiation of late parsed attributes.
3257 LateInstantiatedAttrVec LateAttrs;
3258 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3259
3260 bool MightHaveConstexprVirtualFunctions = false;
3261 for (auto *Member : Pattern->decls()) {
3262 // Don't instantiate members not belonging in this semantic context.
3263 // e.g. for:
3264 // @code
3265 // template <int i> class A {
3266 // class B *g;
3267 // };
3268 // @endcode
3269 // 'class B' has the template as lexical context but semantically it is
3270 // introduced in namespace scope.
3271 if (Member->getDeclContext() != Pattern)
3272 continue;
3273
3274 // BlockDecls can appear in a default-member-initializer. They must be the
3275 // child of a BlockExpr, so we only know how to instantiate them from there.
3276 // Similarly, lambda closure types are recreated when instantiating the
3277 // corresponding LambdaExpr.
3278 if (isa<BlockDecl>(Member) ||
3279 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3280 continue;
3281
3282 if (Member->isInvalidDecl()) {
3283 Instantiation->setInvalidDecl();
3284 continue;
3285 }
3286
3287 Decl *NewMember = Instantiator.Visit(Member);
3288 if (NewMember) {
3289 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3290 Fields.push_back(Field);
3291 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3292 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3293 // specialization causes the implicit instantiation of the definitions
3294 // of unscoped member enumerations.
3295 // Record a point of instantiation for this implicit instantiation.
3296 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3297 Enum->isCompleteDefinition()) {
3298 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3299 assert(MSInfo && "no spec info for member enum specialization");
3301 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3302 }
3303 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3304 if (SA->isFailed()) {
3305 // A static_assert failed. Bail out; instantiating this
3306 // class is probably not meaningful.
3307 Instantiation->setInvalidDecl();
3308 break;
3309 }
3310 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3311 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3312 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3313 MightHaveConstexprVirtualFunctions = true;
3314 }
3315
3316 if (NewMember->isInvalidDecl())
3317 Instantiation->setInvalidDecl();
3318 } else {
3319 // FIXME: Eventually, a NULL return will mean that one of the
3320 // instantiations was a semantic disaster, and we'll want to mark the
3321 // declaration invalid.
3322 // For now, we expect to skip some members that we can't yet handle.
3323 }
3324 }
3325
3326 // Finish checking fields.
3327 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3329 CheckCompletedCXXClass(nullptr, Instantiation);
3330
3331 // Default arguments are parsed, if not instantiated. We can go instantiate
3332 // default arg exprs for default constructors if necessary now. Unless we're
3333 // parsing a class, in which case wait until that's finished.
3334 if (ParsingClassDepth == 0)
3336
3337 // Instantiate late parsed attributes, and attach them to their decls.
3338 // See Sema::InstantiateAttrs
3339 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3340 E = LateAttrs.end(); I != E; ++I) {
3341 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3342 CurrentInstantiationScope = I->Scope;
3343
3344 // Allow 'this' within late-parsed attributes.
3345 auto *ND = cast<NamedDecl>(I->NewDecl);
3346 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3347 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3348 ND->isCXXInstanceMember());
3349
3350 Attr *NewAttr =
3351 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3352 if (NewAttr)
3353 I->NewDecl->addAttr(NewAttr);
3355 Instantiator.getStartingScope());
3356 }
3357 Instantiator.disableLateAttributeInstantiation();
3358 LateAttrs.clear();
3359
3361
3362 // FIXME: We should do something similar for explicit instantiations so they
3363 // end up in the right module.
3364 if (TSK == TSK_ImplicitInstantiation) {
3365 Instantiation->setLocation(Pattern->getLocation());
3366 Instantiation->setLocStart(Pattern->getInnerLocStart());
3367 Instantiation->setBraceRange(Pattern->getBraceRange());
3368 }
3369
3370 if (!Instantiation->isInvalidDecl()) {
3371 // Perform any dependent diagnostics from the pattern.
3372 if (Pattern->isDependentContext())
3373 PerformDependentDiagnostics(Pattern, TemplateArgs);
3374
3375 // Instantiate any out-of-line class template partial
3376 // specializations now.
3378 P = Instantiator.delayed_partial_spec_begin(),
3379 PEnd = Instantiator.delayed_partial_spec_end();
3380 P != PEnd; ++P) {
3382 P->first, P->second)) {
3383 Instantiation->setInvalidDecl();
3384 break;
3385 }
3386 }
3387
3388 // Instantiate any out-of-line variable template partial
3389 // specializations now.
3391 P = Instantiator.delayed_var_partial_spec_begin(),
3392 PEnd = Instantiator.delayed_var_partial_spec_end();
3393 P != PEnd; ++P) {
3395 P->first, P->second)) {
3396 Instantiation->setInvalidDecl();
3397 break;
3398 }
3399 }
3400 }
3401
3402 // Exit the scope of this instantiation.
3403 SavedContext.pop();
3404
3405 if (!Instantiation->isInvalidDecl()) {
3406 // Always emit the vtable for an explicit instantiation definition
3407 // of a polymorphic class template specialization. Otherwise, eagerly
3408 // instantiate only constexpr virtual functions in preparation for their use
3409 // in constant evaluation.
3411 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3412 else if (MightHaveConstexprVirtualFunctions)
3413 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3414 /*ConstexprOnly*/ true);
3415 }
3416
3417 Consumer.HandleTagDeclDefinition(Instantiation);
3418
3419 return Instantiation->isInvalidDecl();
3420}
3421
3422/// Instantiate the definition of an enum from a given pattern.
3423///
3424/// \param PointOfInstantiation The point of instantiation within the
3425/// source code.
3426/// \param Instantiation is the declaration whose definition is being
3427/// instantiated. This will be a member enumeration of a class
3428/// temploid specialization, or a local enumeration within a
3429/// function temploid specialization.
3430/// \param Pattern The templated declaration from which the instantiation
3431/// occurs.
3432/// \param TemplateArgs The template arguments to be substituted into
3433/// the pattern.
3434/// \param TSK The kind of implicit or explicit instantiation to perform.
3435///
3436/// \return \c true if an error occurred, \c false otherwise.
3437bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3438 EnumDecl *Instantiation, EnumDecl *Pattern,
3439 const MultiLevelTemplateArgumentList &TemplateArgs,
3441 EnumDecl *PatternDef = Pattern->getDefinition();
3442 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3443 Instantiation->getInstantiatedFromMemberEnum(),
3444 Pattern, PatternDef, TSK,/*Complain*/true))
3445 return true;
3446 Pattern = PatternDef;
3447
3448 // Record the point of instantiation.
3449 if (MemberSpecializationInfo *MSInfo
3450 = Instantiation->getMemberSpecializationInfo()) {
3451 MSInfo->setTemplateSpecializationKind(TSK);
3452 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3453 }
3454
3455 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3456 if (Inst.isInvalid())
3457 return true;
3458 if (Inst.isAlreadyInstantiating())
3459 return false;
3460 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3461 "instantiating enum definition");
3462
3463 // The instantiation is visible here, even if it was first declared in an
3464 // unimported module.
3465 Instantiation->setVisibleDespiteOwningModule();
3466
3467 // Enter the scope of this instantiation. We don't use
3468 // PushDeclContext because we don't have a scope.
3469 ContextRAII SavedContext(*this, Instantiation);
3472
3473 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3474
3475 // Pull attributes from the pattern onto the instantiation.
3476 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3477
3478 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3479 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3480
3481 // Exit the scope of this instantiation.
3482 SavedContext.pop();
3483
3484 return Instantiation->isInvalidDecl();
3485}
3486
3487
3488/// Instantiate the definition of a field from the given pattern.
3489///
3490/// \param PointOfInstantiation The point of instantiation within the
3491/// source code.
3492/// \param Instantiation is the declaration whose definition is being
3493/// instantiated. This will be a class of a class temploid
3494/// specialization, or a local enumeration within a function temploid
3495/// specialization.
3496/// \param Pattern The templated declaration from which the instantiation
3497/// occurs.
3498/// \param TemplateArgs The template arguments to be substituted into
3499/// the pattern.
3500///
3501/// \return \c true if an error occurred, \c false otherwise.
3503 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3504 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3505 // If there is no initializer, we don't need to do anything.
3506 if (!Pattern->hasInClassInitializer())
3507 return false;
3508
3509 assert(Instantiation->getInClassInitStyle() ==
3510 Pattern->getInClassInitStyle() &&
3511 "pattern and instantiation disagree about init style");
3512
3513 // Error out if we haven't parsed the initializer of the pattern yet because
3514 // we are waiting for the closing brace of the outer class.
3515 Expr *OldInit = Pattern->getInClassInitializer();
3516 if (!OldInit) {
3517 RecordDecl *PatternRD = Pattern->getParent();
3518 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3519 Diag(PointOfInstantiation,
3520 diag::err_default_member_initializer_not_yet_parsed)
3521 << OutermostClass << Pattern;
3522 Diag(Pattern->getEndLoc(),
3523 diag::note_default_member_initializer_not_yet_parsed);
3524 Instantiation->setInvalidDecl();
3525 return true;
3526 }
3527
3528 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3529 if (Inst.isInvalid())
3530 return true;
3531 if (Inst.isAlreadyInstantiating()) {
3532 // Error out if we hit an instantiation cycle for this initializer.
3533 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3534 << Instantiation;
3535 return true;
3536 }
3537 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3538 "instantiating default member init");
3539
3540 // Enter the scope of this instantiation. We don't use PushDeclContext because
3541 // we don't have a scope.
3542 ContextRAII SavedContext(*this, Instantiation->getParent());
3545 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3546 PointOfInstantiation, Instantiation, CurContext};
3547
3548 LocalInstantiationScope Scope(*this, true);
3549
3550 // Instantiate the initializer.
3552 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3553
3554 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3555 /*CXXDirectInit=*/false);
3556 Expr *Init = NewInit.get();
3557 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3559 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3560
3561 if (auto *L = getASTMutationListener())
3562 L->DefaultMemberInitializerInstantiated(Instantiation);
3563
3564 // Return true if the in-class initializer is still missing.
3565 return !Instantiation->getInClassInitializer();
3566}
3567
3568namespace {
3569 /// A partial specialization whose template arguments have matched
3570 /// a given template-id.
3571 struct PartialSpecMatchResult {
3574 };
3575}
3576
3578 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3579 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3581 return true;
3582
3584 ClassTemplateSpec->getSpecializedTemplate()
3585 ->getPartialSpecializations(PartialSpecs);
3586 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3587 TemplateDeductionInfo Info(Loc);
3588 if (!DeduceTemplateArguments(PartialSpecs[I],
3589 ClassTemplateSpec->getTemplateArgs(), Info))
3590 return true;
3591 }
3592
3593 return false;
3594}
3595
3596/// Get the instantiation pattern to use to instantiate the definition of a
3597/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3598/// template or of a partial specialization).
3601 Sema &S, SourceLocation PointOfInstantiation,
3602 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3604 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3605 if (Inst.isInvalid())
3606 return {/*Invalid=*/true};
3607 if (Inst.isAlreadyInstantiating())
3608 return {/*Invalid=*/false};
3609
3610 llvm::PointerUnion<ClassTemplateDecl *,
3612 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3613 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
3614 // Find best matching specialization.
3615 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3616
3617 // C++ [temp.class.spec.match]p1:
3618 // When a class template is used in a context that requires an
3619 // instantiation of the class, it is necessary to determine
3620 // whether the instantiation is to be generated using the primary
3621 // template or one of the partial specializations. This is done by
3622 // matching the template arguments of the class template
3623 // specialization with the template argument lists of the partial
3624 // specializations.
3625 typedef PartialSpecMatchResult MatchResult;
3628 Template->getPartialSpecializations(PartialSpecs);
3629 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3630 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3631 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3632 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3634 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
3635 // Store the failed-deduction information for use in diagnostics, later.
3636 // TODO: Actually use the failed-deduction info?
3637 FailedCandidates.addCandidate().set(
3638 DeclAccessPair::make(Template, AS_public), Partial,
3640 (void)Result;
3641 } else {
3642 Matched.push_back(PartialSpecMatchResult());
3643 Matched.back().Partial = Partial;
3644 Matched.back().Args = Info.takeCanonical();
3645 }
3646 }
3647
3648 // If we're dealing with a member template where the template parameters
3649 // have been instantiated, this provides the original template parameters
3650 // from which the member template's parameters were instantiated.
3651
3652 if (Matched.size() >= 1) {
3653 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3654 if (Matched.size() == 1) {
3655 // -- If exactly one matching specialization is found, the
3656 // instantiation is generated from that specialization.
3657 // We don't need to do anything for this.
3658 } else {
3659 // -- If more than one matching specialization is found, the
3660 // partial order rules (14.5.4.2) are used to determine
3661 // whether one of the specializations is more specialized
3662 // than the others. If none of the specializations is more
3663 // specialized than all of the other matching
3664 // specializations, then the use of the class template is
3665 // ambiguous and the program is ill-formed.
3667 PEnd = Matched.end();
3668 P != PEnd; ++P) {
3670 P->Partial, Best->Partial, PointOfInstantiation) ==
3671 P->Partial)
3672 Best = P;
3673 }
3674
3675 // Determine if the best partial specialization is more specialized than
3676 // the others.
3677 bool Ambiguous = false;
3678 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3679 PEnd = Matched.end();
3680 P != PEnd; ++P) {
3682 P->Partial, Best->Partial,
3683 PointOfInstantiation) != Best->Partial) {
3684 Ambiguous = true;
3685 break;
3686 }
3687 }
3688
3689 if (Ambiguous) {
3690 // Partial ordering did not produce a clear winner. Complain.
3691 Inst.Clear();
3692 ClassTemplateSpec->setInvalidDecl();
3693 S.Diag(PointOfInstantiation,
3694 diag::err_partial_spec_ordering_ambiguous)
3695 << ClassTemplateSpec;
3696
3697 // Print the matching partial specializations.
3698 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3699 PEnd = Matched.end();
3700 P != PEnd; ++P)
3701 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
3703 P->Partial->getTemplateParameters(), *P->Args);
3704
3705 return {/*Invalid=*/true};
3706 }
3707 }
3708
3709 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
3710 } else {
3711 // -- If no matches are found, the instantiation is generated
3712 // from the primary template.
3713 }
3714 }
3715
3716 CXXRecordDecl *Pattern = nullptr;
3717 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3718 if (auto *PartialSpec =
3719 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
3720 // Instantiate using the best class template partial specialization.
3721 while (PartialSpec->getInstantiatedFromMember()) {
3722 // If we've found an explicit specialization of this class template,
3723 // stop here and use that as the pattern.
3724 if (PartialSpec->isMemberSpecialization())
3725 break;
3726
3727 PartialSpec = PartialSpec->getInstantiatedFromMember();
3728 }
3729 Pattern = PartialSpec;
3730 } else {
3731 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3732 while (Template->getInstantiatedFromMemberTemplate()) {
3733 // If we've found an explicit specialization of this class template,
3734 // stop here and use that as the pattern.
3735 if (Template->isMemberSpecialization())
3736 break;
3737
3738 Template = Template->getInstantiatedFromMemberTemplate();
3739 }
3740 Pattern = Template->getTemplatedDecl();
3741 }
3742
3743 return Pattern;
3744}
3745
3747 SourceLocation PointOfInstantiation,
3748 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3749 TemplateSpecializationKind TSK, bool Complain) {
3750 // Perform the actual instantiation on the canonical declaration.
3751 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
3752 ClassTemplateSpec->getCanonicalDecl());
3753 if (ClassTemplateSpec->isInvalidDecl())
3754 return true;
3755
3757 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
3758 ClassTemplateSpec, TSK);
3759 if (!Pattern.isUsable())
3760 return Pattern.isInvalid();
3761
3762 return InstantiateClass(
3763 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
3764 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
3765}
3766
3767/// Instantiates the definitions of all of the member
3768/// of the given class, which is an instantiation of a class template
3769/// or a member class of a template.
3770void
3772 CXXRecordDecl *Instantiation,
3773 const MultiLevelTemplateArgumentList &TemplateArgs,
3775 // FIXME: We need to notify the ASTMutationListener that we did all of these
3776 // things, in case we have an explicit instantiation definition in a PCM, a
3777 // module, or preamble, and the declaration is in an imported AST.
3778 assert(
3781 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
3782 "Unexpected template specialization kind!");
3783 for (auto *D : Instantiation->decls()) {
3784 bool SuppressNew = false;
3785 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
3786 if (FunctionDecl *Pattern =
3787 Function->getInstantiatedFromMemberFunction()) {
3788
3789 if (Function->isIneligibleOrNotSelected())
3790 continue;
3791
3792 if (Function->getTrailingRequiresClause()) {
3793 ConstraintSatisfaction Satisfaction;
3794 if (CheckFunctionConstraints(Function, Satisfaction) ||
3795 !Satisfaction.IsSatisfied) {
3796 continue;
3797 }
3798 }
3799
3800 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3801 continue;
3802
3803 MemberSpecializationInfo *MSInfo =
3804 Function->getMemberSpecializationInfo();
3805 assert(MSInfo && "No member specialization information?");
3806 if (MSInfo->getTemplateSpecializationKind()
3808 continue;
3809
3810 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3811 Function,
3813 MSInfo->getPointOfInstantiation(),
3814 SuppressNew) ||
3815 SuppressNew)
3816 continue;
3817
3818 // C++11 [temp.explicit]p8:
3819 // An explicit instantiation definition that names a class template
3820 // specialization explicitly instantiates the class template
3821 // specialization and is only an explicit instantiation definition
3822 // of members whose definition is visible at the point of
3823 // instantiation.
3824 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
3825 continue;
3826
3827 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3828
3829 if (Function->isDefined()) {
3830 // Let the ASTConsumer know that this function has been explicitly
3831 // instantiated now, and its linkage might have changed.
3833 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
3834 InstantiateFunctionDefinition(PointOfInstantiation, Function);
3835 } else if (TSK == TSK_ImplicitInstantiation) {
3837 std::make_pair(Function, PointOfInstantiation));
3838 }
3839 }
3840 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
3841 if (isa<VarTemplateSpecializationDecl>(Var))
3842 continue;
3843
3844 if (Var->isStaticDataMember()) {
3845 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3846 continue;
3847
3849 assert(MSInfo && "No member specialization information?");
3850 if (MSInfo->getTemplateSpecializationKind()
3852 continue;
3853
3854 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3855 Var,
3857 MSInfo->getPointOfInstantiation(),
3858 SuppressNew) ||
3859 SuppressNew)
3860 continue;
3861
3863 // C++0x [temp.explicit]p8:
3864 // An explicit instantiation definition that names a class template
3865 // specialization explicitly instantiates the class template
3866 // specialization and is only an explicit instantiation definition
3867 // of members whose definition is visible at the point of
3868 // instantiation.
3870 continue;
3871
3872 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3873 InstantiateVariableDefinition(PointOfInstantiation, Var);
3874 } else {
3875 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3876 }
3877 }
3878 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
3879 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3880 continue;
3881
3882 // Always skip the injected-class-name, along with any
3883 // redeclarations of nested classes, since both would cause us
3884 // to try to instantiate the members of a class twice.
3885 // Skip closure types; they'll get instantiated when we instantiate
3886 // the corresponding lambda-expression.
3887 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
3888 Record->isLambda())
3889 continue;
3890
3891 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
3892 assert(MSInfo && "No member specialization information?");
3893
3894 if (MSInfo->getTemplateSpecializationKind()
3896 continue;
3897
3898 if (Context.getTargetInfo().getTriple().isOSWindows() &&
3900 // On Windows, explicit instantiation decl of the outer class doesn't
3901 // affect the inner class. Typically extern template declarations are
3902 // used in combination with dll import/export annotations, but those
3903 // are not propagated from the outer class templates to inner classes.
3904 // Therefore, do not instantiate inner classes on this platform, so
3905 // that users don't end up with undefined symbols during linking.
3906 continue;
3907 }
3908
3909 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3910 Record,
3912 MSInfo->getPointOfInstantiation(),
3913 SuppressNew) ||
3914 SuppressNew)
3915 continue;
3916
3917 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3918 assert(Pattern && "Missing instantiated-from-template information");
3919
3920 if (!Record->getDefinition()) {
3921 if (!Pattern->getDefinition()) {
3922 // C++0x [temp.explicit]p8:
3923 // An explicit instantiation definition that names a class template
3924 // specialization explicitly instantiates the class template
3925 // specialization and is only an explicit instantiation definition
3926 // of members whose definition is visible at the point of
3927 // instantiation.
3929 MSInfo->setTemplateSpecializationKind(TSK);
3930 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3931 }
3932
3933 continue;
3934 }
3935
3936 InstantiateClass(PointOfInstantiation, Record, Pattern,
3937 TemplateArgs,
3938 TSK);
3939 } else {
3941 Record->getTemplateSpecializationKind() ==
3943 Record->setTemplateSpecializationKind(TSK);
3944 MarkVTableUsed(PointOfInstantiation, Record, true);
3945 }
3946 }
3947
3948 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
3949 if (Pattern)
3950 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
3951 TSK);
3952 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
3953 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
3954 assert(MSInfo && "No member specialization information?");
3955
3956 if (MSInfo->getTemplateSpecializationKind()
3958 continue;
3959
3961 PointOfInstantiation, TSK, Enum,
3963 MSInfo->getPointOfInstantiation(), SuppressNew) ||
3964 SuppressNew)
3965 continue;
3966
3967 if (Enum->getDefinition())
3968 continue;
3969
3970 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
3971 assert(Pattern && "Missing instantiated-from-template information");
3972
3974 if (!Pattern->getDefinition())
3975 continue;
3976
3977 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
3978 } else {
3979 MSInfo->setTemplateSpecializationKind(TSK);
3980 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3981 }
3982 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3983 // No need to instantiate in-class initializers during explicit
3984 // instantiation.
3985 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
3986 CXXRecordDecl *ClassPattern =
3987 Instantiation->getTemplateInstantiationPattern();
3989 ClassPattern->lookup(Field->getDeclName());
3990 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
3991 assert(Pattern);
3992 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
3993 TemplateArgs);
3994 }
3995 }
3996 }
3997}
3998
3999/// Instantiate the definitions of all of the members of the
4000/// given class template specialization, which was named as part of an
4001/// explicit instantiation.
4002void
4004 SourceLocation PointOfInstantiation,
4005 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4007 // C++0x [temp.explicit]p7:
4008 // An explicit instantiation that names a class template
4009 // specialization is an explicit instantion of the same kind
4010 // (declaration or definition) of each of its members (not
4011 // including members inherited from base classes) that has not
4012 // been previously explicitly specialized in the translation unit
4013 // containing the explicit instantiation, except as described
4014 // below.
4015 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4016 getTemplateInstantiationArgs(ClassTemplateSpec),
4017 TSK);
4018}
4019
4022 if (!S)
4023 return S;
4024
4025 TemplateInstantiator Instantiator(*this, TemplateArgs,
4027 DeclarationName());
4028 return Instantiator.TransformStmt(S);
4029}
4030
4033 const MultiLevelTemplateArgumentList &TemplateArgs,
4035 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4036 DeclarationName());
4037 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4038}
4039
4042 if (!E)
4043 return E;
4044
4045 TemplateInstantiator Instantiator(*this, TemplateArgs,
4047 DeclarationName());
4048 return Instantiator.TransformExpr(E);
4049}
4050
4053 const MultiLevelTemplateArgumentList &TemplateArgs) {
4054 if (!E)
4055 return E;
4056
4057 // This is where we need to make sure we 'know' constraint checking needs to
4058 // happen.
4059 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4060 DeclarationName());
4061 return Instantiator.TransformExpr(E);
4062}
4063
4065 const MultiLevelTemplateArgumentList &TemplateArgs,
4066 bool CXXDirectInit) {
4067 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4068 DeclarationName());
4069 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4070}
4071
4072bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4073 const MultiLevelTemplateArgumentList &TemplateArgs,
4074 SmallVectorImpl<Expr *> &Outputs) {
4075 if (Exprs.empty())
4076 return false;
4077
4078 TemplateInstantiator Instantiator(*this, TemplateArgs,
4080 DeclarationName());
4081 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4082 IsCall, Outputs);
4083}
4084
4087 const MultiLevelTemplateArgumentList &TemplateArgs) {
4088 if (!NNS)
4089 return NestedNameSpecifierLoc();
4090
4091 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4092 DeclarationName());
4093 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4094}
4095
4096/// Do template substitution on declaration name info.
4099 const MultiLevelTemplateArgumentList &TemplateArgs) {
4100 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4101 NameInfo.getName());
4102 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4103}
4104
4107 TemplateName Name, SourceLocation Loc,
4108 const MultiLevelTemplateArgumentList &TemplateArgs) {
4109 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4110 DeclarationName());
4111 CXXScopeSpec SS;
4112 SS.Adopt(QualifierLoc);
4113 return Instantiator.TransformTemplateName(SS, Name, Loc);
4114}
4115
4116static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4117 // When storing ParmVarDecls in the local instantiation scope, we always
4118 // want to use the ParmVarDecl from the canonical function declaration,
4119 // since the map is then valid for any redeclaration or definition of that
4120 // function.
4121 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4122 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4123 unsigned i = PV->getFunctionScopeIndex();
4124 // This parameter might be from a freestanding function type within the
4125 // function and isn't necessarily referring to one of FD's parameters.
4126 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4127 return FD->getCanonicalDecl()->getParamDecl(i);
4128 }
4129 }
4130 return D;
4131}
4132
4133
4134llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4137 for (LocalInstantiationScope *Current = this; Current;
4138 Current = Current->Outer) {
4139
4140 // Check if we found something within this scope.
4141 const Decl *CheckD = D;
4142 do {
4143 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4144 if (Found != Current->LocalDecls.end())
4145 return &Found->second;
4146
4147 // If this is a tag declaration, it's possible that we need to look for
4148 // a previous declaration.
4149 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4150 CheckD = Tag->getPreviousDecl();
4151 else
4152 CheckD = nullptr;
4153 } while (CheckD);
4154
4155 // If we aren't combined with our outer scope, we're done.
4156 if (!Current->CombineWithOuterScope)
4157 break;
4158 }
4159
4160 // If we're performing a partial substitution during template argument
4161 // deduction, we may not have values for template parameters yet.
4162 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4163 isa<TemplateTemplateParmDecl>(D))
4164 return nullptr;
4165
4166 // Local types referenced prior to definition may require instantiation.
4167 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4168 if (RD->isLocalClass())
4169 return nullptr;
4170
4171 // Enumeration types referenced prior to definition may appear as a result of
4172 // error recovery.
4173 if (isa<EnumDecl>(D))
4174 return nullptr;
4175
4176 // Materialized typedefs/type alias for implicit deduction guides may require
4177 // instantiation.
4178 if (isa<TypedefNameDecl>(D) &&
4179 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4180 return nullptr;
4181
4182 // If we didn't find the decl, then we either have a sema bug, or we have a
4183 // forward reference to a label declaration. Return null to indicate that
4184 // we have an uninstantiated label.
4185 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4186 return nullptr;
4187}
4188
4191 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4192 if (Stored.isNull()) {
4193#ifndef NDEBUG
4194 // It should not be present in any surrounding scope either.
4195 LocalInstantiationScope *Current = this;
4196 while (Current->CombineWithOuterScope && Current->Outer) {
4197 Current = Current->Outer;
4198 assert(!Current->LocalDecls.contains(D) &&
4199 "Instantiated local in inner and outer scopes");
4200 }
4201#endif
4202 Stored = Inst;
4203 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
4204 Pack->push_back(cast<VarDecl>(Inst));
4205 } else {
4206 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
4207 }
4208}
4209
4211 VarDecl *Inst) {
4213 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
4214 Pack->push_back(Inst);
4215}
4216
4218#ifndef NDEBUG
4219 // This should be the first time we've been told about this decl.
4220 for (LocalInstantiationScope *Current = this;
4221 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4222 assert(!Current->LocalDecls.contains(D) &&
4223 "Creating local pack after instantiation of local");
4224#endif
4225
4227 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4229 Stored = Pack;
4230 ArgumentPacks.push_back(Pack);
4231}
4232
4234 for (DeclArgumentPack *Pack : ArgumentPacks)
4235 if (llvm::is_contained(*Pack, D))
4236 return true;
4237 return false;
4238}
4239
4241 const TemplateArgument *ExplicitArgs,
4242 unsigned NumExplicitArgs) {
4243 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4244 "Already have a partially-substituted pack");
4245 assert((!PartiallySubstitutedPack
4246 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4247 "Wrong number of arguments in partially-substituted pack");
4248 PartiallySubstitutedPack = Pack;
4249 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4250 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4251}
4252
4254 const TemplateArgument **ExplicitArgs,
4255 unsigned *NumExplicitArgs) const {
4256 if (ExplicitArgs)
4257 *ExplicitArgs = nullptr;
4258 if (NumExplicitArgs)
4259 *NumExplicitArgs = 0;
4260
4261 for (const LocalInstantiationScope *Current = this; Current;
4262 Current = Current->Outer) {
4263 if (Current->PartiallySubstitutedPack) {
4264 if (ExplicitArgs)
4265 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4266 if (NumExplicitArgs)
4267 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4268
4269 return Current->PartiallySubstitutedPack;
4270 }
4271
4272 if (!Current->CombineWithOuterScope)
4273 break;
4274 }
4275
4276 return nullptr;
4277}
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:89
Defines the clang::LangOptions interface.
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.
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:1059
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:2543
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:1564
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2125
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:683
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:743
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:2869
QualType getOriginalType() const
Definition: Type.h:2882
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3083
QualType getElementType() const
Definition: Type.h:3104
Attr - This represents one attribute.
Definition: Attr.h:40
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:4988
QualType getModifiedType() const
Definition: Type.h:5010
Pointer to a block type.
Definition: Type.h:2920
QualType getPointeeType() const
Definition: Type.h:2932
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:2035
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
Decl * getLambdaContextDecl() const
Retrieve the declaration that provides additional context for a lambda, when the normal declaration c...
Definition: DeclCXX.cpp:1643
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1537
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:1834
base_class_range bases()
Definition: DeclCXX.h:606
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1009
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:552
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:600
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1888
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1863
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1855
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1841
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:511
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1874
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...
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:1347
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1409
bool isFileContext() const
Definition: DeclBase.h:2021
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1209
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1728
bool isTranslationUnit() const
Definition: DeclBase.h:2026
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1890
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2206
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1242
ValueDecl * getDecl()
Definition: Expr.h:1310
SourceLocation getLocation() const
Definition: Expr.h:1318
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1029
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1194
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:576
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:221
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:133
bool isFileContextDecl() const
Definition: DeclBase.cpp:409
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:932
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:275
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1086
bool isInvalidDecl() const
Definition: DeclBase.h:571
SourceLocation getLocation() const
Definition: DeclBase.h:432
void setLocation(SourceLocation L)
Definition: DeclBase.h:433
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:917
DeclContext * getDeclContext()
Definition: DeclBase.h:441
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:337
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:886
bool hasAttr() const
Definition: DeclBase.h:560
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:946
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:838
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:825
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:810
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2029
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:819
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:796
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1850
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3391
QualType getElementType() const
Definition: Type.h:3407
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1542
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:845
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic.
Definition: Diagnostic.h:626
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:5757
QualType getNamedType() const
Retrieve the type named by the qualified-id.
Definition: Type.h:5795
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3758
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4017
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:4798
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4824
EnumDecl * getDefinition() const
Definition: Decl.h:3861
This represents one expression.
Definition: Expr.h:110
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:431
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:186
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:271
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:215
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:330
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:503
Represents a member of a struct/union/class.
Definition: Decl.h:2962
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4456
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3120
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3114
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3172
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:1919
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2603
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:4017
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2367
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2248
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4497
VarDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition: ExprCXX.h:4524
iterator end() const
Definition: ExprCXX.h:4533
VarDecl * getExpansion(unsigned I) const
Get an expansion of the parameter pack by index.
Definition: ExprCXX.h:4539
VarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:4531
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition: ExprCXX.h:4536
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition: ExprCXX.h:4527
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, VarDecl *ParamPack, SourceLocation NameLoc, ArrayRef< VarDecl * > Params)
Definition: ExprCXX.cpp:1711
iterator begin() const
Definition: ExprCXX.h:4532
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4117
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4345
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1455
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:3777
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3751
QualType getReturnType() const
Definition: Type.h:4035
One of these records is kept for each identifier that is lexed.
ArrayRef< TemplateArgument > getTemplateArguments() const
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:508
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.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1937
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:2151
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:363
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:496
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:4688
QualType getUnderlyingType() const
Definition: Type.h:4704
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3031
QualType getPointeeType() const
Definition: Type.h:3047
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:632
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:663
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:654
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:672
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:677
Describes a module or submodule.
Definition: Module.h:104
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:263
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:247
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:268
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:313
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:1823
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Definition: Decl.cpp:1672
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:5956
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:5977
Sugar for parentheses used when specifying types.
Definition: Type.h:2814
QualType getInnerType() const
Definition: Type.h:2823
Represents a parameter to a function.
Definition: Decl.h:1724
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1784
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2953
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1853
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1841
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2978
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1757
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1845
bool hasInheritedDefaultArg() const
Definition: Decl.h:1857
Expr * getDefaultArg()
Definition: Decl.cpp:2941
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2983
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1774
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1861
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2840
QualType getPointeeType() const
Definition: Type.h:2850
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1985
SourceLocation getLocation() const
Definition: Expr.h:2041
IdentKind getIdentKind() const
Definition: Expr.h:2035
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition: Type.h:736
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3338
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:944
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:803
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6747
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6787
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6840
The collection of all-type qualifiers we support.
Definition: Type.h:146
void removeObjCLifetime()
Definition: Type.h:357
Represents a struct/union/class.
Definition: Decl.h:4036
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4933
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:911
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2951
QualType getPointeeTypeAsWritten() const
Definition: Type.h:2967
Represents the body of a requires-expression.
Definition: DeclCXX.h:2013
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:507
SourceLocation getLParenLoc() const
Definition: ExprConcepts.h:575
SourceLocation getRParenLoc() const
Definition: ExprConcepts.h:576
RequiresExprBodyDecl * getBody() const
Definition: ExprConcepts.h:551
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:9603
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6755
A RAII object to temporarily push a declaration context.
Definition: Sema.h:1024
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:3456
DefaultedComparisonKind asComparison() const
Definition: Sema.h:3479
CXXSpecialMember asSpecialMember() const
Definition: Sema.h:3478
A helper class for building up ExtParameterInfos.
Definition: Sema.h:10096
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9912
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:356
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:9532
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9970
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.
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:9548
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1919
void ActOnFinishDelayedMemberInitializers(Decl *Record)
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, bool Final=false, const TemplateArgumentList *Innermost=nullptr, 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...
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:9535
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6965
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
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:8470
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:407
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition: Sema.h:9564
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1689
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
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:3312
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:16774
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:1685
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info)
Perform template argument deduction to determine whether the given template arguments match the given...
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
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:7513
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 ...
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:9110
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:15085
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:9589
void PrintInstantiationStack()
Prints the current instantiation stack through a series of notes.
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
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:1513
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:9597
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:419
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:10071
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.
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21629
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition: Sema.h:9573
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:6213
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.